repo_name
stringlengths 6
100
| path
stringlengths 4
294
| copies
stringlengths 1
5
| size
stringlengths 4
6
| content
stringlengths 606
896k
| license
stringclasses 15
values |
---|---|---|---|---|---|
RossBrunton/django | django/core/management/commands/check.py | 316 | 1892 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.apps import apps
from django.core import checks
from django.core.checks.registry import registry
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = "Checks the entire Django project for potential problems."
requires_system_checks = False
def add_arguments(self, parser):
parser.add_argument('args', metavar='app_label', nargs='*')
parser.add_argument('--tag', '-t', action='append', dest='tags',
help='Run only checks labeled with given tag.')
parser.add_argument('--list-tags', action='store_true', dest='list_tags',
help='List available tags.')
parser.add_argument('--deploy', action='store_true', dest='deploy',
help='Check deployment settings.')
def handle(self, *app_labels, **options):
include_deployment_checks = options['deploy']
if options.get('list_tags'):
self.stdout.write('\n'.join(sorted(registry.tags_available(include_deployment_checks))))
return
if app_labels:
app_configs = [apps.get_app_config(app_label) for app_label in app_labels]
else:
app_configs = None
tags = options.get('tags')
if tags:
try:
invalid_tag = next(
tag for tag in tags if not checks.tag_exists(tag, include_deployment_checks)
)
except StopIteration:
# no invalid tags
pass
else:
raise CommandError('There is no system check with the "%s" tag.' % invalid_tag)
self.check(
app_configs=app_configs,
tags=tags,
display_num_errors=True,
include_deployment_checks=include_deployment_checks,
)
| bsd-3-clause |
wfnex/openbras | src/VPP/test/test_vxlan.py | 2 | 9043 | #!/usr/bin/env python
import socket
from util import ip4n_range
import unittest
from framework import VppTestCase, VppTestRunner
from template_bd import BridgeDomain
from scapy.layers.l2 import Ether
from scapy.layers.inet import IP, UDP
from scapy.layers.vxlan import VXLAN
from scapy.utils import atol
class TestVxlan(BridgeDomain, VppTestCase):
""" VXLAN Test Case """
def __init__(self, *args):
BridgeDomain.__init__(self)
VppTestCase.__init__(self, *args)
def encapsulate(self, pkt, vni):
"""
Encapsulate the original payload frame by adding VXLAN header with its
UDP, IP and Ethernet fields
"""
return (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) /
UDP(sport=self.dport, dport=self.dport, chksum=0) /
VXLAN(vni=vni, flags=self.flags) /
pkt)
def encap_mcast(self, pkt, src_ip, src_mac, vni):
"""
Encapsulate the original payload frame by adding VXLAN header with its
UDP, IP and Ethernet fields
"""
return (Ether(src=src_mac, dst=self.mcast_mac) /
IP(src=src_ip, dst=self.mcast_ip4) /
UDP(sport=self.dport, dport=self.dport, chksum=0) /
VXLAN(vni=vni, flags=self.flags) /
pkt)
def decapsulate(self, pkt):
"""
Decapsulate the original payload frame by removing VXLAN header
"""
# check if is set I flag
self.assertEqual(pkt[VXLAN].flags, int('0x8', 16))
return pkt[VXLAN].payload
# Method for checking VXLAN encapsulation.
#
def check_encapsulation(self, pkt, vni, local_only=False, mcast_pkt=False):
# TODO: add error messages
# Verify source MAC is VPP_MAC and destination MAC is MY_MAC resolved
# by VPP using ARP.
self.assertEqual(pkt[Ether].src, self.pg0.local_mac)
if not local_only:
if not mcast_pkt:
self.assertEqual(pkt[Ether].dst, self.pg0.remote_mac)
else:
self.assertEqual(pkt[Ether].dst, type(self).mcast_mac)
# Verify VXLAN tunnel source IP is VPP_IP and destination IP is MY_IP.
self.assertEqual(pkt[IP].src, self.pg0.local_ip4)
if not local_only:
if not mcast_pkt:
self.assertEqual(pkt[IP].dst, self.pg0.remote_ip4)
else:
self.assertEqual(pkt[IP].dst, type(self).mcast_ip4)
# Verify UDP destination port is VXLAN 4789, source UDP port could be
# arbitrary.
self.assertEqual(pkt[UDP].dport, type(self).dport)
# TODO: checksum check
# Verify VNI
self.assertEqual(pkt[VXLAN].vni, vni)
@classmethod
def create_vxlan_flood_test_bd(cls, vni, n_ucast_tunnels):
# Create 10 ucast vxlan tunnels under bd
ip_range_start = 10
ip_range_end = ip_range_start + n_ucast_tunnels
next_hop_address = cls.pg0.remote_ip4n
for dest_ip4n in ip4n_range(next_hop_address, ip_range_start,
ip_range_end):
# add host route so dest_ip4n will not be resolved
cls.vapi.ip_add_del_route(dest_ip4n, 32, next_hop_address)
r = cls.vapi.vxlan_add_del_tunnel(
src_addr=cls.pg0.local_ip4n,
dst_addr=dest_ip4n,
vni=vni)
cls.vapi.sw_interface_set_l2_bridge(r.sw_if_index, bd_id=vni)
@classmethod
def add_del_shared_mcast_dst_load(cls, is_add):
"""
add or del tunnels sharing the same mcast dst
to test vxlan ref_count mechanism
"""
n_shared_dst_tunnels = 2000
vni_start = 10000
vni_end = vni_start + n_shared_dst_tunnels
for vni in range(vni_start, vni_end):
r = cls.vapi.vxlan_add_del_tunnel(
src_addr=cls.pg0.local_ip4n,
dst_addr=cls.mcast_ip4n,
mcast_sw_if_index=1,
vni=vni,
is_add=is_add)
if r.sw_if_index == 0xffffffff:
raise "bad sw_if_index"
@classmethod
def add_shared_mcast_dst_load(cls):
cls.add_del_shared_mcast_dst_load(is_add=1)
@classmethod
def del_shared_mcast_dst_load(cls):
cls.add_del_shared_mcast_dst_load(is_add=0)
@classmethod
def add_del_mcast_tunnels_load(cls, is_add):
"""
add or del tunnels to test vxlan stability
"""
n_distinct_dst_tunnels = 200
ip_range_start = 10
ip_range_end = ip_range_start + n_distinct_dst_tunnels
for dest_ip4n in ip4n_range(cls.mcast_ip4n, ip_range_start,
ip_range_end):
vni = bytearray(dest_ip4n)[3]
cls.vapi.vxlan_add_del_tunnel(
src_addr=cls.pg0.local_ip4n,
dst_addr=dest_ip4n,
mcast_sw_if_index=1,
vni=vni,
is_add=is_add)
@classmethod
def add_mcast_tunnels_load(cls):
cls.add_del_mcast_tunnels_load(is_add=1)
@classmethod
def del_mcast_tunnels_load(cls):
cls.add_del_mcast_tunnels_load(is_add=0)
# Class method to start the VXLAN test case.
# Overrides setUpClass method in VppTestCase class.
# Python try..except statement is used to ensure that the tear down of
# the class will be executed even if exception is raised.
# @param cls The class pointer.
@classmethod
def setUpClass(cls):
super(TestVxlan, cls).setUpClass()
try:
cls.dport = 4789
cls.flags = 0x8
# Create 2 pg interfaces.
cls.create_pg_interfaces(range(4))
for pg in cls.pg_interfaces:
pg.admin_up()
# Configure IPv4 addresses on VPP pg0.
cls.pg0.config_ip4()
# Resolve MAC address for VPP's IP address on pg0.
cls.pg0.resolve_arp()
# Our Multicast address
cls.mcast_ip4 = '239.1.1.1'
cls.mcast_ip4n = socket.inet_pton(socket.AF_INET, cls.mcast_ip4)
iplong = atol(cls.mcast_ip4)
cls.mcast_mac = "01:00:5e:%02x:%02x:%02x" % (
(iplong >> 16) & 0x7F, (iplong >> 8) & 0xFF, iplong & 0xFF)
# Create VXLAN VTEP on VPP pg0, and put vxlan_tunnel0 and pg1
# into BD.
cls.single_tunnel_bd = 1
r = cls.vapi.vxlan_add_del_tunnel(
src_addr=cls.pg0.local_ip4n,
dst_addr=cls.pg0.remote_ip4n,
vni=cls.single_tunnel_bd)
cls.vapi.sw_interface_set_l2_bridge(r.sw_if_index,
bd_id=cls.single_tunnel_bd)
cls.vapi.sw_interface_set_l2_bridge(cls.pg1.sw_if_index,
bd_id=cls.single_tunnel_bd)
# Setup vni 2 to test multicast flooding
cls.n_ucast_tunnels = 10
cls.mcast_flood_bd = 2
cls.create_vxlan_flood_test_bd(cls.mcast_flood_bd,
cls.n_ucast_tunnels)
r = cls.vapi.vxlan_add_del_tunnel(
src_addr=cls.pg0.local_ip4n,
dst_addr=cls.mcast_ip4n,
mcast_sw_if_index=1,
vni=cls.mcast_flood_bd)
cls.vapi.sw_interface_set_l2_bridge(r.sw_if_index,
bd_id=cls.mcast_flood_bd)
cls.vapi.sw_interface_set_l2_bridge(cls.pg2.sw_if_index,
bd_id=cls.mcast_flood_bd)
# Add and delete mcast tunnels to check stability
cls.add_shared_mcast_dst_load()
cls.add_mcast_tunnels_load()
cls.del_shared_mcast_dst_load()
cls.del_mcast_tunnels_load()
# Setup vni 3 to test unicast flooding
cls.ucast_flood_bd = 3
cls.create_vxlan_flood_test_bd(cls.ucast_flood_bd,
cls.n_ucast_tunnels)
cls.vapi.sw_interface_set_l2_bridge(cls.pg3.sw_if_index,
bd_id=cls.ucast_flood_bd)
except Exception:
super(TestVxlan, cls).tearDownClass()
raise
# Method to define VPP actions before tear down of the test case.
# Overrides tearDown method in VppTestCase class.
# @param self The object pointer.
def tearDown(self):
super(TestVxlan, self).tearDown()
if not self.vpp_dead:
self.logger.info(self.vapi.cli("show bridge-domain 1 detail"))
self.logger.info(self.vapi.cli("show bridge-domain 2 detail"))
self.logger.info(self.vapi.cli("show bridge-domain 3 detail"))
self.logger.info(self.vapi.cli("show vxlan tunnel"))
if __name__ == '__main__':
unittest.main(testRunner=VppTestRunner)
| bsd-3-clause |
ncliam/serverpos | openerp/addons/l10n_be_intrastat/l10n_be_intrastat.py | 258 | 7828 | # -*- encoding: utf-8 -*-
##############################################################################
#
# Odoo, Open Source Business Applications
# Copyright (C) 2014-2015 Odoo S.A. <http://www.odoo.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import fields, osv
class account_invoice(osv.osv):
_inherit = "account.invoice"
_columns = {
'incoterm_id': fields.many2one(
'stock.incoterms', 'Incoterm',
help="International Commercial Terms are a series of predefined commercial terms "
"used in international transactions."),
'intrastat_transaction_id': fields.many2one(
'l10n_be_intrastat.transaction', 'Intrastat Transaction Type',
help="Intrastat nature of transaction"),
'transport_mode_id': fields.many2one(
'l10n_be_intrastat.transport_mode', 'Intrastat Transport Mode'),
'intrastat_country_id': fields.many2one(
'res.country', 'Intrastat Country',
help='Intrastat country, delivery for sales, origin for purchases',
domain=[('intrastat','=',True)]),
}
class intrastat_region(osv.osv):
_name = 'l10n_be_intrastat.region'
_columns = {
'code': fields.char('Code', required=True),
'country_id': fields.many2one('res.country', 'Country'),
'name': fields.char('Name', translate=True),
'description': fields.char('Description'),
}
_sql_constraints = [
('l10n_be_intrastat_regioncodeunique', 'UNIQUE (code)', 'Code must be unique.'),
]
class intrastat_transaction(osv.osv):
_name = 'l10n_be_intrastat.transaction'
_rec_name = 'code'
_columns = {
'code': fields.char('Code', required=True, readonly=True),
'description': fields.text('Description', readonly=True),
}
_sql_constraints = [
('l10n_be_intrastat_trcodeunique', 'UNIQUE (code)', 'Code must be unique.'),
]
class intrastat_transport_mode(osv.osv):
_name = 'l10n_be_intrastat.transport_mode'
_columns = {
'code': fields.char('Code', required=True, readonly=True),
'name': fields.char('Description', readonly=True),
}
_sql_constraints = [
('l10n_be_intrastat_trmodecodeunique', 'UNIQUE (code)', 'Code must be unique.'),
]
class product_category(osv.osv):
_name = "product.category"
_inherit = "product.category"
_columns = {
'intrastat_id': fields.many2one('report.intrastat.code', 'Intrastat Code'),
}
def get_intrastat_recursively(self, cr, uid, category, context=None):
""" Recursively search in categories to find an intrastat code id
:param category : Browse record of a category
"""
if category.intrastat_id:
res = category.intrastat_id.id
elif category.parent_id:
res = self.get_intrastat_recursively(cr, uid, category.parent_id, context=context)
else:
res = None
return res
class product_product(osv.osv):
_name = "product.product"
_inherit = "product.product"
def get_intrastat_recursively(self, cr, uid, id, context=None):
""" Recursively search in categories to find an intrastat code id
"""
product = self.browse(cr, uid, id, context=context)
if product.intrastat_id:
res = product.intrastat_id.id
elif product.categ_id:
res = self.pool['product.category'].get_intrastat_recursively(
cr, uid, product.categ_id, context=context)
else:
res = None
return res
class purchase_order(osv.osv):
_inherit = "purchase.order"
def _prepare_invoice(self, cr, uid, order, line_ids, context=None):
"""
copy incoterm from purchase order to invoice
"""
invoice = super(purchase_order, self)._prepare_invoice(
cr, uid, order, line_ids, context=context)
if order.incoterm_id:
invoice['incoterm_id'] = order.incoterm_id.id
#Try to determine products origin
if order.partner_id.country_id:
#It comes from supplier
invoice['intrastat_country_id'] = order.partner_id.country_id.id
return invoice
class report_intrastat_code(osv.osv):
_inherit = "report.intrastat.code"
_columns = {
'description': fields.text('Description', translate=True),
}
class res_company(osv.osv):
_inherit = "res.company"
_columns = {
'region_id': fields.many2one('l10n_be_intrastat.region', 'Intrastat region'),
'transport_mode_id': fields.many2one('l10n_be_intrastat.transport_mode',
'Default transport mode'),
'incoterm_id': fields.many2one('stock.incoterms', 'Default incoterm for Intrastat',
help="International Commercial Terms are a series of "
"predefined commercial terms used in international "
"transactions."),
}
class sale_order(osv.osv):
_inherit = "sale.order"
def _prepare_invoice(self, cr, uid, saleorder, lines, context=None):
"""
copy incoterm from sale order to invoice
"""
invoice = super(sale_order, self)._prepare_invoice(
cr, uid, saleorder, lines, context=context)
if saleorder.incoterm:
invoice['incoterm_id'] = saleorder.incoterm.id
# Guess products destination
if saleorder.partner_shipping_id.country_id:
invoice['intrastat_country_id'] = saleorder.partner_shipping_id.country_id.id
elif saleorder.partner_id.country_id:
invoice['intrastat_country_id'] = saleorder.partner_id.country_id.id
elif saleorder.partner_invoice_id.country_id:
invoice['intrastat_country_id'] = saleorder.partner_invoice_id.country_id.id
return invoice
class stock_warehouse(osv.osv):
_inherit = "stock.warehouse"
_columns = {
'region_id': fields.many2one('l10n_be_intrastat.region', 'Intrastat region'),
}
def get_regionid_from_locationid(self, cr, uid, location_id, context=None):
location_model = self.pool['stock.location']
location = location_model.browse(cr, uid, location_id, context=context)
location_ids = location_model.search(cr, uid,
[('parent_left', '<=', location.parent_left),
('parent_right', '>=', location.parent_right)],
context=context)
warehouse_ids = self.search(cr, uid,
[('lot_stock_id', 'in', location_ids),
('region_id', '!=', False)],
context=context)
warehouses = self.browse(cr, uid, warehouse_ids, context=context)
if warehouses and warehouses[0]:
return warehouses[0].region_id.id
return None
| agpl-3.0 |
davidbrazdil/nacl | tools/process_oprofile_x86_64.py | 12 | 17097 | #!/usr/bin/python
# Copyright (c) 2011 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Post-process Oprofile logs for x86-64 nexes running under sel_ldr.
Maps event counts in the "anon" region, to the appropriate addresses
in the nexe assembly. "Anon" represents the untrusted sandbox.
This will become unnecessary once we get immutable files for our .nexe
so that sel_ldr can use mmap the .nexe instead of copying it in
(Oprofile should understand mmap).
Remember to look at the oprofile log for the time spent in the
trusted code / OS (this only lists time spent in the untrusted code).
"""
# TODO(jvoung): consider using addr2line to look up functions with
# the linenum / file info instead of the using the rangemap.
# Pro: less custom code and possibility of understanding Dwarf info.
# Con: lots of exec()s to cover all the samples...
import commands
import getopt
import math
import re
import sys
def Debug(mesg):
sys.stdout.flush() # Make stdout/stderr come out in order.
print >>sys.stderr, "# ", mesg
return
def DemangleFunc(fun_name):
# In case the disassembly was done without the objdump "-C" flag.
# Heuristic for detecting already demangled names
# (c++filt will hate you for giving it an already demangled name)
if ('(' in fun_name or
'*' in fun_name or
':' in fun_name or
'&' in fun_name):
return fun_name
return commands.getoutput("c++filt " + fun_name)
# Assume addresses in inputs (logs and assembly files) are all this base.
ADDRESS_BASE = 16
ADDRESS_DIGIT = '[a-f0-9]'
def GetUntrustedBase(sel_ldr_log_fd):
""" Parse the sel_ldr debug output to find the base of the untrusted memory
region.
Returns the base address. """
untrusted_base = None
for line in sel_ldr_log_fd:
# base is the mem start addr printed by sel_ldr
if line.find('mem start addr') != -1:
fields = line.split()
untrusted_base = int(fields[-1], ADDRESS_BASE)
break
assert untrusted_base is not None, "Couldn't parse untrusted base"
Debug("untrusted_base = %s" % hex(untrusted_base))
return untrusted_base
#--------------- Parse Oprofile Log ---------------
def CheckIfInSelLdrRegion(line, cur_range_base):
""" Checks if we are reading the part of the oprofile --details log
pertaining to the untrusted sandbox in sel_ldr's address space.
Returns the base of that memory region or None. """
fields = line.split()
# cur_range_base should be set if we are already parsing the
# untrusted sandbox section of the log.
if cur_range_base:
# Check if we are exiting the untrusted sandbox section of the log.
# The header of a new non-untrusted-sandbox section should look like:
# 00000000 samples pct foo.so foo.so /path-to/foo.so
if len(fields) >= 6:
Debug('Likely exiting sel_ldr section to a new section: %s' % fields[3])
# Check if the next section is also a sel_ldr region
return CheckIfInSelLdrRegion(line, None)
else:
return cur_range_base
else:
# Check if we are entering the untrusted-sandbox section of the log.
# The header of such a section should look like:
#
# 00000000 samples pct anon (tgid:22067 range:0xBASE-0xEND)
# (sel_ldr or chrome) anon (tgid:22067 range:...)
#
# I.e., 10 fields...
if (len(fields) == 10
and (fields[6] == 'sel_ldr'
or fields[6] == 'chrome'
or fields[6] == 'nacl_helper_bootstrap')
and ('anon' == fields[3])):
Debug('Likely starting sel_ldr section: %s %s' % (fields[3], fields[6]))
range_token = fields[9]
range_re = re.compile('range:0x(' + ADDRESS_DIGIT + '+)-0x')
match = range_re.search(range_token)
if match:
range_str = match.group(1)
range_base = int(range_str, ADDRESS_BASE)
Debug('Likely range base is %s' % hex(range_base))
return range_base
else:
Debug("Couldn't parse range base for: " + str(fields))
return None
else:
return None
def UpdateAddrEventMap(line, sel_ldr_range_base, untrusted_base, addr_to_event):
""" Add an event count to the addr_to_event map if the line of data looks
like an event count. Example:
vma samples %
0000028a 1 1.8e-04
"""
fields = line.split()
if len(fields) == 3:
# deal with numbers like fffffff484494ca5 which are actually negative
address = int(fields[0], ADDRESS_BASE)
if address > 0x8000000000000000:
address = -((0xffffffffffffffff - address) + 1)
address = address + sel_ldr_range_base - untrusted_base
sample_count = int(fields[1])
cur = addr_to_event.get(address, 0)
addr_to_event[address] = cur + sample_count
return
def CheckTrustedRecord(line, trusted_events, filter_events):
""" Checks if this line is a samplecount for a trusted function. Because
oprofile understands these, we just use its aggregate count.
Updates the trusted_events map."""
# oprofile function records have the following format:
# address sample_count percent image_name app_name symbol_name
# Some symbol names have spaces (function prototypes), so only split 6 words.
fields = line.split(None, 5)
if len(fields) < 6:
return False
image_name = fields[3]
symbol_name = fields[5].rstrip()
# 2 cases: we want only 'relevant' samples, or we want all of them.
# Either way, ignore the untrusted region.
if (image_name == "anon" and symbol_name.find('sel_ldr') != -1):
return False
try: # catch lines that aren't records (e.g. the CPU type)
sample_count = int(fields[1])
except ValueError:
return False
if (filter_events and not (image_name.endswith('sel_ldr')
or image_name.startswith('llc')
or image_name.endswith('.so')
or image_name == 'no-vmlinux'
or image_name == 'chrome'
or image_name == 'nacl_helper_bootstrap')):
trusted_events['FILTERED'] = trusted_events.get('FILTERED',0) + sample_count
return False
# If there are duplicate function names, just use the first instance.
# (Most likely they are from shared libraries in different processes, and
# because the opreport output is sorted, the top one is most likely to be
# our process of interest, and the rest are not.)
key = image_name + ':' + symbol_name
trusted_events[key] = trusted_events.get(key, sample_count)
return True
def GetAddressToEventSelLdr(fd, filter_events, untrusted_base):
""" Returns 2 maps: addr_to_event: address (int) -> event count (int)
and trusted_events: func (str) - > event count (int)"""
addr_to_event = {}
trusted_events = {}
sel_ldr_range_base = None
for line in fd:
sel_ldr_range_base = CheckIfInSelLdrRegion(line, sel_ldr_range_base)
if sel_ldr_range_base:
# If we've parsed the header of the region and know the base of
# this range, start picking up event counts.
UpdateAddrEventMap(line,
sel_ldr_range_base,
untrusted_base,
addr_to_event)
else:
CheckTrustedRecord(line, trusted_events, filter_events)
fd.seek(0) # Reset for future use...
return addr_to_event, trusted_events
#--------------- Parse Assembly File ---------------
def CompareBounds((lb1, ub1), (lb2, ub2)):
# Shouldn't be overlapping, so both the upper and lower
# should be less than the other's lower bound
if (lb1 < lb2) and (ub1 < lb2):
return -1
elif (lb1 > ub2) and (ub1 > ub2):
return 1
else:
# Somewhere between, not necessarily equal.
return 0
class RangeMapSorted(object):
""" Simple range map using a sorted list of pairs
((lowerBound, upperBound), data). """
ranges = []
# Error indexes (< 0)
kGREATER = -2
kLESS = -1
def FindIndex(self, lb, ub):
length = len(self.ranges)
return self.FindIndexFrom(lb, ub,
int(math.ceil(length / 2.0)), 0, length)
def FindIndexFrom(self, lb, ub, CurGuess, CurL, CurH):
length = len(self.ranges)
# If it is greater than the last index, it is greater than all.
if CurGuess >= length:
return self.kGREATER
((lb2, ub2), _) = self.ranges[CurGuess]
comp = CompareBounds((lb, ub), (lb2, ub2))
if comp == 0:
return CurGuess
elif comp < 0:
# If it is less than index 0, it is less than all.
if CurGuess == 0:
return self.kLESS
NextL = CurL
NextH = CurGuess
NextGuess = CurGuess - int (math.ceil((NextH - NextL) / 2.0))
else:
# If it is greater than the last index, it is greater than all.
if CurGuess >= length - 1:
return self.kGREATER
NextL = CurGuess
NextH = CurH
NextGuess = CurGuess + int (math.ceil((NextH - NextL) / 2.0))
return self.FindIndexFrom(lb, ub, NextGuess, NextL, NextH)
def Add(self, lb, ub, data):
""" Add a mapping from [lb, ub] --> data """
index = self.FindIndex(lb, ub)
range_data = ((lb, ub), data)
if index == self.kLESS:
self.ranges.insert(0, range_data)
elif index == self.kGREATER:
self.ranges.append(range_data)
else:
self.ranges.insert(index, range_data)
def Lookup(self, key):
""" Get the data that falls within the range. """
index = self.FindIndex(key, key)
# Check if it is out of range.
if index < 0:
return None
((lb, ub), d) = self.ranges[index]
# Double check that the key actually falls in range.
if lb <= key and key <= ub:
return d
else:
return None
def GetRangeFromKey(self, key):
index = self.FindIndex(key, key)
# Check if it is out of range.
if index < 0:
return None
((lb, ub), _) = self.ranges[index]
# Double check that the key actually falls in range.
if lb <= key and key <= ub:
return (lb, ub)
else:
return None
ADDRESS_RE = re.compile('(' + ADDRESS_DIGIT + '+):')
FUNC_RE = re.compile('(' + ADDRESS_DIGIT + '+) <(.*)>:')
def GetAssemblyAddress(line):
""" Look for lines of assembly that look like
address: [byte] [byte]... [instruction in text]
"""
fields = line.split()
if len(fields) > 1:
match = ADDRESS_RE.search(fields[0])
if match:
return int(match.group(1), ADDRESS_BASE)
return None
def GetAssemblyRanges(fd):
""" Return a RangeMap that tracks the boundaries of each function.
E.g., [0x20000, 0x2003f] --> "foo"
[0x20040, 0x20060] --> "bar"
"""
rmap = RangeMapSorted()
cur_start = None
cur_func = None
cur_end = None
for line in fd:
# If we are within a function body...
if cur_func:
# Check if it has ended (with a newline)
if line.strip() == '':
assert (cur_start and cur_end)
rmap.Add(cur_start, cur_end, cur_func)
cur_start = None
cur_end = None
cur_func = None
else:
maybe_addr = GetAssemblyAddress(line)
if maybe_addr:
cur_end = maybe_addr
else:
# Not yet within a function body. Check if we are entering.
# The header should look like:
# 0000000000020040 <foo>:
match = FUNC_RE.search(line)
if match:
cur_start = int(match.group(1), ADDRESS_BASE)
cur_func = match.group(2)
fd.seek(0) # reset for future use.
return rmap
#--------------- Summarize Data ---------------
def PrintTopFunctions(assembly_ranges, address_to_events, trusted_events):
""" Prints the N functions with the top event counts """
func_events = {}
some_addrs_not_found = False
for (addr, count) in address_to_events.iteritems():
func = assembly_ranges.Lookup(addr)
if (func):
# Function labels are mostly unique, except when we have ASM labels
# that we mistake for functions. E.g., "loop:" is a common ASM label.
# Thus, to get a unique value, we must append the unique key range
# to the function label.
(lb, ub) = assembly_ranges.GetRangeFromKey(addr)
key = (func, lb, ub)
cur_count = func_events.get(key, 0)
func_events[key] = cur_count + count
else:
Debug('No matching function for addr/count: %s %d'
% (hex(addr), count))
some_addrs_not_found = True
if some_addrs_not_found:
# Addresses < 0x20000 are likely trampoline addresses.
Debug('NOTE: sample addrs < 0x20000 are likely trampolines')
filtered_events = trusted_events.pop('FILTERED', 0)
# convert trusted functions (which are just functions and not ranges) into
# the same format and mix them with untrusted. Just use 0s for the ranges
for (func, count) in trusted_events.iteritems():
key = (func, 0, 0)
func_events[key] = count
flattened = func_events.items()
def CompareCounts ((k1, c1), (k2, c2)):
if c1 < c2:
return -1
elif c1 == c2:
return 0
else:
return 1
flattened.sort(cmp=CompareCounts, reverse=True)
top_30 = flattened[:30]
total_samples = (sum(address_to_events.itervalues())
+ sum(trusted_events.itervalues()))
print "============= Top 30 Functions ==============="
print "EVENTS\t\tPCT\tCUM\tFUNC [LOW_VMA, UPPER_VMA]"
cum_pct = 0.0
for ((func, lb, ub), count) in top_30:
pct = 100.0 * count / total_samples
cum_pct += pct
print "%d\t\t%.2f\t%.2f\t%s [%s, %s]" % (count, pct, cum_pct,
DemangleFunc(func), hex(lb), hex(ub))
print "%d samples filtered (%.2f%% of all samples)" % (filtered_events,
100.0 * filtered_events / (filtered_events + total_samples))
#--------------- Annotate Assembly ---------------
def PrintAnnotatedAssembly(fd_in, address_to_events, fd_out):
""" Writes to output, a version of assembly_file which has event
counts in the form #; EVENTS: N
This lets us know which instructions took the most time, etc.
"""
for line in fd_in:
line = line.strip()
maybe_addr = GetAssemblyAddress(line)
if maybe_addr in address_to_events:
event_count = address_to_events[maybe_addr]
print >>fd_out, "%s #; EVENTS: %d" % (line, event_count)
else:
print >>fd_out, line
fd_in.seek(0) # reset for future use.
#--------------- Main ---------------
def main(argv):
try:
opts, args = getopt.getopt(argv[1:],
'l:s:o:m:f',
['oprofilelog=',
'assembly=',
'output=',
'memmap=',
'untrusted_base=',
])
assembly_file = None
assembly_fd = None
oprof_log = None
oprof_fd = None
output = sys.stdout
out_name = None
filter_events = False
# Get the untrusted base address from either a sel_ldr log
# which prints out the mapping, or from the command line directly.
mapfile_name = None
mapfile_fd = None
untrusted_base = None
for o, a in opts:
if o in ('-l', '--oprofilelog'):
oprof_log = a
oprof_fd = open(oprof_log, 'r')
elif o in ('-s', '--assembly'):
assembly_file = a
assembly_fd = open(assembly_file, 'r')
elif o in ('-o', '--output'):
out_name = a
output = open(out_name, 'w')
elif o in ('-m', '--memmap'):
mapfile_name = a
try:
mapfile_fd = open(mapfile_name, 'r')
except IOError:
pass
elif o in ('-b', '--untrusted_base'):
untrusted_base = a
elif o == '-f':
filter_events = True
else:
assert False, 'unhandled option'
if untrusted_base:
if mapfile_fd:
print 'Error: Specified both untrusted_base directly and w/ memmap file'
sys.exit(1)
untrusted_base = int(untrusted_base, 16)
else:
if mapfile_fd:
Debug('Parsing sel_ldr output for untrusted memory base: %s' %
mapfile_name)
untrusted_base = GetUntrustedBase(mapfile_fd)
else:
print 'Error: Need sel_ldr log --memmap or --untrusted_base.'
sys.exit(1)
if assembly_file and oprof_log:
Debug('Parsing assembly file of nexe: %s' % assembly_file)
assembly_ranges = GetAssemblyRanges(assembly_fd)
Debug('Parsing oprofile log: %s' % oprof_log)
untrusted_events, trusted_events = \
GetAddressToEventSelLdr(oprof_fd, filter_events, untrusted_base)
Debug('Printing the top functions (most events)')
PrintTopFunctions(assembly_ranges, untrusted_events, trusted_events)
Debug('Printing annotated assembly to %s (or stdout)' % out_name)
PrintAnnotatedAssembly(assembly_fd, untrusted_events, output)
else:
print 'Need assembly file(%s) and oprofile log(%s)!' \
% (assembly_file, oprof_log)
sys.exit(1)
except getopt.GetoptError, err:
print str(err)
sys.exit(1)
if __name__ == '__main__':
main(sys.argv)
| bsd-3-clause |
ivanhorvath/openshift-tools | openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/installer_checkpoint/callback_plugins/installer_checkpoint.py | 24 | 6571 | """Ansible callback plugin to print a summary completion status of installation
phases.
"""
from datetime import datetime
from ansible.plugins.callback import CallbackBase
from ansible import constants as C
class CallbackModule(CallbackBase):
"""This callback summarizes installation phase status."""
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'aggregate'
CALLBACK_NAME = 'installer_checkpoint'
CALLBACK_NEEDS_WHITELIST = False
def __init__(self):
super(CallbackModule, self).__init__()
def v2_playbook_on_stats(self, stats):
# Set the order of the installer phases
installer_phases = [
'installer_phase_initialize',
'installer_phase_health',
'installer_phase_etcd',
'installer_phase_nfs',
'installer_phase_loadbalancer',
'installer_phase_master',
'installer_phase_master_additional',
'installer_phase_node',
'installer_phase_glusterfs',
'installer_phase_hosted',
'installer_phase_web_console',
'installer_phase_metrics',
'installer_phase_logging',
'installer_phase_prometheus',
'installer_phase_servicecatalog',
'installer_phase_management',
]
# Define the attributes of the installer phases
phase_attributes = {
'installer_phase_initialize': {
'title': 'Initialization',
'playbook': ''
},
'installer_phase_health': {
'title': 'Health Check',
'playbook': 'playbooks/openshift-checks/pre-install.yml'
},
'installer_phase_etcd': {
'title': 'etcd Install',
'playbook': 'playbooks/openshift-etcd/config.yml'
},
'installer_phase_nfs': {
'title': 'NFS Install',
'playbook': 'playbooks/openshift-nfs/config.yml'
},
'installer_phase_loadbalancer': {
'title': 'Load balancer Install',
'playbook': 'playbooks/openshift-loadbalancer/config.yml'
},
'installer_phase_master': {
'title': 'Master Install',
'playbook': 'playbooks/openshift-master/config.yml'
},
'installer_phase_master_additional': {
'title': 'Master Additional Install',
'playbook': 'playbooks/openshift-master/additional_config.yml'
},
'installer_phase_node': {
'title': 'Node Install',
'playbook': 'playbooks/openshift-node/config.yml'
},
'installer_phase_glusterfs': {
'title': 'GlusterFS Install',
'playbook': 'playbooks/openshift-glusterfs/config.yml'
},
'installer_phase_hosted': {
'title': 'Hosted Install',
'playbook': 'playbooks/openshift-hosted/config.yml'
},
'installer_phase_web_console': {
'title': 'Web Console Install',
'playbook': 'playbooks/openshift-web-console/config.yml'
},
'installer_phase_metrics': {
'title': 'Metrics Install',
'playbook': 'playbooks/openshift-metrics/config.yml'
},
'installer_phase_logging': {
'title': 'Logging Install',
'playbook': 'playbooks/openshift-logging/config.yml'
},
'installer_phase_prometheus': {
'title': 'Prometheus Install',
'playbook': 'playbooks/openshift-prometheus/config.yml'
},
'installer_phase_servicecatalog': {
'title': 'Service Catalog Install',
'playbook': 'playbooks/openshift-service-catalog/config.yml'
},
'installer_phase_management': {
'title': 'Management Install',
'playbook': 'playbooks/openshift-management/config.yml'
},
}
# Find the longest phase title
max_column = 0
for phase in phase_attributes:
max_column = max(max_column, len(phase_attributes[phase]['title']))
if '_run' in stats.custom:
self._display.banner('INSTALLER STATUS')
for phase in installer_phases:
phase_title = phase_attributes[phase]['title']
padding = max_column - len(phase_title) + 2
if phase in stats.custom['_run']:
phase_status = stats.custom['_run'][phase]['status']
phase_time = phase_time_delta(stats.custom['_run'][phase])
self._display.display(
'{}{}: {} ({})'.format(phase_title, ' ' * padding, phase_status, phase_time),
color=self.phase_color(phase_status))
if phase_status == 'In Progress' and phase != 'installer_phase_initialize':
self._display.display(
'\tThis phase can be restarted by running: {}'.format(
phase_attributes[phase]['playbook']))
if 'message' in stats.custom['_run'][phase]:
self._display.display(
'\t{}'.format(
stats.custom['_run'][phase]['message']))
self._display.display("", screen_only=True)
def phase_color(self, status):
""" Return color code for installer phase"""
valid_status = [
'In Progress',
'Complete',
]
if status not in valid_status:
self._display.warning('Invalid phase status defined: {}'.format(status))
if status == 'Complete':
phase_color = C.COLOR_OK
elif status == 'In Progress':
phase_color = C.COLOR_ERROR
else:
phase_color = C.COLOR_WARN
return phase_color
def phase_time_delta(phase):
""" Calculate the difference between phase start and end times """
time_format = '%Y%m%d%H%M%SZ'
phase_start = datetime.strptime(phase['start'], time_format)
if 'end' not in phase:
# The phase failed so set the end time to now
phase_end = datetime.now()
else:
phase_end = datetime.strptime(phase['end'], time_format)
delta = str(phase_end - phase_start).split(".")[0] # Trim microseconds
return delta
| apache-2.0 |
philipz/PyCV-time | opencv-official-samples/2.4.9/demo.py | 7 | 5157 | #!/usr/bin/env python
'''
Sample-launcher application.
'''
import Tkinter as tk
from ScrolledText import ScrolledText
from glob import glob
from common import splitfn
import webbrowser
from subprocess import Popen
#from IPython.Shell import IPShellEmbed
#ipshell = IPShellEmbed()
exclude_list = ['demo', 'common']
class LinkManager:
def __init__(self, text, url_callback = None):
self.text = text
self.text.tag_config("link", foreground="blue", underline=1)
self.text.tag_bind("link", "<Enter>", self._enter)
self.text.tag_bind("link", "<Leave>", self._leave)
self.text.tag_bind("link", "<Button-1>", self._click)
self.url_callback = url_callback
self.reset()
def reset(self):
self.links = {}
def add(self, action):
# add an action to the manager. returns tags to use in
# associated text widget
tag = "link-%d" % len(self.links)
self.links[tag] = action
return "link", tag
def _enter(self, event):
self.text.config(cursor="hand2")
def _leave(self, event):
self.text.config(cursor="")
def _click(self, event):
for tag in self.text.tag_names(tk.CURRENT):
if tag.startswith("link-"):
proc = self.links[tag]
if callable(proc):
proc()
else:
if self.url_callback:
self.url_callback(proc)
class App:
def __init__(self):
root = tk.Tk()
root.title('OpenCV Demo')
self.win = win = tk.PanedWindow(root, orient=tk.HORIZONTAL, sashrelief=tk.RAISED, sashwidth=4)
self.win.pack(fill=tk.BOTH, expand=1)
left = tk.Frame(win)
right = tk.Frame(win)
win.add(left)
win.add(right)
scrollbar = tk.Scrollbar(left, orient=tk.VERTICAL)
self.demos_lb = demos_lb = tk.Listbox(left, yscrollcommand=scrollbar.set)
scrollbar.config(command=demos_lb.yview)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
demos_lb.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)
self.samples = {}
for fn in glob('*.py'):
name = splitfn(fn)[1]
if fn[0] != '_' and name not in exclude_list:
demos_lb.insert(tk.END, name)
self.samples[name] = fn
demos_lb.bind('<<ListboxSelect>>', self.on_demo_select)
self.cmd_entry = cmd_entry = tk.Entry(right)
cmd_entry.bind('<Return>', self.on_run)
run_btn = tk.Button(right, command=self.on_run, text='Run', width=8)
self.text = text = ScrolledText(right, font=('arial', 12, 'normal'), width = 30, wrap='word')
self.linker = linker = LinkManager(text, self.on_link)
self.text.tag_config("header1", font=('arial', 14, 'bold'))
self.text.tag_config("header2", font=('arial', 12, 'bold'))
text.config(state='disabled')
text.pack(fill='both', expand=1, side=tk.BOTTOM)
cmd_entry.pack(fill='x', side='left' , expand=1)
run_btn.pack()
def on_link(self, url):
print url
webbrowser.open(url)
def on_demo_select(self, evt):
name = self.demos_lb.get( self.demos_lb.curselection()[0] )
fn = self.samples[name]
loc = {}
execfile(fn, loc)
descr = loc.get('__doc__', 'no-description')
self.linker.reset()
self.text.config(state='normal')
self.text.delete(1.0, tk.END)
self.format_text(descr)
self.text.config(state='disabled')
self.cmd_entry.delete(0, tk.END)
self.cmd_entry.insert(0, fn)
def format_text(self, s):
text = self.text
lines = s.splitlines()
for i, s in enumerate(lines):
s = s.rstrip()
if i == 0 and not s:
continue
if s and s == '='*len(s):
text.tag_add('header1', 'end-2l', 'end-1l')
elif s and s == '-'*len(s):
text.tag_add('header2', 'end-2l', 'end-1l')
else:
text.insert('end', s+'\n')
def add_link(start, end, url):
for tag in self.linker.add(url):
text.tag_add(tag, start, end)
self.match_text(r'http://\S+', add_link)
def match_text(self, pattern, tag_proc, regexp=True):
text = self.text
text.mark_set('matchPos', '1.0')
count = tk.IntVar()
while True:
match_index = text.search(pattern, 'matchPos', count=count, regexp=regexp, stopindex='end')
if not match_index: break
end_index = text.index( "%s+%sc" % (match_index, count.get()) )
text.mark_set('matchPos', end_index)
if callable(tag_proc):
tag_proc(match_index, end_index, text.get(match_index, end_index))
else:
text.tag_add(tag_proc, match_index, end_index)
def on_run(self, *args):
cmd = self.cmd_entry.get()
print 'running:', cmd
Popen("python " + cmd, shell=True)
def run(self):
tk.mainloop()
if __name__ == '__main__':
App().run()
| mit |
biskett/mic | tests/test_archive.py | 5 | 26592 | """
It is used to test mic/archive.py
"""
import os
import shutil
import unittest
from mic import archive
class ArchiveTest(unittest.TestCase):
"""
test pulic methods in archive.py
"""
def setUp(self):
"""Create files and directories for later use"""
self.relative_file = './sdfb.gxdf.bzws.zzz'
abs_file = '/tmp/adsdfb.gxdf.bzws.zzz'
bare_file = 'abc.def.bz.zzz'
self.relative_dir = './sdf.zzz'
abs_dir = '/tmp/asdf.zzz'
bare_dir = 'abd.zzz'
self.wrong_format_file = './sdbs.werxdf.bz.zzz'
self.files = [self.relative_file, abs_file, bare_file]
self.dirs = [self.relative_dir, abs_dir, bare_dir]
for file_item in self.files:
os.system('touch %s' % file_item)
for dir_item in self.dirs:
self.create_dir(dir_item)
shutil.copy(self.relative_file, '%s/1.txt' % dir_item)
shutil.copy(self.relative_file, '%s/2.txt' % dir_item)
self.create_dir('%s/dir1' % dir_item)
self.create_dir('%s/dir2' % dir_item)
def tearDown(self):
"""Clean up unuseful file and directory """
try:
for file_item in self.files:
os.remove(file_item)
for dir_item in self.dirs:
shutil.rmtree(dir_item, ignore_errors=True)
except OSError:
pass
def create_dir(self, dir_name):
"""Create directories and ignore any erros """
try:
os.makedirs(dir_name)
except OSError:
pass
def test_get_compress_formats(self):
"""Test get compress format """
compress_list = archive.get_compress_formats()
compress_list.sort()
self.assertEqual(compress_list, ['bz2', 'gz', 'lzo'])
def test_compress_negtive_file_path_is_required(self):
"""Test if the first parameter: file path is empty"""
with self.assertRaises(OSError):
archive.compress('', 'bz2')
def test_compress_negtive_compress_format_is_required(self):
"""Test if the second parameter: compress format is empty"""
with self.assertRaises(ValueError):
archive.compress(self.relative_file, '')
def test_compress_negtive_parameters_are_all_required(self):
"""Test if two parameters are both empty"""
with self.assertRaises(OSError):
archive.compress('', '')
def test_compress_negtive_file_not_exist(self):
"""Test target file does not exist"""
with self.assertRaises(OSError):
archive.compress('a.py', 'bz2')
def test_compress_negtive_file_is_dir(self):
"""Test target is one direcoty, which is not supported"""
with self.assertRaises(OSError):
archive.compress(self.relative_dir, 'bz2')
def test_compress_negtive_wrong_compress_format(self):
"""Test wrong compress format"""
with self.assertRaises(ValueError):
archive.compress(self.relative_file, 'bzip2')
def _compress_negtive_gz_command_not_exists(self):
#TODO: test if command like 'pigz', 'gzip' does not exist
pass
def _compress_negtive_lzo_command_not_exists(self):
#TODO: test if command 'lzop' does not exist
pass
def _compress_negtive_bz2_command_not_exists(self):
#TODO: test if command like 'pbzip2', 'bzip2' does not exist
pass
def test_compress_gz(self):
"""Test compress format: gz"""
for file_item in self.files:
output_name = archive.compress(file_item, 'gz')
self.assertEqual('%s.gz' % file_item, output_name)
self.assertTrue(os.path.exists(output_name))
os.remove(output_name)
def test_compress_bz2(self):
"""Test compress format: bz2"""
for file_item in self.files:
output_name = archive.compress(file_item, 'bz2')
self.assertEqual('%s.bz2' % file_item, output_name)
self.assertTrue(os.path.exists(output_name))
os.remove(output_name)
def _test_compress_lzo(self):
"""Test compress format: lzo"""
for file_item in self.files:
output_name = archive.compress(file_item, 'lzo')
self.assertEqual('%s.lzo' % file_item, output_name)
self.assertTrue(os.path.exists(output_name))
os.remove(output_name)
def test_decompress_negtive_file_path_is_required(self):
"""Test if the first parameter: file to be uncompressed is empty"""
with self.assertRaises(OSError):
archive.decompress('', 'bz')
def test_decompress_compress_format_is_empty(self):
"""Test if the second parameter: compress format is empty string"""
output_name = archive.compress(self.relative_file, 'gz')
self.assertEqual('%s.gz' % self.relative_file, output_name)
self.assertTrue(os.path.exists(output_name))
self.assertFalse(os.path.exists(self.relative_file))
archive.decompress(output_name, '')
self.assertTrue(os.path.exists(self.relative_file))
def test_decompress_negtive_parameters_are_empty(self):
"""Test if two parameters are both empty string"""
with self.assertRaises(OSError):
archive.decompress('', '')
def test_decompress_negtive_file_not_exist(self):
"""Test decompress target does not exist"""
with self.assertRaises(OSError):
archive.decompress('tresa.py', 'bz2')
def test_decompress_negtive_path_is_dir(self):
"""Test decompress target is a directory"""
with self.assertRaises(OSError):
archive.decompress(self.relative_dir, 'bz2')
def _decompress_negtive_not_corresponding(self):
# TODO: test if path is .lzo, but given format is bz2
pass
def test_decompress_negtive_wrong_compress_format(self):
"""Test wrong decompress format"""
with self.assertRaises(ValueError):
archive.decompress(self.relative_file, 'bzip2')
def test_decompress_negtive_wrong_file_format(self):
"""Test wrong target format"""
with self.assertRaises(Exception):
archive.decompress(self.wrong_format_file, 'bz2')
def test_decompress_gz(self):
"""Test decompress
Format: gz
both two parameters are given, one is target file,
the other is corresponding compress format"""
for file_item in self.files:
output_name = archive.compress(file_item, 'gz')
self.assertEqual('%s.gz' % file_item, output_name)
self.assertTrue(os.path.exists(output_name))
self.assertFalse(os.path.exists(file_item))
archive.decompress(output_name, 'gz')
self.assertTrue(os.path.exists(file_item))
def test_decompress_gz_no_compress_format(self):
"""Test decompress
Format: gz
one parameters is given, only target file"""
for file_item in self.files:
output_name = archive.compress(file_item, 'gz')
self.assertEqual('%s.gz' % file_item, output_name)
self.assertTrue(os.path.exists(output_name))
self.assertFalse(os.path.exists(file_item))
archive.decompress(output_name)
self.assertTrue(os.path.exists(file_item))
def test_decompress_bz2(self):
"""Test decompress
Format: bz2
both two parameters are given, one is target file,
the other is corresponding compress format"""
for file_item in self.files:
output_name = archive.compress(file_item, 'bz2')
self.assertEqual('%s.bz2' % file_item, output_name)
self.assertTrue(os.path.exists(output_name))
self.assertFalse(os.path.exists(file_item))
archive.decompress(output_name, 'bz2')
self.assertTrue(os.path.exists(file_item))
def test_decompress_bz2_no_compress_format(self):
"""Test decompress
Format: bz2
one parameters is given, only target file"""
for file_item in self.files:
output_name = archive.compress(file_item, 'bz2')
self.assertEqual('%s.bz2' % file_item, output_name)
self.assertTrue(os.path.exists(output_name))
self.assertFalse(os.path.exists(file_item))
archive.decompress(output_name)
self.assertTrue(os.path.exists(file_item))
def _test_decompress_lzo(self):
"""Test decompress
Format: lzo
both two parameters are given, one is target file,
the other is corresponding compress format"""
for file_item in self.files:
output_name = archive.compress(file_item, 'lzo')
self.assertEqual('%s.lzo' % file_item, output_name)
self.assertTrue(os.path.exists(output_name))
self.assertFalse(os.path.exists(file_item))
archive.decompress(output_name, 'lzo')
self.assertTrue(os.path.exists(file_item))
def _test_decompress_lzo_no_compress_format(self):
"""Test decompress
Format: lzo
one parameters is given, only target file"""
for file_item in self.files:
output_name = archive.compress(file_item, 'lzo')
self.assertEqual('%s.lzo' % file_item, output_name)
self.assertTrue(os.path.exists(output_name))
self.assertFalse(os.path.exists(file_item))
archive.decompress(output_name)
self.assertTrue(os.path.exists(file_item))
def test_get_archive_formats(self):
"""Test get archive format"""
archive_formats = archive.get_archive_formats()
archive_formats.sort()
self.assertEqual(archive_formats,
["bztar", "gztar", "lzotar", "tar", 'zip'])
def test_get_archive_suffixes(self):
"""Test get archive suffixes"""
archive_suffixes = archive.get_archive_suffixes()
archive_suffixes.sort()
self.assertEqual(archive_suffixes,
['.tar', '.tar.bz', '.tar.bz2', '.tar.gz', '.tar.lzo',
'.taz', '.tbz', '.tbz2', '.tgz', '.tzo', '.zip'])
def test_make_archive_negtive_archive_name_is_required(self):
"""Test if first parameter: file path is empty"""
with self.assertRaises(Exception):
archive.make_archive('', self.relative_dir)
def test_extract_archive_negtive_archive_name_is_required(self):
"""Test if first parameter: file path is empty"""
with self.assertRaises(Exception):
archive.extract_archive('', self.relative_dir)
def test_make_archive_negtive_target_name_is_required(self):
"""Test if second parameter: target name is empty"""
with self.assertRaises(Exception):
archive.make_archive('a.zip', '')
def _extract_archive_negtive_target_name_is_required(self):
# Not sure if the current dir will be used ?
# TODO:
pass
def test_make_archive_negtive_parameters_are_empty(self):
"""Test if both parameters are empty"""
with self.assertRaises(Exception):
archive.make_archive('', '')
def test_extract_archive_negtive_parameters_are_empty(self):
"""Test if both parameters are empty"""
with self.assertRaises(Exception):
archive.extract_archive('', '')
def test_make_archive_negtive_target_path_not_exists(self):
"""Test if file path does not exist"""
fake_file = 'abcdfsdf'
with self.assertRaises(Exception):
archive.make_archive('a.tar', fake_file)
with self.assertRaises(Exception):
archive.make_archive('a.zip', fake_file)
def test_extract_archive_negtive_path_not_exists(self):
"""Test if file path does not exist"""
fake_file = 'abcdfsdf'
with self.assertRaises(Exception):
archive.extract_archive(fake_file, self.relative_dir)
def test_extract_archive_negtive_target_is_file(self):
"""Test if the extract target is file"""
out_file = '%s.tar' % self.relative_dir
self.assertTrue(archive.make_archive(out_file, self.relative_dir))
self.assertTrue(os.path.exists(out_file))
with self.assertRaises(Exception):
archive.extract_archive(out_file, self.relative_file)
os.remove(out_file)
def test_make_archive_wrong_format(self):
"""Test wrong make_archive format"""
with self.assertRaises(Exception):
archive.make_archive('a.sfsfrwe', self.relative_dir)
def test_make_archive_tar_with_different_name(self):
""" Test make_archive format: tar
It packs the source with another name"""
for item in self.files + self.dirs:
out_file = 'abcd.tar'
self.assertTrue(archive.make_archive(out_file, item))
self.assertTrue(os.path.exists(out_file))
os.remove(out_file)
def test_make_archive_tar(self):
""" Test make_archive format: tar"""
for item in self.files + self.dirs:
out_file = '%s.tar' % item
self.assertTrue(archive.make_archive(out_file, item))
self.assertTrue(os.path.exists(out_file))
os.remove(out_file)
def test_extract_archive_tar(self):
""" Test extract format: tar"""
for item in self.files:
out_file = '%s.tar' % item
self.assertTrue(archive.make_archive(out_file, item))
self.assertTrue(os.path.exists(out_file))
out_dir = 'un_tar_dir'
archive.extract_archive(out_file, out_dir)
self.assertTrue(os.path.exists(os.path.join(
out_dir,
os.path.basename(item))))
shutil.rmtree(out_dir)
for item in self.dirs:
out_file = '%s.tar' % item
self.assertTrue(archive.make_archive(out_file, item))
self.assertTrue(os.path.exists(out_file))
out_dir = 'un_tar_dir'
archive.extract_archive(out_file, out_dir)
self.assertTrue(os.path.exists(os.path.join(out_dir, '1.txt')))
self.assertTrue(os.path.exists(os.path.join(out_dir, '2.txt')))
self.assertTrue(os.path.exists(os.path.join(out_dir, 'dir1')))
self.assertTrue(os.path.exists(os.path.join(out_dir, 'dir2')))
shutil.rmtree(out_dir)
def test_make_archive_zip_with_different_name(self):
""" Test make_archive format: zip
It packs the source with another name"""
for item in self.files + self.dirs:
out_file = 'a.zip'
self.assertTrue(archive.make_archive(out_file, item))
self.assertTrue(os.path.exists(out_file))
os.remove(out_file)
def test_make_archive_zip(self):
""" Test make_archive format: zip"""
for item in self.files + self.dirs:
out_file = '%s.zip' % item
self.assertTrue(archive.make_archive(out_file, item))
self.assertTrue(os.path.exists(out_file))
os.remove(out_file)
def _extract_archive_zip(self):
""" Test extract archive format: zip"""
for item in self.files + self.dirs:
out_file = '%s.zip' % item
self.assertTrue(archive.make_archive(out_file, item))
self.assertTrue(os.path.exists(out_file))
out_dir = 'un_tar_dir'
archive.extract_archive(out_file, out_dir)
self.assertTrue(os.path.exists(os.path.join(out_dir, item)))
shutil.rmtree(out_dir)
def _test_make_archive_tzo_with_different_name(self):
""" Test make_archive format: tzo
It packs the source with another name"""
for item in self.files + self.dirs:
out_file = 'abc.tzo'
self.assertTrue(archive.make_archive(out_file, item))
self.assertTrue(os.path.exists(out_file))
os.remove(out_file)
def _test_make_archive_tzo(self):
""" Test make_archive format: tzo"""
for item in self.files + self.dirs:
out_file = '%s.tzo' % item
self.assertTrue(archive.make_archive(out_file, item))
self.assertTrue(os.path.exists(out_file))
os.remove(out_file)
def _extract_archive_tzo(self):
""" Test extract format: tzo"""
for item in self.files + self.dirs:
out_file = '%s.tzo' % item
self.assertTrue(archive.make_archive(out_file, item))
self.assertTrue(os.path.exists(out_file))
out_dir = 'un_tar_dir'
archive.extract_archive(out_file, out_dir)
self.assertTrue(os.path.exists(os.path.join(out_dir, item)))
shutil.rmtree(out_dir)
def _test_make_archive_tar_lzo_with_different_name(self):
""" Test make_archive format: lzo
It packs the source with another name"""
for item in self.files + self.dirs:
out_file = 'abc.tar.lzo'
self.assertTrue(archive.make_archive(out_file, item))
self.assertTrue(os.path.exists(out_file))
os.remove(out_file)
def _test_make_archive_tar_lzo(self):
""" Test make_archive format: lzo"""
for item in self.files + self.dirs:
out_file = '%s.tar.lzo' % item
self.assertTrue(archive.make_archive(out_file, item))
self.assertTrue(os.path.exists(out_file))
os.remove(out_file)
def _extract_archive_tar_lzo(self):
""" Test extract_archive format: lzo"""
for item in self.files + self.dirs:
out_file = '%s.tar.lzo' % item
self.assertTrue(archive.make_archive(out_file, item))
self.assertTrue(os.path.exists(out_file))
out_dir = 'un_tar_dir'
archive.extract_archive(out_file, out_dir)
self.assertTrue(os.path.exists(os.path.join(out_dir, item)))
shutil.rmtree(out_dir)
def test_make_archive_taz_with_different_name(self):
""" Test make_archive format: taz
It packs the source with another name"""
for item in self.files + self.dirs:
out_file = 'abcd.taz'
self.assertTrue(archive.make_archive(out_file, item))
self.assertTrue(os.path.exists(out_file))
os.remove(out_file)
def test_make_archive_taz(self):
""" Test make_archive format: taz"""
for item in self.files + self.dirs:
out_file = '%s.taz' % item
self.assertTrue(archive.make_archive(out_file, item))
self.assertTrue(os.path.exists(out_file))
os.remove(out_file)
def _extract_archive_taz(self):
""" Test extract archive format: taz"""
for item in self.files + self.dirs:
out_file = '%s.taz' % item
self.assertTrue(archive.make_archive(out_file, item))
self.assertTrue(os.path.exists(out_file))
out_dir = 'un_tar_dir'
archive.extract_archive(out_file, out_dir)
self.assertTrue(os.path.exists(os.path.join(out_dir, item)))
shutil.rmtree(out_dir)
def test_make_archive_tgz_with_different_name(self):
""" Test make_archive format: tgz
It packs the source with anotehr name"""
for item in self.files + self.dirs:
out_file = 'abc.tgz'
self.assertTrue(archive.make_archive(out_file, item))
self.assertTrue(os.path.exists(out_file))
os.remove(out_file)
def test_make_archive_tgz(self):
""" Test make_archive format: tgz"""
for item in self.files + self.dirs:
out_file = '%s.tgz' % item
self.assertTrue(archive.make_archive(out_file, item))
self.assertTrue(os.path.exists(out_file))
os.remove(out_file)
def _extract_archive_tgz(self):
""" Test extract archive format: tgz"""
for item in self.files + self.dirs:
out_file = '%s.tgz' % item
self.assertTrue(archive.make_archive(out_file, item))
self.assertTrue(os.path.exists(out_file))
out_dir = 'un_tar_dir'
archive.extract_archive(out_file, out_dir)
self.assertTrue(os.path.exists(os.path.join(out_dir, item)))
shutil.rmtree(out_dir)
def test_make_archive_tar_gz_with_different_name(self):
""" Test make_archive format: tar.gz
It packs the source with another name"""
for item in self.files + self.dirs:
out_file = 'erwe.tar.gz'
self.assertTrue(archive.make_archive(out_file, item))
self.assertTrue(os.path.exists(out_file))
os.remove(out_file)
def test_make_archive_tar_gz(self):
""" Test make_archive format: tar.gz"""
for item in self.files + self.dirs:
out_file = '%s.tar.gz' % item
self.assertTrue(archive.make_archive(out_file, item))
self.assertTrue(os.path.exists(out_file))
os.remove(out_file)
def _extract_archive_tar_gz(self):
""" Test extract archive format: tar.gz"""
for item in self.files + self.dirs:
out_file = '%s.tar.gz' % item
self.assertTrue(archive.make_archive(out_file, item))
self.assertTrue(os.path.exists(out_file))
out_dir = 'un_tar_dir'
archive.extract_archive(out_file, out_dir)
self.assertTrue(os.path.exists(os.path.join(out_dir, item)))
shutil.rmtree(out_dir)
def test_make_archive_tbz_with_different_name(self):
""" Test make_archive format: tbz
It packs the source with another name"""
for item in self.files + self.dirs:
out_file = 'sdfsd.tbz'
self.assertTrue(archive.make_archive(out_file, item))
self.assertTrue(os.path.exists(out_file))
os.remove(out_file)
def test_make_archive_tbz(self):
""" Test make_archive format: tbz"""
for item in self.files + self.dirs:
out_file = '%s.tbz' % item
self.assertTrue(archive.make_archive(out_file, item))
self.assertTrue(os.path.exists(out_file))
os.remove(out_file)
def _extract_archive_tbz(self):
""" Test extract format: tbz"""
for item in self.files + self.dirs:
out_file = '%s.tbz' % item
self.assertTrue(archive.make_archive(out_file, item))
self.assertTrue(os.path.exists(out_file))
out_dir = 'un_tar_dir'
archive.extract_archive(out_file, out_dir)
self.assertTrue(os.path.exists(os.path.join(out_dir, item)))
shutil.rmtree(out_dir)
def test_make_archive_tbz2_with_different_name(self):
""" Test make_archive format: tbz2
It packs source with another name"""
for item in self.files + self.dirs:
out_file = 'sfsfd.tbz2'
self.assertTrue(archive.make_archive(out_file, item))
self.assertTrue(os.path.exists(out_file))
os.remove(out_file)
def test_make_archive_tbz2(self):
""" Test make_archive format: tbz2"""
for item in self.files + self.dirs:
out_file = '%s.tbz2' % item
self.assertTrue(archive.make_archive(out_file, item))
self.assertTrue(os.path.exists(out_file))
os.remove(out_file)
def _extract_archive_tbz2(self):
""" Test extract format: tbz2"""
for item in self.files + self.dirs:
out_file = '%s.tbz2' % item
self.assertTrue(archive.make_archive(out_file, item))
self.assertTrue(os.path.exists(out_file))
out_dir = 'un_tar_dir'
archive.extract_archive(out_file, out_dir)
self.assertTrue(os.path.exists(os.path.join(out_dir, item)))
shutil.rmtree(out_dir)
def test_make_archive_tar_bz_with_different_name(self):
""" Test make_archive format: tar.bz
It packs source with antoher name"""
for item in self.files + self.dirs:
out_file = 'sdf.tar.bz'
self.assertTrue(archive.make_archive(out_file, item))
self.assertTrue(os.path.exists(out_file))
os.remove(out_file)
def test_make_archive_tar_bz(self):
""" Test make_archive format: tar.bz"""
for item in self.files + self.dirs:
out_file = '%s.tar.bz' % item
self.assertTrue(archive.make_archive(out_file, item))
self.assertTrue(os.path.exists(out_file))
os.remove(out_file)
def _extract_archive_tar_bz(self):
""" Test extract format: tar.bz"""
for item in self.files + self.dirs:
out_file = '%s.tar.bz' % item
self.assertTrue(archive.make_archive(out_file, item))
self.assertTrue(os.path.exists(out_file))
out_dir = 'un_tar_dir'
archive.extract_archive(out_file, out_dir)
self.assertTrue(os.path.exists(os.path.join(out_dir, item)))
shutil.rmtree(out_dir)
def test_make_archive_tar_bz2_with_different_name(self):
""" Test make_archive format: tar.bz2
it packs the source with another name """
for item in self.files + self.dirs:
out_file = 'df.tar.bz2'
self.assertTrue(archive.make_archive(out_file, item))
self.assertTrue(os.path.exists(out_file))
os.remove(out_file)
def test_make_archive_tar_bz2(self):
""" Test make_archive format: tar.bz2"""
for item in self.files + self.dirs:
out_file = '%s.tar.bz2' % item
self.assertTrue(archive.make_archive(out_file, item))
self.assertTrue(os.path.exists(out_file))
os.remove(out_file)
def _extract_archive_tar_bz2(self):
""" Test extract format: tar.bz2"""
for item in self.files + self.dirs:
out_file = '%s.tar.bz2' % item
self.assertTrue(archive.make_archive(out_file, item))
self.assertTrue(os.path.exists(out_file))
out_dir = 'un_tar_dir'
archive.extract_archive(out_file, out_dir)
self.assertTrue(os.path.exists(os.path.join(out_dir, item)))
shutil.rmtree(out_dir)
if __name__ == "__main__":
unittest.main()
| gpl-2.0 |
creeptonik/videojs-live-card | node_modules/node-sass/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py | 1284 | 100329 | # Copyright (c) 2013 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.
import collections
import copy
import hashlib
import json
import multiprocessing
import os.path
import re
import signal
import subprocess
import sys
import gyp
import gyp.common
from gyp.common import OrderedSet
import gyp.msvs_emulation
import gyp.MSVSUtil as MSVSUtil
import gyp.xcode_emulation
from cStringIO import StringIO
from gyp.common import GetEnvironFallback
import gyp.ninja_syntax as ninja_syntax
generator_default_variables = {
'EXECUTABLE_PREFIX': '',
'EXECUTABLE_SUFFIX': '',
'STATIC_LIB_PREFIX': 'lib',
'STATIC_LIB_SUFFIX': '.a',
'SHARED_LIB_PREFIX': 'lib',
# Gyp expects the following variables to be expandable by the build
# system to the appropriate locations. Ninja prefers paths to be
# known at gyp time. To resolve this, introduce special
# variables starting with $! and $| (which begin with a $ so gyp knows it
# should be treated specially, but is otherwise an invalid
# ninja/shell variable) that are passed to gyp here but expanded
# before writing out into the target .ninja files; see
# ExpandSpecial.
# $! is used for variables that represent a path and that can only appear at
# the start of a string, while $| is used for variables that can appear
# anywhere in a string.
'INTERMEDIATE_DIR': '$!INTERMEDIATE_DIR',
'SHARED_INTERMEDIATE_DIR': '$!PRODUCT_DIR/gen',
'PRODUCT_DIR': '$!PRODUCT_DIR',
'CONFIGURATION_NAME': '$|CONFIGURATION_NAME',
# Special variables that may be used by gyp 'rule' targets.
# We generate definitions for these variables on the fly when processing a
# rule.
'RULE_INPUT_ROOT': '${root}',
'RULE_INPUT_DIRNAME': '${dirname}',
'RULE_INPUT_PATH': '${source}',
'RULE_INPUT_EXT': '${ext}',
'RULE_INPUT_NAME': '${name}',
}
# Placates pylint.
generator_additional_non_configuration_keys = []
generator_additional_path_sections = []
generator_extra_sources_for_rules = []
generator_filelist_paths = None
generator_supports_multiple_toolsets = gyp.common.CrossCompileRequested()
def StripPrefix(arg, prefix):
if arg.startswith(prefix):
return arg[len(prefix):]
return arg
def QuoteShellArgument(arg, flavor):
"""Quote a string such that it will be interpreted as a single argument
by the shell."""
# Rather than attempting to enumerate the bad shell characters, just
# whitelist common OK ones and quote anything else.
if re.match(r'^[a-zA-Z0-9_=.\\/-]+$', arg):
return arg # No quoting necessary.
if flavor == 'win':
return gyp.msvs_emulation.QuoteForRspFile(arg)
return "'" + arg.replace("'", "'" + '"\'"' + "'") + "'"
def Define(d, flavor):
"""Takes a preprocessor define and returns a -D parameter that's ninja- and
shell-escaped."""
if flavor == 'win':
# cl.exe replaces literal # characters with = in preprocesor definitions for
# some reason. Octal-encode to work around that.
d = d.replace('#', '\\%03o' % ord('#'))
return QuoteShellArgument(ninja_syntax.escape('-D' + d), flavor)
def AddArch(output, arch):
"""Adds an arch string to an output path."""
output, extension = os.path.splitext(output)
return '%s.%s%s' % (output, arch, extension)
class Target(object):
"""Target represents the paths used within a single gyp target.
Conceptually, building a single target A is a series of steps:
1) actions/rules/copies generates source/resources/etc.
2) compiles generates .o files
3) link generates a binary (library/executable)
4) bundle merges the above in a mac bundle
(Any of these steps can be optional.)
From a build ordering perspective, a dependent target B could just
depend on the last output of this series of steps.
But some dependent commands sometimes need to reach inside the box.
For example, when linking B it needs to get the path to the static
library generated by A.
This object stores those paths. To keep things simple, member
variables only store concrete paths to single files, while methods
compute derived values like "the last output of the target".
"""
def __init__(self, type):
# Gyp type ("static_library", etc.) of this target.
self.type = type
# File representing whether any input dependencies necessary for
# dependent actions have completed.
self.preaction_stamp = None
# File representing whether any input dependencies necessary for
# dependent compiles have completed.
self.precompile_stamp = None
# File representing the completion of actions/rules/copies, if any.
self.actions_stamp = None
# Path to the output of the link step, if any.
self.binary = None
# Path to the file representing the completion of building the bundle,
# if any.
self.bundle = None
# On Windows, incremental linking requires linking against all the .objs
# that compose a .lib (rather than the .lib itself). That list is stored
# here. In this case, we also need to save the compile_deps for the target,
# so that the the target that directly depends on the .objs can also depend
# on those.
self.component_objs = None
self.compile_deps = None
# Windows only. The import .lib is the output of a build step, but
# because dependents only link against the lib (not both the lib and the
# dll) we keep track of the import library here.
self.import_lib = None
def Linkable(self):
"""Return true if this is a target that can be linked against."""
return self.type in ('static_library', 'shared_library')
def UsesToc(self, flavor):
"""Return true if the target should produce a restat rule based on a TOC
file."""
# For bundles, the .TOC should be produced for the binary, not for
# FinalOutput(). But the naive approach would put the TOC file into the
# bundle, so don't do this for bundles for now.
if flavor == 'win' or self.bundle:
return False
return self.type in ('shared_library', 'loadable_module')
def PreActionInput(self, flavor):
"""Return the path, if any, that should be used as a dependency of
any dependent action step."""
if self.UsesToc(flavor):
return self.FinalOutput() + '.TOC'
return self.FinalOutput() or self.preaction_stamp
def PreCompileInput(self):
"""Return the path, if any, that should be used as a dependency of
any dependent compile step."""
return self.actions_stamp or self.precompile_stamp
def FinalOutput(self):
"""Return the last output of the target, which depends on all prior
steps."""
return self.bundle or self.binary or self.actions_stamp
# A small discourse on paths as used within the Ninja build:
# All files we produce (both at gyp and at build time) appear in the
# build directory (e.g. out/Debug).
#
# Paths within a given .gyp file are always relative to the directory
# containing the .gyp file. Call these "gyp paths". This includes
# sources as well as the starting directory a given gyp rule/action
# expects to be run from. We call the path from the source root to
# the gyp file the "base directory" within the per-.gyp-file
# NinjaWriter code.
#
# All paths as written into the .ninja files are relative to the build
# directory. Call these paths "ninja paths".
#
# We translate between these two notions of paths with two helper
# functions:
#
# - GypPathToNinja translates a gyp path (i.e. relative to the .gyp file)
# into the equivalent ninja path.
#
# - GypPathToUniqueOutput translates a gyp path into a ninja path to write
# an output file; the result can be namespaced such that it is unique
# to the input file name as well as the output target name.
class NinjaWriter(object):
def __init__(self, hash_for_rules, target_outputs, base_dir, build_dir,
output_file, toplevel_build, output_file_name, flavor,
toplevel_dir=None):
"""
base_dir: path from source root to directory containing this gyp file,
by gyp semantics, all input paths are relative to this
build_dir: path from source root to build output
toplevel_dir: path to the toplevel directory
"""
self.hash_for_rules = hash_for_rules
self.target_outputs = target_outputs
self.base_dir = base_dir
self.build_dir = build_dir
self.ninja = ninja_syntax.Writer(output_file)
self.toplevel_build = toplevel_build
self.output_file_name = output_file_name
self.flavor = flavor
self.abs_build_dir = None
if toplevel_dir is not None:
self.abs_build_dir = os.path.abspath(os.path.join(toplevel_dir,
build_dir))
self.obj_ext = '.obj' if flavor == 'win' else '.o'
if flavor == 'win':
# See docstring of msvs_emulation.GenerateEnvironmentFiles().
self.win_env = {}
for arch in ('x86', 'x64'):
self.win_env[arch] = 'environment.' + arch
# Relative path from build output dir to base dir.
build_to_top = gyp.common.InvertRelativePath(build_dir, toplevel_dir)
self.build_to_base = os.path.join(build_to_top, base_dir)
# Relative path from base dir to build dir.
base_to_top = gyp.common.InvertRelativePath(base_dir, toplevel_dir)
self.base_to_build = os.path.join(base_to_top, build_dir)
def ExpandSpecial(self, path, product_dir=None):
"""Expand specials like $!PRODUCT_DIR in |path|.
If |product_dir| is None, assumes the cwd is already the product
dir. Otherwise, |product_dir| is the relative path to the product
dir.
"""
PRODUCT_DIR = '$!PRODUCT_DIR'
if PRODUCT_DIR in path:
if product_dir:
path = path.replace(PRODUCT_DIR, product_dir)
else:
path = path.replace(PRODUCT_DIR + '/', '')
path = path.replace(PRODUCT_DIR + '\\', '')
path = path.replace(PRODUCT_DIR, '.')
INTERMEDIATE_DIR = '$!INTERMEDIATE_DIR'
if INTERMEDIATE_DIR in path:
int_dir = self.GypPathToUniqueOutput('gen')
# GypPathToUniqueOutput generates a path relative to the product dir,
# so insert product_dir in front if it is provided.
path = path.replace(INTERMEDIATE_DIR,
os.path.join(product_dir or '', int_dir))
CONFIGURATION_NAME = '$|CONFIGURATION_NAME'
path = path.replace(CONFIGURATION_NAME, self.config_name)
return path
def ExpandRuleVariables(self, path, root, dirname, source, ext, name):
if self.flavor == 'win':
path = self.msvs_settings.ConvertVSMacros(
path, config=self.config_name)
path = path.replace(generator_default_variables['RULE_INPUT_ROOT'], root)
path = path.replace(generator_default_variables['RULE_INPUT_DIRNAME'],
dirname)
path = path.replace(generator_default_variables['RULE_INPUT_PATH'], source)
path = path.replace(generator_default_variables['RULE_INPUT_EXT'], ext)
path = path.replace(generator_default_variables['RULE_INPUT_NAME'], name)
return path
def GypPathToNinja(self, path, env=None):
"""Translate a gyp path to a ninja path, optionally expanding environment
variable references in |path| with |env|.
See the above discourse on path conversions."""
if env:
if self.flavor == 'mac':
path = gyp.xcode_emulation.ExpandEnvVars(path, env)
elif self.flavor == 'win':
path = gyp.msvs_emulation.ExpandMacros(path, env)
if path.startswith('$!'):
expanded = self.ExpandSpecial(path)
if self.flavor == 'win':
expanded = os.path.normpath(expanded)
return expanded
if '$|' in path:
path = self.ExpandSpecial(path)
assert '$' not in path, path
return os.path.normpath(os.path.join(self.build_to_base, path))
def GypPathToUniqueOutput(self, path, qualified=True):
"""Translate a gyp path to a ninja path for writing output.
If qualified is True, qualify the resulting filename with the name
of the target. This is necessary when e.g. compiling the same
path twice for two separate output targets.
See the above discourse on path conversions."""
path = self.ExpandSpecial(path)
assert not path.startswith('$'), path
# Translate the path following this scheme:
# Input: foo/bar.gyp, target targ, references baz/out.o
# Output: obj/foo/baz/targ.out.o (if qualified)
# obj/foo/baz/out.o (otherwise)
# (and obj.host instead of obj for cross-compiles)
#
# Why this scheme and not some other one?
# 1) for a given input, you can compute all derived outputs by matching
# its path, even if the input is brought via a gyp file with '..'.
# 2) simple files like libraries and stamps have a simple filename.
obj = 'obj'
if self.toolset != 'target':
obj += '.' + self.toolset
path_dir, path_basename = os.path.split(path)
assert not os.path.isabs(path_dir), (
"'%s' can not be absolute path (see crbug.com/462153)." % path_dir)
if qualified:
path_basename = self.name + '.' + path_basename
return os.path.normpath(os.path.join(obj, self.base_dir, path_dir,
path_basename))
def WriteCollapsedDependencies(self, name, targets, order_only=None):
"""Given a list of targets, return a path for a single file
representing the result of building all the targets or None.
Uses a stamp file if necessary."""
assert targets == filter(None, targets), targets
if len(targets) == 0:
assert not order_only
return None
if len(targets) > 1 or order_only:
stamp = self.GypPathToUniqueOutput(name + '.stamp')
targets = self.ninja.build(stamp, 'stamp', targets, order_only=order_only)
self.ninja.newline()
return targets[0]
def _SubninjaNameForArch(self, arch):
output_file_base = os.path.splitext(self.output_file_name)[0]
return '%s.%s.ninja' % (output_file_base, arch)
def WriteSpec(self, spec, config_name, generator_flags):
"""The main entry point for NinjaWriter: write the build rules for a spec.
Returns a Target object, which represents the output paths for this spec.
Returns None if there are no outputs (e.g. a settings-only 'none' type
target)."""
self.config_name = config_name
self.name = spec['target_name']
self.toolset = spec['toolset']
config = spec['configurations'][config_name]
self.target = Target(spec['type'])
self.is_standalone_static_library = bool(
spec.get('standalone_static_library', 0))
# Track if this target contains any C++ files, to decide if gcc or g++
# should be used for linking.
self.uses_cpp = False
self.is_mac_bundle = gyp.xcode_emulation.IsMacBundle(self.flavor, spec)
self.xcode_settings = self.msvs_settings = None
if self.flavor == 'mac':
self.xcode_settings = gyp.xcode_emulation.XcodeSettings(spec)
if self.flavor == 'win':
self.msvs_settings = gyp.msvs_emulation.MsvsSettings(spec,
generator_flags)
arch = self.msvs_settings.GetArch(config_name)
self.ninja.variable('arch', self.win_env[arch])
self.ninja.variable('cc', '$cl_' + arch)
self.ninja.variable('cxx', '$cl_' + arch)
self.ninja.variable('cc_host', '$cl_' + arch)
self.ninja.variable('cxx_host', '$cl_' + arch)
self.ninja.variable('asm', '$ml_' + arch)
if self.flavor == 'mac':
self.archs = self.xcode_settings.GetActiveArchs(config_name)
if len(self.archs) > 1:
self.arch_subninjas = dict(
(arch, ninja_syntax.Writer(
OpenOutput(os.path.join(self.toplevel_build,
self._SubninjaNameForArch(arch)),
'w')))
for arch in self.archs)
# Compute predepends for all rules.
# actions_depends is the dependencies this target depends on before running
# any of its action/rule/copy steps.
# compile_depends is the dependencies this target depends on before running
# any of its compile steps.
actions_depends = []
compile_depends = []
# TODO(evan): it is rather confusing which things are lists and which
# are strings. Fix these.
if 'dependencies' in spec:
for dep in spec['dependencies']:
if dep in self.target_outputs:
target = self.target_outputs[dep]
actions_depends.append(target.PreActionInput(self.flavor))
compile_depends.append(target.PreCompileInput())
actions_depends = filter(None, actions_depends)
compile_depends = filter(None, compile_depends)
actions_depends = self.WriteCollapsedDependencies('actions_depends',
actions_depends)
compile_depends = self.WriteCollapsedDependencies('compile_depends',
compile_depends)
self.target.preaction_stamp = actions_depends
self.target.precompile_stamp = compile_depends
# Write out actions, rules, and copies. These must happen before we
# compile any sources, so compute a list of predependencies for sources
# while we do it.
extra_sources = []
mac_bundle_depends = []
self.target.actions_stamp = self.WriteActionsRulesCopies(
spec, extra_sources, actions_depends, mac_bundle_depends)
# If we have actions/rules/copies, we depend directly on those, but
# otherwise we depend on dependent target's actions/rules/copies etc.
# We never need to explicitly depend on previous target's link steps,
# because no compile ever depends on them.
compile_depends_stamp = (self.target.actions_stamp or compile_depends)
# Write out the compilation steps, if any.
link_deps = []
sources = extra_sources + spec.get('sources', [])
if sources:
if self.flavor == 'mac' and len(self.archs) > 1:
# Write subninja file containing compile and link commands scoped to
# a single arch if a fat binary is being built.
for arch in self.archs:
self.ninja.subninja(self._SubninjaNameForArch(arch))
pch = None
if self.flavor == 'win':
gyp.msvs_emulation.VerifyMissingSources(
sources, self.abs_build_dir, generator_flags, self.GypPathToNinja)
pch = gyp.msvs_emulation.PrecompiledHeader(
self.msvs_settings, config_name, self.GypPathToNinja,
self.GypPathToUniqueOutput, self.obj_ext)
else:
pch = gyp.xcode_emulation.MacPrefixHeader(
self.xcode_settings, self.GypPathToNinja,
lambda path, lang: self.GypPathToUniqueOutput(path + '-' + lang))
link_deps = self.WriteSources(
self.ninja, config_name, config, sources, compile_depends_stamp, pch,
spec)
# Some actions/rules output 'sources' that are already object files.
obj_outputs = [f for f in sources if f.endswith(self.obj_ext)]
if obj_outputs:
if self.flavor != 'mac' or len(self.archs) == 1:
link_deps += [self.GypPathToNinja(o) for o in obj_outputs]
else:
print "Warning: Actions/rules writing object files don't work with " \
"multiarch targets, dropping. (target %s)" % spec['target_name']
elif self.flavor == 'mac' and len(self.archs) > 1:
link_deps = collections.defaultdict(list)
compile_deps = self.target.actions_stamp or actions_depends
if self.flavor == 'win' and self.target.type == 'static_library':
self.target.component_objs = link_deps
self.target.compile_deps = compile_deps
# Write out a link step, if needed.
output = None
is_empty_bundle = not link_deps and not mac_bundle_depends
if link_deps or self.target.actions_stamp or actions_depends:
output = self.WriteTarget(spec, config_name, config, link_deps,
compile_deps)
if self.is_mac_bundle:
mac_bundle_depends.append(output)
# Bundle all of the above together, if needed.
if self.is_mac_bundle:
output = self.WriteMacBundle(spec, mac_bundle_depends, is_empty_bundle)
if not output:
return None
assert self.target.FinalOutput(), output
return self.target
def _WinIdlRule(self, source, prebuild, outputs):
"""Handle the implicit VS .idl rule for one source file. Fills |outputs|
with files that are generated."""
outdir, output, vars, flags = self.msvs_settings.GetIdlBuildData(
source, self.config_name)
outdir = self.GypPathToNinja(outdir)
def fix_path(path, rel=None):
path = os.path.join(outdir, path)
dirname, basename = os.path.split(source)
root, ext = os.path.splitext(basename)
path = self.ExpandRuleVariables(
path, root, dirname, source, ext, basename)
if rel:
path = os.path.relpath(path, rel)
return path
vars = [(name, fix_path(value, outdir)) for name, value in vars]
output = [fix_path(p) for p in output]
vars.append(('outdir', outdir))
vars.append(('idlflags', flags))
input = self.GypPathToNinja(source)
self.ninja.build(output, 'idl', input,
variables=vars, order_only=prebuild)
outputs.extend(output)
def WriteWinIdlFiles(self, spec, prebuild):
"""Writes rules to match MSVS's implicit idl handling."""
assert self.flavor == 'win'
if self.msvs_settings.HasExplicitIdlRulesOrActions(spec):
return []
outputs = []
for source in filter(lambda x: x.endswith('.idl'), spec['sources']):
self._WinIdlRule(source, prebuild, outputs)
return outputs
def WriteActionsRulesCopies(self, spec, extra_sources, prebuild,
mac_bundle_depends):
"""Write out the Actions, Rules, and Copies steps. Return a path
representing the outputs of these steps."""
outputs = []
if self.is_mac_bundle:
mac_bundle_resources = spec.get('mac_bundle_resources', [])[:]
else:
mac_bundle_resources = []
extra_mac_bundle_resources = []
if 'actions' in spec:
outputs += self.WriteActions(spec['actions'], extra_sources, prebuild,
extra_mac_bundle_resources)
if 'rules' in spec:
outputs += self.WriteRules(spec['rules'], extra_sources, prebuild,
mac_bundle_resources,
extra_mac_bundle_resources)
if 'copies' in spec:
outputs += self.WriteCopies(spec['copies'], prebuild, mac_bundle_depends)
if 'sources' in spec and self.flavor == 'win':
outputs += self.WriteWinIdlFiles(spec, prebuild)
stamp = self.WriteCollapsedDependencies('actions_rules_copies', outputs)
if self.is_mac_bundle:
xcassets = self.WriteMacBundleResources(
extra_mac_bundle_resources + mac_bundle_resources, mac_bundle_depends)
partial_info_plist = self.WriteMacXCassets(xcassets, mac_bundle_depends)
self.WriteMacInfoPlist(partial_info_plist, mac_bundle_depends)
return stamp
def GenerateDescription(self, verb, message, fallback):
"""Generate and return a description of a build step.
|verb| is the short summary, e.g. ACTION or RULE.
|message| is a hand-written description, or None if not available.
|fallback| is the gyp-level name of the step, usable as a fallback.
"""
if self.toolset != 'target':
verb += '(%s)' % self.toolset
if message:
return '%s %s' % (verb, self.ExpandSpecial(message))
else:
return '%s %s: %s' % (verb, self.name, fallback)
def WriteActions(self, actions, extra_sources, prebuild,
extra_mac_bundle_resources):
# Actions cd into the base directory.
env = self.GetToolchainEnv()
all_outputs = []
for action in actions:
# First write out a rule for the action.
name = '%s_%s' % (action['action_name'], self.hash_for_rules)
description = self.GenerateDescription('ACTION',
action.get('message', None),
name)
is_cygwin = (self.msvs_settings.IsRuleRunUnderCygwin(action)
if self.flavor == 'win' else False)
args = action['action']
depfile = action.get('depfile', None)
if depfile:
depfile = self.ExpandSpecial(depfile, self.base_to_build)
pool = 'console' if int(action.get('ninja_use_console', 0)) else None
rule_name, _ = self.WriteNewNinjaRule(name, args, description,
is_cygwin, env, pool,
depfile=depfile)
inputs = [self.GypPathToNinja(i, env) for i in action['inputs']]
if int(action.get('process_outputs_as_sources', False)):
extra_sources += action['outputs']
if int(action.get('process_outputs_as_mac_bundle_resources', False)):
extra_mac_bundle_resources += action['outputs']
outputs = [self.GypPathToNinja(o, env) for o in action['outputs']]
# Then write out an edge using the rule.
self.ninja.build(outputs, rule_name, inputs,
order_only=prebuild)
all_outputs += outputs
self.ninja.newline()
return all_outputs
def WriteRules(self, rules, extra_sources, prebuild,
mac_bundle_resources, extra_mac_bundle_resources):
env = self.GetToolchainEnv()
all_outputs = []
for rule in rules:
# Skip a rule with no action and no inputs.
if 'action' not in rule and not rule.get('rule_sources', []):
continue
# First write out a rule for the rule action.
name = '%s_%s' % (rule['rule_name'], self.hash_for_rules)
args = rule['action']
description = self.GenerateDescription(
'RULE',
rule.get('message', None),
('%s ' + generator_default_variables['RULE_INPUT_PATH']) % name)
is_cygwin = (self.msvs_settings.IsRuleRunUnderCygwin(rule)
if self.flavor == 'win' else False)
pool = 'console' if int(rule.get('ninja_use_console', 0)) else None
rule_name, args = self.WriteNewNinjaRule(
name, args, description, is_cygwin, env, pool)
# TODO: if the command references the outputs directly, we should
# simplify it to just use $out.
# Rules can potentially make use of some special variables which
# must vary per source file.
# Compute the list of variables we'll need to provide.
special_locals = ('source', 'root', 'dirname', 'ext', 'name')
needed_variables = set(['source'])
for argument in args:
for var in special_locals:
if '${%s}' % var in argument:
needed_variables.add(var)
def cygwin_munge(path):
# pylint: disable=cell-var-from-loop
if is_cygwin:
return path.replace('\\', '/')
return path
inputs = [self.GypPathToNinja(i, env) for i in rule.get('inputs', [])]
# If there are n source files matching the rule, and m additional rule
# inputs, then adding 'inputs' to each build edge written below will
# write m * n inputs. Collapsing reduces this to m + n.
sources = rule.get('rule_sources', [])
num_inputs = len(inputs)
if prebuild:
num_inputs += 1
if num_inputs > 2 and len(sources) > 2:
inputs = [self.WriteCollapsedDependencies(
rule['rule_name'], inputs, order_only=prebuild)]
prebuild = []
# For each source file, write an edge that generates all the outputs.
for source in sources:
source = os.path.normpath(source)
dirname, basename = os.path.split(source)
root, ext = os.path.splitext(basename)
# Gather the list of inputs and outputs, expanding $vars if possible.
outputs = [self.ExpandRuleVariables(o, root, dirname,
source, ext, basename)
for o in rule['outputs']]
if int(rule.get('process_outputs_as_sources', False)):
extra_sources += outputs
was_mac_bundle_resource = source in mac_bundle_resources
if was_mac_bundle_resource or \
int(rule.get('process_outputs_as_mac_bundle_resources', False)):
extra_mac_bundle_resources += outputs
# Note: This is n_resources * n_outputs_in_rule. Put to-be-removed
# items in a set and remove them all in a single pass if this becomes
# a performance issue.
if was_mac_bundle_resource:
mac_bundle_resources.remove(source)
extra_bindings = []
for var in needed_variables:
if var == 'root':
extra_bindings.append(('root', cygwin_munge(root)))
elif var == 'dirname':
# '$dirname' is a parameter to the rule action, which means
# it shouldn't be converted to a Ninja path. But we don't
# want $!PRODUCT_DIR in there either.
dirname_expanded = self.ExpandSpecial(dirname, self.base_to_build)
extra_bindings.append(('dirname', cygwin_munge(dirname_expanded)))
elif var == 'source':
# '$source' is a parameter to the rule action, which means
# it shouldn't be converted to a Ninja path. But we don't
# want $!PRODUCT_DIR in there either.
source_expanded = self.ExpandSpecial(source, self.base_to_build)
extra_bindings.append(('source', cygwin_munge(source_expanded)))
elif var == 'ext':
extra_bindings.append(('ext', ext))
elif var == 'name':
extra_bindings.append(('name', cygwin_munge(basename)))
else:
assert var == None, repr(var)
outputs = [self.GypPathToNinja(o, env) for o in outputs]
if self.flavor == 'win':
# WriteNewNinjaRule uses unique_name for creating an rsp file on win.
extra_bindings.append(('unique_name',
hashlib.md5(outputs[0]).hexdigest()))
self.ninja.build(outputs, rule_name, self.GypPathToNinja(source),
implicit=inputs,
order_only=prebuild,
variables=extra_bindings)
all_outputs.extend(outputs)
return all_outputs
def WriteCopies(self, copies, prebuild, mac_bundle_depends):
outputs = []
env = self.GetToolchainEnv()
for copy in copies:
for path in copy['files']:
# Normalize the path so trailing slashes don't confuse us.
path = os.path.normpath(path)
basename = os.path.split(path)[1]
src = self.GypPathToNinja(path, env)
dst = self.GypPathToNinja(os.path.join(copy['destination'], basename),
env)
outputs += self.ninja.build(dst, 'copy', src, order_only=prebuild)
if self.is_mac_bundle:
# gyp has mac_bundle_resources to copy things into a bundle's
# Resources folder, but there's no built-in way to copy files to other
# places in the bundle. Hence, some targets use copies for this. Check
# if this file is copied into the current bundle, and if so add it to
# the bundle depends so that dependent targets get rebuilt if the copy
# input changes.
if dst.startswith(self.xcode_settings.GetBundleContentsFolderPath()):
mac_bundle_depends.append(dst)
return outputs
def WriteMacBundleResources(self, resources, bundle_depends):
"""Writes ninja edges for 'mac_bundle_resources'."""
xcassets = []
for output, res in gyp.xcode_emulation.GetMacBundleResources(
generator_default_variables['PRODUCT_DIR'],
self.xcode_settings, map(self.GypPathToNinja, resources)):
output = self.ExpandSpecial(output)
if os.path.splitext(output)[-1] != '.xcassets':
isBinary = self.xcode_settings.IsBinaryOutputFormat(self.config_name)
self.ninja.build(output, 'mac_tool', res,
variables=[('mactool_cmd', 'copy-bundle-resource'), \
('binary', isBinary)])
bundle_depends.append(output)
else:
xcassets.append(res)
return xcassets
def WriteMacXCassets(self, xcassets, bundle_depends):
"""Writes ninja edges for 'mac_bundle_resources' .xcassets files.
This add an invocation of 'actool' via the 'mac_tool.py' helper script.
It assumes that the assets catalogs define at least one imageset and
thus an Assets.car file will be generated in the application resources
directory. If this is not the case, then the build will probably be done
at each invocation of ninja."""
if not xcassets:
return
extra_arguments = {}
settings_to_arg = {
'XCASSETS_APP_ICON': 'app-icon',
'XCASSETS_LAUNCH_IMAGE': 'launch-image',
}
settings = self.xcode_settings.xcode_settings[self.config_name]
for settings_key, arg_name in settings_to_arg.iteritems():
value = settings.get(settings_key)
if value:
extra_arguments[arg_name] = value
partial_info_plist = None
if extra_arguments:
partial_info_plist = self.GypPathToUniqueOutput(
'assetcatalog_generated_info.plist')
extra_arguments['output-partial-info-plist'] = partial_info_plist
outputs = []
outputs.append(
os.path.join(
self.xcode_settings.GetBundleResourceFolder(),
'Assets.car'))
if partial_info_plist:
outputs.append(partial_info_plist)
keys = QuoteShellArgument(json.dumps(extra_arguments), self.flavor)
extra_env = self.xcode_settings.GetPerTargetSettings()
env = self.GetSortedXcodeEnv(additional_settings=extra_env)
env = self.ComputeExportEnvString(env)
bundle_depends.extend(self.ninja.build(
outputs, 'compile_xcassets', xcassets,
variables=[('env', env), ('keys', keys)]))
return partial_info_plist
def WriteMacInfoPlist(self, partial_info_plist, bundle_depends):
"""Write build rules for bundle Info.plist files."""
info_plist, out, defines, extra_env = gyp.xcode_emulation.GetMacInfoPlist(
generator_default_variables['PRODUCT_DIR'],
self.xcode_settings, self.GypPathToNinja)
if not info_plist:
return
out = self.ExpandSpecial(out)
if defines:
# Create an intermediate file to store preprocessed results.
intermediate_plist = self.GypPathToUniqueOutput(
os.path.basename(info_plist))
defines = ' '.join([Define(d, self.flavor) for d in defines])
info_plist = self.ninja.build(
intermediate_plist, 'preprocess_infoplist', info_plist,
variables=[('defines',defines)])
env = self.GetSortedXcodeEnv(additional_settings=extra_env)
env = self.ComputeExportEnvString(env)
if partial_info_plist:
intermediate_plist = self.GypPathToUniqueOutput('merged_info.plist')
info_plist = self.ninja.build(
intermediate_plist, 'merge_infoplist',
[partial_info_plist, info_plist])
keys = self.xcode_settings.GetExtraPlistItems(self.config_name)
keys = QuoteShellArgument(json.dumps(keys), self.flavor)
isBinary = self.xcode_settings.IsBinaryOutputFormat(self.config_name)
self.ninja.build(out, 'copy_infoplist', info_plist,
variables=[('env', env), ('keys', keys),
('binary', isBinary)])
bundle_depends.append(out)
def WriteSources(self, ninja_file, config_name, config, sources, predepends,
precompiled_header, spec):
"""Write build rules to compile all of |sources|."""
if self.toolset == 'host':
self.ninja.variable('ar', '$ar_host')
self.ninja.variable('cc', '$cc_host')
self.ninja.variable('cxx', '$cxx_host')
self.ninja.variable('ld', '$ld_host')
self.ninja.variable('ldxx', '$ldxx_host')
self.ninja.variable('nm', '$nm_host')
self.ninja.variable('readelf', '$readelf_host')
if self.flavor != 'mac' or len(self.archs) == 1:
return self.WriteSourcesForArch(
self.ninja, config_name, config, sources, predepends,
precompiled_header, spec)
else:
return dict((arch, self.WriteSourcesForArch(
self.arch_subninjas[arch], config_name, config, sources, predepends,
precompiled_header, spec, arch=arch))
for arch in self.archs)
def WriteSourcesForArch(self, ninja_file, config_name, config, sources,
predepends, precompiled_header, spec, arch=None):
"""Write build rules to compile all of |sources|."""
extra_defines = []
if self.flavor == 'mac':
cflags = self.xcode_settings.GetCflags(config_name, arch=arch)
cflags_c = self.xcode_settings.GetCflagsC(config_name)
cflags_cc = self.xcode_settings.GetCflagsCC(config_name)
cflags_objc = ['$cflags_c'] + \
self.xcode_settings.GetCflagsObjC(config_name)
cflags_objcc = ['$cflags_cc'] + \
self.xcode_settings.GetCflagsObjCC(config_name)
elif self.flavor == 'win':
asmflags = self.msvs_settings.GetAsmflags(config_name)
cflags = self.msvs_settings.GetCflags(config_name)
cflags_c = self.msvs_settings.GetCflagsC(config_name)
cflags_cc = self.msvs_settings.GetCflagsCC(config_name)
extra_defines = self.msvs_settings.GetComputedDefines(config_name)
# See comment at cc_command for why there's two .pdb files.
pdbpath_c = pdbpath_cc = self.msvs_settings.GetCompilerPdbName(
config_name, self.ExpandSpecial)
if not pdbpath_c:
obj = 'obj'
if self.toolset != 'target':
obj += '.' + self.toolset
pdbpath = os.path.normpath(os.path.join(obj, self.base_dir, self.name))
pdbpath_c = pdbpath + '.c.pdb'
pdbpath_cc = pdbpath + '.cc.pdb'
self.WriteVariableList(ninja_file, 'pdbname_c', [pdbpath_c])
self.WriteVariableList(ninja_file, 'pdbname_cc', [pdbpath_cc])
self.WriteVariableList(ninja_file, 'pchprefix', [self.name])
else:
cflags = config.get('cflags', [])
cflags_c = config.get('cflags_c', [])
cflags_cc = config.get('cflags_cc', [])
# Respect environment variables related to build, but target-specific
# flags can still override them.
if self.toolset == 'target':
cflags_c = (os.environ.get('CPPFLAGS', '').split() +
os.environ.get('CFLAGS', '').split() + cflags_c)
cflags_cc = (os.environ.get('CPPFLAGS', '').split() +
os.environ.get('CXXFLAGS', '').split() + cflags_cc)
elif self.toolset == 'host':
cflags_c = (os.environ.get('CPPFLAGS_host', '').split() +
os.environ.get('CFLAGS_host', '').split() + cflags_c)
cflags_cc = (os.environ.get('CPPFLAGS_host', '').split() +
os.environ.get('CXXFLAGS_host', '').split() + cflags_cc)
defines = config.get('defines', []) + extra_defines
self.WriteVariableList(ninja_file, 'defines',
[Define(d, self.flavor) for d in defines])
if self.flavor == 'win':
self.WriteVariableList(ninja_file, 'asmflags',
map(self.ExpandSpecial, asmflags))
self.WriteVariableList(ninja_file, 'rcflags',
[QuoteShellArgument(self.ExpandSpecial(f), self.flavor)
for f in self.msvs_settings.GetRcflags(config_name,
self.GypPathToNinja)])
include_dirs = config.get('include_dirs', [])
env = self.GetToolchainEnv()
if self.flavor == 'win':
include_dirs = self.msvs_settings.AdjustIncludeDirs(include_dirs,
config_name)
self.WriteVariableList(ninja_file, 'includes',
[QuoteShellArgument('-I' + self.GypPathToNinja(i, env), self.flavor)
for i in include_dirs])
if self.flavor == 'win':
midl_include_dirs = config.get('midl_include_dirs', [])
midl_include_dirs = self.msvs_settings.AdjustMidlIncludeDirs(
midl_include_dirs, config_name)
self.WriteVariableList(ninja_file, 'midl_includes',
[QuoteShellArgument('-I' + self.GypPathToNinja(i, env), self.flavor)
for i in midl_include_dirs])
pch_commands = precompiled_header.GetPchBuildCommands(arch)
if self.flavor == 'mac':
# Most targets use no precompiled headers, so only write these if needed.
for ext, var in [('c', 'cflags_pch_c'), ('cc', 'cflags_pch_cc'),
('m', 'cflags_pch_objc'), ('mm', 'cflags_pch_objcc')]:
include = precompiled_header.GetInclude(ext, arch)
if include: ninja_file.variable(var, include)
arflags = config.get('arflags', [])
self.WriteVariableList(ninja_file, 'cflags',
map(self.ExpandSpecial, cflags))
self.WriteVariableList(ninja_file, 'cflags_c',
map(self.ExpandSpecial, cflags_c))
self.WriteVariableList(ninja_file, 'cflags_cc',
map(self.ExpandSpecial, cflags_cc))
if self.flavor == 'mac':
self.WriteVariableList(ninja_file, 'cflags_objc',
map(self.ExpandSpecial, cflags_objc))
self.WriteVariableList(ninja_file, 'cflags_objcc',
map(self.ExpandSpecial, cflags_objcc))
self.WriteVariableList(ninja_file, 'arflags',
map(self.ExpandSpecial, arflags))
ninja_file.newline()
outputs = []
has_rc_source = False
for source in sources:
filename, ext = os.path.splitext(source)
ext = ext[1:]
obj_ext = self.obj_ext
if ext in ('cc', 'cpp', 'cxx'):
command = 'cxx'
self.uses_cpp = True
elif ext == 'c' or (ext == 'S' and self.flavor != 'win'):
command = 'cc'
elif ext == 's' and self.flavor != 'win': # Doesn't generate .o.d files.
command = 'cc_s'
elif (self.flavor == 'win' and ext == 'asm' and
not self.msvs_settings.HasExplicitAsmRules(spec)):
command = 'asm'
# Add the _asm suffix as msvs is capable of handling .cc and
# .asm files of the same name without collision.
obj_ext = '_asm.obj'
elif self.flavor == 'mac' and ext == 'm':
command = 'objc'
elif self.flavor == 'mac' and ext == 'mm':
command = 'objcxx'
self.uses_cpp = True
elif self.flavor == 'win' and ext == 'rc':
command = 'rc'
obj_ext = '.res'
has_rc_source = True
else:
# Ignore unhandled extensions.
continue
input = self.GypPathToNinja(source)
output = self.GypPathToUniqueOutput(filename + obj_ext)
if arch is not None:
output = AddArch(output, arch)
implicit = precompiled_header.GetObjDependencies([input], [output], arch)
variables = []
if self.flavor == 'win':
variables, output, implicit = precompiled_header.GetFlagsModifications(
input, output, implicit, command, cflags_c, cflags_cc,
self.ExpandSpecial)
ninja_file.build(output, command, input,
implicit=[gch for _, _, gch in implicit],
order_only=predepends, variables=variables)
outputs.append(output)
if has_rc_source:
resource_include_dirs = config.get('resource_include_dirs', include_dirs)
self.WriteVariableList(ninja_file, 'resource_includes',
[QuoteShellArgument('-I' + self.GypPathToNinja(i, env), self.flavor)
for i in resource_include_dirs])
self.WritePchTargets(ninja_file, pch_commands)
ninja_file.newline()
return outputs
def WritePchTargets(self, ninja_file, pch_commands):
"""Writes ninja rules to compile prefix headers."""
if not pch_commands:
return
for gch, lang_flag, lang, input in pch_commands:
var_name = {
'c': 'cflags_pch_c',
'cc': 'cflags_pch_cc',
'm': 'cflags_pch_objc',
'mm': 'cflags_pch_objcc',
}[lang]
map = { 'c': 'cc', 'cc': 'cxx', 'm': 'objc', 'mm': 'objcxx', }
cmd = map.get(lang)
ninja_file.build(gch, cmd, input, variables=[(var_name, lang_flag)])
def WriteLink(self, spec, config_name, config, link_deps):
"""Write out a link step. Fills out target.binary. """
if self.flavor != 'mac' or len(self.archs) == 1:
return self.WriteLinkForArch(
self.ninja, spec, config_name, config, link_deps)
else:
output = self.ComputeOutput(spec)
inputs = [self.WriteLinkForArch(self.arch_subninjas[arch], spec,
config_name, config, link_deps[arch],
arch=arch)
for arch in self.archs]
extra_bindings = []
build_output = output
if not self.is_mac_bundle:
self.AppendPostbuildVariable(extra_bindings, spec, output, output)
# TODO(yyanagisawa): more work needed to fix:
# https://code.google.com/p/gyp/issues/detail?id=411
if (spec['type'] in ('shared_library', 'loadable_module') and
not self.is_mac_bundle):
extra_bindings.append(('lib', output))
self.ninja.build([output, output + '.TOC'], 'solipo', inputs,
variables=extra_bindings)
else:
self.ninja.build(build_output, 'lipo', inputs, variables=extra_bindings)
return output
def WriteLinkForArch(self, ninja_file, spec, config_name, config,
link_deps, arch=None):
"""Write out a link step. Fills out target.binary. """
command = {
'executable': 'link',
'loadable_module': 'solink_module',
'shared_library': 'solink',
}[spec['type']]
command_suffix = ''
implicit_deps = set()
solibs = set()
order_deps = set()
if 'dependencies' in spec:
# Two kinds of dependencies:
# - Linkable dependencies (like a .a or a .so): add them to the link line.
# - Non-linkable dependencies (like a rule that generates a file
# and writes a stamp file): add them to implicit_deps
extra_link_deps = set()
for dep in spec['dependencies']:
target = self.target_outputs.get(dep)
if not target:
continue
linkable = target.Linkable()
if linkable:
new_deps = []
if (self.flavor == 'win' and
target.component_objs and
self.msvs_settings.IsUseLibraryDependencyInputs(config_name)):
new_deps = target.component_objs
if target.compile_deps:
order_deps.add(target.compile_deps)
elif self.flavor == 'win' and target.import_lib:
new_deps = [target.import_lib]
elif target.UsesToc(self.flavor):
solibs.add(target.binary)
implicit_deps.add(target.binary + '.TOC')
else:
new_deps = [target.binary]
for new_dep in new_deps:
if new_dep not in extra_link_deps:
extra_link_deps.add(new_dep)
link_deps.append(new_dep)
final_output = target.FinalOutput()
if not linkable or final_output != target.binary:
implicit_deps.add(final_output)
extra_bindings = []
if self.uses_cpp and self.flavor != 'win':
extra_bindings.append(('ld', '$ldxx'))
output = self.ComputeOutput(spec, arch)
if arch is None and not self.is_mac_bundle:
self.AppendPostbuildVariable(extra_bindings, spec, output, output)
is_executable = spec['type'] == 'executable'
# The ldflags config key is not used on mac or win. On those platforms
# linker flags are set via xcode_settings and msvs_settings, respectively.
env_ldflags = os.environ.get('LDFLAGS', '').split()
if self.flavor == 'mac':
ldflags = self.xcode_settings.GetLdflags(config_name,
self.ExpandSpecial(generator_default_variables['PRODUCT_DIR']),
self.GypPathToNinja, arch)
ldflags = env_ldflags + ldflags
elif self.flavor == 'win':
manifest_base_name = self.GypPathToUniqueOutput(
self.ComputeOutputFileName(spec))
ldflags, intermediate_manifest, manifest_files = \
self.msvs_settings.GetLdflags(config_name, self.GypPathToNinja,
self.ExpandSpecial, manifest_base_name,
output, is_executable,
self.toplevel_build)
ldflags = env_ldflags + ldflags
self.WriteVariableList(ninja_file, 'manifests', manifest_files)
implicit_deps = implicit_deps.union(manifest_files)
if intermediate_manifest:
self.WriteVariableList(
ninja_file, 'intermediatemanifest', [intermediate_manifest])
command_suffix = _GetWinLinkRuleNameSuffix(
self.msvs_settings.IsEmbedManifest(config_name))
def_file = self.msvs_settings.GetDefFile(self.GypPathToNinja)
if def_file:
implicit_deps.add(def_file)
else:
# Respect environment variables related to build, but target-specific
# flags can still override them.
ldflags = env_ldflags + config.get('ldflags', [])
if is_executable and len(solibs):
rpath = 'lib/'
if self.toolset != 'target':
rpath += self.toolset
ldflags.append(r'-Wl,-rpath=\$$ORIGIN/%s' % rpath)
ldflags.append('-Wl,-rpath-link=%s' % rpath)
self.WriteVariableList(ninja_file, 'ldflags',
map(self.ExpandSpecial, ldflags))
library_dirs = config.get('library_dirs', [])
if self.flavor == 'win':
library_dirs = [self.msvs_settings.ConvertVSMacros(l, config_name)
for l in library_dirs]
library_dirs = ['/LIBPATH:' + QuoteShellArgument(self.GypPathToNinja(l),
self.flavor)
for l in library_dirs]
else:
library_dirs = [QuoteShellArgument('-L' + self.GypPathToNinja(l),
self.flavor)
for l in library_dirs]
libraries = gyp.common.uniquer(map(self.ExpandSpecial,
spec.get('libraries', [])))
if self.flavor == 'mac':
libraries = self.xcode_settings.AdjustLibraries(libraries, config_name)
elif self.flavor == 'win':
libraries = self.msvs_settings.AdjustLibraries(libraries)
self.WriteVariableList(ninja_file, 'libs', library_dirs + libraries)
linked_binary = output
if command in ('solink', 'solink_module'):
extra_bindings.append(('soname', os.path.split(output)[1]))
extra_bindings.append(('lib',
gyp.common.EncodePOSIXShellArgument(output)))
if self.flavor != 'win':
link_file_list = output
if self.is_mac_bundle:
# 'Dependency Framework.framework/Versions/A/Dependency Framework' ->
# 'Dependency Framework.framework.rsp'
link_file_list = self.xcode_settings.GetWrapperName()
if arch:
link_file_list += '.' + arch
link_file_list += '.rsp'
# If an rspfile contains spaces, ninja surrounds the filename with
# quotes around it and then passes it to open(), creating a file with
# quotes in its name (and when looking for the rsp file, the name
# makes it through bash which strips the quotes) :-/
link_file_list = link_file_list.replace(' ', '_')
extra_bindings.append(
('link_file_list',
gyp.common.EncodePOSIXShellArgument(link_file_list)))
if self.flavor == 'win':
extra_bindings.append(('binary', output))
if ('/NOENTRY' not in ldflags and
not self.msvs_settings.GetNoImportLibrary(config_name)):
self.target.import_lib = output + '.lib'
extra_bindings.append(('implibflag',
'/IMPLIB:%s' % self.target.import_lib))
pdbname = self.msvs_settings.GetPDBName(
config_name, self.ExpandSpecial, output + '.pdb')
output = [output, self.target.import_lib]
if pdbname:
output.append(pdbname)
elif not self.is_mac_bundle:
output = [output, output + '.TOC']
else:
command = command + '_notoc'
elif self.flavor == 'win':
extra_bindings.append(('binary', output))
pdbname = self.msvs_settings.GetPDBName(
config_name, self.ExpandSpecial, output + '.pdb')
if pdbname:
output = [output, pdbname]
if len(solibs):
extra_bindings.append(('solibs', gyp.common.EncodePOSIXShellList(solibs)))
ninja_file.build(output, command + command_suffix, link_deps,
implicit=list(implicit_deps),
order_only=list(order_deps),
variables=extra_bindings)
return linked_binary
def WriteTarget(self, spec, config_name, config, link_deps, compile_deps):
extra_link_deps = any(self.target_outputs.get(dep).Linkable()
for dep in spec.get('dependencies', [])
if dep in self.target_outputs)
if spec['type'] == 'none' or (not link_deps and not extra_link_deps):
# TODO(evan): don't call this function for 'none' target types, as
# it doesn't do anything, and we fake out a 'binary' with a stamp file.
self.target.binary = compile_deps
self.target.type = 'none'
elif spec['type'] == 'static_library':
self.target.binary = self.ComputeOutput(spec)
if (self.flavor not in ('mac', 'openbsd', 'netbsd', 'win') and not
self.is_standalone_static_library):
self.ninja.build(self.target.binary, 'alink_thin', link_deps,
order_only=compile_deps)
else:
variables = []
if self.xcode_settings:
libtool_flags = self.xcode_settings.GetLibtoolflags(config_name)
if libtool_flags:
variables.append(('libtool_flags', libtool_flags))
if self.msvs_settings:
libflags = self.msvs_settings.GetLibFlags(config_name,
self.GypPathToNinja)
variables.append(('libflags', libflags))
if self.flavor != 'mac' or len(self.archs) == 1:
self.AppendPostbuildVariable(variables, spec,
self.target.binary, self.target.binary)
self.ninja.build(self.target.binary, 'alink', link_deps,
order_only=compile_deps, variables=variables)
else:
inputs = []
for arch in self.archs:
output = self.ComputeOutput(spec, arch)
self.arch_subninjas[arch].build(output, 'alink', link_deps[arch],
order_only=compile_deps,
variables=variables)
inputs.append(output)
# TODO: It's not clear if libtool_flags should be passed to the alink
# call that combines single-arch .a files into a fat .a file.
self.AppendPostbuildVariable(variables, spec,
self.target.binary, self.target.binary)
self.ninja.build(self.target.binary, 'alink', inputs,
# FIXME: test proving order_only=compile_deps isn't
# needed.
variables=variables)
else:
self.target.binary = self.WriteLink(spec, config_name, config, link_deps)
return self.target.binary
def WriteMacBundle(self, spec, mac_bundle_depends, is_empty):
assert self.is_mac_bundle
package_framework = spec['type'] in ('shared_library', 'loadable_module')
output = self.ComputeMacBundleOutput()
if is_empty:
output += '.stamp'
variables = []
self.AppendPostbuildVariable(variables, spec, output, self.target.binary,
is_command_start=not package_framework)
if package_framework and not is_empty:
variables.append(('version', self.xcode_settings.GetFrameworkVersion()))
self.ninja.build(output, 'package_framework', mac_bundle_depends,
variables=variables)
else:
self.ninja.build(output, 'stamp', mac_bundle_depends,
variables=variables)
self.target.bundle = output
return output
def GetToolchainEnv(self, additional_settings=None):
"""Returns the variables toolchain would set for build steps."""
env = self.GetSortedXcodeEnv(additional_settings=additional_settings)
if self.flavor == 'win':
env = self.GetMsvsToolchainEnv(
additional_settings=additional_settings)
return env
def GetMsvsToolchainEnv(self, additional_settings=None):
"""Returns the variables Visual Studio would set for build steps."""
return self.msvs_settings.GetVSMacroEnv('$!PRODUCT_DIR',
config=self.config_name)
def GetSortedXcodeEnv(self, additional_settings=None):
"""Returns the variables Xcode would set for build steps."""
assert self.abs_build_dir
abs_build_dir = self.abs_build_dir
return gyp.xcode_emulation.GetSortedXcodeEnv(
self.xcode_settings, abs_build_dir,
os.path.join(abs_build_dir, self.build_to_base), self.config_name,
additional_settings)
def GetSortedXcodePostbuildEnv(self):
"""Returns the variables Xcode would set for postbuild steps."""
postbuild_settings = {}
# CHROMIUM_STRIP_SAVE_FILE is a chromium-specific hack.
# TODO(thakis): It would be nice to have some general mechanism instead.
strip_save_file = self.xcode_settings.GetPerTargetSetting(
'CHROMIUM_STRIP_SAVE_FILE')
if strip_save_file:
postbuild_settings['CHROMIUM_STRIP_SAVE_FILE'] = strip_save_file
return self.GetSortedXcodeEnv(additional_settings=postbuild_settings)
def AppendPostbuildVariable(self, variables, spec, output, binary,
is_command_start=False):
"""Adds a 'postbuild' variable if there is a postbuild for |output|."""
postbuild = self.GetPostbuildCommand(spec, output, binary, is_command_start)
if postbuild:
variables.append(('postbuilds', postbuild))
def GetPostbuildCommand(self, spec, output, output_binary, is_command_start):
"""Returns a shell command that runs all the postbuilds, and removes
|output| if any of them fails. If |is_command_start| is False, then the
returned string will start with ' && '."""
if not self.xcode_settings or spec['type'] == 'none' or not output:
return ''
output = QuoteShellArgument(output, self.flavor)
postbuilds = gyp.xcode_emulation.GetSpecPostbuildCommands(spec, quiet=True)
if output_binary is not None:
postbuilds = self.xcode_settings.AddImplicitPostbuilds(
self.config_name,
os.path.normpath(os.path.join(self.base_to_build, output)),
QuoteShellArgument(
os.path.normpath(os.path.join(self.base_to_build, output_binary)),
self.flavor),
postbuilds, quiet=True)
if not postbuilds:
return ''
# Postbuilds expect to be run in the gyp file's directory, so insert an
# implicit postbuild to cd to there.
postbuilds.insert(0, gyp.common.EncodePOSIXShellList(
['cd', self.build_to_base]))
env = self.ComputeExportEnvString(self.GetSortedXcodePostbuildEnv())
# G will be non-null if any postbuild fails. Run all postbuilds in a
# subshell.
commands = env + ' (' + \
' && '.join([ninja_syntax.escape(command) for command in postbuilds])
command_string = (commands + '); G=$$?; '
# Remove the final output if any postbuild failed.
'((exit $$G) || rm -rf %s) ' % output + '&& exit $$G)')
if is_command_start:
return '(' + command_string + ' && '
else:
return '$ && (' + command_string
def ComputeExportEnvString(self, env):
"""Given an environment, returns a string looking like
'export FOO=foo; export BAR="${FOO} bar;'
that exports |env| to the shell."""
export_str = []
for k, v in env:
export_str.append('export %s=%s;' %
(k, ninja_syntax.escape(gyp.common.EncodePOSIXShellArgument(v))))
return ' '.join(export_str)
def ComputeMacBundleOutput(self):
"""Return the 'output' (full output path) to a bundle output directory."""
assert self.is_mac_bundle
path = generator_default_variables['PRODUCT_DIR']
return self.ExpandSpecial(
os.path.join(path, self.xcode_settings.GetWrapperName()))
def ComputeOutputFileName(self, spec, type=None):
"""Compute the filename of the final output for the current target."""
if not type:
type = spec['type']
default_variables = copy.copy(generator_default_variables)
CalculateVariables(default_variables, {'flavor': self.flavor})
# Compute filename prefix: the product prefix, or a default for
# the product type.
DEFAULT_PREFIX = {
'loadable_module': default_variables['SHARED_LIB_PREFIX'],
'shared_library': default_variables['SHARED_LIB_PREFIX'],
'static_library': default_variables['STATIC_LIB_PREFIX'],
'executable': default_variables['EXECUTABLE_PREFIX'],
}
prefix = spec.get('product_prefix', DEFAULT_PREFIX.get(type, ''))
# Compute filename extension: the product extension, or a default
# for the product type.
DEFAULT_EXTENSION = {
'loadable_module': default_variables['SHARED_LIB_SUFFIX'],
'shared_library': default_variables['SHARED_LIB_SUFFIX'],
'static_library': default_variables['STATIC_LIB_SUFFIX'],
'executable': default_variables['EXECUTABLE_SUFFIX'],
}
extension = spec.get('product_extension')
if extension:
extension = '.' + extension
else:
extension = DEFAULT_EXTENSION.get(type, '')
if 'product_name' in spec:
# If we were given an explicit name, use that.
target = spec['product_name']
else:
# Otherwise, derive a name from the target name.
target = spec['target_name']
if prefix == 'lib':
# Snip out an extra 'lib' from libs if appropriate.
target = StripPrefix(target, 'lib')
if type in ('static_library', 'loadable_module', 'shared_library',
'executable'):
return '%s%s%s' % (prefix, target, extension)
elif type == 'none':
return '%s.stamp' % target
else:
raise Exception('Unhandled output type %s' % type)
def ComputeOutput(self, spec, arch=None):
"""Compute the path for the final output of the spec."""
type = spec['type']
if self.flavor == 'win':
override = self.msvs_settings.GetOutputName(self.config_name,
self.ExpandSpecial)
if override:
return override
if arch is None and self.flavor == 'mac' and type in (
'static_library', 'executable', 'shared_library', 'loadable_module'):
filename = self.xcode_settings.GetExecutablePath()
else:
filename = self.ComputeOutputFileName(spec, type)
if arch is None and 'product_dir' in spec:
path = os.path.join(spec['product_dir'], filename)
return self.ExpandSpecial(path)
# Some products go into the output root, libraries go into shared library
# dir, and everything else goes into the normal place.
type_in_output_root = ['executable', 'loadable_module']
if self.flavor == 'mac' and self.toolset == 'target':
type_in_output_root += ['shared_library', 'static_library']
elif self.flavor == 'win' and self.toolset == 'target':
type_in_output_root += ['shared_library']
if arch is not None:
# Make sure partial executables don't end up in a bundle or the regular
# output directory.
archdir = 'arch'
if self.toolset != 'target':
archdir = os.path.join('arch', '%s' % self.toolset)
return os.path.join(archdir, AddArch(filename, arch))
elif type in type_in_output_root or self.is_standalone_static_library:
return filename
elif type == 'shared_library':
libdir = 'lib'
if self.toolset != 'target':
libdir = os.path.join('lib', '%s' % self.toolset)
return os.path.join(libdir, filename)
else:
return self.GypPathToUniqueOutput(filename, qualified=False)
def WriteVariableList(self, ninja_file, var, values):
assert not isinstance(values, str)
if values is None:
values = []
ninja_file.variable(var, ' '.join(values))
def WriteNewNinjaRule(self, name, args, description, is_cygwin, env, pool,
depfile=None):
"""Write out a new ninja "rule" statement for a given command.
Returns the name of the new rule, and a copy of |args| with variables
expanded."""
if self.flavor == 'win':
args = [self.msvs_settings.ConvertVSMacros(
arg, self.base_to_build, config=self.config_name)
for arg in args]
description = self.msvs_settings.ConvertVSMacros(
description, config=self.config_name)
elif self.flavor == 'mac':
# |env| is an empty list on non-mac.
args = [gyp.xcode_emulation.ExpandEnvVars(arg, env) for arg in args]
description = gyp.xcode_emulation.ExpandEnvVars(description, env)
# TODO: we shouldn't need to qualify names; we do it because
# currently the ninja rule namespace is global, but it really
# should be scoped to the subninja.
rule_name = self.name
if self.toolset == 'target':
rule_name += '.' + self.toolset
rule_name += '.' + name
rule_name = re.sub('[^a-zA-Z0-9_]', '_', rule_name)
# Remove variable references, but not if they refer to the magic rule
# variables. This is not quite right, as it also protects these for
# actions, not just for rules where they are valid. Good enough.
protect = [ '${root}', '${dirname}', '${source}', '${ext}', '${name}' ]
protect = '(?!' + '|'.join(map(re.escape, protect)) + ')'
description = re.sub(protect + r'\$', '_', description)
# gyp dictates that commands are run from the base directory.
# cd into the directory before running, and adjust paths in
# the arguments to point to the proper locations.
rspfile = None
rspfile_content = None
args = [self.ExpandSpecial(arg, self.base_to_build) for arg in args]
if self.flavor == 'win':
rspfile = rule_name + '.$unique_name.rsp'
# The cygwin case handles this inside the bash sub-shell.
run_in = '' if is_cygwin else ' ' + self.build_to_base
if is_cygwin:
rspfile_content = self.msvs_settings.BuildCygwinBashCommandLine(
args, self.build_to_base)
else:
rspfile_content = gyp.msvs_emulation.EncodeRspFileList(args)
command = ('%s gyp-win-tool action-wrapper $arch ' % sys.executable +
rspfile + run_in)
else:
env = self.ComputeExportEnvString(env)
command = gyp.common.EncodePOSIXShellList(args)
command = 'cd %s; ' % self.build_to_base + env + command
# GYP rules/actions express being no-ops by not touching their outputs.
# Avoid executing downstream dependencies in this case by specifying
# restat=1 to ninja.
self.ninja.rule(rule_name, command, description, depfile=depfile,
restat=True, pool=pool,
rspfile=rspfile, rspfile_content=rspfile_content)
self.ninja.newline()
return rule_name, args
def CalculateVariables(default_variables, params):
"""Calculate additional variables for use in the build (called by gyp)."""
global generator_additional_non_configuration_keys
global generator_additional_path_sections
flavor = gyp.common.GetFlavor(params)
if flavor == 'mac':
default_variables.setdefault('OS', 'mac')
default_variables.setdefault('SHARED_LIB_SUFFIX', '.dylib')
default_variables.setdefault('SHARED_LIB_DIR',
generator_default_variables['PRODUCT_DIR'])
default_variables.setdefault('LIB_DIR',
generator_default_variables['PRODUCT_DIR'])
# Copy additional generator configuration data from Xcode, which is shared
# by the Mac Ninja generator.
import gyp.generator.xcode as xcode_generator
generator_additional_non_configuration_keys = getattr(xcode_generator,
'generator_additional_non_configuration_keys', [])
generator_additional_path_sections = getattr(xcode_generator,
'generator_additional_path_sections', [])
global generator_extra_sources_for_rules
generator_extra_sources_for_rules = getattr(xcode_generator,
'generator_extra_sources_for_rules', [])
elif flavor == 'win':
exts = gyp.MSVSUtil.TARGET_TYPE_EXT
default_variables.setdefault('OS', 'win')
default_variables['EXECUTABLE_SUFFIX'] = '.' + exts['executable']
default_variables['STATIC_LIB_PREFIX'] = ''
default_variables['STATIC_LIB_SUFFIX'] = '.' + exts['static_library']
default_variables['SHARED_LIB_PREFIX'] = ''
default_variables['SHARED_LIB_SUFFIX'] = '.' + exts['shared_library']
# Copy additional generator configuration data from VS, which is shared
# by the Windows Ninja generator.
import gyp.generator.msvs as msvs_generator
generator_additional_non_configuration_keys = getattr(msvs_generator,
'generator_additional_non_configuration_keys', [])
generator_additional_path_sections = getattr(msvs_generator,
'generator_additional_path_sections', [])
gyp.msvs_emulation.CalculateCommonVariables(default_variables, params)
else:
operating_system = flavor
if flavor == 'android':
operating_system = 'linux' # Keep this legacy behavior for now.
default_variables.setdefault('OS', operating_system)
default_variables.setdefault('SHARED_LIB_SUFFIX', '.so')
default_variables.setdefault('SHARED_LIB_DIR',
os.path.join('$!PRODUCT_DIR', 'lib'))
default_variables.setdefault('LIB_DIR',
os.path.join('$!PRODUCT_DIR', 'obj'))
def ComputeOutputDir(params):
"""Returns the path from the toplevel_dir to the build output directory."""
# generator_dir: relative path from pwd to where make puts build files.
# Makes migrating from make to ninja easier, ninja doesn't put anything here.
generator_dir = os.path.relpath(params['options'].generator_output or '.')
# output_dir: relative path from generator_dir to the build directory.
output_dir = params.get('generator_flags', {}).get('output_dir', 'out')
# Relative path from source root to our output files. e.g. "out"
return os.path.normpath(os.path.join(generator_dir, output_dir))
def CalculateGeneratorInputInfo(params):
"""Called by __init__ to initialize generator values based on params."""
# E.g. "out/gypfiles"
toplevel = params['options'].toplevel_dir
qualified_out_dir = os.path.normpath(os.path.join(
toplevel, ComputeOutputDir(params), 'gypfiles'))
global generator_filelist_paths
generator_filelist_paths = {
'toplevel': toplevel,
'qualified_out_dir': qualified_out_dir,
}
def OpenOutput(path, mode='w'):
"""Open |path| for writing, creating directories if necessary."""
gyp.common.EnsureDirExists(path)
return open(path, mode)
def CommandWithWrapper(cmd, wrappers, prog):
wrapper = wrappers.get(cmd, '')
if wrapper:
return wrapper + ' ' + prog
return prog
def GetDefaultConcurrentLinks():
"""Returns a best-guess for a number of concurrent links."""
pool_size = int(os.environ.get('GYP_LINK_CONCURRENCY', 0))
if pool_size:
return pool_size
if sys.platform in ('win32', 'cygwin'):
import ctypes
class MEMORYSTATUSEX(ctypes.Structure):
_fields_ = [
("dwLength", ctypes.c_ulong),
("dwMemoryLoad", ctypes.c_ulong),
("ullTotalPhys", ctypes.c_ulonglong),
("ullAvailPhys", ctypes.c_ulonglong),
("ullTotalPageFile", ctypes.c_ulonglong),
("ullAvailPageFile", ctypes.c_ulonglong),
("ullTotalVirtual", ctypes.c_ulonglong),
("ullAvailVirtual", ctypes.c_ulonglong),
("sullAvailExtendedVirtual", ctypes.c_ulonglong),
]
stat = MEMORYSTATUSEX()
stat.dwLength = ctypes.sizeof(stat)
ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat))
# VS 2015 uses 20% more working set than VS 2013 and can consume all RAM
# on a 64 GB machine.
mem_limit = max(1, stat.ullTotalPhys / (5 * (2 ** 30))) # total / 5GB
hard_cap = max(1, int(os.environ.get('GYP_LINK_CONCURRENCY_MAX', 2**32)))
return min(mem_limit, hard_cap)
elif sys.platform.startswith('linux'):
if os.path.exists("/proc/meminfo"):
with open("/proc/meminfo") as meminfo:
memtotal_re = re.compile(r'^MemTotal:\s*(\d*)\s*kB')
for line in meminfo:
match = memtotal_re.match(line)
if not match:
continue
# Allow 8Gb per link on Linux because Gold is quite memory hungry
return max(1, int(match.group(1)) / (8 * (2 ** 20)))
return 1
elif sys.platform == 'darwin':
try:
avail_bytes = int(subprocess.check_output(['sysctl', '-n', 'hw.memsize']))
# A static library debug build of Chromium's unit_tests takes ~2.7GB, so
# 4GB per ld process allows for some more bloat.
return max(1, avail_bytes / (4 * (2 ** 30))) # total / 4GB
except:
return 1
else:
# TODO(scottmg): Implement this for other platforms.
return 1
def _GetWinLinkRuleNameSuffix(embed_manifest):
"""Returns the suffix used to select an appropriate linking rule depending on
whether the manifest embedding is enabled."""
return '_embed' if embed_manifest else ''
def _AddWinLinkRules(master_ninja, embed_manifest):
"""Adds link rules for Windows platform to |master_ninja|."""
def FullLinkCommand(ldcmd, out, binary_type):
resource_name = {
'exe': '1',
'dll': '2',
}[binary_type]
return '%(python)s gyp-win-tool link-with-manifests $arch %(embed)s ' \
'%(out)s "%(ldcmd)s" %(resname)s $mt $rc "$intermediatemanifest" ' \
'$manifests' % {
'python': sys.executable,
'out': out,
'ldcmd': ldcmd,
'resname': resource_name,
'embed': embed_manifest }
rule_name_suffix = _GetWinLinkRuleNameSuffix(embed_manifest)
use_separate_mspdbsrv = (
int(os.environ.get('GYP_USE_SEPARATE_MSPDBSRV', '0')) != 0)
dlldesc = 'LINK%s(DLL) $binary' % rule_name_suffix.upper()
dllcmd = ('%s gyp-win-tool link-wrapper $arch %s '
'$ld /nologo $implibflag /DLL /OUT:$binary '
'@$binary.rsp' % (sys.executable, use_separate_mspdbsrv))
dllcmd = FullLinkCommand(dllcmd, '$binary', 'dll')
master_ninja.rule('solink' + rule_name_suffix,
description=dlldesc, command=dllcmd,
rspfile='$binary.rsp',
rspfile_content='$libs $in_newline $ldflags',
restat=True,
pool='link_pool')
master_ninja.rule('solink_module' + rule_name_suffix,
description=dlldesc, command=dllcmd,
rspfile='$binary.rsp',
rspfile_content='$libs $in_newline $ldflags',
restat=True,
pool='link_pool')
# Note that ldflags goes at the end so that it has the option of
# overriding default settings earlier in the command line.
exe_cmd = ('%s gyp-win-tool link-wrapper $arch %s '
'$ld /nologo /OUT:$binary @$binary.rsp' %
(sys.executable, use_separate_mspdbsrv))
exe_cmd = FullLinkCommand(exe_cmd, '$binary', 'exe')
master_ninja.rule('link' + rule_name_suffix,
description='LINK%s $binary' % rule_name_suffix.upper(),
command=exe_cmd,
rspfile='$binary.rsp',
rspfile_content='$in_newline $libs $ldflags',
pool='link_pool')
def GenerateOutputForConfig(target_list, target_dicts, data, params,
config_name):
options = params['options']
flavor = gyp.common.GetFlavor(params)
generator_flags = params.get('generator_flags', {})
# build_dir: relative path from source root to our output files.
# e.g. "out/Debug"
build_dir = os.path.normpath(
os.path.join(ComputeOutputDir(params), config_name))
toplevel_build = os.path.join(options.toplevel_dir, build_dir)
master_ninja_file = OpenOutput(os.path.join(toplevel_build, 'build.ninja'))
master_ninja = ninja_syntax.Writer(master_ninja_file, width=120)
# Put build-time support tools in out/{config_name}.
gyp.common.CopyTool(flavor, toplevel_build)
# Grab make settings for CC/CXX.
# The rules are
# - The priority from low to high is gcc/g++, the 'make_global_settings' in
# gyp, the environment variable.
# - If there is no 'make_global_settings' for CC.host/CXX.host or
# 'CC_host'/'CXX_host' enviroment variable, cc_host/cxx_host should be set
# to cc/cxx.
if flavor == 'win':
ar = 'lib.exe'
# cc and cxx must be set to the correct architecture by overriding with one
# of cl_x86 or cl_x64 below.
cc = 'UNSET'
cxx = 'UNSET'
ld = 'link.exe'
ld_host = '$ld'
else:
ar = 'ar'
cc = 'cc'
cxx = 'c++'
ld = '$cc'
ldxx = '$cxx'
ld_host = '$cc_host'
ldxx_host = '$cxx_host'
ar_host = 'ar'
cc_host = None
cxx_host = None
cc_host_global_setting = None
cxx_host_global_setting = None
clang_cl = None
nm = 'nm'
nm_host = 'nm'
readelf = 'readelf'
readelf_host = 'readelf'
build_file, _, _ = gyp.common.ParseQualifiedTarget(target_list[0])
make_global_settings = data[build_file].get('make_global_settings', [])
build_to_root = gyp.common.InvertRelativePath(build_dir,
options.toplevel_dir)
wrappers = {}
for key, value in make_global_settings:
if key == 'AR':
ar = os.path.join(build_to_root, value)
if key == 'AR.host':
ar_host = os.path.join(build_to_root, value)
if key == 'CC':
cc = os.path.join(build_to_root, value)
if cc.endswith('clang-cl'):
clang_cl = cc
if key == 'CXX':
cxx = os.path.join(build_to_root, value)
if key == 'CC.host':
cc_host = os.path.join(build_to_root, value)
cc_host_global_setting = value
if key == 'CXX.host':
cxx_host = os.path.join(build_to_root, value)
cxx_host_global_setting = value
if key == 'LD':
ld = os.path.join(build_to_root, value)
if key == 'LD.host':
ld_host = os.path.join(build_to_root, value)
if key == 'NM':
nm = os.path.join(build_to_root, value)
if key == 'NM.host':
nm_host = os.path.join(build_to_root, value)
if key == 'READELF':
readelf = os.path.join(build_to_root, value)
if key == 'READELF.host':
readelf_host = os.path.join(build_to_root, value)
if key.endswith('_wrapper'):
wrappers[key[:-len('_wrapper')]] = os.path.join(build_to_root, value)
# Support wrappers from environment variables too.
for key, value in os.environ.iteritems():
if key.lower().endswith('_wrapper'):
key_prefix = key[:-len('_wrapper')]
key_prefix = re.sub(r'\.HOST$', '.host', key_prefix)
wrappers[key_prefix] = os.path.join(build_to_root, value)
if flavor == 'win':
configs = [target_dicts[qualified_target]['configurations'][config_name]
for qualified_target in target_list]
shared_system_includes = None
if not generator_flags.get('ninja_use_custom_environment_files', 0):
shared_system_includes = \
gyp.msvs_emulation.ExtractSharedMSVSSystemIncludes(
configs, generator_flags)
cl_paths = gyp.msvs_emulation.GenerateEnvironmentFiles(
toplevel_build, generator_flags, shared_system_includes, OpenOutput)
for arch, path in cl_paths.iteritems():
if clang_cl:
# If we have selected clang-cl, use that instead.
path = clang_cl
command = CommandWithWrapper('CC', wrappers,
QuoteShellArgument(path, 'win'))
if clang_cl:
# Use clang-cl to cross-compile for x86 or x86_64.
command += (' -m32' if arch == 'x86' else ' -m64')
master_ninja.variable('cl_' + arch, command)
cc = GetEnvironFallback(['CC_target', 'CC'], cc)
master_ninja.variable('cc', CommandWithWrapper('CC', wrappers, cc))
cxx = GetEnvironFallback(['CXX_target', 'CXX'], cxx)
master_ninja.variable('cxx', CommandWithWrapper('CXX', wrappers, cxx))
if flavor == 'win':
master_ninja.variable('ld', ld)
master_ninja.variable('idl', 'midl.exe')
master_ninja.variable('ar', ar)
master_ninja.variable('rc', 'rc.exe')
master_ninja.variable('ml_x86', 'ml.exe')
master_ninja.variable('ml_x64', 'ml64.exe')
master_ninja.variable('mt', 'mt.exe')
else:
master_ninja.variable('ld', CommandWithWrapper('LINK', wrappers, ld))
master_ninja.variable('ldxx', CommandWithWrapper('LINK', wrappers, ldxx))
master_ninja.variable('ar', GetEnvironFallback(['AR_target', 'AR'], ar))
if flavor != 'mac':
# Mac does not use readelf/nm for .TOC generation, so avoiding polluting
# the master ninja with extra unused variables.
master_ninja.variable(
'nm', GetEnvironFallback(['NM_target', 'NM'], nm))
master_ninja.variable(
'readelf', GetEnvironFallback(['READELF_target', 'READELF'], readelf))
if generator_supports_multiple_toolsets:
if not cc_host:
cc_host = cc
if not cxx_host:
cxx_host = cxx
master_ninja.variable('ar_host', GetEnvironFallback(['AR_host'], ar_host))
master_ninja.variable('nm_host', GetEnvironFallback(['NM_host'], nm_host))
master_ninja.variable('readelf_host',
GetEnvironFallback(['READELF_host'], readelf_host))
cc_host = GetEnvironFallback(['CC_host'], cc_host)
cxx_host = GetEnvironFallback(['CXX_host'], cxx_host)
# The environment variable could be used in 'make_global_settings', like
# ['CC.host', '$(CC)'] or ['CXX.host', '$(CXX)'], transform them here.
if '$(CC)' in cc_host and cc_host_global_setting:
cc_host = cc_host_global_setting.replace('$(CC)', cc)
if '$(CXX)' in cxx_host and cxx_host_global_setting:
cxx_host = cxx_host_global_setting.replace('$(CXX)', cxx)
master_ninja.variable('cc_host',
CommandWithWrapper('CC.host', wrappers, cc_host))
master_ninja.variable('cxx_host',
CommandWithWrapper('CXX.host', wrappers, cxx_host))
if flavor == 'win':
master_ninja.variable('ld_host', ld_host)
else:
master_ninja.variable('ld_host', CommandWithWrapper(
'LINK', wrappers, ld_host))
master_ninja.variable('ldxx_host', CommandWithWrapper(
'LINK', wrappers, ldxx_host))
master_ninja.newline()
master_ninja.pool('link_pool', depth=GetDefaultConcurrentLinks())
master_ninja.newline()
deps = 'msvc' if flavor == 'win' else 'gcc'
if flavor != 'win':
master_ninja.rule(
'cc',
description='CC $out',
command=('$cc -MMD -MF $out.d $defines $includes $cflags $cflags_c '
'$cflags_pch_c -c $in -o $out'),
depfile='$out.d',
deps=deps)
master_ninja.rule(
'cc_s',
description='CC $out',
command=('$cc $defines $includes $cflags $cflags_c '
'$cflags_pch_c -c $in -o $out'))
master_ninja.rule(
'cxx',
description='CXX $out',
command=('$cxx -MMD -MF $out.d $defines $includes $cflags $cflags_cc '
'$cflags_pch_cc -c $in -o $out'),
depfile='$out.d',
deps=deps)
else:
# TODO(scottmg) Separate pdb names is a test to see if it works around
# http://crbug.com/142362. It seems there's a race between the creation of
# the .pdb by the precompiled header step for .cc and the compilation of
# .c files. This should be handled by mspdbsrv, but rarely errors out with
# c1xx : fatal error C1033: cannot open program database
# By making the rules target separate pdb files this might be avoided.
cc_command = ('ninja -t msvc -e $arch ' +
'-- '
'$cc /nologo /showIncludes /FC '
'@$out.rsp /c $in /Fo$out /Fd$pdbname_c ')
cxx_command = ('ninja -t msvc -e $arch ' +
'-- '
'$cxx /nologo /showIncludes /FC '
'@$out.rsp /c $in /Fo$out /Fd$pdbname_cc ')
master_ninja.rule(
'cc',
description='CC $out',
command=cc_command,
rspfile='$out.rsp',
rspfile_content='$defines $includes $cflags $cflags_c',
deps=deps)
master_ninja.rule(
'cxx',
description='CXX $out',
command=cxx_command,
rspfile='$out.rsp',
rspfile_content='$defines $includes $cflags $cflags_cc',
deps=deps)
master_ninja.rule(
'idl',
description='IDL $in',
command=('%s gyp-win-tool midl-wrapper $arch $outdir '
'$tlb $h $dlldata $iid $proxy $in '
'$midl_includes $idlflags' % sys.executable))
master_ninja.rule(
'rc',
description='RC $in',
# Note: $in must be last otherwise rc.exe complains.
command=('%s gyp-win-tool rc-wrapper '
'$arch $rc $defines $resource_includes $rcflags /fo$out $in' %
sys.executable))
master_ninja.rule(
'asm',
description='ASM $out',
command=('%s gyp-win-tool asm-wrapper '
'$arch $asm $defines $includes $asmflags /c /Fo $out $in' %
sys.executable))
if flavor != 'mac' and flavor != 'win':
master_ninja.rule(
'alink',
description='AR $out',
command='rm -f $out && $ar rcs $arflags $out $in')
master_ninja.rule(
'alink_thin',
description='AR $out',
command='rm -f $out && $ar rcsT $arflags $out $in')
# This allows targets that only need to depend on $lib's API to declare an
# order-only dependency on $lib.TOC and avoid relinking such downstream
# dependencies when $lib changes only in non-public ways.
# The resulting string leaves an uninterpolated %{suffix} which
# is used in the final substitution below.
mtime_preserving_solink_base = (
'if [ ! -e $lib -o ! -e $lib.TOC ]; then '
'%(solink)s && %(extract_toc)s > $lib.TOC; else '
'%(solink)s && %(extract_toc)s > $lib.tmp && '
'if ! cmp -s $lib.tmp $lib.TOC; then mv $lib.tmp $lib.TOC ; '
'fi; fi'
% { 'solink':
'$ld -shared $ldflags -o $lib -Wl,-soname=$soname %(suffix)s',
'extract_toc':
('{ $readelf -d $lib | grep SONAME ; '
'$nm -gD -f p $lib | cut -f1-2 -d\' \'; }')})
master_ninja.rule(
'solink',
description='SOLINK $lib',
restat=True,
command=mtime_preserving_solink_base % {'suffix': '@$link_file_list'},
rspfile='$link_file_list',
rspfile_content=
'-Wl,--whole-archive $in $solibs -Wl,--no-whole-archive $libs',
pool='link_pool')
master_ninja.rule(
'solink_module',
description='SOLINK(module) $lib',
restat=True,
command=mtime_preserving_solink_base % {'suffix': '@$link_file_list'},
rspfile='$link_file_list',
rspfile_content='-Wl,--start-group $in -Wl,--end-group $solibs $libs',
pool='link_pool')
master_ninja.rule(
'link',
description='LINK $out',
command=('$ld $ldflags -o $out '
'-Wl,--start-group $in -Wl,--end-group $solibs $libs'),
pool='link_pool')
elif flavor == 'win':
master_ninja.rule(
'alink',
description='LIB $out',
command=('%s gyp-win-tool link-wrapper $arch False '
'$ar /nologo /ignore:4221 /OUT:$out @$out.rsp' %
sys.executable),
rspfile='$out.rsp',
rspfile_content='$in_newline $libflags')
_AddWinLinkRules(master_ninja, embed_manifest=True)
_AddWinLinkRules(master_ninja, embed_manifest=False)
else:
master_ninja.rule(
'objc',
description='OBJC $out',
command=('$cc -MMD -MF $out.d $defines $includes $cflags $cflags_objc '
'$cflags_pch_objc -c $in -o $out'),
depfile='$out.d',
deps=deps)
master_ninja.rule(
'objcxx',
description='OBJCXX $out',
command=('$cxx -MMD -MF $out.d $defines $includes $cflags $cflags_objcc '
'$cflags_pch_objcc -c $in -o $out'),
depfile='$out.d',
deps=deps)
master_ninja.rule(
'alink',
description='LIBTOOL-STATIC $out, POSTBUILDS',
command='rm -f $out && '
'./gyp-mac-tool filter-libtool libtool $libtool_flags '
'-static -o $out $in'
'$postbuilds')
master_ninja.rule(
'lipo',
description='LIPO $out, POSTBUILDS',
command='rm -f $out && lipo -create $in -output $out$postbuilds')
master_ninja.rule(
'solipo',
description='SOLIPO $out, POSTBUILDS',
command=(
'rm -f $lib $lib.TOC && lipo -create $in -output $lib$postbuilds &&'
'%(extract_toc)s > $lib.TOC'
% { 'extract_toc':
'{ otool -l $lib | grep LC_ID_DYLIB -A 5; '
'nm -gP $lib | cut -f1-2 -d\' \' | grep -v U$$; true; }'}))
# Record the public interface of $lib in $lib.TOC. See the corresponding
# comment in the posix section above for details.
solink_base = '$ld %(type)s $ldflags -o $lib %(suffix)s'
mtime_preserving_solink_base = (
'if [ ! -e $lib -o ! -e $lib.TOC ] || '
# Always force dependent targets to relink if this library
# reexports something. Handling this correctly would require
# recursive TOC dumping but this is rare in practice, so punt.
'otool -l $lib | grep -q LC_REEXPORT_DYLIB ; then '
'%(solink)s && %(extract_toc)s > $lib.TOC; '
'else '
'%(solink)s && %(extract_toc)s > $lib.tmp && '
'if ! cmp -s $lib.tmp $lib.TOC; then '
'mv $lib.tmp $lib.TOC ; '
'fi; '
'fi'
% { 'solink': solink_base,
'extract_toc':
'{ otool -l $lib | grep LC_ID_DYLIB -A 5; '
'nm -gP $lib | cut -f1-2 -d\' \' | grep -v U$$; true; }'})
solink_suffix = '@$link_file_list$postbuilds'
master_ninja.rule(
'solink',
description='SOLINK $lib, POSTBUILDS',
restat=True,
command=mtime_preserving_solink_base % {'suffix': solink_suffix,
'type': '-shared'},
rspfile='$link_file_list',
rspfile_content='$in $solibs $libs',
pool='link_pool')
master_ninja.rule(
'solink_notoc',
description='SOLINK $lib, POSTBUILDS',
restat=True,
command=solink_base % {'suffix':solink_suffix, 'type': '-shared'},
rspfile='$link_file_list',
rspfile_content='$in $solibs $libs',
pool='link_pool')
master_ninja.rule(
'solink_module',
description='SOLINK(module) $lib, POSTBUILDS',
restat=True,
command=mtime_preserving_solink_base % {'suffix': solink_suffix,
'type': '-bundle'},
rspfile='$link_file_list',
rspfile_content='$in $solibs $libs',
pool='link_pool')
master_ninja.rule(
'solink_module_notoc',
description='SOLINK(module) $lib, POSTBUILDS',
restat=True,
command=solink_base % {'suffix': solink_suffix, 'type': '-bundle'},
rspfile='$link_file_list',
rspfile_content='$in $solibs $libs',
pool='link_pool')
master_ninja.rule(
'link',
description='LINK $out, POSTBUILDS',
command=('$ld $ldflags -o $out '
'$in $solibs $libs$postbuilds'),
pool='link_pool')
master_ninja.rule(
'preprocess_infoplist',
description='PREPROCESS INFOPLIST $out',
command=('$cc -E -P -Wno-trigraphs -x c $defines $in -o $out && '
'plutil -convert xml1 $out $out'))
master_ninja.rule(
'copy_infoplist',
description='COPY INFOPLIST $in',
command='$env ./gyp-mac-tool copy-info-plist $in $out $binary $keys')
master_ninja.rule(
'merge_infoplist',
description='MERGE INFOPLISTS $in',
command='$env ./gyp-mac-tool merge-info-plist $out $in')
master_ninja.rule(
'compile_xcassets',
description='COMPILE XCASSETS $in',
command='$env ./gyp-mac-tool compile-xcassets $keys $in')
master_ninja.rule(
'mac_tool',
description='MACTOOL $mactool_cmd $in',
command='$env ./gyp-mac-tool $mactool_cmd $in $out $binary')
master_ninja.rule(
'package_framework',
description='PACKAGE FRAMEWORK $out, POSTBUILDS',
command='./gyp-mac-tool package-framework $out $version$postbuilds '
'&& touch $out')
if flavor == 'win':
master_ninja.rule(
'stamp',
description='STAMP $out',
command='%s gyp-win-tool stamp $out' % sys.executable)
master_ninja.rule(
'copy',
description='COPY $in $out',
command='%s gyp-win-tool recursive-mirror $in $out' % sys.executable)
else:
master_ninja.rule(
'stamp',
description='STAMP $out',
command='${postbuilds}touch $out')
master_ninja.rule(
'copy',
description='COPY $in $out',
command='rm -rf $out && cp -af $in $out')
master_ninja.newline()
all_targets = set()
for build_file in params['build_files']:
for target in gyp.common.AllTargets(target_list,
target_dicts,
os.path.normpath(build_file)):
all_targets.add(target)
all_outputs = set()
# target_outputs is a map from qualified target name to a Target object.
target_outputs = {}
# target_short_names is a map from target short name to a list of Target
# objects.
target_short_names = {}
# short name of targets that were skipped because they didn't contain anything
# interesting.
# NOTE: there may be overlap between this an non_empty_target_names.
empty_target_names = set()
# Set of non-empty short target names.
# NOTE: there may be overlap between this an empty_target_names.
non_empty_target_names = set()
for qualified_target in target_list:
# qualified_target is like: third_party/icu/icu.gyp:icui18n#target
build_file, name, toolset = \
gyp.common.ParseQualifiedTarget(qualified_target)
this_make_global_settings = data[build_file].get('make_global_settings', [])
assert make_global_settings == this_make_global_settings, (
"make_global_settings needs to be the same for all targets. %s vs. %s" %
(this_make_global_settings, make_global_settings))
spec = target_dicts[qualified_target]
if flavor == 'mac':
gyp.xcode_emulation.MergeGlobalXcodeSettingsToSpec(data[build_file], spec)
# If build_file is a symlink, we must not follow it because there's a chance
# it could point to a path above toplevel_dir, and we cannot correctly deal
# with that case at the moment.
build_file = gyp.common.RelativePath(build_file, options.toplevel_dir,
False)
qualified_target_for_hash = gyp.common.QualifiedTarget(build_file, name,
toolset)
hash_for_rules = hashlib.md5(qualified_target_for_hash).hexdigest()
base_path = os.path.dirname(build_file)
obj = 'obj'
if toolset != 'target':
obj += '.' + toolset
output_file = os.path.join(obj, base_path, name + '.ninja')
ninja_output = StringIO()
writer = NinjaWriter(hash_for_rules, target_outputs, base_path, build_dir,
ninja_output,
toplevel_build, output_file,
flavor, toplevel_dir=options.toplevel_dir)
target = writer.WriteSpec(spec, config_name, generator_flags)
if ninja_output.tell() > 0:
# Only create files for ninja files that actually have contents.
with OpenOutput(os.path.join(toplevel_build, output_file)) as ninja_file:
ninja_file.write(ninja_output.getvalue())
ninja_output.close()
master_ninja.subninja(output_file)
if target:
if name != target.FinalOutput() and spec['toolset'] == 'target':
target_short_names.setdefault(name, []).append(target)
target_outputs[qualified_target] = target
if qualified_target in all_targets:
all_outputs.add(target.FinalOutput())
non_empty_target_names.add(name)
else:
empty_target_names.add(name)
if target_short_names:
# Write a short name to build this target. This benefits both the
# "build chrome" case as well as the gyp tests, which expect to be
# able to run actions and build libraries by their short name.
master_ninja.newline()
master_ninja.comment('Short names for targets.')
for short_name in target_short_names:
master_ninja.build(short_name, 'phony', [x.FinalOutput() for x in
target_short_names[short_name]])
# Write phony targets for any empty targets that weren't written yet. As
# short names are not necessarily unique only do this for short names that
# haven't already been output for another target.
empty_target_names = empty_target_names - non_empty_target_names
if empty_target_names:
master_ninja.newline()
master_ninja.comment('Empty targets (output for completeness).')
for name in sorted(empty_target_names):
master_ninja.build(name, 'phony')
if all_outputs:
master_ninja.newline()
master_ninja.build('all', 'phony', list(all_outputs))
master_ninja.default(generator_flags.get('default_target', 'all'))
master_ninja_file.close()
def PerformBuild(data, configurations, params):
options = params['options']
for config in configurations:
builddir = os.path.join(options.toplevel_dir, 'out', config)
arguments = ['ninja', '-C', builddir]
print 'Building [%s]: %s' % (config, arguments)
subprocess.check_call(arguments)
def CallGenerateOutputForConfig(arglist):
# Ignore the interrupt signal so that the parent process catches it and
# kills all multiprocessing children.
signal.signal(signal.SIGINT, signal.SIG_IGN)
(target_list, target_dicts, data, params, config_name) = arglist
GenerateOutputForConfig(target_list, target_dicts, data, params, config_name)
def GenerateOutput(target_list, target_dicts, data, params):
# Update target_dicts for iOS device builds.
target_dicts = gyp.xcode_emulation.CloneConfigurationForDeviceAndEmulator(
target_dicts)
user_config = params.get('generator_flags', {}).get('config', None)
if gyp.common.GetFlavor(params) == 'win':
target_list, target_dicts = MSVSUtil.ShardTargets(target_list, target_dicts)
target_list, target_dicts = MSVSUtil.InsertLargePdbShims(
target_list, target_dicts, generator_default_variables)
if user_config:
GenerateOutputForConfig(target_list, target_dicts, data, params,
user_config)
else:
config_names = target_dicts[target_list[0]]['configurations'].keys()
if params['parallel']:
try:
pool = multiprocessing.Pool(len(config_names))
arglists = []
for config_name in config_names:
arglists.append(
(target_list, target_dicts, data, params, config_name))
pool.map(CallGenerateOutputForConfig, arglists)
except KeyboardInterrupt, e:
pool.terminate()
raise e
else:
for config_name in config_names:
GenerateOutputForConfig(target_list, target_dicts, data, params,
config_name)
| mit |
Bashar/django | django/core/cache/backends/memcached.py | 11 | 7035 | "Memcached cache backend"
import time
import pickle
from django.core.cache.backends.base import BaseCache, DEFAULT_TIMEOUT
from django.utils import six
from django.utils.deprecation import RenameMethodsBase, RemovedInDjango19Warning
from django.utils.encoding import force_str
from django.utils.functional import cached_property
class BaseMemcachedCacheMethods(RenameMethodsBase):
renamed_methods = (
('_get_memcache_timeout', 'get_backend_timeout', RemovedInDjango19Warning),
)
class BaseMemcachedCache(six.with_metaclass(BaseMemcachedCacheMethods, BaseCache)):
def __init__(self, server, params, library, value_not_found_exception):
super(BaseMemcachedCache, self).__init__(params)
if isinstance(server, six.string_types):
self._servers = server.split(';')
else:
self._servers = server
# The exception type to catch from the underlying library for a key
# that was not found. This is a ValueError for python-memcache,
# pylibmc.NotFound for pylibmc, and cmemcache will return None without
# raising an exception.
self.LibraryValueNotFoundException = value_not_found_exception
self._lib = library
self._options = params.get('OPTIONS', None)
@property
def _cache(self):
"""
Implements transparent thread-safe access to a memcached client.
"""
if getattr(self, '_client', None) is None:
self._client = self._lib.Client(self._servers)
return self._client
def get_backend_timeout(self, timeout=DEFAULT_TIMEOUT):
"""
Memcached deals with long (> 30 days) timeouts in a special
way. Call this function to obtain a safe value for your timeout.
"""
if timeout == DEFAULT_TIMEOUT:
return self.default_timeout
if timeout is None:
# Using 0 in memcache sets a non-expiring timeout.
return 0
elif int(timeout) == 0:
# Other cache backends treat 0 as set-and-expire. To achieve this
# in memcache backends, a negative timeout must be passed.
timeout = -1
if timeout > 2592000: # 60*60*24*30, 30 days
# See http://code.google.com/p/memcached/wiki/FAQ
# "You can set expire times up to 30 days in the future. After that
# memcached interprets it as a date, and will expire the item after
# said date. This is a simple (but obscure) mechanic."
#
# This means that we have to switch to absolute timestamps.
timeout += int(time.time())
return int(timeout)
def make_key(self, key, version=None):
# Python 2 memcache requires the key to be a byte string.
return force_str(super(BaseMemcachedCache, self).make_key(key, version))
def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):
key = self.make_key(key, version=version)
return self._cache.add(key, value, self.get_backend_timeout(timeout))
def get(self, key, default=None, version=None):
key = self.make_key(key, version=version)
val = self._cache.get(key)
if val is None:
return default
return val
def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):
key = self.make_key(key, version=version)
self._cache.set(key, value, self.get_backend_timeout(timeout))
def delete(self, key, version=None):
key = self.make_key(key, version=version)
self._cache.delete(key)
def get_many(self, keys, version=None):
new_keys = [self.make_key(x, version=version) for x in keys]
ret = self._cache.get_multi(new_keys)
if ret:
_ = {}
m = dict(zip(new_keys, keys))
for k, v in ret.items():
_[m[k]] = v
ret = _
return ret
def close(self, **kwargs):
self._cache.disconnect_all()
def incr(self, key, delta=1, version=None):
key = self.make_key(key, version=version)
# memcached doesn't support a negative delta
if delta < 0:
return self._cache.decr(key, -delta)
try:
val = self._cache.incr(key, delta)
# python-memcache responds to incr on non-existent keys by
# raising a ValueError, pylibmc by raising a pylibmc.NotFound
# and Cmemcache returns None. In all cases,
# we should raise a ValueError though.
except self.LibraryValueNotFoundException:
val = None
if val is None:
raise ValueError("Key '%s' not found" % key)
return val
def decr(self, key, delta=1, version=None):
key = self.make_key(key, version=version)
# memcached doesn't support a negative delta
if delta < 0:
return self._cache.incr(key, -delta)
try:
val = self._cache.decr(key, delta)
# python-memcache responds to incr on non-existent keys by
# raising a ValueError, pylibmc by raising a pylibmc.NotFound
# and Cmemcache returns None. In all cases,
# we should raise a ValueError though.
except self.LibraryValueNotFoundException:
val = None
if val is None:
raise ValueError("Key '%s' not found" % key)
return val
def set_many(self, data, timeout=DEFAULT_TIMEOUT, version=None):
safe_data = {}
for key, value in data.items():
key = self.make_key(key, version=version)
safe_data[key] = value
self._cache.set_multi(safe_data, self.get_backend_timeout(timeout))
def delete_many(self, keys, version=None):
l = lambda x: self.make_key(x, version=version)
self._cache.delete_multi(map(l, keys))
def clear(self):
self._cache.flush_all()
class MemcachedCache(BaseMemcachedCache):
"An implementation of a cache binding using python-memcached"
def __init__(self, server, params):
import memcache
super(MemcachedCache, self).__init__(server, params,
library=memcache,
value_not_found_exception=ValueError)
@property
def _cache(self):
if getattr(self, '_client', None) is None:
self._client = self._lib.Client(self._servers, pickleProtocol=pickle.HIGHEST_PROTOCOL)
return self._client
class PyLibMCCache(BaseMemcachedCache):
"An implementation of a cache binding using pylibmc"
def __init__(self, server, params):
import pylibmc
super(PyLibMCCache, self).__init__(server, params,
library=pylibmc,
value_not_found_exception=pylibmc.NotFound)
@cached_property
def _cache(self):
client = self._lib.Client(self._servers)
if self._options:
client.behaviors = self._options
return client
| bsd-3-clause |
abdhaleegit/avocado-misc-tests | io/disk/ioping.py | 4 | 2385 | #!/usr/bin/env python
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# See LICENSE for more details.
#
# Copyright: 2017 IBM
# Author:Praveen K Pandey <[email protected]>
#
import os
from avocado import Test
from avocado.utils import process, archive, build
from avocado.utils.software_manager import SoftwareManager
class Ioping(Test):
"""
Disk I/O latency monitoring tool
"""
def setUp(self):
'''
Build Ioping Test
'''
# Check for basic utilities
smm = SoftwareManager()
self.count = self.params.get('count', default='2')
self.mode = self.params.get('mode', default='-C')
self.deadline = self.params.get('deadline', default='10')
self.period = self.params.get('period', default='10')
self.interval = self.params.get('interval', default='1s')
self.size = self.params.get('size', default='4k')
self.wsize = self.params.get('wsize', default='10m')
self.disk = self.params.get('disk', default='/home')
for package in ['gcc', 'make']:
if not smm.check_installed(package) and not smm.install(package):
self.cancel(
"Fail to install %s required for this test." % package)
tarball = self.fetch_asset("ioping.zip", locations="https://github.com/"
"koct9i/ioping/archive/master.zip",
expire='1d')
archive.extract(tarball, self.workdir)
self.sourcedir = os.path.join(self.workdir, 'ioping-master')
build.make(self.sourcedir)
def test(self):
os.chdir(self.sourcedir)
cmd = '%s -c %s -w %s -p %s -i %s -s %s -S %s %s' % (
self.mode, self.count, self.deadline, self.period, self.interval,
self.size, self.wsize, self.disk)
if process.system('./ioping %s' % cmd, ignore_status=True, shell=True):
self.fail("test run fails of %s" % cmd)
| gpl-2.0 |
SivagnanamCiena/ciscoconfparse | ciscoconfparse/ccp_util.py | 3 | 26161 | from collections import MutableSequence
import itertools
import sys
import re
import os
from protocol_values import ASA_TCP_PORTS, ASA_UDP_PORTS
from dns.exception import DNSException
from dns.resolver import Resolver
from dns import reversename, query
if sys.version_info[0]<3:
from ipaddr import IPv4Network, IPv6Network, IPv4Address, IPv6Address
else:
from ipaddress import IPv4Network, IPv6Network, IPv4Address, IPv6Address
""" ccp_util.py - Parse, Query, Build, and Modify IOS-style configurations
Copyright (C) 2014-2015 David Michael Pennington
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/>.
If you need to contact the author, you can do so by emailing:
mike [~at~] pennington [/dot\] net
"""
_IPV6_REGEX_STR = r"""(?!:::\S+?$) # Negative Lookahead for 3 colons
(?P<addr> # Begin a group named 'addr'
(?P<opt1>{0}(?::{0}){{7}}) # no double colons, option 1
|(?P<opt2>(?:{0}:){{1}}(?::{0}){{1,6}}) # match fe80::1
|(?P<opt3>(?:{0}:){{2}}(?::{0}){{1,5}}) # match fe80:a::1
|(?P<opt4>(?:{0}:){{3}}(?::{0}){{1,4}}) # match fe80:a:b::1
|(?P<opt5>(?:{0}:){{4}}(?::{0}){{1,3}}) # match fe80:a:b:c::1
|(?P<opt6>(?:{0}:){{5}}(?::{0}){{1,2}}) # match fe80:a:b:c:d::1
|(?P<opt7>(?:{0}:){{6}}(?::{0}){{1,1}}) # match fe80:a:b:c:d:e::1
|(?P<opt8>:(?::{0}){{1,7}}) # leading double colons
|(?P<opt9>(?:{0}:){{1,7}}:) # trailing double colons
|(?P<opt10>(?:::)) # bare double colons (default route)
) # End group named 'addr'
""".format(r'[0-9a-fA-F]{1,4}')
_IPV6_REGEX_STR_COMPRESSED1 = r"""(?!:::\S+?$)(?P<addr1>(?P<opt1_1>{0}(?::{0}){{7}})|(?P<opt1_2>(?:{0}:){{1}}(?::{0}){{1,6}})|(?P<opt1_3>(?:{0}:){{2}}(?::{0}){{1,5}})|(?P<opt1_4>(?:{0}:){{3}}(?::{0}){{1,4}})|(?P<opt1_5>(?:{0}:){{4}}(?::{0}){{1,3}})|(?P<opt1_6>(?:{0}:){{5}}(?::{0}){{1,2}})|(?P<opt1_7>(?:{0}:){{6}}(?::{0}){{1,1}})|(?P<opt1_8>:(?::{0}){{1,7}})|(?P<opt1_9>(?:{0}:){{1,7}}:)|(?P<opt1_10>(?:::)))""".format(r'[0-9a-fA-F]{1,4}')
_IPV6_REGEX_STR_COMPRESSED2 = r"""(?!:::\S+?$)(?P<addr2>(?P<opt2_1>{0}(?::{0}){{7}})|(?P<opt2_2>(?:{0}:){{1}}(?::{0}){{1,6}})|(?P<opt2_3>(?:{0}:){{2}}(?::{0}){{1,5}})|(?P<opt2_4>(?:{0}:){{3}}(?::{0}){{1,4}})|(?P<opt2_5>(?:{0}:){{4}}(?::{0}){{1,3}})|(?P<opt2_6>(?:{0}:){{5}}(?::{0}){{1,2}})|(?P<opt2_7>(?:{0}:){{6}}(?::{0}){{1,1}})|(?P<opt2_8>:(?::{0}){{1,7}})|(?P<opt2_9>(?:{0}:){{1,7}}:)|(?P<opt2_10>(?:::)))""".format(r'[0-9a-fA-F]{1,4}')
_IPV6_REGEX_STR_COMPRESSED3 = r"""(?!:::\S+?$)(?P<addr3>(?P<opt3_1>{0}(?::{0}){{7}})|(?P<opt3_2>(?:{0}:){{1}}(?::{0}){{1,6}})|(?P<opt3_3>(?:{0}:){{2}}(?::{0}){{1,5}})|(?P<opt3_4>(?:{0}:){{3}}(?::{0}){{1,4}})|(?P<opt3_5>(?:{0}:){{4}}(?::{0}){{1,3}})|(?P<opt3_6>(?:{0}:){{5}}(?::{0}){{1,2}})|(?P<opt3_7>(?:{0}:){{6}}(?::{0}){{1,1}})|(?P<opt3_8>:(?::{0}){{1,7}})|(?P<opt3_9>(?:{0}:){{1,7}}:)|(?P<opt3_10>(?:::)))""".format(r'[0-9a-fA-F]{1,4}')
_RGX_IPV6ADDR = re.compile(_IPV6_REGEX_STR, re.VERBOSE)
_RGX_IPV4ADDR = re.compile(r'^(?P<addr>\d+\.\d+\.\d+\.\d+)')
_RGX_IPV4ADDR_NETMASK = re.compile(
r"""
(?:
^(?P<addr0>\d+\.\d+\.\d+\.\d+)$
|(?:^
(?:(?P<addr1>\d+\.\d+\.\d+\.\d+))(?:\s+|\/)(?:(?P<netmask>\d+\.\d+\.\d+\.\d+))
$)
|^(?:\s*(?P<addr2>\d+\.\d+\.\d+\.\d+)(?:\/(?P<masklen>\d+))\s*)$
)
""",
re.VERBOSE)
## Emulate the old behavior of ipaddr.IPv4Network in Python2, which can use
## IPv4Network with a host address. Google removed that in Python3's
## ipaddress.py module
class IPv4Obj(object):
"""An object to represent IPv4 addresses and IPv4Networks. When :class:`~ccp_util.IPv4Obj` objects are compared or sorted, shorter masks are greater than longer masks. After comparing mask length, numerically higher IP addresses are greater than numerically lower IP addresses.
Kwargs:
- arg (str): A string containing an IPv4 address, and optionally a netmask or masklength. The following address/netmask formats are supported: "10.1.1.1/24", "10.1.1.1 255.255.255.0", "10.1.1.1/255.255.255.0"
Attributes:
- network_object : An IPv4Network object
- ip_object : An IPv4Address object
- ip : An IPv4Address object
- as_binary_tuple (tuple): The address as a tuple of zero-padded binary strings
- as_hex_tuple (tuple): The address as a tuple of zero-padded 8-bit hex strings
- as_decimal (int): The ip address as a decimal integer
- network (str): A string representing the network address
- netmask (str): A string representing the netmask
- prefixlen (int): An integer representing the length of the netmask
- broadcast (str): A string representing the broadcast address
- hostmask (str): A string representing the hostmask
- numhosts (int): An integer representing the number of hosts contained in the network
Returns:
- an instance of :class:`~ccp_util.IPv4Obj`.
"""
def __init__(self, arg='127.0.0.1/32', strict=False):
#RGX_IPV4ADDR = re.compile(r'^(\d+\.\d+\.\d+\.\d+)')
#RGX_IPV4ADDR_NETMASK = re.compile(r'(\d+\.\d+\.\d+\.\d+)\s+(\d+\.\d+\.\d+\.\d+)')
self.arg = arg
mm = _RGX_IPV4ADDR_NETMASK.search(arg)
ERROR = "IPv4Obj couldn't parse '{0}'".format(arg)
assert (not (mm is None)), ERROR
mm_result = mm.groupdict()
addr = mm_result['addr0'] or mm_result['addr1'] \
or mm_result['addr2'] or '127.0.0.1'
masklen = int(mm_result['masklen'] or 32)
netmask = mm_result['netmask']
if netmask:
## ALWAYS check for the netmask first
self.network_object = IPv4Network('{0}/{1}'.format(addr, netmask),
strict=strict)
self.ip_object = IPv4Address('{0}'.format(addr))
else:
self.network_object = IPv4Network('{0}/{1}'.format(addr, masklen),
strict=strict)
self.ip_object = IPv4Address('{0}'.format(addr))
def __repr__(self):
return """<IPv4Obj {0}/{1}>""".format(str(self.ip_object), self.prefixlen)
def __eq__(self, val):
try:
if self.network_object==val.network_object:
return True
return False
except (Exception) as e:
errmsg = "'{0}' cannot compare itself to '{1}': {2}".format(self.__repr__(), val, e)
raise ValueError(errmsg)
def __gt__(self, val):
try:
val_prefixlen = int(getattr(val, 'prefixlen'))
val_nobj = getattr(val, 'network_object')
self_nobj = self.network_object
if (self.network_object.prefixlen<val_prefixlen):
# Sort shorter masks as higher...
return True
elif (self.network_object.prefixlen>val_prefixlen):
return False
elif (self_nobj>val_nobj):
# If masks are equal, rely on Google's sorting...
return True
return False
except:
errmsg = "{0} cannot compare itself to '{1}'".format(self.__repr__(), val)
raise ValueError(errmsg)
def __lt__(self, val):
try:
val_prefixlen = int(getattr(val, 'prefixlen'))
val_nobj = getattr(val, 'network_object')
self_nobj = self.network_object
if (self.network_object.prefixlen>val_prefixlen):
# Sort shorter masks as lower...
return True
elif (self.network_object.prefixlen<val_prefixlen):
return False
elif (self_nobj<val_nobj):
# If masks are equal, rely on Google's sorting...
return True
return False
except:
errmsg = "{0} cannot compare itself to '{1}'".format(self.__repr__(), val)
raise ValueError(errmsg)
def __contains__(self, val):
# Used for "foo in bar"... python calls bar.__contains__(foo)
try:
if (self.network_object.prefixlen==0):
return True
elif self.network_object.prefixlen>val.network_object.prefixlen:
# obvious shortcut... if this object's mask is longer than
# val, this object cannot contain val
return False
else:
#return (val.network in self.network)
return (self.network<=val.network) and \
(self.broadcast>=val.broadcast)
except (Exception) as e:
raise ValueError("Could not check whether '{0}' is contained in '{1}': {2}".format(val, self, e))
def __hash__(self):
# Python3 needs __hash__()
return hash(str(self.ip_object))+hash(str(self.prefixlen))
def __iter__(self):
return self.network_object.__iter__()
def __next__(self):
## For Python3 iteration...
return self.network_object.__next__()
def next(self):
## For Python2 iteration...
return self.network_object.__next__()
@property
def ip(self):
"""Returns the address as an IPv4Address object."""
return self.ip_object
@property
def netmask(self):
"""Returns the network mask as an IPv4Address object."""
return self.network_object.netmask
@property
def prefixlen(self):
"""Returns the length of the network mask as an integer."""
return self.network_object.prefixlen
@property
def broadcast(self):
"""Returns the broadcast address as an IPv4Address object."""
if sys.version_info[0]<3:
return self.network_object.broadcast
else:
return self.network_object.broadcast_address
@property
def network(self):
"""Returns an IPv4Network object, which represents this network.
"""
if sys.version_info[0]<3:
return self.network_object.network
else:
## The ipaddress module returns an "IPAddress" object in Python3...
return IPv4Network('{0}'.format(self.network_object.compressed))
@property
def hostmask(self):
"""Returns the host mask as an IPv4Address object."""
return self.network_object.hostmask
@property
def version(self):
"""Returns the version of the object as an integer. i.e. 4"""
return 4
@property
def numhosts(self):
"""Returns the total number of IP addresses in this network, including broadcast and the "subnet zero" address"""
if sys.version_info[0]<3:
return self.network_object.numhosts
else:
return 2**(32-self.network_object.prefixlen)
@property
def as_decimal(self):
"""Returns the IP address as a decimal integer"""
num_strings = str(self.ip).split('.')
num_strings.reverse() # reverse the order
return sum([int(num)*(256**idx) for idx, num in enumerate(num_strings)])
@property
def as_binary_tuple(self):
"""Returns the IP address as a tuple of zero-padded binary strings"""
return tuple(['{0:08b}'.format(int(num)) for num in \
str(self.ip).split('.')])
@property
def as_hex_tuple(self):
"""Returns the IP address as a tuple of zero-padded hex strings"""
return tuple(['{0:02x}'.format(int(num)) for num in \
str(self.ip).split('.')])
@property
def is_multicast(self):
"""Returns a boolean for whether this is a multicast address"""
return self.network_object.is_multicast
@property
def is_private(self):
"""Returns a boolean for whether this is a private address"""
return self.network_object.is_private
@property
def is_reserved(self):
"""Returns a boolean for whether this is a reserved address"""
return self.network_object.is_reserved
## Emulate the old behavior of ipaddr.IPv6Network in Python2, which can use
## IPv6Network with a host address. Google removed that in Python3's
## ipaddress.py module
class IPv6Obj(object):
"""An object to represent IPv6 addresses and IPv6Networks. When :class:`~ccp_util.IPv6Obj` objects are compared or sorted, shorter masks are greater than longer masks. After comparing mask length, numerically higher IP addresses are greater than numerically lower IP addresses.
Kwargs:
- arg (str): A string containing an IPv6 address, and optionally a netmask or masklength. The following address/netmask formats are supported: "2001::dead:beef", "2001::dead:beef/64",
Attributes:
- network_object : An IPv6Network object
- ip_object : An IPv6Address object
- ip : An IPv6Address object
- as_binary_tuple (tuple): The ipv6 address as a tuple of zero-padded binary strings
- as_decimal (int): The ipv6 address as a decimal integer
- as_hex_tuple (tuple): The ipv6 address as a tuple of zero-padded 8-bit hex strings
- network (str): A string representing the network address
- netmask (str): A string representing the netmask
- prefixlen (int): An integer representing the length of the netmask
- broadcast: raises `NotImplementedError`; IPv6 doesn't use broadcast
- hostmask (str): A string representing the hostmask
- numhosts (int): An integer representing the number of hosts contained in the network
Returns:
- an instance of :class:`~ccp_util.IPv6Obj`.
"""
def __init__(self, arg='::1/128', strict=False):
#arg= _RGX_IPV6ADDR_NETMASK.sub(r'\1/\2', arg) # mangle IOS: 'addr mask'
self.arg = arg
mm = _RGX_IPV6ADDR.search(arg)
assert (not (mm is None)), "IPv6Obj couldn't parse {0}".format(arg)
self.network_object = IPv6Network(arg, strict=strict)
self.ip_object = IPv6Address(mm.group(1))
# 'address_exclude', 'compare_networks', 'hostmask', 'ipv4_mapped', 'iter_subnets', 'iterhosts', 'masked', 'max_prefixlen', 'netmask', 'network', 'numhosts', 'overlaps', 'prefixlen', 'sixtofour', 'subnet', 'supernet', 'teredo', 'with_hostmask', 'with_netmask', 'with_prefixlen'
def __repr__(self):
return """<IPv6Obj {0}/{1}>""".format(str(self.ip_object), self.prefixlen)
def __eq__(self, val):
try:
if self.network_object==val.network_object:
return True
return False
except (Exception) as e:
errmsg = "'{0}' cannot compare itself to '{1}': {2}".format(self.__repr__(), val, e)
raise ValueError(errmsg)
def __gt__(self, val):
try:
val_prefixlen = int(getattr(val, 'prefixlen'))
val_nobj = getattr(val, 'network_object')
self_nobj = self.network_object
if (self.network_object.prefixlen<val_prefixlen):
# Sort shorter masks as higher...
return True
elif (self.network_object.prefixlen>val_prefixlen):
return False
elif (self_nobj>val_nobj):
# If masks are equal, rely on Google's sorting...
return True
return False
except:
errmsg = "{0} cannot compare itself to '{1}'".format(self.__repr__(), val)
raise ValueError(errmsg)
def __lt__(self, val):
try:
val_prefixlen = int(getattr(val, 'prefixlen'))
val_nobj = getattr(val, 'network_object')
self_nobj = self.network_object
if (self.network_object.prefixlen>val_prefixlen):
# Sort shorter masks as lower...
return True
elif (self.network_object.prefixlen<val_prefixlen):
return False
elif (self_nobj<val_nobj):
# If masks are equal, rely on Google's sorting...
return True
return False
except:
errmsg = "{0} cannot compare itself to '{1}'".format(self.__repr__(), val)
raise ValueError(errmsg)
def __contains__(self, val):
# Used for "foo in bar"... python calls bar.__contains__(foo)
try:
if (self.network_object.prefixlen==0):
return True
elif self.network_object.prefixlen>val.network_object.prefixlen:
# obvious shortcut... if this object's mask is longer than
# val, this object cannot contain val
return False
else:
#return (val.network in self.network)
return (self.network<=val.network) and \
(self.broadcast>=val.broadcast)
except (Exception) as e:
raise ValueError("Could not check whether '{0}' is contained in '{1}': {2}".format(val, self, e))
def __hash__(self):
# Python3 needs __hash__()
return hash(str(self.ip_object))+hash(str(self.prefixlen))
def __iter__(self):
return self.network_object.__iter__()
def __next__(self):
## For Python3 iteration...
return self.network_object.__next__()
def next(self):
## For Python2 iteration...
return self.network_object.__next__()
@property
def ip(self):
"""Returns the address as an IPv6Address object."""
return self.ip_object
@property
def netmask(self):
"""Returns the network mask as an IPv6Address object."""
return self.network_object.netmask
@property
def prefixlen(self):
"""Returns the length of the network mask as an integer."""
return self.network_object.prefixlen
@property
def compressed(self):
"""Returns the IPv6 object in compressed form"""
return self.network_object.compressed
@property
def exploded(self):
"""Returns the IPv6 object in exploded form"""
return self.network_object.exploded
@property
def packed(self):
"""Returns the IPv6 object in packed form"""
return self.network_object.packed
@property
def broadcast(self):
raise NotImplementedError("IPv6 does not have broadcasts")
@property
def network(self):
"""Returns an IPv6Network object, which represents this network.
"""
if sys.version_info[0]<3:
return self.network_object.network
else:
## The ipaddress module returns an "IPAddress" object in Python3...
return IPv6Network('{0}'.format(self.network_object.compressed))
@property
def hostmask(self):
"""Returns the host mask as an IPv6Address object."""
return self.network_object.hostmask
@property
def version(self):
"""Returns the version of the object as an integer. i.e. 4"""
return 6
@property
def numhosts(self):
"""Returns the total number of IP addresses in this network, including broadcast and the "subnet zero" address"""
if sys.version_info[0]<3:
return self.network_object.numhosts
else:
return 2**(128-self.network_object.prefixlen)
@property
def as_decimal(self):
"""Returns the IP address as a decimal integer"""
num_strings = str(self.ip.exploded).split(':')
num_strings.reverse() # reverse the order
return sum([int(num, 16)*(256**idx) for idx, num in enumerate(num_strings)])
@property
def as_binary_tuple(self):
"""Returns the IPv6 address as a tuple of zero-padded 8-bit binary strings"""
nested_list = [
['{0:08b}'.format(int(ii, 16)) for ii in [num[0:2], num[2:4]]]
for num in str(self.ip.exploded).split(':')]
return tuple(itertools.chain(*nested_list))
@property
def as_hex_tuple(self):
"""Returns the IPv6 address as a tuple of zero-padded 8-bit hex strings"""
nested_list = [
['{0:02x}'.format(int(ii, 16)) for ii in [num[0:2], num[2:4]]]
for num in str(self.ip.exploded).split(':')]
return tuple(itertools.chain(*nested_list))
@property
def is_multicast(self):
"""Returns a boolean for whether this is a multicast address"""
return self.network_object.is_multicast
@property
def is_private(self):
"""Returns a boolean for whether this is a private address"""
return self.network_object.is_private
@property
def is_reserved(self):
"""Returns a boolean for whether this is a reserved address"""
return self.network_object.is_reserved
@property
def is_link_local(self):
"""Returns a boolean for whether this is an IPv6 link-local address"""
return self.network_object.is_link_local
@property
def is_site_local(self):
"""Returns a boolean for whether this is an IPv6 site-local address"""
return self.network_object.is_site_local
@property
def is_unspecified(self):
"""Returns a boolean for whether this address is not otherwise
classified"""
return self.network_object.is_unspecified
@property
def teredo(self):
return self.network_object.teredo
@property
def sixtofour(self):
return self.network_object.sixtofour
class L4Object(object):
"""Object for Transport-layer protocols; the object ensures that logical operators (such as le, gt, eq, and ne) are parsed correctly, as well as mapping service names to port numbers"""
def __init__(self, protocol='', port_spec='', syntax=''):
self.protocol = protocol
self.port_list = list()
self.syntax = syntax
try:
port_spec = port_spec.strip()
except:
port_spec = port_spec
if syntax=='asa':
if protocol=='tcp':
ports = ASA_TCP_PORTS
elif protocol=='udp':
ports = ASA_UDP_PORTS
else:
raise NotImplementedError("'{0}' is not supported: '{0}'".format(protocol))
else:
raise NotImplementedError("This syntax is unknown: '{0}'".format(syntax))
if 'eq ' in port_spec:
port_str = re.split('\s+', port_spec)[-1]
self.port_list = [int(ports.get(port_str, port_str))]
elif re.search(r'^\S+$', port_spec):
# Technically, 'eq ' is optional...
self.port_list = [int(ports.get(port_spec, port_spec))]
elif 'range ' in port_spec:
port_tmp = re.split('\s+', port_spec)[1:]
self.port_list = range(int(ports.get(port_tmp[0], port_tmp[0])),
int(ports.get(port_tmp[1], port_tmp[1])) + 1)
elif 'lt ' in port_spec:
port_str = re.split('\s+', port_spec)[-1]
self.port_list = range(1, int(ports.get(port_str, port_str)))
elif 'gt ' in port_spec:
port_str = re.split('\s+', port_spec)[-1]
self.port_list = range(int(ports.get(port_str, port_str)) + 1, 65535)
elif 'neq ' in port_spec:
port_str = re.split('\s+', port_spec)[-1]
tmp = set(range(1, 65535))
tmp.remove(int(port_str))
self.port_list = sorted(tmp)
def __eq__(self, val):
if (self.protocol==val.protocol) and (self.port_list==val.port_list):
return True
return False
def __repr__(self):
return "<L4Object {0} {1}>".format(self.protocol, self.port_list)
def dns_lookup(input, timeout=3, server=''):
"""Perform a simple DNS lookup, return results in a dictionary"""
resolver = Resolver()
resolver.timeout = float(timeout)
resolver.lifetime = float(timeout)
if server:
resolver.nameservers = [server]
try:
records = resolver.query(input, 'A')
return {'addrs': [ii.address for ii in records],
'error': '',
'name': input,
}
except DNSException as e:
return {'addrs': [],
'error': repr(e),
'name': input,
}
def dns6_lookup(input, timeout=3, server=''):
"""Perform a simple DNS lookup, return results in a dictionary"""
resolver = Resolver()
resolver.timeout = float(timeout)
resolver.lifetime = float(timeout)
if server:
resolver.nameservers = [server]
try:
records = resolver.query(input, 'AAAA')
return {'addrs': [ii.address for ii in records],
'error': '',
'name': input,
}
except DNSException as e:
return {'addrs': [],
'error': repr(e),
'name': input,
}
_REVERSE_DNS_REGEX = re.compile(r'^\s*\d+\.\d+\.\d+\.\d+\s*$')
def reverse_dns_lookup(input, timeout=3, server=''):
"""Perform a simple reverse DNS lookup, return results in a dictionary"""
assert _REVERSE_DNS_REGEX.search(input), "Invalid address format: '{0}'".format(input)
resolver = Resolver()
resolver.timeout = float(timeout)
resolver.lifetime = float(timeout)
if server:
resolver.nameservers = [server]
try:
tmp = input.strip().split('.')
tmp.reverse()
inaddr = '.'.join(tmp) + ".in-addr.arpa"
records = resolver.query(inaddr, 'PTR')
return {'name': records[0].to_text(),
'lookup': inaddr,
'error': '',
'addr': input,
}
except DNSException as e:
return {'addrs': [],
'lookup': inaddr,
'error': repr(e),
'name': input,
}
| gpl-3.0 |
agentfog/qiime | qiime/filter.py | 15 | 26099 | #!/usr/bin/env python
# File created on 18 May 2010
from __future__ import division
__author__ = "Greg Caporaso"
__copyright__ = "Copyright 2011, The QIIME Project"
__credits__ = ["Greg Caporaso", "Will Van Treuren", "Daniel McDonald",
"Jai Ram Rideout", "Yoshiki Vazquez Baeza"]
__license__ = "GPL"
__version__ = "1.9.1-dev"
__maintainer__ = "Greg Caporaso"
__email__ = "[email protected]"
from collections import defaultdict
from random import shuffle, sample
from numpy import array, inf
from skbio.parse.sequences import parse_fasta, parse_fastq
from skbio.format.sequences import format_fastq_record
from biom import load_table
from qiime.parse import (parse_distmat, parse_mapping_file,
parse_metadata_state_descriptions)
from qiime.format import format_distance_matrix, format_mapping_file
from qiime.util import MetadataMap
def get_otu_ids_from_taxonomy_f(positive_taxa=None,
negative_taxa=None,
metadata_field="taxonomy"):
""" return function to pass to Table.filter_observations for taxon-based filtering
positive_taxa : a list of strings that will be compared to each
taxonomy level in an observation's (i.e., OTU's) metadata_field. If
one of the levels matches exactly (except for case) to an item in
positive_taxa, that OTU will be marked for retention. Default: All
OTUs are retained.
negative_taxa : a list of strings that will be compared to each
taxonomy level in an observation's (i.e., OTU's) metadata_field. If
one of the levels matches exactly (except for case) to an item in
negative_taxa, that OTU will be marked for removal. Default: All
OTUs are retained.
metadata_field : the metadata field to look up in the
observation metadata
Note: string matches are case insensitive.
"""
# define a positive screening function - if the user doesn't pass
# positive_taxa, all OTUs will pass this filter
# (i.e., be marked for retention)
if positive_taxa is None:
positive_taxa = set()
def positive_screen(e):
return True
else:
positive_taxa = set([t.strip().lower() for t in positive_taxa])
def positive_screen(e):
return e in positive_taxa
# define a negative screening function - if the user doesn't pass
# negative_taxa, all OTUs will pass this filter
# (i.e., be marked for retention)
if negative_taxa is None:
negative_taxa = set()
def negative_screen(e):
return False
else:
negative_taxa = set([t.strip().lower() for t in negative_taxa])
def negative_screen(e):
return e in negative_taxa
# The positive_taxa and negative_taxa lists must be mutually exclusive.
if len(positive_taxa & negative_taxa) != 0:
raise ValueError("Your positive and negative taxa lists contain "
"overlapping values. These lists must be mutually "
"exclusive.\nOffending values are: %s" %
' '.join(positive_taxa & negative_taxa))
# Define the function that can be passed to Table.filter_observations
def result(v, oid, md):
positive_hit = False
negative_hit = False
for e in md[metadata_field]:
if positive_screen(e.strip().lower()):
# Note that we don't want to just do
# positive_hit = positive_screen(e.strip())
# we're checking whether any e hits the positive taxa
# and doing that be the same as
# positive_hit = md[metadata_field][-1]
positive_hit = True
if negative_screen(e.strip().lower()):
# see note in previous if statement for why we don't use
# negative_hit = negative_screen(e.strip())
negative_hit = True
return positive_hit and not negative_hit
return result
def sample_ids_from_metadata_description(mapping_f, valid_states_str):
""" Given a description of metadata, return the corresponding sample ids
"""
map_data, map_header, map_comments = parse_mapping_file(mapping_f)
valid_states = parse_metadata_state_descriptions(valid_states_str)
sample_ids = get_sample_ids(map_data, map_header, valid_states)
if len(sample_ids) < 1:
raise ValueError("All samples have been filtered out for the criteria"
" described in the valid states")
return sample_ids
def get_sample_ids(map_data, map_header, states):
"""Takes col states in {col:[vals]} format.
If val starts with !, exclude rather than include.
Combines cols with and, states with or.
For example, Study:Dog,Hand will return rows where Study is Dog or Hand;
Study:Dog,Hand;BodySite:Palm,Stool will return rows where Study is Dog
or Hand _and_ BodySite is Palm or Stool; Study:*,!Dog;BodySite:*,!Stool
will return all rows except the ones where the Study is Dog or the BodySite
is Stool.
"""
name_to_col = dict([(s, map_header.index(s)) for s in states])
good_ids = []
for row in map_data: # remember to exclude header
include = True
for s, vals in states.items():
curr_state = row[name_to_col[s]]
include = include and (curr_state in vals or '*' in vals) \
and not '!' + curr_state in vals
if include:
good_ids.append(row[0])
return good_ids
def sample_ids_from_category_state_coverage(mapping_f,
coverage_category,
subject_category,
min_num_states=None,
required_states=None,
considered_states=None,
splitter_category=None):
"""Filter sample IDs based on subject's coverage of a category.
Given a category that groups samples by subject (subject_category), samples
are filtered by how well a subject covers (i.e. has at least one sample
for) the category states in coverage_category.
Two filtering criteria are provided (min_num_states and required_states).
At least one must be provided. If both are provided, the subject must meet
both criteria to pass the filter (i.e. providing both filters is an AND,
not an OR, operation).
A common use case is to provide a 'time' category for coverage_category and
an 'individual' category for subject_category in order to filter out
individuals from a study that do not have samples for some minimum number
of timepoints (min_num_states) and that do not have samples for certain
timepoints (required_states). For example, this could be the first and last
timepoints in the study.
Returns a set of sample IDs to keep, the number of subjects that were
kept, and a set of the unique category states in coverage_category that
were kept. The set of sample IDs is not guaranteed to be in any specific
order relative to the order of sample IDs or subjects in the mapping file.
Arguments:
mapping_f - metadata mapping file (file-like object)
coverage_category - category to test subjects' coverage (string)
subject_category - category to group samples by subject (string)
min_num_states - minimum number of category states in coverage_category
that a subject must cover (i.e. have at least one sample for) to be
included in results (integer)
required_states - category states in coverage_category that must be
covered by a subject's samples in order to be included in results
(list of strings or items that can be converted to strings)
considered_states - category states that are counted toward the
min_num_states (list of strings or items that can be converted to
strings)
splitter_category - category to split input mapping file on prior to
processing. If not supplied, the mapping file will not be split. If
supplied, a dictionary mapping splitter_category state to results
will be returned instead of the three-element tuple. The supplied
filtering criteria will apply to each split piece of the mapping
file independently (e.g. if an individual passes the filters for
the tongue samples, his/her tongue samples will be included for
the tongue results, even if he/she doesn't pass the filters for the
palm samples)
"""
metadata_map = MetadataMap.parseMetadataMap(mapping_f)
# Make sure our input looks sane.
categories_to_test = [coverage_category, subject_category]
if splitter_category is not None:
categories_to_test.append(splitter_category)
if 'SampleID' in categories_to_test:
raise ValueError("The 'SampleID' category is not suitable for use in "
"this function. Please choose a different category "
"from the metadata mapping file.")
for category in categories_to_test:
if category not in metadata_map.CategoryNames:
raise ValueError("The category '%s' is not in the metadata "
"mapping file." % category)
if len(set(categories_to_test)) < len(categories_to_test):
raise ValueError("The coverage, subject, and (optional) splitter "
"categories must all be unique.")
if required_states is not None:
# required_states must be in coverage_category's states in the mapping
# file.
required_states = set(map(str, required_states))
valid_coverage_states = set(metadata_map.getCategoryValues(
metadata_map.sample_ids, coverage_category))
invalid_coverage_states = required_states - valid_coverage_states
if invalid_coverage_states:
raise ValueError("The category state(s) '%s' are not in the '%s' "
"category in the metadata mapping file." %
(', '.join(invalid_coverage_states),
coverage_category))
if considered_states is not None:
# considered_states is not as restrictive as required_states - we don't
# require that these are present, so it's OK if some of the states
# listed here don't actually show up in the mapping file (allowing
# the user to pass something like range(100) to consider only states
# that fall in some range)
considered_states = set(map(str, considered_states))
# define a function to determine if a state should be considered
consider_state = lambda s: s in considered_states
else:
# define a dummy function to consider all states (the default
# if the user does not provide a list of considered_states)
consider_state = lambda s: True
if min_num_states is None and required_states is None:
raise ValueError("You must specify either the minimum number of "
"category states the subject must have samples for "
"(min_num_states), or the minimal category states "
"the subject must have samples for "
"(required_states), or both. Supplying neither "
"filtering criteria is not supported.")
if splitter_category is None:
results = _filter_sample_ids_from_category_state_coverage(
metadata_map, metadata_map.sample_ids, coverage_category,
subject_category, consider_state, min_num_states,
required_states)
else:
# "Split" the metadata mapping file by extracting only sample IDs that
# match the current splitter category state and using those for the
# actual filtering.
splitter_category_states = defaultdict(list)
for samp_id in metadata_map.sample_ids:
splitter_category_state = \
metadata_map.getCategoryValue(samp_id, splitter_category)
splitter_category_states[splitter_category_state].append(samp_id)
results = {}
for splitter_category_state, sample_ids in \
splitter_category_states.items():
results[splitter_category_state] = \
_filter_sample_ids_from_category_state_coverage(
metadata_map, sample_ids, coverage_category,
subject_category, consider_state, min_num_states,
required_states)
return results
def _filter_sample_ids_from_category_state_coverage(metadata_map,
sample_ids,
coverage_category,
subject_category,
consider_state_fn,
min_num_states=None,
required_states=None):
"""Helper function to perform filtering based on category state coverage.
Not explicitly unit-tested because it is implicitly tested by
sample_ids_from_category_state_coverage's unit tests.
"""
# Build mapping from subject to sample IDs.
subjects = defaultdict(list)
for samp_id in sample_ids:
subject = metadata_map.getCategoryValue(samp_id, subject_category)
subjects[subject].append(samp_id)
# Perform filtering.
samp_ids_to_keep = []
num_subjects_kept = 0
states_kept = []
for subject, samp_ids in subjects.items():
subject_covered_states = set(
metadata_map.getCategoryValues(samp_ids, coverage_category))
# Short-circuit evaluation of ANDing filters.
keep_subject = True
if min_num_states is not None:
# note: when summing a list of boolean values, True == 1 and
# False == 0
if sum([consider_state_fn(s) for s in subject_covered_states]) < \
min_num_states:
keep_subject = False
if keep_subject and required_states is not None:
if len(subject_covered_states & required_states) != \
len(required_states):
keep_subject = False
if keep_subject:
samp_ids_to_keep.extend(samp_ids)
states_kept.extend(subject_covered_states)
num_subjects_kept += 1
return set(samp_ids_to_keep), num_subjects_kept, set(states_kept)
def filter_fasta(input_seqs_f, output_seqs_f, seqs_to_keep, negate=False,
seqid_f=None):
""" Write filtered input_seqs to output_seqs_f which contains only seqs_to_keep
input_seqs can be the output of parse_fasta or parse_fastq
"""
if seqid_f is None:
seqs_to_keep_lookup = {}.fromkeys([seq_id.split()[0]
for seq_id in seqs_to_keep])
# Define a function based on the value of negate
if not negate:
def keep_seq(seq_id):
return seq_id.split()[0] in seqs_to_keep_lookup
else:
def keep_seq(seq_id):
return seq_id.split()[0] not in seqs_to_keep_lookup
else:
if not negate:
keep_seq = seqid_f
else:
keep_seq = lambda x: not seqid_f(x)
for seq_id, seq in parse_fasta(input_seqs_f):
if keep_seq(seq_id):
output_seqs_f.write('>%s\n%s\n' % (seq_id, seq))
output_seqs_f.close()
def filter_fastq(input_seqs_f, output_seqs_f, seqs_to_keep, negate=False,
seqid_f=None):
""" Write filtered input_seqs to output_seqs_f which contains only seqs_to_keep
input_seqs can be the output of parse_fasta or parse_fastq
"""
if seqid_f is None:
seqs_to_keep_lookup = {}.fromkeys([seq_id.split()[0]
for seq_id in seqs_to_keep])
# Define a function based on the value of negate
if not negate:
def keep_seq(seq_id):
return seq_id.split()[0] in seqs_to_keep_lookup
else:
def keep_seq(seq_id):
return seq_id.split()[0] not in seqs_to_keep_lookup
else:
if not negate:
keep_seq = seqid_f
else:
keep_seq = lambda x: not seqid_f(x)
for seq_id, seq, qual in parse_fastq(input_seqs_f,
enforce_qual_range=False):
if keep_seq(seq_id):
output_seqs_f.write(format_fastq_record(seq_id, seq, qual))
output_seqs_f.close()
def filter_mapping_file(map_data, map_header, good_sample_ids,
include_repeat_cols=False, column_rename_ids=None):
"""Filters map according to several criteria.
- keep only sample ids in good_sample_ids
- drop cols that are different in every sample (except id)
- drop cols that are the same in every sample
"""
# keeping samples
to_keep = []
to_keep.extend([i for i in map_data if i[0] in good_sample_ids])
# keeping columns
headers = []
to_keep = zip(*to_keep)
headers.append(map_header[0])
result = [to_keep[0]]
if column_rename_ids:
# reduce in 1 as we are not using the first colum (SampleID)
column_rename_ids = column_rename_ids - 1
for i, l in enumerate(to_keep[1:-1]):
if i == column_rename_ids:
if len(set(l)) != len(result[0]):
raise ValueError(
"The column to rename the samples is not unique.")
result.append(result[0])
result[0] = l
headers.append('SampleID_was_' + map_header[i + 1])
elif include_repeat_cols or len(set(l)) > 1:
headers.append(map_header[i + 1])
result.append(l)
else:
for i, l in enumerate(to_keep[1:-1]):
if include_repeat_cols or len(set(l)) > 1:
headers.append(map_header[i + 1])
result.append(l)
headers.append(map_header[-1])
result.append(to_keep[-1])
result = map(list, zip(*result))
return headers, result
def filter_mapping_file_from_mapping_f(
mapping_f, sample_ids_to_keep, negate=False):
""" Filter rows from a metadata mapping file """
mapping_data, header, comments = parse_mapping_file(mapping_f)
filtered_mapping_data = []
sample_ids_to_keep = {}.fromkeys(sample_ids_to_keep)
for mapping_datum in mapping_data:
hit = mapping_datum[0] in sample_ids_to_keep
if hit and not negate:
filtered_mapping_data.append(mapping_datum)
elif not hit and negate:
filtered_mapping_data.append(mapping_datum)
else:
pass
return format_mapping_file(header, filtered_mapping_data)
def filter_mapping_file_by_metadata_states(mapping_f, valid_states_str):
sample_ids_to_keep = sample_ids_from_metadata_description(
mapping_f,
valid_states_str)
mapping_f.seek(0)
return filter_mapping_file_from_mapping_f(mapping_f, sample_ids_to_keep)
def filter_samples_from_distance_matrix(dm, samples_to_discard, negate=False):
""" Remove specified samples from distance matrix
dm: (sample_ids, dm_data) tuple, as returned from
qiime.parse.parse_distmat; or a file handle that can be passed
to qiime.parse.parse_distmat
"""
try:
sample_ids, dm_data = dm
except ValueError:
# input was provide as a file handle
sample_ids, dm_data = parse_distmat(dm)
sample_lookup = {}.fromkeys([e.split()[0] for e in samples_to_discard])
temp_dm_data = []
new_dm_data = []
new_sample_ids = []
if negate:
def keep_sample(s):
return s in sample_lookup
else:
def keep_sample(s):
return s not in sample_lookup
for row, sample_id in zip(dm_data, sample_ids):
if keep_sample(sample_id):
temp_dm_data.append(row)
new_sample_ids.append(sample_id)
temp_dm_data = array(temp_dm_data).transpose()
for col, sample_id in zip(temp_dm_data, sample_ids):
if keep_sample(sample_id):
new_dm_data.append(col)
new_dm_data = array(new_dm_data).transpose()
return format_distance_matrix(new_sample_ids, new_dm_data)
def negate_tips_to_keep(tips_to_keep, tree):
""" Return the list of tips in the tree that are not in tips_to_keep"""
tips_to_keep = set(tips_to_keep)
# trees can return node names in ways that have multiple quotes, e.g.
# '"node_1"' or ''node_1''. remove them or it can cause problems with
# tips_to_keep not matching
tmp_tips = set([tip.Name for tip in tree.tips()])
tips = set([t.strip('\'').strip('\"') for t in tmp_tips])
return tips - tips_to_keep
def get_seqs_to_keep_lookup_from_biom(biom_f):
otu_table = load_table(biom_f)
return set(otu_table.ids(axis='observation'))
def get_seqs_to_keep_lookup_from_seq_id_file(id_to_keep_f):
"""generate a lookup dict of chimeras in chimera file."""
return (
set([l.split()[0].strip()
for l in id_to_keep_f if l.strip() and not l.startswith('#')])
)
get_seq_ids_from_seq_id_file = get_seqs_to_keep_lookup_from_seq_id_file
def get_seqs_to_keep_lookup_from_fasta_file(fasta_f):
"""return the sequence ids within the fasta file"""
return (
set([seq_id.split()[0] for seq_id, seq in parse_fasta(fasta_f)])
)
get_seq_ids_from_fasta_file = get_seqs_to_keep_lookup_from_fasta_file
# start functions used by filter_samples_from_otu_table.py and
# filter_otus_from_otu_table.py
def get_filter_function(ids_to_keep, min_count, max_count,
min_nonzero, max_nonzero, negate_ids_to_keep=False):
if negate_ids_to_keep:
def f(data_vector, id_, metadata):
return (id_ not in ids_to_keep) and \
(min_count <= data_vector.sum() <= max_count) and \
(min_nonzero <= (data_vector > 0).sum() <= max_nonzero)
else:
def f(data_vector, id_, metadata):
return (id_ in ids_to_keep) and \
(min_count <= data_vector.sum() <= max_count) and \
(min_nonzero <= (data_vector > 0).sum() <= max_nonzero)
return f
def filter_samples_from_otu_table(otu_table, ids_to_keep, min_count, max_count,
negate_ids_to_keep=False):
filter_f = get_filter_function({}.fromkeys(ids_to_keep),
min_count,
max_count,
0, inf, negate_ids_to_keep)
return otu_table.filter(filter_f, axis='sample', inplace=False)
def filter_otus_from_otu_table(otu_table, ids_to_keep, min_count, max_count,
min_samples, max_samples,
negate_ids_to_keep=False):
filter_f = get_filter_function({}.fromkeys(ids_to_keep),
min_count,
max_count,
min_samples, max_samples,
negate_ids_to_keep)
return otu_table.filter(filter_f, axis='observation', inplace=False)
# end functions used by filter_samples_from_otu_table.py and
# filter_otus_from_otu_table.py
def filter_otu_table_to_n_samples(otu_table, n):
""" Filter OTU table to n random samples.
If n is greater than the number of samples or less than zero a
ValueError will be raised.
"""
if not (0 < n <= len(otu_table.ids())):
raise ValueError("Number of samples to filter must be between 0 and "
"the number of samples.")
return otu_table.subsample(n, axis='sample', by_id=True)
def filter_otus_from_otu_map(input_otu_map_fp,
output_otu_map_fp,
min_count,
min_sample_count=1):
""" Filter otus with fewer than min_count sequences from input_otu_map_fp
With very large data sets the number of singletons can be very large,
and it becomes more efficent to filter them at the otu map stage than
the otu table stage.
There are two outputs from this function: the output file (which is the
filtered otu map) and the list of retained otu ids as a set. Since I
need to return the retained ids for pick_open_reference_otus, this
takes filepaths instead of file handles (since it can't be a generator
and return something).
"""
results = set()
output_otu_map_f = open(output_otu_map_fp, 'w')
for line in open(input_otu_map_fp, 'U'):
fields = line.strip().split('\t')
sample_ids = set([e.split('_')[0] for e in fields[1:]])
# only write this line if the otu has more than n sequences (so
# greater than n tab-separated fields including the otu identifier)
if (len(fields) > min_count) and (len(sample_ids) >= min_sample_count):
output_otu_map_f.write(line)
results.add(fields[0].split('\t')[0])
output_otu_map_f.close()
return results
def filter_tree(tree, tips_to_keep):
result = tree.copy()
# don't use this, it doesn't eliminate tips!
# result = tree.getSubTree(tips_to_keep,ignore_missing=True)
def f(node):
if node.istip() and\
node.Name is not None and\
node.Name not in tips_to_keep and\
node.Name.strip().strip('"').strip("'") not in tips_to_keep:
return True
return False
result.removeDeleted(f)
result.prune()
return result
| gpl-2.0 |
viaregio/cartridge | cartridge/shop/tests.py | 2 | 20578 |
from datetime import timedelta
from decimal import Decimal
from operator import mul
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.client import RequestFactory
from django.utils.timezone import now
from django.utils.unittest import skipUnless
from mezzanine.conf import settings
from mezzanine.core.models import CONTENT_STATUS_PUBLISHED
from mezzanine.utils.tests import run_pyflakes_for_package
from mezzanine.utils.tests import run_pep8_for_package
from cartridge.shop.models import Product, ProductOption, ProductVariation
from cartridge.shop.models import Category, Cart, Order, DiscountCode
from cartridge.shop.models import Sale
from cartridge.shop.forms import OrderForm
from cartridge.shop.checkout import CHECKOUT_STEPS
TEST_STOCK = 5
TEST_PRICE = Decimal("20")
class ShopTests(TestCase):
def setUp(self):
"""
Set up test data - category, product and options.
"""
self._published = {"status": CONTENT_STATUS_PUBLISHED}
self._category = Category.objects.create(**self._published)
self._product = Product.objects.create(**self._published)
for option_type in settings.SHOP_OPTION_TYPE_CHOICES:
for i in range(10):
name = "test%s" % i
ProductOption.objects.create(type=option_type[0], name=name)
self._options = ProductOption.objects.as_fields()
def test_views(self):
"""
Test the main shop views for errors.
"""
# Category.
response = self.client.get(self._category.get_absolute_url())
self.assertEqual(response.status_code, 200)
# Product.
response = self.client.get(self._product.get_absolute_url())
self.assertEqual(response.status_code, 200)
# Cart.
response = self.client.get(reverse("shop_cart"))
self.assertEqual(response.status_code, 200)
# Checkout.
response = self.client.get(reverse("shop_checkout"))
self.assertEqual(response.status_code, 200 if not
settings.SHOP_CHECKOUT_ACCOUNT_REQUIRED else 302)
def test_variations(self):
"""
Test creation of variations from options, and management of empty
variations.
"""
total = reduce(mul, [len(v) for v in self._options.values()])
# Clear variations.
self._product.variations.all().delete()
self.assertEqual(self._product.variations.count(), 0)
# Create single empty variation.
self._product.variations.manage_empty()
self.assertEqual(self._product.variations.count(), 1)
# Create variations from all options.
self._product.variations.create_from_options(self._options)
# Should do nothing.
self._product.variations.create_from_options(self._options)
# All options plus empty.
self.assertEqual(self._product.variations.count(), total + 1)
# Remove empty.
self._product.variations.manage_empty()
self.assertEqual(self._product.variations.count(), total)
def test_stock(self):
"""
Test stock checking on product variations.
"""
self._product.variations.all().delete()
self._product.variations.manage_empty()
variation = self._product.variations.all()[0]
variation.num_in_stock = TEST_STOCK
# Check stock field not in use.
self.assertTrue(variation.has_stock())
# Check available and unavailable quantities.
self.assertTrue(variation.has_stock(TEST_STOCK))
self.assertFalse(variation.has_stock(TEST_STOCK + 1))
# Check sold out.
variation = self._product.variations.all()[0]
variation.num_in_stock = 0
self.assertFalse(variation.has_stock())
def assertCategoryFilteredProducts(self, num_products):
"""
Tests the number of products returned by the category's
current filters.
"""
products = Product.objects.filter(self._category.filters())
self.assertEqual(products.distinct().count(), num_products)
def test_category_filters(self):
"""
Test the category filters returns expected results.
"""
self._product.variations.all().delete()
self.assertCategoryFilteredProducts(0)
# Test option filters - add a variation with one option, and
# assign another option as a category filter. Check that no
# products match the filters, then add the first option as a
# category filter and check that the product is matched.
option_field, options = self._options.items()[0]
option1, option2 = options[:2]
# Variation with the first option.
self._product.variations.create_from_options({option_field: [option1]})
# Filter with the second option
option = ProductOption.objects.get(type=option_field[-1], name=option2)
self.assertCategoryFilteredProducts(0)
# First option as a filter.
option = ProductOption.objects.get(type=option_field[-1], name=option1)
self._category.options.add(option)
self.assertCategoryFilteredProducts(1)
# Test price filters - add a price filter that when combined
# with previously created filters, should match no products.
# Update the variations to match the filter for a unit price,
# then with sale prices, checking correct matches based on sale
# dates.
self._category.combined = True
self._category.price_min = TEST_PRICE
self.assertCategoryFilteredProducts(0)
self._product.variations.all().update(unit_price=TEST_PRICE)
self.assertCategoryFilteredProducts(1)
n, d = now(), timedelta(days=1)
tomorrow, yesterday = n + d, n - d
self._product.variations.all().update(unit_price=0,
sale_price=TEST_PRICE,
sale_from=tomorrow)
self.assertCategoryFilteredProducts(0)
self._product.variations.all().update(sale_from=yesterday)
self.assertCategoryFilteredProducts(1)
# Clean up previously added filters and check that explicitly
# assigned products match.
for option in self._category.options.all():
self._category.options.remove(option)
self._category.price_min = None
self.assertCategoryFilteredProducts(0)
self._category.products.add(self._product)
self.assertCategoryFilteredProducts(1)
# Test the ``combined`` field - create a variation which
# matches a price filter, and a separate variation which
# matches an option filter, and check that the filters
# have no results when ``combined`` is set, and that the
# product matches when ``combined`` is disabled.
self._product.variations.all().delete()
self._product.variations.create_from_options({option_field:
[option1, option2]})
# Price variation and filter.
variation = self._product.variations.get(**{option_field: option1})
variation.unit_price = TEST_PRICE
variation.save()
self._category.price_min = TEST_PRICE
# Option variation and filter.
option = ProductOption.objects.get(type=option_field[-1], name=option2)
self._category.options.add(option)
# Check ``combined``.
self._category.combined = True
self.assertCategoryFilteredProducts(0)
self._category.combined = False
self.assertCategoryFilteredProducts(1)
def _add_to_cart(self, variation, quantity):
"""
Given a variation, creates the dict for posting to the cart
form to add the variation, and posts it.
"""
field_names = [f.name for f in ProductVariation.option_fields()]
data = dict(zip(field_names, variation.options()))
data["quantity"] = quantity
self.client.post(variation.product.get_absolute_url(), data)
def _empty_cart(self, cart):
"""
Given a cart, creates the dict for posting to the cart form
to remove all items from the cart, and posts it.
"""
data = {"items-INITIAL_FORMS": 0, "items-TOTAL_FORMS": 0,
"update_cart": 1}
for i, item in enumerate(cart):
data["items-INITIAL_FORMS"] += 1
data["items-TOTAL_FORMS"] += 1
data["items-%s-id" % i] = item.id
data["items-%s-DELETE" % i] = "on"
self.client.post(reverse("shop_cart"), data)
def _reset_variations(self):
"""
Recreates variations and sets up the first.
"""
self._product.variations.all().delete()
self._product.variations.create_from_options(self._options)
variation = self._product.variations.all()[0]
variation.unit_price = TEST_PRICE
variation.num_in_stock = TEST_STOCK * 2
variation.save()
def test_cart(self):
"""
Test the cart object and cart add/remove forms.
"""
# Test initial cart.
cart = Cart.objects.from_request(self.client)
self.assertFalse(cart.has_items())
self.assertEqual(cart.total_quantity(), 0)
self.assertEqual(cart.total_price(), Decimal("0"))
# Add quantity and check stock levels / cart totals.
self._reset_variations()
variation = self._product.variations.all()[0]
self._add_to_cart(variation, TEST_STOCK)
cart = Cart.objects.from_request(self.client)
variation = self._product.variations.all()[0]
self.assertTrue(variation.has_stock(TEST_STOCK))
self.assertFalse(variation.has_stock(TEST_STOCK * 2))
self.assertTrue(cart.has_items())
self.assertEqual(cart.total_quantity(), TEST_STOCK)
self.assertEqual(cart.total_price(), TEST_PRICE * TEST_STOCK)
# Add remaining quantity and check again.
self._add_to_cart(variation, TEST_STOCK)
cart = Cart.objects.from_request(self.client)
variation = self._product.variations.all()[0]
self.assertFalse(variation.has_stock())
self.assertTrue(cart.has_items())
self.assertEqual(cart.total_quantity(), TEST_STOCK * 2)
self.assertEqual(cart.total_price(), TEST_PRICE * TEST_STOCK * 2)
# Remove from cart.
self._empty_cart(cart)
cart = Cart.objects.from_request(self.client)
variation = self._product.variations.all()[0]
self.assertTrue(variation.has_stock(TEST_STOCK * 2))
self.assertFalse(cart.has_items())
self.assertEqual(cart.total_quantity(), 0)
self.assertEqual(cart.total_price(), Decimal("0"))
def test_discount_codes(self):
"""
Test that all types of discount codes are applied.
"""
self._reset_variations()
variation = self._product.variations.all()[0]
invalid_product = Product.objects.create(**self._published)
invalid_product.variations.create_from_options(self._options)
invalid_variation = invalid_product.variations.all()[0]
invalid_variation.unit_price = TEST_PRICE
invalid_variation.num_in_stock = TEST_STOCK * 2
invalid_variation.save()
discount_value = TEST_PRICE / 2
# Set up discounts with and without a specific product, for
# each type of discount.
for discount_target in ("cart", "item"):
for discount_type in ("percent", "deduct"):
code = "%s_%s" % (discount_target, discount_type)
kwargs = {
"code": code,
"discount_%s" % discount_type: discount_value,
"active": True,
}
cart = Cart.objects.from_request(self.client)
self._empty_cart(cart)
self._add_to_cart(variation, 1)
self._add_to_cart(invalid_variation, 1)
discount = DiscountCode.objects.create(**kwargs)
if discount_target == "item":
discount.products.add(variation.product)
post_data = {"discount_code": code}
self.client.post(reverse("shop_cart"), post_data)
discount_total = self.client.session["discount_total"]
if discount_type == "percent":
expected = TEST_PRICE / Decimal("100") * discount_value
if discount_target == "cart":
# Excpected amount applies to entire cart.
cart = Cart.objects.from_request(self.client)
expected *= cart.items.count()
elif discount_type == "deduct":
expected = discount_value
self.assertEqual(discount_total, expected)
if discount_target == "item":
# Test discount isn't applied for an invalid product.
cart = Cart.objects.from_request(self.client)
self._empty_cart(cart)
self._add_to_cart(invalid_variation, 1)
self.client.post(reverse("shop_cart"), post_data)
discount_total = self.client.session.get("discount_total")
self.assertEqual(discount_total, None)
def test_order(self):
"""
Test that a completed order contains cart items and that
they're removed from stock.
"""
# Add to cart.
self._reset_variations()
variation = self._product.variations.all()[0]
self._add_to_cart(variation, TEST_STOCK)
cart = Cart.objects.from_request(self.client)
# Post order.
data = {
"step": len(CHECKOUT_STEPS),
"billing_detail_email": "[email protected]",
"discount_code": "",
}
for field_name, field in OrderForm(None, None).fields.items():
value = field.choices[-1][1] if hasattr(field, "choices") else "1"
data.setdefault(field_name, value)
self.client.post(reverse("shop_checkout"), data)
try:
order = Order.objects.from_request(self.client)
except Order.DoesNotExist:
self.fail("Couldn't create an order")
items = order.items.all()
variation = self._product.variations.all()[0]
self.assertEqual(cart.total_quantity(), 0)
self.assertEqual(len(items), 1)
self.assertEqual(items[0].sku, variation.sku)
self.assertEqual(items[0].quantity, TEST_STOCK)
self.assertEqual(variation.num_in_stock, TEST_STOCK)
self.assertEqual(order.item_total, TEST_PRICE * TEST_STOCK)
def test_syntax(self):
"""
Run pyflakes/pep8 across the code base to check for potential errors.
"""
extra_ignore = (
"redefinition of unused 'digest'",
"redefinition of unused 'OperationalError'",
"'from mezzanine.project_template.settings import *' used",
)
warnings = []
warnings.extend(run_pyflakes_for_package("cartridge",
extra_ignore=extra_ignore))
warnings.extend(run_pep8_for_package("cartridge"))
if warnings:
self.fail("Syntax warnings!\n\n%s" % "\n".join(warnings))
class SaleTests(TestCase):
def setUp(self):
product1 = Product(unit_price="1.27")
product1.save()
ProductVariation(unit_price="1.27", product_id=product1.id).save()
ProductVariation(unit_price="1.27", product_id=product1.id).save()
product2 = Product(unit_price="1.27")
product2.save()
ProductVariation(unit_price="1.27", product_id=product2.id).save()
ProductVariation(unit_price="1.27", product_id=product2.id).save()
sale = Sale(
title="30% OFF - Ken Bruce has gone mad!",
discount_percent="30"
)
sale.save()
sale.products.add(product1)
sale.products.add(product2)
sale.save()
def test_sale_save(self):
"""
Regression test for GitHub issue #24. Incorrect exception handle meant
that in some cases (usually percentage discount) sale_prices were not
being applied to all products and their varitations.
Note: This issues was only relevant using MySQL and with exceptions
turned on (which is the default when DEBUG=True).
"""
# Initially no sale prices will be set.
for product in Product.objects.all():
self.assertFalse(product.sale_price)
for variation in ProductVariation.objects.all():
self.assertFalse(variation.sale_price)
# Activate the sale and verify the prices.
sale = Sale.objects.all()[0]
sale.active = True
sale.save()
# Afterward ensure that all the sale prices have been updated.
for product in Product.objects.all():
self.assertTrue(product.sale_price)
for variation in ProductVariation.objects.all():
self.assertTrue(variation.sale_price)
try:
__import__("stripe")
import mock
except ImportError:
stripe_used = False
else:
stripe_handler = "cartridge.shop.payment.stripe_api.process"
stripe_used = settings.SHOP_HANDLER_PAYMENT == stripe_handler
if stripe_used:
settings.STRIPE_API_KEY = "dummy"
from cartridge.shop.payment import stripe_api
class StripeTests(TestCase):
"""Test the Stripe payment backend"""
def setUp(self):
# Every test needs access to the request factory.
self.factory = RequestFactory()
def test_charge(self, mock_charge):
# Create a fake request object with the test data
request = self.factory.post("/shop/checkout/")
request.POST["card_number"] = "4242424242424242"
request.POST["card_expiry_month"] = "06"
request.POST["card_expiry_year"] = "2014"
request.POST["billing_detail_street"] = "123 Evergreen Terrace"
request.POST["billing_detail_city"] = "Springfield"
request.POST["billing_detail_state"] = "WA"
request.POST["billing_detail_postcode"] = "01234"
request.POST["billing_detail_country"] = "USA"
# Order form isn't used by stripe backend
order_form = None
# Create an order
order = Order.objects.create(total=Decimal("22.37"))
# Code under test
stripe_api.process(request, order_form, order)
# Assertion
mock_charge.create.assert_called_with(
amount=2237,
currency="usd",
card={'number': "4242424242424242",
'exp_month': "06",
'exp_year': "14",
'address_line1': "123 Evergreen Terrace",
'address_city': "Springfield",
'address_state': "WA",
'address_zip': "01234",
'country': "USA"})
StripeTests = skipUnless(stripe_used, "Stripe not used")(StripeTests)
if stripe_used:
charge = "stripe.Charge"
StripeTests.test_charge = mock.patch(charge)(StripeTests.test_charge)
class TaxationTests(TestCase):
def test_default_handler_exists(self):
'''
Ensure that the handler specified in default settings exists as well as
the default setting itself.
'''
from mezzanine.utils.importing import import_dotted_path
settings.use_editable()
assert hasattr(settings, 'SHOP_HANDLER_TAX'), \
'Setting SHOP_HANDLER_TAX not found.'
handler = lambda s: import_dotted_path(s) if s else lambda *args: None
tax_handler = handler(settings.SHOP_HANDLER_TAX)
assert tax_handler is not None, \
'Could not find default SHOP_HANDLER_TAX function.'
def test_set_tax(self):
'''
Regression test to ensure that set_tax still sets the appropriate
session variables.
'''
from cartridge.shop.utils import set_tax
tax_type = 'Tax for Testing'
tax_total = 56.65
class request:
session = {}
set_tax(request, tax_type, tax_total)
assert request.session.get('tax_type') == tax_type, \
'tax_type not set with set_tax'
assert request.session.get('tax_total') == tax_total, \
'tax_total not set with set_tax'
| bsd-2-clause |
venkatant/msproject | flow_statistics.py | 1 | 7329 | __author__ = 'venkat'
from header import *
from json_http_handler import *
class FlowWindow:
bottom_frame = 0
bottom_row = 0
class FlowTable:
def __init__(self):
self.dest_ip = None
self.dest_mask = None
self.dest_mac = None
self.dest_port = None
self.dest_node = None
return
def updateflowtable(self, destIp, destMask, destMac, destPort, destNode):
self.dest_ip = destIp
self.dest_mask = destMask
self.dest_mac = destMac
self.dest_port = destPort
self.dest_node = destNode
return
def displayflowtable(self):
print(self.dest_ip,
self.dest_mask,
self.dest_mac,
self.dest_port,
self.dest_node)
return
class FlowStatistics:
def __init__(self):
self.listbox = None
self.toplevel = None
self.no_of_flows = 0
def CurSelet(self):
print("Hello")
switch = str((self.mylistbox.get(self.mylistbox.curselection())))
print(switch)
def fillListWithNodesInfo(self):
'''
Create an object of Http JSON Handler Class to receive
resp from respective Rest URL's
'''
http_obj = HttpJsonHandler()
json_nodes = http_obj.getnodeinfo()
for node in json_nodes['nodeProperties']:
self.listbox.insert(END, node['node']['id'])
def displayFlowTableTitle(self, bottom_frame, bottom_row):
for column in range(5):
if column == 0:
label = Label(bottom_frame, text="Destination IP", borderwidth=0, width=15, fg="red")
elif column == 1:
label = Label(bottom_frame, text="Destination Mask", borderwidth=0, width=15, fg="red")
elif column == 2:
label = Label(bottom_frame, text="Output Mac", borderwidth=0, width=15, fg="red")
elif column == 3:
label = Label(bottom_frame, text="Output Port", borderwidth=0, width=15, fg="red")
elif column == 4:
label = Label(bottom_frame, text="Output Node", borderwidth=0, width=25, fg="red")
label.configure(bg="white")
label.grid(row=bottom_row, column=column, sticky="nsew", padx=1, pady=1)
return
def displayFlowTableContent(self, flow_list, flow_window_obj):
bottom_frame = flow_window_obj.bottom_frame
bottom_row = flow_window_obj.bottom_row
#for row in range(4):
for row in flow_list:
current_row = []
for column in range(5):
if column == 0:
label = Label(bottom_frame, text="%s" % row.dest_ip, borderwidth=0, width=15)
elif column == 1:
label = Label(bottom_frame, text="%s" % row.dest_mask, borderwidth=0, width=15)
elif column == 2:
label = Label(bottom_frame, text="%s" % row.dest_mac, borderwidth=0, width=15)
elif column == 3:
label = Label(bottom_frame, text="%s" % row.dest_port, borderwidth=0, width=15)
elif column == 4:
label = Label(bottom_frame, text="%s" % row.dest_node, borderwidth=0, width=25)
label.configure(bg="white")
label.grid(row=bottom_row, column=column, sticky="nsew", padx=1, pady=1)
current_row.append(label)
bottom_row += 1
for column in range(5):
bottom_frame.grid_columnconfigure(column, weight=1)
return
def CurListSelet(self, evt, flow_window_obj):
#mylistbox = evt.widget
switch=str((self.listbox.get(self.listbox.curselection())))
print(switch)
'''
Create an object of Http JSON Handler Class to receive
resp from respective Rest URL's
'''
http_obj = HttpJsonHandler()
json_flows = http_obj.getflowinfo(switch)
no_of_flows = 0
flow_list = []
for flowCount in json_flows['flowStatistic']:
destIp = json_flows['flowStatistic'][no_of_flows]['flow']['match']['matchField'][0]['value']
destMask = json_flows['flowStatistic'][no_of_flows]['flow']['match']['matchField'][0]['mask']
destPort = 0
destnode = '00:00:00:00:00:00:00:00'
try:
destMac = json_flows['flowStatistic'][no_of_flows]['flow']['actions'][0]['address']
try:
destPort = json_flows['flowStatistic'][no_of_flows]['flow']['actions'][1]['port']['id']
destnode = json_flows['flowStatistic'][no_of_flows]['flow']['actions'][1]['port']['node']['id']
except:
print('')
except KeyError:
destPort = json_flows['flowStatistic'][no_of_flows]['flow']['actions'][0]['port']['id']
destnode = json_flows['flowStatistic'][no_of_flows]['flow']['actions'][0]['port']['node']['id']
destMac = '000000000000'
# destIp, destMask, destMac, destPort, destNode
# Create an instance of FlowTable class
flow_table_entry = FlowTable()
flow_table_entry.updateflowtable(destIp, destMask, destMac, destPort, destnode)
flow_list.append(flow_table_entry)
no_of_flows += 1
flow_table_entry.displayflowtable()
# sort the list with switch_is as Key
flow_list.sort(key=lambda host:host.dest_ip)
self.displayFlowTableContent(flow_list, flow_window_obj)
def flowstatistics():
# Create an instance of FlowTable class
#flow_table_entry = FlowTable()
# Create an instance of FlowStatistics class
obj = FlowStatistics()
'''
scrollbar.config(command=obj.mylistbox.yview)
submit = Button(obj.toplevel, text="Submit", command=obj.CurSelet)
submit.pack()
'''
toplevel = Toplevel()
toplevel.title("Flow Monitoring")
toplevel.geometry("750x250")
top_row = 0
bottom_row = 0
top_frame = Frame(toplevel)
top_frame.pack(side=TOP)
top_label = Label(top_frame, text=" SELECT SWITCH TO GET FLOW ENTRIES", fg="red", borderwidth=0, width=40)
top_label.grid(row=top_row, rowspan=1)
top_row += 1
bottom_frame = Frame(toplevel)
bottom_frame.pack(side=TOP)
bottom_label = Label(bottom_frame, fg="green")
bottom_label.grid(row=bottom_row)
bottom_row += 1
scrollbar = Scrollbar(top_frame)
obj.listbox = Listbox(top_frame, yscrollcommand=scrollbar.set)
obj.listbox.config(height=4)
# Fills the list of nodes in the List Box
obj.fillListWithNodesInfo()
obj.listbox.grid(row=top_row, column=0, sticky="nsew", padx=1, pady=1)
scrollbar.grid(row=top_row, column=1, sticky="nsew", padx=1, pady=1)
scrollbar.config(command=obj.listbox.yview)
obj.displayFlowTableTitle(bottom_frame, bottom_row)
bottom_row += 1
flow_window_obj = FlowWindow()
flow_window_obj.bottom_row = bottom_row
flow_window_obj.bottom_frame = bottom_frame
# Below code to activate on selection of items in List Box
obj.listbox.bind('<<ListboxSelect>>', lambda event, arg=flow_window_obj: obj.CurListSelet(event, flow_window_obj))
return | gpl-2.0 |
ninotoshi/tensorflow | tensorflow/contrib/learn/python/learn/tests/test_custom_decay.py | 7 | 2270 | # Copyright 2015-present The Scikit Flow 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import random
from tensorflow.contrib.learn.python import learn
from tensorflow.contrib.learn.python.learn import datasets
from tensorflow.contrib.learn.python.learn.estimators._sklearn import accuracy_score
from tensorflow.contrib.learn.python.learn.estimators._sklearn import train_test_split
class CustomDecayTest(tf.test.TestCase):
def testIrisExponentialDecay(self):
random.seed(42)
iris = datasets.load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris.data,
iris.target,
test_size=0.2,
random_state=42)
# setup exponential decay function
def exp_decay(global_step):
return tf.train.exponential_decay(learning_rate=0.1,
global_step=global_step,
decay_steps=100,
decay_rate=0.001)
classifier = learn.TensorFlowDNNClassifier(hidden_units=[10, 20, 10],
n_classes=3,
steps=500,
learning_rate=exp_decay)
classifier.fit(X_train, y_train)
score = accuracy_score(y_test, classifier.predict(X_test))
self.assertGreater(score, 0.65, "Failed with score = {0}".format(score))
if __name__ == "__main__":
tf.test.main()
| apache-2.0 |
rosenvladimirov/odoo-fixes | stock_account/wizard/stock_change_standard_price.py | 315 | 3824 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import fields, osv
from openerp.tools.translate import _
import openerp.addons.decimal_precision as dp
class change_standard_price(osv.osv_memory):
_name = "stock.change.standard.price"
_description = "Change Standard Price"
_columns = {
'new_price': fields.float('Price', required=True, digits_compute=dp.get_precision('Product Price'),
help="If cost price is increased, stock variation account will be debited "
"and stock output account will be credited with the value = (difference of amount * quantity available).\n"
"If cost price is decreased, stock variation account will be creadited and stock input account will be debited."),
}
def default_get(self, cr, uid, fields, context=None):
""" To get default values for the object.
@param self: The object pointer.
@param cr: A database cursor
@param uid: ID of the user currently logged in
@param fields: List of fields for which we want default values
@param context: A standard dictionary
@return: A dictionary which of fields with values.
"""
if context is None:
context = {}
if context.get("active_model") == 'product.product':
product_pool = self.pool.get('product.product')
else:
product_pool = self.pool.get('product.template')
product_obj = product_pool.browse(cr, uid, context.get('active_id', False))
res = super(change_standard_price, self).default_get(cr, uid, fields, context=context)
price = product_obj.standard_price
if 'new_price' in fields:
res.update({'new_price': price})
return res
def change_price(self, cr, uid, ids, context=None):
""" Changes the Standard Price of Product.
And creates an account move accordingly.
@param self: The object pointer.
@param cr: A database cursor
@param uid: ID of the user currently logged in
@param ids: List of IDs selected
@param context: A standard dictionary
@return:
"""
if context is None:
context = {}
rec_id = context.get('active_id', False)
assert rec_id, _('Active ID is not set in Context.')
if context.get("active_model") == 'product.product':
prod_obj = self.pool.get('product.product')
rec_id = prod_obj.browse(cr, uid, rec_id, context=context).product_tmpl_id.id
prod_obj = self.pool.get('product.template')
res = self.browse(cr, uid, ids, context=context)
prod_obj.do_change_standard_price(cr, uid, [rec_id], res[0].new_price, context)
return {'type': 'ir.actions.act_window_close'}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
tracyjacks/PyMetWeather | pymetweather/pymetweather.py | 1 | 13941 | import curses
from datetime import date, timedelta
import locale
from textwrap import fill
from pymetweather.forecasts import WeatherForecast
from pymetweather.get_args import get_command_line_args, get_config_args
locale.setlocale(locale.LC_ALL, '')
class WeatherPrinter(object):
def __init__(self, forecast, screen_width):
self.fcs = forecast
self.cols = [
(['Time'], 5, '{$:02}:00'),
(['Conditions'], 22, '{W}'),
(['Precipitation', 'probability'], 15, '{Pp:>3} %'),
(['Temperature', '(Feels Like)'], 14, '{T:>2} {F} °C'),
(['Wind Speed', '(Gust)'], 16, '{S:>2} {G} mph'),
(['Wind', 'Direction'], 12, '{D:>3}'),
(['Relative', 'Humidity'], 10, '{H} %'),
(['Visibility'], 12, '{V}'),
(['UV', 'Index'], 7, '{U}')]
self.daily_cols = [
(['Day'], 13, '{$}', '{$}'),
(['Conditions'], 22, '{W}', '{W}'),
(['Precipitation', 'probability'], 15,
'{PPd:>3} %', '{PPn:>3} %'),
(['Max day/', 'Min night', 'Temperature', '(Feels like)'], 14,
'{Dm:>2} {FDm} °C', '{Nm:>2} {FNm} °C'),
(['Wind Speed', '(Gust)'], 16,
'{S:>2} {Gn} mph', '{S:>2} {Gm} mph'),
(['Wind', 'Direction'], 12, '{D:>3}', '{D:>3}'),
(['Relative', 'Humidity'], 10, '{Hn} %', '{Hm} %'),
(['Visibility'], 12, '{V}', '{V}')]
self.top_pad = curses.newpad(2000, 500)
self.tab_pad = curses.newpad(2000, 500)
self.bottom_bar = curses.newpad(1, 500)
self.help_screen_pad = curses.newpad(500, 500)
self.top_maxy = 0
self.tab_maxy = 0
self.tab_maxx = 0
self.screen_width = screen_width
self.print_bottom_bar()
self.setup_help()
@staticmethod
def addustr(win, text, *args):
win.addstr(text.encode('utf-8'), *args)
def print_help_screen(self, top_only):
if not top_only:
self.addustr(self.tab_pad, self.help_string)
self.tab_maxy = self.help_maxy
self.tab_maxx = self.help_maxx
def setup_help(self):
help = [
('q', 'Quit'),
('?', 'Show this help'),
('t', "Today's weather"),
('d', 'Five day summary'),
('0', "Today's weather"),
('1', "Tomorrow's weather"),
('2', 'Weather for 2 days later'),
('3', 'Weather for 3 days later'),
('4', 'Weather for 4 days later'),
('5–9', 'UK outlook for the next month'),
('l', 'UK outlook for the next month'),
('left arrow', 'scroll left'),
('right arrow', 'scroll left'),
('up arrow', 'scroll up'),
('down arrow', 'scroll down'),
]
c1width = max([len(k[0]) for k in help])
c2width = max([len(k[1]) for k in help])
self.help_string = ''
for h in help:
self.help_string += h[0].ljust(c1width + 1) + ' : ' + h[1] + '\n'
self.help_string = self.help_string.strip('\n')
self.help_maxy = len(help) - 1
self.help_maxx = c1width + c2width - 1
def print_bottom_bar(self):
self.addustr(
self.bottom_bar, '?: help q: quit t: today '
'd: 5 day summary 1–4: days 1 to 4 '
'l: longterm'.ljust(499),
curses.A_REVERSE | curses.A_BOLD)
def print_longer_term_weather(self):
regf1 = self.fcs.reg_fcs[2]['Paragraph']
regf2 = self.fcs.reg_fcs[3]['Paragraph']
self.addustr(
self.top_pad, self.wrap_text(regf1['title']), curses.A_BOLD)
self.addustr(self.top_pad, '\n' + self.wrap_text(regf1['$']) + '\n\n')
self.addustr(
self.top_pad, self.wrap_text(regf2['title']), curses.A_BOLD)
self.addustr(self.top_pad, '\n' + self.wrap_text(regf2['$']))
self.top_maxy = self.top_pad.getyx()[0] + 1
def wrap_text(self, text):
return fill(text, self.screen_width)
def print_hourly_top(self, n_day, day):
title = 'Weather for {}, {}'.format(
self.fcs.site_name, day.strftime('%A %d %B %Y'))
self.addustr(self.top_pad, self.wrap_text(title) + '\n', curses.A_BOLD)
regfindex = 0
regf = self.fcs.reg_fcs[0]['Paragraph']
if n_day == 0:
if 'Headline' in regf[regfindex]['title']:
self.addustr(self.top_pad, self.wrap_text(regf[regfindex]['$'])
+ '\n\n')
regfindex += 1
if 'Today' in regf[regfindex]['title']:
today_text = self.wrap_text('Today: ' + regf[regfindex]['$'])
self.addustr(self.top_pad, today_text[:7], curses.A_BOLD)
self.addustr(self.top_pad, today_text[7:] + '\n\n')
regfindex += 1
if 'Tonight' in regf[regfindex]['title']:
tonight_text = self.wrap_text(regf[regfindex]['title'] + ' ' +
regf[regfindex]['$'])
lent = len(regf[regfindex]['title'])
self.addustr(self.top_pad, tonight_text[:lent], curses.A_BOLD)
self.addustr(self.top_pad, tonight_text[lent:] + '\n\n')
regfindex += 1
elif n_day == 1:
for regfindex in range(len(regf)):
if day.strftime('%A') in regf[regfindex]['title']:
self.addustr(
self.top_pad,
self.wrap_text(regf[regfindex]['$']) + '\n\n')
break
else:
regf = self.fcs.reg_fcs[1]['Paragraph']
outlook = self.wrap_text(regf['title'] + ' ' + regf['$'])
lent = len(regf['title']) + 1
self.addustr(self.top_pad, '\n' + outlook[:lent], curses.A_BOLD)
self.addustr(self.top_pad, outlook[lent:] + '\n\n')
self.top_maxy = self.top_pad.getyx()[0] + 1
def print_hourly_tab(self, n_day, period):
width_counter = 0
for c in self.cols:
for i, head in enumerate(c[0]):
head_text = '{:^{}}'.format(head, c[1])
self.tab_pad.move(i, width_counter)
self.addustr(self.tab_pad, head_text, curses.A_BOLD)
width_counter += c[1]
top_row = (
self.tab_pad.getyx()[0] + max([len(c[0]) for c in self.cols]) - 1)
for i, rep in enumerate(period['Rep']):
width_counter = 0
for c in self.cols:
cell_text = '{:^{}}'.format(c[2].format(**rep), c[1])
self.tab_pad.move(top_row + i, width_counter)
self.addustr(self.tab_pad, cell_text)
width_counter += c[1]
self.tab_maxy = self.tab_pad.getyx()[0]
self.tab_maxx = sum([c[1] for c in self.cols]) - 2
def print_hourly_weather(self, n_day, top_only=False):
day = date.today() + timedelta(n_day)
period = self.fcs.hourly_fcs['Period'][n_day]
assert period['value'] == day.strftime('%Y-%m-%dZ')
self.print_hourly_top(n_day, day)
if not top_only:
self.print_hourly_tab(n_day, period)
def print_weather_brief(self, top_only=False):
period = self.fcs.daily_fcs['Period']
width_counter = 0
for c in self.daily_cols:
for i, head in enumerate(c[0]):
head_text = '{:^{}}'.format(head, c[1])
self.tab_pad.move(i, width_counter)
self.addustr(self.tab_pad, head_text, curses.A_BOLD)
width_counter += c[1]
top_row = (
self.tab_pad.getyx()[0] +
max([len(c[0]) for c in self.daily_cols]))
c = self.daily_cols[0]
for i, rep in enumerate(period):
cell_text = '{:<{}} '.format(rep['value'], c[1] - 3)
self.tab_pad.move(top_row + i * 4, 0)
self.addustr(self.tab_pad, cell_text)
cell_text = '{:>{}} '.format(
c[2].format(**rep['Rep'][0]), c[1] - 3)
self.tab_pad.move(top_row + i * 4 + 1, 0)
self.addustr(self.tab_pad, cell_text)
cell_text = '{:>{}} '.format(
c[3].format(**rep['Rep'][1]), c[1] - 3)
self.tab_pad.move(top_row + i * 4 + 2, 0)
self.addustr(self.tab_pad, cell_text)
for i, rep in enumerate(period):
rep = rep['Rep']
width_counter = self.daily_cols[0][1]
for c in self.daily_cols[1:]:
cell_text = '{:^{}}'.format(c[2].format(**rep[0]), c[1])
self.tab_pad.move(top_row + i * 4 + 1, width_counter)
self.addustr(self.tab_pad, cell_text)
cell_text = '{:^{}}'.format(c[3].format(**rep[1]), c[1])
self.tab_pad.move(top_row + i * 4 + 2, width_counter)
self.addustr(self.tab_pad, cell_text)
width_counter += c[1]
self.tab_maxy = self.tab_pad.getyx()[0]
self.tab_maxx = sum([c[1] for c in self.daily_cols]) - 2
def print_screen(self, screen, screen_width=None, top_only=False):
if screen_width is not None:
self.screen_width = screen_width
self.top_pad.clear()
self.top_maxy = 0
if not top_only:
self.tab_maxy = 0
self.tab_maxx = 0
self.tab_pad.clear()
if screen in range(0, 5):
self.print_hourly_weather(screen, top_only)
elif screen == 8:
self.print_longer_term_weather()
elif screen == 7:
self.print_weather_brief(top_only)
elif screen == 9:
self.print_help_screen(top_only)
class WeatherApp(object):
key_map = {
'0': 0, '1': 1, '2': 2, '3': 3, '4': 4,
'5': 8, '6': 8, '7': 8, '8': 8, '9': 9,
't': 0,
'l': 8,
'd': 7,
'b': 7,
'?': 9}
def __init__(self, stdscr, fcs, start_screen=0):
self.stdscr = stdscr
curses.curs_set(0)
curses.use_default_colors()
self.fcs = fcs
self.scrolly = 0
self.scrollx = 0
self.maxy = 0
self.maxx = 0
self.y = self.stdscr.getmaxyx()[0] - 1
self.x = self.stdscr.getmaxyx()[1] - 1
self.printer = WeatherPrinter(self.fcs, self.x + 1)
self.print_screen(start_screen)
def print_resize(self):
self.y = self.stdscr.getmaxyx()[0] - 1
self.x = self.stdscr.getmaxyx()[1] - 1
self.printer.print_screen(self.screen_showing, self.x + 1, True)
self.maxx = max(self.printer.tab_maxx, self.x - 1)
self.maxy = self.printer.tab_maxy + self.printer.top_maxy
if self.y > (self.maxy - self.scrolly):
self.scrolly = max(self.maxy - (self.y - 1), 0)
if self.x > (self.maxx - self.scrollx):
self.scrollx = max(self.maxx - (self.x - 1), 0)
self.draw_screen()
def print_screen(self, screen):
self.screen_showing = screen
self.scrolly = 0
self.scrollx = 0
self.printer.print_screen(self.screen_showing)
self.maxy = self.printer.tab_maxy + self.printer.top_maxy
self.maxx = max(self.printer.tab_maxx, self.x - 1)
self.draw_screen()
def draw_screen(self):
self.stdscr.clear()
self.stdscr.refresh()
top_y = self.printer.top_maxy
try:
assert self.y == self.stdscr.getmaxyx()[0] - 1
assert self.x == self.stdscr.getmaxyx()[1] - 1
except AssertionError:
self.print_resize()
return
self.printer.top_pad.noutrefresh(
self.scrolly, 0, 0, 0, min(top_y, self.y), self.x)
if self.y - (top_y - self.scrolly) > 1:
self.printer.tab_pad.noutrefresh(
max(0, self.scrolly - top_y), self.scrollx,
top_y - self.scrolly, 0,
self.y, self.x)
self.printer.bottom_bar.noutrefresh(
0, 0, self.y, 0, self.y, self.x)
try:
assert self.y == self.stdscr.getmaxyx()[0] - 1
assert self.x == self.stdscr.getmaxyx()[1] - 1
except AssertionError:
self.print_resize()
return
with open('/tmp/log', 'a') as f:
f.write('{}\t{}\t{}\t{}\t{}\t{}\n'.format(
self.maxy, self.y, self.scrolly,
self.maxx, self.x, self.scrollx))
curses.doupdate()
def main_loop(self):
while True:
c = self.stdscr.getkey()
if c == 'q':
return
elif c in self.key_map and self.screen_showing != self.key_map[c]:
self.print_screen(self.key_map[c])
elif c == 'KEY_RESIZE':
self.print_resize()
elif c == 'KEY_DOWN':
if self.scrolly + self.y - 1 < self.maxy:
self.scrolly += 1
self.draw_screen()
elif c == 'KEY_UP' and self.scrolly != 0:
self.scrolly -= 1
self.draw_screen()
elif c == 'KEY_LEFT' and self.scrollx != 0:
self.scrollx -= 1
self.draw_screen()
elif c == 'KEY_RIGHT':
if self.scrollx + self.x - 1 < self.maxx:
self.scrollx += 1
self.draw_screen()
def run_curses_app(screen, fcs):
wap = WeatherApp(screen, fcs)
wap.main_loop()
def run_app(args):
fcs = WeatherForecast(args['api_key'], args['location'], args['datadir'])
if args['quiet_update']:
fcs.load(True)
return
fcs.load(args['dont_update'])
curses.wrapper(run_curses_app, fcs)
def main():
args = get_config_args()
args.update(get_command_line_args())
run_app(args)
| gpl-2.0 |
ktnyt/chainer | chainer/testing/distribution_test.py | 2 | 12804 | import functools
import unittest
import numpy
import chainer
from chainer.backends import cuda
from chainer.testing import array
from chainer.testing import attr
from chainer import utils
def skip_not_in_test_target(test_target):
def decorator(f):
@functools.wraps(f)
def new_f(self, *args, **kwargs):
if test_target not in self.test_targets:
self.skipTest(
"\'%s\' is not exist in test_targets." % test_target)
else:
f(self, *args, **kwargs)
return new_f
return decorator
class distribution_unittest(unittest.TestCase):
scipy_onebyone = False
def setUp(self):
self.support = 'real'
if not hasattr(self, 'event_shape'):
self.event_shape = ()
self.continuous = True
self.test_targets = set()
self.options = {}
self.setUp_configure()
targets_not_found = self.test_targets - {
"batch_shape", "cdf", "entropy", "event_shape", "icdf", "log_cdf",
"log_prob", "log_survival", "mean", "prob", "sample", "stddev",
"support", "survival", "variance"}
if targets_not_found:
raise ValueError(
"invalid target(s): {}".format(targets_not_found))
if self.is_variable:
self.params = {k: chainer.Variable(v)
for k, v in self.params.items()}
def scipy_onebyone_params_iter(self):
for index in numpy.ndindex(self.shape):
yield {k: v[index] for k, v in self.scipy_params.items()}
@property
def cpu_dist(self):
params = self.params
params.update(self.options)
return self.dist(**params)
@property
def gpu_dist(self):
if self.is_variable:
gpu_params = {k: cuda.to_gpu(v.data)
for k, v in self.params.items()}
gpu_params = {k: chainer.Variable(v)
for k, v in gpu_params.items()}
else:
gpu_params = {k: cuda.to_gpu(v)
for k, v in self.params.items()}
gpu_params.update(self.options)
return self.dist(**gpu_params)
@skip_not_in_test_target('batch_shape')
def test_batch_shape_cpu(self):
self.assertEqual(self.cpu_dist.batch_shape, self.shape)
@attr.gpu
@skip_not_in_test_target('batch_shape')
def test_batch_shape_gpu(self):
self.assertEqual(self.gpu_dist.batch_shape, self.shape)
def check_cdf(self, is_gpu):
smp = self.sample_for_test()
if is_gpu:
cdf1 = self.gpu_dist.cdf(cuda.to_gpu(smp)).data
else:
cdf1 = self.cpu_dist.cdf(smp).data
cdf2 = self.scipy_dist.cdf(smp, **self.scipy_params)
array.assert_allclose(cdf1, cdf2)
@skip_not_in_test_target('cdf')
def test_cdf_cpu(self):
self.check_cdf(False)
@attr.gpu
@skip_not_in_test_target('cdf')
def test_cdf_gpu(self):
self.check_cdf(True)
def check_entropy(self, is_gpu):
if is_gpu:
ent1 = self.gpu_dist.entropy.data
else:
ent1 = self.cpu_dist.entropy.data
if self.scipy_onebyone:
ent2 = []
for one_params in self.scipy_onebyone_params_iter():
ent2.append(self.scipy_dist.entropy(**one_params))
ent2 = numpy.vstack(ent2).reshape(self.shape)
else:
ent2 = self.scipy_dist.entropy(**self.scipy_params)
array.assert_allclose(ent1, ent2)
@skip_not_in_test_target('entropy')
def test_entropy_cpu(self):
self.check_entropy(False)
@attr.gpu
@skip_not_in_test_target('entropy')
def test_entropy_gpu(self):
self.check_entropy(True)
@skip_not_in_test_target('event_shape')
def test_event_shape_cpu(self):
self.assertEqual(self.cpu_dist.event_shape, self.event_shape)
@attr.gpu
@skip_not_in_test_target('event_shape')
def test_event_shape_gpu(self):
self.assertEqual(self.gpu_dist.event_shape, self.event_shape)
def check_icdf(self, is_gpu):
smp = numpy.random.uniform(
1e-5, 1 - 1e-5, self.sample_shape + self.shape
).astype(numpy.float32)
if is_gpu:
icdf1 = self.gpu_dist.icdf(cuda.to_gpu(smp)).data
else:
icdf1 = self.cpu_dist.icdf(smp).data
icdf2 = self.scipy_dist.ppf(smp, **self.scipy_params)
array.assert_allclose(icdf1, icdf2)
@skip_not_in_test_target('icdf')
def test_icdf_cpu(self):
self.check_icdf(False)
@attr.gpu
@skip_not_in_test_target('icdf')
def test_icdf_gpu(self):
self.check_icdf(True)
def check_log_cdf(self, is_gpu):
smp = self.sample_for_test()
if is_gpu:
log_cdf1 = self.gpu_dist.log_cdf(cuda.to_gpu(smp)).data
else:
log_cdf1 = self.cpu_dist.log_cdf(smp).data
log_cdf2 = self.scipy_dist.logcdf(smp, **self.scipy_params)
array.assert_allclose(log_cdf1, log_cdf2)
@skip_not_in_test_target('log_cdf')
def test_log_cdf_cpu(self):
self.check_log_cdf(False)
@attr.gpu
@skip_not_in_test_target('log_cdf')
def test_log_cdf_gpu(self):
self.check_log_cdf(True)
def check_log_prob(self, is_gpu):
smp = self.sample_for_test()
if is_gpu:
log_prob1 = self.gpu_dist.log_prob(cuda.to_gpu(smp)).data
else:
log_prob1 = self.cpu_dist.log_prob(smp).data
if self.continuous:
scipy_prob = self.scipy_dist.logpdf
else:
scipy_prob = self.scipy_dist.logpmf
if self.scipy_onebyone:
onebyone_smp = smp.reshape(*[
utils.size_of_shape(sh)
for sh in [self.sample_shape, self.shape, self.event_shape]])
onebyone_smp = numpy.swapaxes(onebyone_smp, 0, 1)
onebyone_smp = onebyone_smp.reshape((-1,) + self.sample_shape
+ self.event_shape)
log_prob2 = []
for one_params, one_smp in zip(
self.scipy_onebyone_params_iter(), onebyone_smp):
log_prob2.append(scipy_prob(one_smp, **one_params))
log_prob2 = numpy.vstack(log_prob2)
log_prob2 = log_prob2.reshape(
utils.size_of_shape(self.shape), -1).T
log_prob2 = log_prob2.reshape(self.sample_shape + self.shape)
else:
log_prob2 = scipy_prob(smp, **self.scipy_params)
array.assert_allclose(log_prob1, log_prob2)
@skip_not_in_test_target('log_prob')
def test_log_prob_cpu(self):
self.check_log_prob(False)
@attr.gpu
@skip_not_in_test_target('log_prob')
def test_log_prob_gpu(self):
self.check_log_prob(True)
def check_log_survival(self, is_gpu):
smp = self.sample_for_test()
if is_gpu:
log_survival1 = \
self.gpu_dist.log_survival_function(cuda.to_gpu(smp)).data
else:
log_survival1 = self.cpu_dist.log_survival_function(smp).data
log_survival2 = self.scipy_dist.logsf(smp, **self.scipy_params)
array.assert_allclose(log_survival1, log_survival2)
@skip_not_in_test_target('log_survival')
def test_log_survival_cpu(self):
self.check_log_survival(False)
@attr.gpu
@skip_not_in_test_target('log_survival')
def test_log_survival_gpu(self):
self.check_log_survival(True)
def check_mean(self, is_gpu):
if is_gpu:
mean1 = self.gpu_dist.mean.data
else:
mean1 = self.cpu_dist.mean.data
if self.scipy_onebyone:
mean2 = []
for one_params in self.scipy_onebyone_params_iter():
mean2.append(self.scipy_dist.mean(**one_params))
mean2 = numpy.vstack(mean2).reshape(
self.shape + self.cpu_dist.event_shape)
else:
mean2 = self.scipy_dist.mean(**self.scipy_params)
array.assert_allclose(mean1, mean2)
@skip_not_in_test_target('mean')
def test_mean_cpu(self):
self.check_mean(False)
@attr.gpu
@skip_not_in_test_target('mean')
def test_mean_gpu(self):
self.check_mean(True)
def check_prob(self, is_gpu):
smp = self.sample_for_test()
if is_gpu:
prob1 = self.gpu_dist.prob(cuda.to_gpu(smp)).data
else:
prob1 = self.cpu_dist.prob(smp).data
if self.continuous:
prob2 = self.scipy_dist.pdf(smp, **self.scipy_params)
else:
prob2 = self.scipy_dist.pmf(smp, **self.scipy_params)
array.assert_allclose(prob1, prob2)
@skip_not_in_test_target('prob')
def test_prob_cpu(self):
self.check_prob(False)
@attr.gpu
@skip_not_in_test_target('prob')
def test_prob_gpu(self):
self.check_prob(True)
def check_sample(self, is_gpu):
if is_gpu:
smp1 = self.gpu_dist.sample(
sample_shape=(100000,)+self.sample_shape).data
else:
smp1 = self.cpu_dist.sample(
sample_shape=(100000,)+self.sample_shape).data
if self.scipy_onebyone:
smp2 = []
for one_params in self.scipy_onebyone_params_iter():
smp2.append(self.scipy_dist.rvs(
size=(100000,)+self.sample_shape, **one_params))
smp2 = numpy.vstack(smp2)
smp2 = smp2.reshape((utils.size_of_shape(self.shape), 100000)
+ self.sample_shape
+ self.cpu_dist.event_shape)
smp2 = numpy.rollaxis(
smp2, 0, smp2.ndim-len(self.cpu_dist.event_shape))
smp2 = smp2.reshape((100000,) + self.sample_shape + self.shape
+ self.cpu_dist.event_shape)
else:
smp2 = self.scipy_dist.rvs(
size=(100000,) + self.sample_shape + self.shape,
**self.scipy_params)
array.assert_allclose(smp1.mean(axis=0), smp2.mean(axis=0),
atol=3e-2, rtol=3e-2)
array.assert_allclose(smp1.std(axis=0), smp2.std(axis=0),
atol=3e-2, rtol=3e-2)
@skip_not_in_test_target('sample')
def test_sample_cpu(self):
self.check_sample(False)
@attr.gpu
@skip_not_in_test_target('sample')
def test_sample_gpu(self):
self.check_sample(True)
def check_stddev(self, is_gpu):
if is_gpu:
stddev1 = self.gpu_dist.stddev.data
else:
stddev1 = self.cpu_dist.stddev.data
stddev2 = self.scipy_dist.std(**self.scipy_params)
array.assert_allclose(stddev1, stddev2)
@skip_not_in_test_target('stddev')
def test_stddev_cpu(self):
self.check_stddev(False)
@attr.gpu
@skip_not_in_test_target('stddev')
def test_stddev_gpu(self):
self.check_stddev(True)
@skip_not_in_test_target('support')
def test_support_cpu(self):
self.assertEqual(self.cpu_dist.support, self.support)
@attr.gpu
@skip_not_in_test_target('support')
def test_support_gpu(self):
self.assertEqual(self.gpu_dist.support, self.support)
def check_survival(self, is_gpu):
smp = self.sample_for_test()
if is_gpu:
survival1 = self.gpu_dist.survival_function(
cuda.to_gpu(smp)).data
else:
survival1 = self.cpu_dist.survival_function(smp).data
survival2 = self.scipy_dist.sf(smp, **self.scipy_params)
array.assert_allclose(survival1, survival2)
@skip_not_in_test_target('survival')
def test_survival_cpu(self):
self.check_survival(False)
@attr.gpu
@skip_not_in_test_target('survival')
def test_survival_gpu(self):
self.check_survival(True)
def check_variance(self, is_gpu):
if is_gpu:
variance1 = self.gpu_dist.variance.data
else:
variance1 = self.cpu_dist.variance.data
if self.scipy_onebyone:
variance2 = []
for one_params in self.scipy_onebyone_params_iter():
variance2.append(self.scipy_dist.var(**one_params))
variance2 = numpy.vstack(variance2).reshape(
self.shape + self.cpu_dist.event_shape)
else:
variance2 = self.scipy_dist.var(**self.scipy_params)
array.assert_allclose(variance1, variance2)
@skip_not_in_test_target('variance')
def test_variance_cpu(self):
self.check_variance(False)
@attr.gpu
@skip_not_in_test_target('variance')
def test_variance_gpu(self):
self.check_variance(True)
| mit |
jcarva/digital_image_processing_assignments | spatial_domain/python/task1_6.py | 1 | 1722 | # coding=UTF-8
# 1.6. Limiarização aplicada sobre Y, com limiar m e duas opções: a) m
# escolhido pelo usuáio; b) m = média de valores da banda Y;
import numpy as np
import utils
import color
def main():
image = utils.load_image('lenna.png')
yiq_image = color.rgb2yiq(image)
grayscale_image = yiq_image[:, :, 2] # Y
threshold_value = 255 * 0.2
mean_value = np.mean(grayscale_image)
threshold_user_image = _segment(grayscale_image, threshold_value)
original_threshold_user_image = np.copy(yiq_image)
original_threshold_user_image[:, :, 2] = threshold_user_image
original_threshold_user_image = color.yiq2rgb(original_threshold_user_image)
threshold_mean_image = _segment(grayscale_image, mean_value)
original_threshold_mean_image = np.copy(yiq_image)
original_threshold_mean_image[:, :, 2] = threshold_mean_image
original_threshold_mean_image = color.yiq2rgb(original_threshold_mean_image)
utils.display_single_image('Original Image', image)
utils.display_single_image('YIQ Image', yiq_image)
utils.display_single_image('Y Channel', grayscale_image)
utils.display_single_image('Y Threshold (User ' + str(threshold_value) + ')', threshold_user_image)
utils.display_single_image('Back to Original (User ' + str(threshold_value) + ')', original_threshold_user_image)
utils.display_single_image('Y Threshold (Mean ' + str(mean_value) + ')', threshold_mean_image)
utils.display_single_image('Back to Original (Mean ' + str(mean_value) + ')', original_threshold_mean_image)
utils.wait_key_and_destroy_windows()
def _segment(image, m):
output = (image >= m) * 255
return output
if __name__ == "__main__":
main() | gpl-3.0 |
PXke/invenio | invenio/legacy/websubmit/functions/Create_Modify_Interface.py | 1 | 12922 | ## This file is part of Invenio.
## Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 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.
"""
This is the Create_Modify_Interface function (along with its helpers).
It is used by WebSubmit for the "Modify Bibliographic Information" action.
"""
__revision__ = "$Id$"
import os
import re
import time
import pprint
from invenio.legacy.dbquery import run_sql
from invenio.legacy.websubmit.config import InvenioWebSubmitFunctionError
from invenio.legacy.websubmit.functions.Retrieve_Data import Get_Field
from invenio.ext.logging import register_exception
def Create_Modify_Interface_getfieldval_fromfile(cur_dir, fld=""):
"""Read a field's value from its corresponding text file in 'cur_dir' (if it exists) into memory.
Delete the text file after having read-in its value.
This function is called on the reload of the modify-record page. This way, the field in question
can be populated with the value last entered by the user (before reload), instead of always being
populated with the value still found in the DB.
"""
fld_val = ""
if len(fld) > 0 and os.access("%s/%s" % (cur_dir, fld), os.R_OK|os.W_OK):
fp = open( "%s/%s" % (cur_dir, fld), "r" )
fld_val = fp.read()
fp.close()
try:
os.unlink("%s/%s"%(cur_dir, fld))
except OSError:
# Cannot unlink file - ignore, let WebSubmit main handle this
pass
fld_val = fld_val.strip()
return fld_val
def Create_Modify_Interface_getfieldval_fromDBrec(fieldcode, recid):
"""Read a field's value from the record stored in the DB.
This function is called when the Create_Modify_Interface function is called for the first time
when modifying a given record, and field values must be retrieved from the database.
"""
fld_val = ""
if fieldcode != "":
for next_field_code in [x.strip() for x in fieldcode.split(",")]:
fld_val += "%s\n" % Get_Field(next_field_code, recid)
fld_val = fld_val.rstrip('\n')
return fld_val
def Create_Modify_Interface_transform_date(fld_val):
"""Accept a field's value as a string. If the value is a date in one of the following formats:
DD Mon YYYY (e.g. 23 Apr 2005)
YYYY-MM-DD (e.g. 2005-04-23)
...transform this date value into "DD/MM/YYYY" (e.g. 23/04/2005).
"""
if re.search("^[0-9]{2} [a-z]{3} [0-9]{4}$", fld_val, re.IGNORECASE) is not None:
try:
fld_val = time.strftime("%d/%m/%Y", time.strptime(fld_val, "%d %b %Y"))
except (ValueError, TypeError):
# bad date format:
pass
elif re.search("^[0-9]{4}-[0-9]{2}-[0-9]{2}$", fld_val, re.IGNORECASE) is not None:
try:
fld_val = time.strftime("%d/%m/%Y", time.strptime(fld_val, "%Y-%m-%d"))
except (ValueError,TypeError):
# bad date format:
pass
return fld_val
def Create_Modify_Interface(parameters, curdir, form, user_info=None):
"""
Create an interface for the modification of a document, based on
the fields that the user has chosen to modify. This avoids having
to redefine a submission page for the modifications, but rely on
the elements already defined for the initial submission i.e. SBI
action (The only page that needs to be built for the modification
is the page letting the user specify a document to modify).
This function should be added at step 1 of your modification
workflow, after the functions that retrieves report number and
record id (Get_Report_Number, Get_Recid). Functions at step 2 are
the one executed upon successful submission of the form.
Create_Modify_Interface expects the following parameters:
* "fieldnameMBI" - the name of a text file in the submission
working directory that contains a list of the names of the
WebSubmit fields to include in the Modification interface.
These field names are separated by"\n" or "+".
Given the list of WebSubmit fields to be included in the
modification interface, the values for each field are retrieved
for the given record (by way of each WebSubmit field being
configured with a MARC Code in the WebSubmit database). An HTML
FORM is then created. This form allows a user to modify certain
field values for a record.
The file referenced by 'fieldnameMBI' is usually generated from a
multiple select form field): users can then select one or several
fields to modify
Note that the function will display WebSubmit Response elements,
but will not be able to set an initial value: this must be done by
the Response element iteself.
Additionally the function creates an internal field named
'Create_Modify_Interface_DONE' on the interface, that can be
retrieved in curdir after the form has been submitted.
This flag is an indicator for the function that displayed values
should not be retrieved from the database, but from the submitted
values (in case the page is reloaded). You can also rely on this
value when building your WebSubmit Response element in order to
retrieve value either from the record, or from the submission
directory.
"""
global sysno,rn
t = ""
# variables declaration
fieldname = parameters['fieldnameMBI']
# Path of file containing fields to modify
the_globals = {
'doctype' : doctype,
'action' : action,
'act' : action, ## for backward compatibility
'step' : step,
'access' : access,
'ln' : ln,
'curdir' : curdir,
'uid' : user_info['uid'],
'uid_email' : user_info['email'],
'rn' : rn,
'last_step' : last_step,
'action_score' : action_score,
'__websubmit_in_jail__' : True,
'form': form,
'sysno': sysno,
'user_info' : user_info,
'__builtins__' : globals()['__builtins__'],
'Request_Print': Request_Print
}
if os.path.exists("%s/%s" % (curdir, fieldname)):
fp = open( "%s/%s" % (curdir, fieldname), "r" )
fieldstext = fp.read()
fp.close()
fieldstext = re.sub("\+","\n", fieldstext)
fields = fieldstext.split("\n")
else:
res = run_sql("SELECT fidesc FROM sbmFIELDDESC WHERE name=%s", (fieldname,))
if len(res) == 1:
fields = res[0][0].replace(" ", "")
fields = re.findall("<optionvalue=.*>", fields)
regexp = re.compile("""<optionvalue=(?P<quote>['|"]?)(?P<value>.*?)(?P=quote)""")
fields = [regexp.search(x) for x in fields]
fields = [x.group("value") for x in fields if x is not None]
fields = [x for x in fields if x not in ("Select", "select")]
else:
raise InvenioWebSubmitFunctionError("cannot find fields to modify")
#output some text
t = t+"<CENTER bgcolor=\"white\">The document <B>%s</B> has been found in the database.</CENTER><br />Please modify the following fields:<br />Then press the 'END' button at the bottom of the page<br />\n" % rn
for field in fields:
subfield = ""
value = ""
marccode = ""
text = ""
# retrieve and display the modification text
t = t + "<FONT color=\"darkblue\">\n"
res = run_sql("SELECT modifytext FROM sbmFIELDDESC WHERE name=%s", (field,))
if len(res)>0:
t = t + "<small>%s</small> </FONT>\n" % res[0][0]
# retrieve the marc code associated with the field
res = run_sql("SELECT marccode FROM sbmFIELDDESC WHERE name=%s", (field,))
if len(res) > 0:
marccode = res[0][0]
# then retrieve the previous value of the field
if os.path.exists("%s/%s" % (curdir, "Create_Modify_Interface_DONE")):
# Page has been reloaded - get field value from text file on server, not from DB record
value = Create_Modify_Interface_getfieldval_fromfile(curdir, field)
else:
# First call to page - get field value from DB record
value = Create_Modify_Interface_getfieldval_fromDBrec(marccode, sysno)
# If field is a date value, transform date into format DD/MM/YYYY:
value = Create_Modify_Interface_transform_date(value)
res = run_sql("SELECT * FROM sbmFIELDDESC WHERE name=%s", (field,))
if len(res) > 0:
element_type = res[0][3]
numcols = res[0][6]
numrows = res[0][5]
size = res[0][4]
maxlength = res[0][7]
val = res[0][8]
fidesc = res[0][9]
if element_type == "T":
text = "<TEXTAREA name=\"%s\" rows=%s cols=%s wrap>%s</TEXTAREA>" % (field, numrows, numcols, value)
elif element_type == "F":
text = "<INPUT TYPE=\"file\" name=\"%s\" size=%s maxlength=\"%s\">" % (field, size, maxlength)
elif element_type == "I":
value = re.sub("[\n\r\t]+", "", value)
text = "<INPUT name=\"%s\" size=%s value=\"%s\"> " % (field, size, val)
text = text + "<SCRIPT>document.forms[0].%s.value=\"%s\";</SCRIPT>" % (field, value)
elif element_type == "H":
text = "<INPUT type=\"hidden\" name=\"%s\" value=\"%s\">" % (field, val)
text = text + "<SCRIPT>document.forms[0].%s.value=\"%s\";</SCRIPT>" % (field, value)
elif element_type == "S":
values = re.split("[\n\r]+", value)
text = fidesc
if re.search("%s\[\]" % field, fidesc):
multipletext = "[]"
else:
multipletext = ""
if len(values) > 0 and not(len(values) == 1 and values[0] == ""):
text += "<SCRIPT>\n"
text += "var i = 0;\n"
text += "el = document.forms[0].elements['%s%s'];\n" % (field, multipletext)
text += "max = el.length;\n"
for val in values:
text += "var found = 0;\n"
text += "var i=0;\n"
text += "while (i != max) {\n"
text += " if (el.options[i].value == \"%s\" || el.options[i].text == \"%s\") {\n" % (val, val)
text += " el.options[i].selected = true;\n"
text += " found = 1;\n"
text += " }\n"
text += " i=i+1;\n"
text += "}\n"
#text += "if (found == 0) {\n"
#text += " el[el.length] = new Option(\"%s\", \"%s\", 1,1);\n"
#text += "}\n"
text += "</SCRIPT>\n"
elif element_type == "D":
text = fidesc
elif element_type == "R":
try:
co = compile(fidesc.replace("\r\n", "\n"), "<string>", "exec")
## Note this exec is safe WRT global variable because the
## Create_Modify_Interface has already been parsed by
## execfile within a protected environment.
the_globals['text'] = ''
exec co in the_globals
text = the_globals['text']
except:
msg = "Error in evaluating response element %s with globals %s" % (pprint.pformat(field), pprint.pformat(globals()))
register_exception(req=None, alert_admin=True, prefix=msg)
raise InvenioWebSubmitFunctionError(msg)
else:
text = "%s: unknown field type" % field
t = t + "<small>%s</small>" % text
# output our flag field
t += '<input type="hidden" name="Create_Modify_Interface_DONE" value="DONE\n" />'
# output some more text
t = t + "<br /><br /><CENTER><small><INPUT type=\"button\" width=400 height=50 name=\"End\" value=\"END\" onClick=\"document.forms[0].step.value = 2;user_must_confirm_before_leaving_page = false;document.forms[0].submit();\"></small></CENTER></H4>"
return t
| gpl-2.0 |
quonb/atom-generator | atom_generator/video.py | 1 | 2028 | import re
class YouTube(object):
def __init__(self, url=None):
self._video_id = self._extract_id(url)
def __call__(self, url=False):
if url is None or url:
self._video_id = self._extract_id(url)
return self._video_id
def _extract_id(self, url=None):
"""Extract youtube video ID
Based on `youtube_dl` code
"""
if not url:
return None
YOUTUBE_URL = r"""^
(?:
(?:https?://)? # http(s):// (optional)
(?:(?:(?:
(?:\w+\.)?youtube(?:-nocookie)?\.com/|
tube\.majestyc\.net/|
youtube\.googleapis\.com/) # the various hostnames, with wildcard subdomains
(?:.*?\#/)? # handle anchor (#/) redirect urls
(?: # the various things that can precede the ID:
(?:(?:v|embed|e)/)| # v/ or embed/ or e/
(?: # or the v= param in all its forms
(?:
(?:watch|movie)(?:_popup)?(?:\.php)?
)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
(?:\?|\#!?) # the params delimiter ? or # or #!
(?:.*?&)? # any other preceding param (like /?s=tuff&v=xxxx)
v=
)
))|
youtu\.be/ # just youtu.be/xxxx
)
)? # all until now is optional -> you can pass the naked ID
([0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
(?(1).+)? # if we found the ID, everything can follow
$"""
video_id = re.match(YOUTUBE_URL, str(url), re.VERBOSE)
return video_id and video_id.group(1)
def thumbnail(self):
return self._video_id and "http://i.ytimg.com/vi/%s/0.jpg" % self._video_id
def video(self):
return self._video_id and "http://www.youtube.com/watch?v=%s" % self._video_id
| apache-2.0 |
RockchipOpensourceCommunity/popmetal-kernel-3.14 | tools/perf/scripts/python/futex-contention.py | 11261 | 1486 | # futex contention
# (c) 2010, Arnaldo Carvalho de Melo <[email protected]>
# Licensed under the terms of the GNU GPL License version 2
#
# Translation of:
#
# http://sourceware.org/systemtap/wiki/WSFutexContention
#
# to perf python scripting.
#
# Measures futex contention
import os, sys
sys.path.append(os.environ['PERF_EXEC_PATH'] + '/scripts/python/Perf-Trace-Util/lib/Perf/Trace')
from Util import *
process_names = {}
thread_thislock = {}
thread_blocktime = {}
lock_waits = {} # long-lived stats on (tid,lock) blockage elapsed time
process_names = {} # long-lived pid-to-execname mapping
def syscalls__sys_enter_futex(event, ctxt, cpu, s, ns, tid, comm,
nr, uaddr, op, val, utime, uaddr2, val3):
cmd = op & FUTEX_CMD_MASK
if cmd != FUTEX_WAIT:
return # we don't care about originators of WAKE events
process_names[tid] = comm
thread_thislock[tid] = uaddr
thread_blocktime[tid] = nsecs(s, ns)
def syscalls__sys_exit_futex(event, ctxt, cpu, s, ns, tid, comm,
nr, ret):
if thread_blocktime.has_key(tid):
elapsed = nsecs(s, ns) - thread_blocktime[tid]
add_stats(lock_waits, (tid, thread_thislock[tid]), elapsed)
del thread_blocktime[tid]
del thread_thislock[tid]
def trace_begin():
print "Press control+C to stop and show the summary"
def trace_end():
for (tid, lock) in lock_waits:
min, max, avg, count = lock_waits[tid, lock]
print "%s[%d] lock %x contended %d times, %d avg ns" % \
(process_names[tid], tid, lock, count, avg)
| gpl-2.0 |
orlov-vo/mtasa | vendor/google-breakpad/src/tools/gyp/test/ninja/solibs_avoid_relinking/gyptest-solibs-avoid-relinking.py | 216 | 1427 | #!/usr/bin/env python
# Copyright (c) 2012 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.
"""
Verify that relinking a solib doesn't relink a dependent executable if the
solib's public API hasn't changed.
"""
import os
import sys
import TestCommon
import TestGyp
# NOTE(fischman): This test will not work with other generators because the
# API-hash-based-mtime-preservation optimization is only implemented in
# ninja.py. It could be extended to the make.py generator as well pretty
# easily, probably.
# (also, it tests ninja-specific out paths, which would have to be generalized
# if this was extended to other generators).
test = TestGyp.TestGyp(formats=['ninja'])
test.run_gyp('solibs_avoid_relinking.gyp')
# Build the executable, grab its timestamp, touch the solib's source, rebuild
# executable, ensure timestamp hasn't changed.
test.build('solibs_avoid_relinking.gyp', 'b')
test.built_file_must_exist('b' + TestCommon.exe_suffix)
pre_stat = os.stat(test.built_file_path('b' + TestCommon.exe_suffix))
os.utime(os.path.join(test.workdir, 'solib.cc'),
(pre_stat.st_atime, pre_stat.st_mtime + 100))
test.sleep()
test.build('solibs_avoid_relinking.gyp', 'b')
post_stat = os.stat(test.built_file_path('b' + TestCommon.exe_suffix))
if pre_stat.st_mtime != post_stat.st_mtime:
test.fail_test()
else:
test.pass_test()
| gpl-3.0 |
readevalprint/mezzanine | mezzanine/utils/cache.py | 5 | 3908 | from __future__ import unicode_literals
from hashlib import md5
from time import time
from django.core.cache import cache
from django.utils.lru_cache import lru_cache
from django.utils.cache import _i18n_cache_key_suffix
from mezzanine.conf import settings
from mezzanine.utils.sites import current_site_id
from mezzanine.utils.conf import middlewares_or_subclasses_installed
def _hashed_key(key):
"""
Hash keys when talking directly to the cache API, to avoid
keys longer than the backend supports (eg memcache limit is 255)
"""
return md5(key.encode("utf-8")).hexdigest()
def cache_set(key, value, timeout=None, refreshed=False):
"""
Wrapper for ``cache.set``. Stores the cache entry packed with
the desired cache expiry time. When the entry is retrieved from
cache, the packed expiry time is also checked, and if past,
the stale cache entry is stored again with an expiry that has
``CACHE_SET_DELAY_SECONDS`` added to it. In this case the entry
is not returned, so that a cache miss occurs and the entry
should be set by the caller, but all other callers will still get
the stale entry, so no real cache misses ever occur.
"""
if timeout is None:
timeout = settings.CACHE_MIDDLEWARE_SECONDS
refresh_time = timeout + time()
real_timeout = timeout + settings.CACHE_SET_DELAY_SECONDS
packed = (value, refresh_time, refreshed)
return cache.set(_hashed_key(key), packed, real_timeout)
def cache_get(key):
"""
Wrapper for ``cache.get``. The expiry time for the cache entry
is stored with the entry. If the expiry time has past, put the
stale entry back into cache, and don't return it to trigger a
fake cache miss.
"""
packed = cache.get(_hashed_key(key))
if packed is None:
return None
value, refresh_time, refreshed = packed
if (time() > refresh_time) and not refreshed:
cache_set(key, value, settings.CACHE_SET_DELAY_SECONDS, True)
return None
return value
@lru_cache(maxsize=None)
def cache_installed():
"""
Returns ``True`` if a cache backend is configured, and the
cache middleware classes or subclasses thereof are present.
This will be evaluated once per run, and then cached.
"""
has_key = bool(getattr(settings, "NEVERCACHE_KEY", ""))
return (has_key and settings.CACHES and not settings.TESTING and
middlewares_or_subclasses_installed([
"mezzanine.core.middleware.UpdateCacheMiddleware",
"mezzanine.core.middleware.FetchFromCacheMiddleware",
]))
def cache_key_prefix(request):
"""
Cache key for Mezzanine's cache middleware. Adds the current
site ID.
"""
cache_key = "%s.%s.%s" % (
settings.CACHE_MIDDLEWARE_KEY_PREFIX,
current_site_id(),
# This last part used to indicate the device type for the request,
# but device detection was removed in Mezzanine 4.3.
# The "default" value was kept to maintain existing cache keys.
# See: https://github.com/stephenmcd/mezzanine/pull/1783
"default",
)
return _i18n_cache_key_suffix(request, cache_key)
def nevercache_token():
"""
Returns the secret token that delimits content wrapped in
the ``nevercache`` template tag.
"""
return "nevercache." + settings.NEVERCACHE_KEY
def add_cache_bypass(url):
"""
Adds the current time to the querystring of the URL to force a
cache reload. Used for when a form post redirects back to a
page that should display updated content, such as new comments or
ratings.
"""
if not cache_installed():
return url
hash_str = ""
if "#" in url:
url, hash_str = url.split("#", 1)
hash_str = "#" + hash_str
url += "?" if "?" not in url else "&"
return url + "t=" + str(time()).replace(".", "") + hash_str
| bsd-2-clause |
kc-lab/dms2dfe | dms2dfe/lib/io_data_files.py | 2 | 14758 | #!usr/bin/python
# Copyright 2016, Rohan Dandage <[email protected],[email protected]>
# This program is distributed under General Public License v. 3.
"""
================================
``io_data_files``
================================
"""
import sys
import pandas as pd
from os.path import exists,basename,abspath,dirname,expanduser
import logging
from glob import glob
import numpy as np
from dms2dfe.lib.io_seq_files import get_fsta_feats
logging.basicConfig(format='[%(asctime)s] %(levelname)s\tfrom %(filename)s in %(funcName)s(..): %(message)s',level=logging.DEBUG) # filename=cfg_xls_fh+'.log'
import pickle
## DEFS
def is_cfg_ok(cfg_dh,cfgs) :
"""
Checks if the required files are present in given directory.
:param cfg_dh: path to directory.
:param cfgs: list of names of files.
"""
cfg_dh_cfgs=glob(cfg_dh+"/*")
cfg_dh_cfgs=[basename(cfg_dh_cfg) for cfg_dh_cfg in cfg_dh_cfgs]
for cfg in cfgs : # check if required sheets are present
if not cfg in cfg_dh_cfgs :
logging.error("%s does not exist" % cfg)
return False
break
return True
def auto_find_missing_paths(prj_dh):
"""
Finds the missing paths in the configuration given in cfg/ directory
:param prj_dh: path to the project directory
"""
info=pd.read_csv(prj_dh+"/cfg/info")
info_path_vars=[varn for varn in info['varname'] if ("_fh" in varn) or ("_dh" in varn)]
info=info.set_index("varname")
#find pdb_fh and fsta_fh in prj_dh
if pd.isnull(info.loc["pdb_fh","input"]):
try:
info.loc["pdb_fh","input"]=glob("%s/*.pdb" % prj_dh)[0]
except:
logging.error("can not find .pdb file")
if pd.isnull(info.loc["fsta_fh","input"]):
try:
fsta_fhs=glob("%s/*.fasta" % prj_dh)
for fsta_fh in fsta_fhs:
if not (('prt' in fsta_fh) or ('_cctmr1.' in fsta_fh)):
info.loc["fsta_fh","input"]=fsta_fh
break
except:
logging.error("could not find .fasta file")
info_paths=[info.loc[info_path_var,"input"] for info_path_var in info_path_vars]
info.reset_index().to_csv(prj_dh+"/cfg/info",index=False)
# if any(pd.isnull(info_paths)):
info_paths_missing=[v for v in info_path_vars if (pd.isnull(info.loc[v,"input"]) and info.loc[v,"default"])]
if len(info_paths_missing)>0:
logging.error("Values for following variables are missing in 'project_dir/cfg/info' file.")
# print [p for p in info_paths if pd.isnull(p)]
print info_paths_missing
sys.exit()
def get_raw_input(info,var):
"""
Get intearactive inputs from user
:param info: dict, with information about experiment
:param var: variable whose value is obtained from interactive shell
"""
# from dms2dfe.lib.io_dfs import set_index
# info=set_index(info,'var')
val=raw_input("%s: %s (default: %s) =" % (var,info.loc[var, "description"],info.loc[var, "default"]))
return val
from dms2dfe.lib.io_seq_files import cctmr_fasta2ref_fasta
def info2src(prj_dh):
"""
This converts `.csv` configuration file to `.py` source file saved in `/tmp/`.
:param prj_dh: path to project directory
"""
import subprocess
from dms2dfe.lib.io_seq_files import fasta_nts2prt
csv2src("%s/../cfg/info" % abspath(dirname(__file__)),"%s/../tmp/info.py" % (abspath(dirname(__file__))))
auto_find_missing_paths(prj_dh)
info=pd.read_csv(prj_dh+"/cfg/info")
# info=auto_find_missing_paths(prj_dh)
info_path_vars=[varn for varn in info['varname'] if ("_fh" in varn) or ("_dh" in varn)]
info=info.set_index("varname")
# find still missing paths ones
info_paths=[info.loc[info_path_var,"input"] for info_path_var in info_path_vars]
for info_path_var,info_path in zip(info_path_vars,info_paths):
# if not exists(info_path):
if not ('bowtie' in info_path):
if not exists(info_path):
if info_path_var=='rscript_fh':
info_path = subprocess.check_output(["which", "Rscript"]).replace('\n','')
# print info_path
while not exists(info_path):
logging.error('Path to files do not exist. Include correct path in cfg/info. %s : %s' % (info_path_var,info_path))
info_path=get_raw_input(info,info_path_var)
info.loc[info_path_var,'input']=info_path
if not pd.isnull(info.loc['cctmr','input']):
cctmr=info.loc['cctmr','input']
cctmr=[int("%s" % i) for i in cctmr.split(" ")]
fsta_fh=cctmr_fasta2ref_fasta(info.loc['fsta_fh','input'],cctmr)
else:
fsta_fh=info.loc['fsta_fh','input']
info.loc['prj_dh','input']=abspath(prj_dh)
info.loc['fsta_id','input'],info.loc['fsta_seq','input'],info.loc['fsta_len','input']=get_fsta_feats(fsta_fh)
host=info.loc['host','input']
if pd.isnull(host):
host=info.loc['host','default']
info.loc['prt_seq','input']=fasta_nts2prt(fsta_fh,host=host).replace('*','X')
info.reset_index().to_csv(prj_dh+"/cfg/info",index=False)
csv2src(prj_dh+"/cfg/info","%s/../tmp/info.py" % (abspath(dirname(__file__))))
csv2src(prj_dh+"/cfg/info",prj_dh+"/cfg/info.py")
logging.info("configuration compiled: %s/cfg/info" % prj_dh)
def csv2src(csv_fh,src_fh):
"""
This writes `.csv` to `.py` source file.
:param csv_fh: path to input `.csv` file.
:param src_fh: path to output `.py` source file.
"""
info=pd.read_csv(csv_fh)
info=info.set_index('varname')
src_f=open(src_fh,'w')
src_f.write("#!usr/bin/python\n")
src_f.write("\n")
src_f.write("# source file for dms2dfe's configuration \n")
src_f.write("\n")
for var in info.iterrows() :
val=info['input'][var[0]]
if pd.isnull(val):
val=info['default'][var[0]]
src_f.write("%s='%s' #%s\n" % (var[0],val,info["description"][var[0]]))
src_f.close()
def raw_input2info(prj_dh,inputORdefault):
"""
This writes configuration `.csv` file from `raw_input` from prompt.
:param prj_dh: path to project directory.
:param inputORdefault: column name "input" or "default".
"""
info=pd.read_csv(prj_dh+"/cfg/info")
info=info.set_index("varname",drop=True)
for var in info.index.values:
val=raw_input("%s (default: %s) =" % (info.loc[var, "description"],info.loc[var, "default"]))
if not val=='':
info.loc[var, inputORdefault]=val
info.reset_index().to_csv("%s/cfg/info" % prj_dh, index=False)
def is_xls_ok(cfg_xls,cfg_xls_sheetnames_required) :
"""
Checks if the required sheets are present in the configuration excel file.
:param cfg_xls: path to configuration excel file
"""
cfg_xls_sheetnames=cfg_xls.sheet_names
cfg_xls_sheetnames= [str(x) for x in cfg_xls_sheetnames]# unicode to str
for qry_sheet_namei in cfg_xls_sheetnames_required : # check if required sheets are present
#qry_sheet_namei=str(qry_sheet_namei)
if not qry_sheet_namei in cfg_xls_sheetnames :
logging.error("pipeline : sheetname '%s' does not exist" % qry_sheet_namei)
return False
break
return True
def is_info_ok(xls_fh):
"""
This checks the sanity of info sheet in the configuration excel file.
For example if the files exists or not.
:param cfg_xls: path to configuration excel file
"""
info=pd.read_excel(xls_fh,'info')
info_path_vars=[varn for varn in info['varname'] if ("_fh" in varn) or ("_dh" in varn)]
info=info.set_index("varname")
info_paths=[info.loc[info_path_var,"input"] for info_path_var in info_path_vars]
for info_path in info_paths:
if not pd.isnull(info_path):
if not exists(info_path):
return False #(info_path_vars[info_paths.index(info_path)],info_path)
break
return True
def xls2h5(cfg_xls,cfg_h5,cfg_xls_sheetnames_required) :
"""
Converts configuration excel file to HDF5(h5) file.
Here sheets in excel files are converted to groups in HDF5 file.
:param cfg_xls: path to configuration excel file
"""
for qry_sheet_namei in cfg_xls_sheetnames_required:
qry_sheet_df=cfg_xls.parse(qry_sheet_namei)
qry_sheet_df=qry_sheet_df.astype(str) # suppress unicode error
qry_sheet_df.columns=[col.replace(" ","_") for col in qry_sheet_df.columns]
cfg_h5.put("cfg/"+qry_sheet_namei,convert2h5form(qry_sheet_df), format='table', data_columns=True)
return cfg_h5
def xls2csvs(cfg_xls,cfg_xls_sheetnames_required,output_dh):
"""
Converts configuration excel file to HDF5(h5) file.
Here sheets in excel files are converted to groups in HDF5 file.
:param cfg_xls: path to configuration excel file
"""
for qry_sheet_namei in cfg_xls_sheetnames_required:
qry_sheet_df=cfg_xls.parse(qry_sheet_namei)
qry_sheet_df=qry_sheet_df.astype(str) # suppress unicode error
qry_sheet_df.to_csv("%s/%s" % (output_dh,qry_sheet_namei))
# print "%s/%s" % (output_dh,qry_sheet_namei)
def convert2h5form(df):
"""
Convert dataframe compatible to Hdf5 format
:param df: pandas dataframe
"""
from dms2dfe.lib.io_strs import convertstr2format
df.columns=[convertstr2format(col,"^[a-zA-Z0-9_]*$") for col in df.columns.tolist()]
return df
def csvs2h5(dh,sub_dh_list,fn_list,output_dh,cfg_h5):
"""
This converts the csv files to tables in HDF5.
:param dh: path to the directory with csv files
:param fn_list: list of filenames of the csv files
"""
for fn in fn_list:
for sub_dh in sub_dh_list : # get aas or cds
fh=output_dh+"/"+dh+"/"+sub_dh+"/"+fn+""
df=pd.read_csv(fh) # get mat to df
df=df.loc[:,[col.replace(" ","_") for col in list(df.columns) if not (('index' in col) or ('Unnamed' in col)) ]]
exec("cfg_h5.put('%s/%s/%s',df, format='table', data_columns=True)" % (dh,sub_dh,str(fn)),locals(), globals()) # store the otpts in h5 eg. cds/N/lbl
# print("cfg_h5.put('%s/%s/%s',df.convert_objects(), format='table', data_columns=True)" % (dh,sub_dh,str(fn))) # store the otpts in h5 eg. cds/N/lbl
def csvs2h5(dh,sub_dh_list,fn_list):
"""
This converts csvs into HDF5 tables.
:param dh: path to the directory with csv files
:param fn_list: list of filenames of the csv files
"""
for fn in fn_list:
for sub_dh in sub_dh_list : # get aas or cds
fh=output_dh+"/"+dh+"/"+sub_dh+"/"+fn+""
key=dh+"/"+sub_dh+"/"+fn
if (exists(fh)) and (key in cfg_h5):
df=pd.read_csv(fh) # get mat to df
key=key+"2"
cfg_h5.put(key,df.convert_objects(), format='table', data_columns=True) # store the otpts in h5 eg. cds/N/lbl
#mut_lbl_fit_comparison
def getusable_lbls_list(prj_dh):
"""
This detects the samples that can be processed.
:param prj_dh: path to project directory.
:returns lbls_list: list of names of samples that can be processed.
"""
lbls=pd.read_csv(prj_dh+'/cfg/lbls')
lbls=lbls.set_index('varname')
lbls_list=[]
#data_lbl cols: NiA mutids NiS NiN NiNcut NiNcutlog NiScut NiScutlog NiAcut NiAcutlog
for lbli,lbl in lbls.iterrows() :
# print "%s/data_lbl/%s/%s" % (prj_dh,'aas',str(lbli))
if (not exists("%s/data_lbl/%s/%s" % (prj_dh,'aas',str(lbli)))):
fh_1=expanduser(str(lbl['fhs_1']))
lbl_mat_mut_cds_fh=[fh for fh in glob(fh_1+"*") if '.mat_mut_cds' in fh]
if len(lbl_mat_mut_cds_fh)!=0:
lbl_mat_mut_cds_fh=lbl_mat_mut_cds_fh[0]
lbls_list.append([lbli,lbl_mat_mut_cds_fh])
else :
fh_1="%s/data_mutmat/%s" % (prj_dh,basename(fh_1))
# print fh_1
lbl_mat_mut_cds_fh=[fh for fh in glob(fh_1+"*") if '.mat_mut_cds' in fh]
if len(lbl_mat_mut_cds_fh)!=0:
lbl_mat_mut_cds_fh=lbl_mat_mut_cds_fh[0]
lbls_list.append([lbli,lbl_mat_mut_cds_fh])
else:
logging.warning("can not find: %s" % fh_1)
# else:
# logging.info("already processed: %s" % (str(lbli)))
return lbls_list
def getusable_fits_list(prj_dh,data_fit_dh='data_fit'):
"""
This gets the list of samples that can be processed for fitness estimations.
:param prj_dh: path to project directory.
:returns fits_pairs_list: list of tuples with names of input and selected samples.
"""
if exists('%s/cfg/fit'% (prj_dh)):
fits=pd.read_csv(prj_dh+'/cfg/fit')
if "Unnamed: 0" in fits.columns:
fits=fits.drop("Unnamed: 0", axis=1)
fits_pairs_list=[]
sel_cols=[col for col in fits.columns.tolist() if "sel_" in col]
for pairi in fits.index.values :
unsel_lbl=fits.loc[pairi,"unsel"]
sels=list(fits.loc[pairi,sel_cols])
# print sels
for sel_lbl in sels :
if not pd.isnull(sel_lbl):
fit_lbl=sel_lbl+"_WRT_"+unsel_lbl
if (not exists("%s/%s/%s/%s" % (prj_dh,data_fit_dh,'aas',fit_lbl))):
fits_pairs_list.append([unsel_lbl,sel_lbl])
else :
logging.info("already processed: %s" % (fit_lbl))
return fits_pairs_list
else:
logging.warning("ana3_mutmat2fit : getusable_fits_list : not fits in cfg/fit")
return []
def getusable_comparison_list(prj_dh):
"""
This converts the table of tests and controls in configuration file into tuples of test and control.
:param prj_dh: path to project directory.
"""
comparisons=pd.read_csv(prj_dh+'/cfg/comparison')
comparisons=comparisons.set_index('ctrl')
comparison_list=[]
for ctrl,row in comparisons.iterrows() :
row=row[~row.isnull()]
for test in row[0:] :
comparison_list.append([ctrl,test])
return comparison_list
def to_pkl(data,fh):
"""
Saves a dict in pkl format
:param data: dict, containing data
:param fh: path to the output pkl file
"""
if not fh is None:
with open(fh, 'wb') as f:
pickle.dump(data, f, -1)
def read_pkl(fh):
"""
Reads a file in pkl format
:param fh: path to the pkl file
:returns data: dict, containing data
"""
with open(fh,'rb') as f:
return pickle.load(f)
| gpl-3.0 |
citrix-openstack-build/neutron-vpnaas | tools/install_venv.py | 102 | 2304 | #!/usr/bin/env python
# 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.
"""
Installation script for Neutron's development virtualenv
"""
from __future__ import print_function
import os
import sys
import install_venv_common as install_venv
def print_help():
help = """
Neutron development environment setup is complete.
Neutron development uses virtualenv to track and manage Python dependencies
while in development and testing.
To activate the Neutron virtualenv for the extent of your current shell
session you can run:
$ source .venv/bin/activate
Or, if you prefer, you can run commands in the virtualenv on a case by case
basis by running:
$ tools/with_venv.sh <your command>
Also, make test will automatically use the virtualenv.
"""
print(help)
def main(argv):
root = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
venv = os.path.join(root, '.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 = 'Neutron'
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()
if __name__ == '__main__':
main(sys.argv)
| apache-2.0 |
jsjohnst/tornado | tornado/httpserver.py | 96 | 11915 | #!/usr/bin/env python
#
# Copyright 2009 Facebook
#
# 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 non-blocking, single-threaded HTTP server.
Typical applications have little direct interaction with the `HTTPServer`
class except to start a server at the beginning of the process
(and even that is often done indirectly via `tornado.web.Application.listen`).
.. versionchanged:: 4.0
The ``HTTPRequest`` class that used to live in this module has been moved
to `tornado.httputil.HTTPServerRequest`. The old name remains as an alias.
"""
from __future__ import absolute_import, division, print_function, with_statement
import socket
from tornado.escape import native_str
from tornado.http1connection import HTTP1ServerConnection, HTTP1ConnectionParameters
from tornado import gen
from tornado import httputil
from tornado import iostream
from tornado import netutil
from tornado.tcpserver import TCPServer
from tornado.util import Configurable
class HTTPServer(TCPServer, Configurable,
httputil.HTTPServerConnectionDelegate):
r"""A non-blocking, single-threaded HTTP server.
A server is defined by a subclass of `.HTTPServerConnectionDelegate`,
or, for backwards compatibility, a callback that takes an
`.HTTPServerRequest` as an argument. The delegate is usually a
`tornado.web.Application`.
`HTTPServer` supports keep-alive connections by default
(automatically for HTTP/1.1, or for HTTP/1.0 when the client
requests ``Connection: keep-alive``).
If ``xheaders`` is ``True``, we support the
``X-Real-Ip``/``X-Forwarded-For`` and
``X-Scheme``/``X-Forwarded-Proto`` headers, which override the
remote IP and URI scheme/protocol for all requests. These headers
are useful when running Tornado behind a reverse proxy or load
balancer. The ``protocol`` argument can also be set to ``https``
if Tornado is run behind an SSL-decoding proxy that does not set one of
the supported ``xheaders``.
To make this server serve SSL traffic, send the ``ssl_options`` keyword
argument with an `ssl.SSLContext` object. For compatibility with older
versions of Python ``ssl_options`` may also be a dictionary of keyword
arguments for the `ssl.wrap_socket` method.::
ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ssl_ctx.load_cert_chain(os.path.join(data_dir, "mydomain.crt"),
os.path.join(data_dir, "mydomain.key"))
HTTPServer(applicaton, ssl_options=ssl_ctx)
`HTTPServer` initialization follows one of three patterns (the
initialization methods are defined on `tornado.tcpserver.TCPServer`):
1. `~tornado.tcpserver.TCPServer.listen`: simple single-process::
server = HTTPServer(app)
server.listen(8888)
IOLoop.current().start()
In many cases, `tornado.web.Application.listen` can be used to avoid
the need to explicitly create the `HTTPServer`.
2. `~tornado.tcpserver.TCPServer.bind`/`~tornado.tcpserver.TCPServer.start`:
simple multi-process::
server = HTTPServer(app)
server.bind(8888)
server.start(0) # Forks multiple sub-processes
IOLoop.current().start()
When using this interface, an `.IOLoop` must *not* be passed
to the `HTTPServer` constructor. `~.TCPServer.start` will always start
the server on the default singleton `.IOLoop`.
3. `~tornado.tcpserver.TCPServer.add_sockets`: advanced multi-process::
sockets = tornado.netutil.bind_sockets(8888)
tornado.process.fork_processes(0)
server = HTTPServer(app)
server.add_sockets(sockets)
IOLoop.current().start()
The `~.TCPServer.add_sockets` interface is more complicated,
but it can be used with `tornado.process.fork_processes` to
give you more flexibility in when the fork happens.
`~.TCPServer.add_sockets` can also be used in single-process
servers if you want to create your listening sockets in some
way other than `tornado.netutil.bind_sockets`.
.. versionchanged:: 4.0
Added ``decompress_request``, ``chunk_size``, ``max_header_size``,
``idle_connection_timeout``, ``body_timeout``, ``max_body_size``
arguments. Added support for `.HTTPServerConnectionDelegate`
instances as ``request_callback``.
.. versionchanged:: 4.1
`.HTTPServerConnectionDelegate.start_request` is now called with
two arguments ``(server_conn, request_conn)`` (in accordance with the
documentation) instead of one ``(request_conn)``.
.. versionchanged:: 4.2
`HTTPServer` is now a subclass of `tornado.util.Configurable`.
"""
def __init__(self, *args, **kwargs):
# Ignore args to __init__; real initialization belongs in
# initialize since we're Configurable. (there's something
# weird in initialization order between this class,
# Configurable, and TCPServer so we can't leave __init__ out
# completely)
pass
def initialize(self, request_callback, no_keep_alive=False, io_loop=None,
xheaders=False, ssl_options=None, protocol=None,
decompress_request=False,
chunk_size=None, max_header_size=None,
idle_connection_timeout=None, body_timeout=None,
max_body_size=None, max_buffer_size=None):
self.request_callback = request_callback
self.no_keep_alive = no_keep_alive
self.xheaders = xheaders
self.protocol = protocol
self.conn_params = HTTP1ConnectionParameters(
decompress=decompress_request,
chunk_size=chunk_size,
max_header_size=max_header_size,
header_timeout=idle_connection_timeout or 3600,
max_body_size=max_body_size,
body_timeout=body_timeout)
TCPServer.__init__(self, io_loop=io_loop, ssl_options=ssl_options,
max_buffer_size=max_buffer_size,
read_chunk_size=chunk_size)
self._connections = set()
@classmethod
def configurable_base(cls):
return HTTPServer
@classmethod
def configurable_default(cls):
return HTTPServer
@gen.coroutine
def close_all_connections(self):
while self._connections:
# Peek at an arbitrary element of the set
conn = next(iter(self._connections))
yield conn.close()
def handle_stream(self, stream, address):
context = _HTTPRequestContext(stream, address,
self.protocol)
conn = HTTP1ServerConnection(
stream, self.conn_params, context)
self._connections.add(conn)
conn.start_serving(self)
def start_request(self, server_conn, request_conn):
return _ServerRequestAdapter(self, server_conn, request_conn)
def on_close(self, server_conn):
self._connections.remove(server_conn)
class _HTTPRequestContext(object):
def __init__(self, stream, address, protocol):
self.address = address
# Save the socket's address family now so we know how to
# interpret self.address even after the stream is closed
# and its socket attribute replaced with None.
if stream.socket is not None:
self.address_family = stream.socket.family
else:
self.address_family = None
# In HTTPServerRequest we want an IP, not a full socket address.
if (self.address_family in (socket.AF_INET, socket.AF_INET6) and
address is not None):
self.remote_ip = address[0]
else:
# Unix (or other) socket; fake the remote address.
self.remote_ip = '0.0.0.0'
if protocol:
self.protocol = protocol
elif isinstance(stream, iostream.SSLIOStream):
self.protocol = "https"
else:
self.protocol = "http"
self._orig_remote_ip = self.remote_ip
self._orig_protocol = self.protocol
def __str__(self):
if self.address_family in (socket.AF_INET, socket.AF_INET6):
return self.remote_ip
elif isinstance(self.address, bytes):
# Python 3 with the -bb option warns about str(bytes),
# so convert it explicitly.
# Unix socket addresses are str on mac but bytes on linux.
return native_str(self.address)
else:
return str(self.address)
def _apply_xheaders(self, headers):
"""Rewrite the ``remote_ip`` and ``protocol`` fields."""
# Squid uses X-Forwarded-For, others use X-Real-Ip
ip = headers.get("X-Forwarded-For", self.remote_ip)
ip = ip.split(',')[-1].strip()
ip = headers.get("X-Real-Ip", ip)
if netutil.is_valid_ip(ip):
self.remote_ip = ip
# AWS uses X-Forwarded-Proto
proto_header = headers.get(
"X-Scheme", headers.get("X-Forwarded-Proto",
self.protocol))
if proto_header in ("http", "https"):
self.protocol = proto_header
def _unapply_xheaders(self):
"""Undo changes from `_apply_xheaders`.
Xheaders are per-request so they should not leak to the next
request on the same connection.
"""
self.remote_ip = self._orig_remote_ip
self.protocol = self._orig_protocol
class _ServerRequestAdapter(httputil.HTTPMessageDelegate):
"""Adapts the `HTTPMessageDelegate` interface to the interface expected
by our clients.
"""
def __init__(self, server, server_conn, request_conn):
self.server = server
self.connection = request_conn
self.request = None
if isinstance(server.request_callback,
httputil.HTTPServerConnectionDelegate):
self.delegate = server.request_callback.start_request(
server_conn, request_conn)
self._chunks = None
else:
self.delegate = None
self._chunks = []
def headers_received(self, start_line, headers):
if self.server.xheaders:
self.connection.context._apply_xheaders(headers)
if self.delegate is None:
self.request = httputil.HTTPServerRequest(
connection=self.connection, start_line=start_line,
headers=headers)
else:
return self.delegate.headers_received(start_line, headers)
def data_received(self, chunk):
if self.delegate is None:
self._chunks.append(chunk)
else:
return self.delegate.data_received(chunk)
def finish(self):
if self.delegate is None:
self.request.body = b''.join(self._chunks)
self.request._parse_body()
self.server.request_callback(self.request)
else:
self.delegate.finish()
self._cleanup()
def on_connection_close(self):
if self.delegate is None:
self._chunks = None
else:
self.delegate.on_connection_close()
self._cleanup()
def _cleanup(self):
if self.server.xheaders:
self.connection.context._unapply_xheaders()
HTTPRequest = httputil.HTTPServerRequest
| apache-2.0 |
helifu/kudu | python/kudu/tests/test_scanner.py | 2 | 14089 | #
# 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 division
from kudu.compat import unittest
from kudu.tests.util import TestScanBase
from kudu.tests.common import KuduTestBase, TimeoutError
import kudu
import datetime
import time
import pytest
class TestScanner(TestScanBase):
@classmethod
def setUpClass(self):
super(TestScanner, self).setUpClass()
def setUp(self):
pass
def test_scan_rows_basic(self):
# Let's scan with no predicates
scanner = self.table.scanner().open()
tuples = scanner.read_all_tuples()
self.assertEqual(sorted(tuples), self.tuples)
def test_scan_rows_simple_predicate(self):
key = self.table['key']
preds = [key > 19, key < 50]
def _read_predicates(preds):
scanner = self.table.scanner()
scanner.add_predicates(preds)
scanner.open()
return scanner.read_all_tuples()
tuples = _read_predicates(preds)
self.assertEqual(sorted(tuples), self.tuples[20:50])
# verify predicates reusable
tuples = _read_predicates(preds)
self.assertEqual(sorted(tuples), self.tuples[20:50])
def test_scan_limit(self):
# Set limits both below and above the max number of rows.
limits = [self.nrows - 1, self.nrows, self.nrows + 1]
for limit in limits:
scanner = self.table.scanner()
scanner.set_limit(limit)
tuples = scanner.read_all_tuples()
self.assertEqual(len(tuples), min(limit, self.nrows))
def test_scan_rows_string_predicate_and_projection(self):
scanner = self.table.scanner()
scanner.set_projected_column_names(['key', 'string_val'])
sv = self.table['string_val']
scanner.add_predicates([sv >= 'hello_20',
sv <= 'hello_22'])
scanner.set_fault_tolerant()
scanner.open()
tuples = scanner.read_all_tuples()
self.assertEqual(sorted(tuples), [(20, 'hello_20'), (22, 'hello_22')])
def test_scan_rows_in_list_predicate(self):
"""
Test scanner with an InList predicate and
a string comparison predicate
"""
key_list = [2, 98]
scanner = self.table.scanner()
scanner.set_fault_tolerant()\
.add_predicates([
self.table[0].in_list(key_list),
self.table['string_val'] >= 'hello_9'
])
scanner.open()
tuples = scanner.read_all_tuples()
self.assertEqual(tuples, [self.tuples[98]])
def test_scan_rows_is_not_null_predicate(self):
"""
Test scanner with an IsNotNull predicate on string_val column
"""
pred = self.table['string_val'].is_not_null()
scanner = self.table.scanner()
scanner.add_predicate(pred)
scanner.open()
tuples = scanner.read_all_tuples()
rows = [i for i in range(100) if i % 2 == 0]
self.assertEqual(sorted(tuples), [self.tuples[i] for i in rows])
def test_scan_rows_is_null_predicate(self):
"""
Test scanner with an IsNull predicate on string_val column
"""
pred = self.table['string_val'].is_null()
scanner = self.table.scanner()
scanner.add_predicate(pred)
scanner.open()
tuples = scanner.read_all_tuples()
rows = [i for i in range(100) if i % 2 != 0]
self.assertEqual(sorted(tuples), [self.tuples[i] for i in rows])
def test_index_projection_with_schema(self):
scanner = self.table.scanner()
scanner.set_projected_column_indexes([0, 1])
scanner.set_fault_tolerant()
scanner.open()
tuples = scanner.read_all_tuples()
# Build schema to check against
builder = kudu.schema_builder()
builder.add_column('key', kudu.int32, nullable=False)
builder.add_column('int_val', kudu.int32)
builder.set_primary_keys(['key'])
expected_schema = builder.build()
# Build new schema from projection schema
builder = kudu.schema_builder()
for col in scanner.get_projection_schema():
builder.copy_column(col)
builder.set_primary_keys(['key'])
new_schema = builder.build()
self.assertEqual(tuples, [t[0:2] for t in self.tuples])
self.assertTrue(expected_schema.equals(new_schema))
def test_scan_with_bounds(self):
scanner = self.table.scanner()
scanner.set_fault_tolerant()\
.add_lower_bound({'key': 50})\
.add_exclusive_upper_bound({'key': 55})
scanner.open()
tuples = scanner.read_all_tuples()
self.assertEqual(sorted(tuples), self.tuples[50:55])
def test_scan_invalid_predicates(self):
scanner = self.table.scanner()
sv = self.table['string_val']
with self.assertRaises(TypeError):
scanner.add_predicates([sv >= None])
with self.assertRaises(TypeError):
scanner.add_predicates([sv >= 1])
with self.assertRaises(TypeError):
scanner.add_predicates([sv.in_list(['testing',
datetime.datetime.utcnow()])])
with self.assertRaises(TypeError):
scanner.add_predicates([sv.in_list([
'hello_20',
120
])])
def test_scan_batch_by_batch(self):
scanner = self.table.scanner()
scanner.set_fault_tolerant()
lower_bound = scanner.new_bound()
lower_bound['key'] = 10
scanner.add_lower_bound(lower_bound)
upper_bound = scanner.new_bound()
upper_bound['key'] = 90
scanner.add_exclusive_upper_bound(upper_bound)
scanner.open()
tuples = []
while scanner.has_more_rows():
batch = scanner.next_batch()
tuples.extend(batch.as_tuples())
self.assertEqual(sorted(tuples), self.tuples[10:90])
def test_unixtime_micros(self):
"""
Test setting and getting unixtime_micros fields
"""
# Insert new rows
self.insert_new_unixtime_micros_rows()
# Validate results
scanner = self.table.scanner()
scanner.set_fault_tolerant().open()
self.assertEqual(sorted(self.tuples), scanner.read_all_tuples())
def test_read_mode(self):
"""
Test scanning in latest, snapshot and read_your_writes read modes.
"""
# Delete row
self.delete_insert_row_for_read_test()
# Check scanner results prior to delete
scanner = self.table.scanner()
scanner.set_read_mode('snapshot')\
.set_snapshot(self.snapshot_timestamp)\
.open()
self.assertEqual(sorted(self.tuples[1:]), sorted(scanner.read_all_tuples()))
# Check scanner results after delete with latest mode
timeout = time.time() + 10
check_tuples = []
while check_tuples != sorted(self.tuples):
if time.time() > timeout:
raise TimeoutError("Could not validate results in allocated" +
"time.")
scanner = self.table.scanner()
scanner.set_read_mode(kudu.READ_LATEST)\
.open()
check_tuples = sorted(scanner.read_all_tuples())
# Avoid tight looping
time.sleep(0.05)
# Check scanner results after delete with read_your_writes mode
scanner = self.table.scanner()
scanner.set_read_mode('read_your_writes')\
.open()
self.assertEqual(sorted(self.tuples), sorted(scanner.read_all_tuples()))
def test_resource_metrics_and_cache_blocks(self):
"""
Test getting the resource metrics after scanning and
setting the scanner to not cache blocks.
"""
# Build scanner and read through all batches and retrieve metrics.
scanner = self.table.scanner()
scanner.set_fault_tolerant().set_cache_blocks(False).open()
scanner.read_all_tuples()
metrics = scanner.get_resource_metrics()
# Confirm that the scanner returned cache hit and miss values.
self.assertTrue('cfile_cache_hit_bytes' in metrics)
self.assertTrue('cfile_cache_miss_bytes' in metrics)
def verify_pred_type_scans(self, preds, row_indexes, count_only=False):
# Using the incoming list of predicates, verify that the row returned
# matches the inserted tuple at the row indexes specified in a
# slice object
scanner = self.type_table.scanner()
scanner.set_fault_tolerant()
scanner.add_predicates(preds)
scanner.set_projected_column_names(self.projected_names_w_o_float)
tuples = scanner.open().read_all_tuples()
# verify rows
if count_only:
self.assertEqual(len(self.type_test_rows[row_indexes]), len(tuples))
else:
self.assertEqual(sorted(self.type_test_rows[row_indexes]), tuples)
def test_unixtime_micros_pred(self):
# Test unixtime_micros value predicate
self._test_unixtime_micros_pred()
def test_bool_pred(self):
# Test a boolean value predicate
self._test_bool_pred()
def test_double_pred(self):
# Test a double precision float predicate
self._test_double_pred()
def test_float_pred(self):
# Test a single precision float predicate
# Does a row check count only
self._test_float_pred()
def test_decimal_pred(self):
if kudu.CLIENT_SUPPORTS_DECIMAL:
# Test a decimal predicate
self._test_decimal_pred()
def test_binary_pred(self):
# Test a binary predicate
self._test_binary_pred()
def test_scan_selection(self):
"""
This test confirms that setting the scan selection policy on the
scanner does not cause any errors. There is no way to confirm
that the policy was actually set. This functionality is
tested in the C++ test:
ClientTest.TestReplicatedMultiTabletTableFailover.
"""
for policy in ['leader', kudu.CLOSEST_REPLICA, 2]:
scanner = self.table.scanner()
scanner.set_selection(policy)
scanner.open()
self.assertEqual(sorted(scanner.read_all_tuples()),
sorted(self.tuples))
@pytest.mark.skipif(not (kudu.CLIENT_SUPPORTS_PANDAS),
reason="Pandas required to run this test.")
def test_scanner_to_pandas_types(self):
"""
This test confirms that data types are converted as expected to Pandas.
"""
import numpy as np
scanner = self.type_table.scanner()
df = scanner.to_pandas()
types = df.dtypes
if kudu.CLIENT_SUPPORTS_DECIMAL:
self.assertEqual(types[0], np.int64)
self.assertEqual(types[1], 'datetime64[ns, UTC]')
self.assertEqual(types[2], np.object)
self.assertEqual(types[3], np.object)
self.assertEqual(types[4], np.bool)
self.assertEqual(types[5], np.float64)
self.assertEqual(types[6], np.int8)
self.assertEqual(types[7], np.object)
self.assertEqual(types[8], np.float32)
else:
self.assertEqual(types[0], np.int64)
self.assertEqual(types[1], 'datetime64[ns, UTC]')
self.assertEqual(types[2], np.object)
self.assertEqual(types[3], np.bool)
self.assertEqual(types[4], np.float64)
self.assertEqual(types[5], np.int8)
self.assertEqual(types[6], np.object)
self.assertEqual(types[7], np.float32)
@pytest.mark.skipif(not (kudu.CLIENT_SUPPORTS_PANDAS),
reason="Pandas required to run this test.")
def test_scanner_to_pandas_row_count(self):
"""
This test confirms that the record counts match between Pandas and the scanner.
"""
scanner = self.type_table.scanner()
scanner_count = len(scanner.read_all_tuples())
scanner = self.type_table.scanner()
df = scanner.to_pandas()
self.assertEqual(scanner_count, df.shape[0])
@pytest.mark.skipif(not (kudu.CLIENT_SUPPORTS_PANDAS),
reason="Pandas required to run this test.")
def test_scanner_to_pandas_index(self):
"""
This test confirms that an index is correctly applied.
"""
scanner = self.type_table.scanner()
df = scanner.to_pandas(index='key')
self.assertEqual(df.index.name, 'key')
self.assertEqual(list(df.index), [1, 2])
@pytest.mark.skipif((not(kudu.CLIENT_SUPPORTS_PANDAS) or
(not(kudu.CLIENT_SUPPORTS_DECIMAL))),
reason="Pandas and Decimal support required to run this test.")
def test_scanner_to_pandas_index(self):
"""
This test confirms that a decimal column is coerced to a double when specified.
"""
import numpy as np
scanner = self.type_table.scanner()
df = scanner.to_pandas(coerce_float=True)
types = df.dtypes
self.assertEqual(types[2], np.float64)
| apache-2.0 |
nikolhm/Pokus | knownpaths.py | 1 | 9583 | import ctypes, sys
from ctypes import windll, wintypes
from uuid import UUID
class GUID(ctypes.Structure): # [1]
_fields_ = [
("Data1", wintypes.DWORD),
("Data2", wintypes.WORD),
("Data3", wintypes.WORD),
("Data4", wintypes.BYTE * 8)
]
def __init__(self, uuid_):
ctypes.Structure.__init__(self)
self.Data1, self.Data2, self.Data3, self.Data4[0], self.Data4[1], rest = uuid_.fields
for i in range(2, 8):
self.Data4[i] = rest>>(8 - i - 1)*8 & 0xff
class FOLDERID: # [2]
AccountPictures = UUID('{008ca0b1-55b4-4c56-b8a8-4de4b299d3be}')
AdminTools = UUID('{724EF170-A42D-4FEF-9F26-B60E846FBA4F}')
ApplicationShortcuts = UUID('{A3918781-E5F2-4890-B3D9-A7E54332328C}')
CameraRoll = UUID('{AB5FB87B-7CE2-4F83-915D-550846C9537B}')
CDBurning = UUID('{9E52AB10-F80D-49DF-ACB8-4330F5687855}')
CommonAdminTools = UUID('{D0384E7D-BAC3-4797-8F14-CBA229B392B5}')
CommonOEMLinks = UUID('{C1BAE2D0-10DF-4334-BEDD-7AA20B227A9D}')
CommonPrograms = UUID('{0139D44E-6AFE-49F2-8690-3DAFCAE6FFB8}')
CommonStartMenu = UUID('{A4115719-D62E-491D-AA7C-E74B8BE3B067}')
CommonStartup = UUID('{82A5EA35-D9CD-47C5-9629-E15D2F714E6E}')
CommonTemplates = UUID('{B94237E7-57AC-4347-9151-B08C6C32D1F7}')
Contacts = UUID('{56784854-C6CB-462b-8169-88E350ACB882}')
Cookies = UUID('{2B0F765D-C0E9-4171-908E-08A611B84FF6}')
Desktop = UUID('{B4BFCC3A-DB2C-424C-B029-7FE99A87C641}')
DeviceMetadataStore = UUID('{5CE4A5E9-E4EB-479D-B89F-130C02886155}')
Documents = UUID('{FDD39AD0-238F-46AF-ADB4-6C85480369C7}')
DocumentsLibrary = UUID('{7B0DB17D-9CD2-4A93-9733-46CC89022E7C}')
Downloads = UUID('{374DE290-123F-4565-9164-39C4925E467B}')
Favorites = UUID('{1777F761-68AD-4D8A-87BD-30B759FA33DD}')
Fonts = UUID('{FD228CB7-AE11-4AE3-864C-16F3910AB8FE}')
GameTasks = UUID('{054FAE61-4DD8-4787-80B6-090220C4B700}')
History = UUID('{D9DC8A3B-B784-432E-A781-5A1130A75963}')
ImplicitAppShortcuts = UUID('{BCB5256F-79F6-4CEE-B725-DC34E402FD46}')
InternetCache = UUID('{352481E8-33BE-4251-BA85-6007CAEDCF9D}')
Libraries = UUID('{1B3EA5DC-B587-4786-B4EF-BD1DC332AEAE}')
Links = UUID('{bfb9d5e0-c6a9-404c-b2b2-ae6db6af4968}')
LocalAppData = UUID('{F1B32785-6FBA-4FCF-9D55-7B8E7F157091}')
LocalAppDataLow = UUID('{A520A1A4-1780-4FF6-BD18-167343C5AF16}')
LocalizedResourcesDir = UUID('{2A00375E-224C-49DE-B8D1-440DF7EF3DDC}')
Music = UUID('{4BD8D571-6D19-48D3-BE97-422220080E43}')
MusicLibrary = UUID('{2112AB0A-C86A-4FFE-A368-0DE96E47012E}')
NetHood = UUID('{C5ABBF53-E17F-4121-8900-86626FC2C973}')
OriginalImages = UUID('{2C36C0AA-5812-4b87-BFD0-4CD0DFB19B39}')
PhotoAlbums = UUID('{69D2CF90-FC33-4FB7-9A0C-EBB0F0FCB43C}')
PicturesLibrary = UUID('{A990AE9F-A03B-4E80-94BC-9912D7504104}')
Pictures = UUID('{33E28130-4E1E-4676-835A-98395C3BC3BB}')
Playlists = UUID('{DE92C1C7-837F-4F69-A3BB-86E631204A23}')
PrintHood = UUID('{9274BD8D-CFD1-41C3-B35E-B13F55A758F4}')
Profile = UUID('{5E6C858F-0E22-4760-9AFE-EA3317B67173}')
ProgramData = UUID('{62AB5D82-FDC1-4DC3-A9DD-070D1D495D97}')
ProgramFiles = UUID('{905e63b6-c1bf-494e-b29c-65b732d3d21a}')
ProgramFilesX64 = UUID('{6D809377-6AF0-444b-8957-A3773F02200E}')
ProgramFilesX86 = UUID('{7C5A40EF-A0FB-4BFC-874A-C0F2E0B9FA8E}')
ProgramFilesCommon = UUID('{F7F1ED05-9F6D-47A2-AAAE-29D317C6F066}')
ProgramFilesCommonX64 = UUID('{6365D5A7-0F0D-45E5-87F6-0DA56B6A4F7D}')
ProgramFilesCommonX86 = UUID('{DE974D24-D9C6-4D3E-BF91-F4455120B917}')
Programs = UUID('{A77F5D77-2E2B-44C3-A6A2-ABA601054A51}')
Public = UUID('{DFDF76A2-C82A-4D63-906A-5644AC457385}')
PublicDesktop = UUID('{C4AA340D-F20F-4863-AFEF-F87EF2E6BA25}')
PublicDocuments = UUID('{ED4824AF-DCE4-45A8-81E2-FC7965083634}')
PublicDownloads = UUID('{3D644C9B-1FB8-4f30-9B45-F670235F79C0}')
PublicGameTasks = UUID('{DEBF2536-E1A8-4c59-B6A2-414586476AEA}')
PublicLibraries = UUID('{48DAF80B-E6CF-4F4E-B800-0E69D84EE384}')
PublicMusic = UUID('{3214FAB5-9757-4298-BB61-92A9DEAA44FF}')
PublicPictures = UUID('{B6EBFB86-6907-413C-9AF7-4FC2ABF07CC5}')
PublicRingtones = UUID('{E555AB60-153B-4D17-9F04-A5FE99FC15EC}')
PublicUserTiles = UUID('{0482af6c-08f1-4c34-8c90-e17ec98b1e17}')
PublicVideos = UUID('{2400183A-6185-49FB-A2D8-4A392A602BA3}')
QuickLaunch = UUID('{52a4f021-7b75-48a9-9f6b-4b87a210bc8f}')
Recent = UUID('{AE50C081-EBD2-438A-8655-8A092E34987A}')
RecordedTVLibrary = UUID('{1A6FDBA2-F42D-4358-A798-B74D745926C5}')
ResourceDir = UUID('{8AD10C31-2ADB-4296-A8F7-E4701232C972}')
Ringtones = UUID('{C870044B-F49E-4126-A9C3-B52A1FF411E8}')
RoamingAppData = UUID('{3EB685DB-65F9-4CF6-A03A-E3EF65729F3D}')
RoamedTileImages = UUID('{AAA8D5A5-F1D6-4259-BAA8-78E7EF60835E}')
RoamingTiles = UUID('{00BCFC5A-ED94-4e48-96A1-3F6217F21990}')
SampleMusic = UUID('{B250C668-F57D-4EE1-A63C-290EE7D1AA1F}')
SamplePictures = UUID('{C4900540-2379-4C75-844B-64E6FAF8716B}')
SamplePlaylists = UUID('{15CA69B3-30EE-49C1-ACE1-6B5EC372AFB5}')
SampleVideos = UUID('{859EAD94-2E85-48AD-A71A-0969CB56A6CD}')
SavedGames = UUID('{4C5C32FF-BB9D-43b0-B5B4-2D72E54EAAA4}')
SavedSearches = UUID('{7d1d3a04-debb-4115-95cf-2f29da2920da}')
Screenshots = UUID('{b7bede81-df94-4682-a7d8-57a52620b86f}')
SearchHistory = UUID('{0D4C3DB6-03A3-462F-A0E6-08924C41B5D4}')
SearchTemplates = UUID('{7E636BFE-DFA9-4D5E-B456-D7B39851D8A9}')
SendTo = UUID('{8983036C-27C0-404B-8F08-102D10DCFD74}')
SidebarDefaultParts = UUID('{7B396E54-9EC5-4300-BE0A-2482EBAE1A26}')
SidebarParts = UUID('{A75D362E-50FC-4fb7-AC2C-A8BEAA314493}')
SkyDrive = UUID('{A52BBA46-E9E1-435f-B3D9-28DAA648C0F6}')
SkyDriveCameraRoll = UUID('{767E6811-49CB-4273-87C2-20F355E1085B}')
SkyDriveDocuments = UUID('{24D89E24-2F19-4534-9DDE-6A6671FBB8FE}')
SkyDrivePictures = UUID('{339719B5-8C47-4894-94C2-D8F77ADD44A6}')
StartMenu = UUID('{625B53C3-AB48-4EC1-BA1F-A1EF4146FC19}')
Startup = UUID('{B97D20BB-F46A-4C97-BA10-5E3608430854}')
System = UUID('{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}')
SystemX86 = UUID('{D65231B0-B2F1-4857-A4CE-A8E7C6EA7D27}')
Templates = UUID('{A63293E8-664E-48DB-A079-DF759E0509F7}')
UserPinned = UUID('{9E3995AB-1F9C-4F13-B827-48B24B6C7174}')
UserProfiles = UUID('{0762D272-C50A-4BB0-A382-697DCD729B80}')
UserProgramFiles = UUID('{5CD7AEE2-2219-4A67-B85D-6C9CE15660CB}')
UserProgramFilesCommon = UUID('{BCBD3057-CA5C-4622-B42D-BC56DB0AE516}')
Videos = UUID('{18989B1D-99B5-455B-841C-AB7C74E4DDFC}')
VideosLibrary = UUID('{491E922F-5643-4AF4-A7EB-4E7A138D8174}')
Windows = UUID('{F38BF404-1D43-42F2-9305-67DE0B28FC23}')
class UserHandle: # [3]
current = wintypes.HANDLE(0)
common = wintypes.HANDLE(-1)
_CoTaskMemFree = windll.ole32.CoTaskMemFree # [4]
_CoTaskMemFree.restype= None
_CoTaskMemFree.argtypes = [ctypes.c_void_p]
_SHGetKnownFolderPath = windll.shell32.SHGetKnownFolderPath # [5] [3]
_SHGetKnownFolderPath.argtypes = [
ctypes.POINTER(GUID), wintypes.DWORD, wintypes.HANDLE, ctypes.POINTER(ctypes.c_wchar_p)
]
class PathNotFoundException(Exception): pass
def get_path(folderid, user_handle=UserHandle.common):
fid = GUID(folderid)
pPath = ctypes.c_wchar_p()
S_OK = 0
if _SHGetKnownFolderPath(ctypes.byref(fid), 0, user_handle, ctypes.byref(pPath)) != S_OK:
raise PathNotFoundException()
path = pPath.value
_CoTaskMemFree(pPath)
return path
if __name__ == '__main__':
if len(sys.argv) < 2 or sys.argv[1] in ['-?', '/?']:
print('python knownpaths.py FOLDERID {current|common}')
sys.exit(0)
try:
folderid = getattr(FOLDERID, sys.argv[1])
except AttributeError:
print('Unknown folder id "%s"' % sys.argv[1], file=sys.stderr)
sys.exit(1)
try:
if len(sys.argv) == 2:
print(get_path(folderid))
else:
print(get_path(folderid, getattr(UserHandle, sys.argv[2])))
except PathNotFoundException:
print('Folder not found "%s"' % ' '.join(sys.argv[1:]), file=sys.stderr)
sys.exit(1)
# [1] http://msdn.microsoft.com/en-us/library/windows/desktop/aa373931.aspx
# [2] http://msdn.microsoft.com/en-us/library/windows/desktop/dd378457.aspx
# [3] http://msdn.microsoft.com/en-us/library/windows/desktop/bb762188.aspx
# [4] http://msdn.microsoft.com/en-us/library/windows/desktop/ms680722.aspx
# [5] http://www.themacaque.com/?p=954
| mit |
Mustard-Systems-Ltd/pyzmq | perf/perf.py | 6 | 5316 | #!/usr/bin/env python
# coding: utf-8
# Copyright (C) PyZMQ Developers
# Distributed under the terms of the Modified BSD License.
#
# Some original test code Copyright (c) 2007-2010 iMatix Corporation,
# Used under LGPLv3
import argparse
import time
from multiprocessing import Process
import zmq
def parse_args(argv=None):
parser = argparse.ArgumentParser(description='Run a zmq performance test')
parser.add_argument('-p', '--poll', action='store_true',
help='use a zmq Poller instead of raw send/recv')
parser.add_argument('-c', '--copy', action='store_true',
help='copy messages instead of using zero-copy')
parser.add_argument('-s', '--size', type=int, default=10240,
help='size (in bytes) of the test message')
parser.add_argument('-n', '--count', type=int, default=10240,
help='number of test messages to send')
parser.add_argument('--url', dest='url', type=str, default='tcp://127.0.0.1:5555',
help='the zmq URL on which to run the test')
parser.add_argument(dest='test', type=str, default='lat', choices=['lat', 'thr'],
help='which test to run')
return parser.parse_args(argv)
def latency_echo(url, count, poll, copy):
"""echo messages on a REP socket
Should be started before `latency`
"""
ctx = zmq.Context()
s = ctx.socket(zmq.REP)
if poll:
p = zmq.Poller()
p.register(s)
s.bind(url)
block = zmq.NOBLOCK if poll else 0
for i in range(count):
if poll:
res = p.poll()
msg = s.recv(block, copy=copy)
if poll:
res = p.poll()
s.send(msg, block, copy=copy)
msg = s.recv()
assert msg == b'done'
s.close()
ctx.term()
def latency(url, count, size, poll, copy):
"""Perform a latency test"""
ctx = zmq.Context()
s = ctx.socket(zmq.REQ)
s.setsockopt(zmq.LINGER, -1)
s.connect(url)
if poll:
p = zmq.Poller()
p.register(s)
msg = b' ' * size
watch = zmq.Stopwatch()
block = zmq.NOBLOCK if poll else 0
time.sleep(1)
watch.start()
for i in range (0, count):
if poll:
res = p.poll()
assert(res[0][1] & zmq.POLLOUT)
s.send(msg, block, copy=copy)
if poll:
res = p.poll()
assert(res[0][1] & zmq.POLLIN)
msg = s.recv(block, copy=copy)
assert len(msg) == size
elapsed = watch.stop()
s.send(b'done')
latency = elapsed / (count * 2.)
print ("message size : %8i [B]" % (size, ))
print ("roundtrip count: %8i [msgs]" % (count, ))
print ("mean latency : %12.3f [µs]" % (latency, ))
print ("test time : %12.3f [s]" % (elapsed * 1e-6, ))
def pusher(url, count, size, copy, poll):
"""send a bunch of messages on a PUSH socket"""
ctx = zmq.Context()
s = ctx.socket(zmq.PUSH)
# Add your socket options here.
# For example ZMQ_RATE, ZMQ_RECOVERY_IVL and ZMQ_MCAST_LOOP for PGM.
if poll:
p = zmq.Poller()
p.register(s)
s.connect(url)
msg = zmq.Message(b' ' * size)
block = zmq.NOBLOCK if poll else 0
for i in range(count):
if poll:
res = p.poll()
assert(res[0][1] & zmq.POLLOUT)
s.send(msg, block, copy=copy)
s.close()
ctx.term()
def throughput(url, count, size, poll, copy):
"""recv a bunch of messages on a PULL socket
Should be started before `pusher`
"""
ctx = zmq.Context()
s = ctx.socket(zmq.PULL)
# Add your socket options here.
# For example ZMQ_RATE, ZMQ_RECOVERY_IVL and ZMQ_MCAST_LOOP for PGM.
if poll:
p = zmq.Poller()
p.register(s)
s.bind(url)
watch = zmq.Stopwatch()
block = zmq.NOBLOCK if poll else 0
# Wait for the other side to connect.
msg = s.recv()
assert len (msg) == size
watch.start()
for i in range (count-1):
if poll:
res = p.poll()
msg = s.recv(block, copy=copy)
elapsed = watch.stop()
if elapsed == 0:
elapsed = 1
throughput = (1e6 * float(count)) / float(elapsed)
megabits = float(throughput * size * 8) / 1e6
print ("message size : %8i [B]" % (size, ))
print ("message count : %8i [msgs]" % (count, ))
print ("mean throughput: %8.0f [msg/s]" % (throughput, ))
print ("mean throughput: %12.3f [Mb/s]" % (megabits, ))
print ("test time : %12.3f [s]" % (elapsed * 1e-6, ))
def main():
args = parse_args()
tic = time.time()
if args.test == 'lat':
bg = Process(target=latency_echo, args=(args.url, args.count, args.poll, args.copy))
bg.start()
latency(args.url, args.count, args.size, args.poll, args.copy)
elif args.test == 'thr':
bg = Process(target=throughput, args=(args.url, args.count, args.size, args.poll, args.copy))
bg.start()
pusher(args.url, args.count, args.size, args.poll, args.copy)
bg.join()
toc = time.time()
if (toc - tic) < 3:
print ("For best results, tests should take at least a few seconds.")
if __name__ == '__main__':
main()
| bsd-3-clause |
martinbuc/missionplanner | Lib/lib2to3/pgen2/parse.py | 68 | 8254 | # Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""Parser engine for the grammar tables generated by pgen.
The grammar table must be loaded first.
See Parser/parser.c in the Python distribution for additional info on
how this parsing engine works.
"""
# Local imports
from . import token
class ParseError(Exception):
"""Exception to signal the parser is stuck."""
def __init__(self, msg, type, value, context):
Exception.__init__(self, "%s: type=%r, value=%r, context=%r" %
(msg, type, value, context))
self.msg = msg
self.type = type
self.value = value
self.context = context
class Parser(object):
"""Parser engine.
The proper usage sequence is:
p = Parser(grammar, [converter]) # create instance
p.setup([start]) # prepare for parsing
<for each input token>:
if p.addtoken(...): # parse a token; may raise ParseError
break
root = p.rootnode # root of abstract syntax tree
A Parser instance may be reused by calling setup() repeatedly.
A Parser instance contains state pertaining to the current token
sequence, and should not be used concurrently by different threads
to parse separate token sequences.
See driver.py for how to get input tokens by tokenizing a file or
string.
Parsing is complete when addtoken() returns True; the root of the
abstract syntax tree can then be retrieved from the rootnode
instance variable. When a syntax error occurs, addtoken() raises
the ParseError exception. There is no error recovery; the parser
cannot be used after a syntax error was reported (but it can be
reinitialized by calling setup()).
"""
def __init__(self, grammar, convert=None):
"""Constructor.
The grammar argument is a grammar.Grammar instance; see the
grammar module for more information.
The parser is not ready yet for parsing; you must call the
setup() method to get it started.
The optional convert argument is a function mapping concrete
syntax tree nodes to abstract syntax tree nodes. If not
given, no conversion is done and the syntax tree produced is
the concrete syntax tree. If given, it must be a function of
two arguments, the first being the grammar (a grammar.Grammar
instance), and the second being the concrete syntax tree node
to be converted. The syntax tree is converted from the bottom
up.
A concrete syntax tree node is a (type, value, context, nodes)
tuple, where type is the node type (a token or symbol number),
value is None for symbols and a string for tokens, context is
None or an opaque value used for error reporting (typically a
(lineno, offset) pair), and nodes is a list of children for
symbols, and None for tokens.
An abstract syntax tree node may be anything; this is entirely
up to the converter function.
"""
self.grammar = grammar
self.convert = convert or (lambda grammar, node: node)
def setup(self, start=None):
"""Prepare for parsing.
This *must* be called before starting to parse.
The optional argument is an alternative start symbol; it
defaults to the grammar's start symbol.
You can use a Parser instance to parse any number of programs;
each time you call setup() the parser is reset to an initial
state determined by the (implicit or explicit) start symbol.
"""
if start is None:
start = self.grammar.start
# Each stack entry is a tuple: (dfa, state, node).
# A node is a tuple: (type, value, context, children),
# where children is a list of nodes or None, and context may be None.
newnode = (start, None, None, [])
stackentry = (self.grammar.dfas[start], 0, newnode)
self.stack = [stackentry]
self.rootnode = None
self.used_names = set() # Aliased to self.rootnode.used_names in pop()
def addtoken(self, type, value, context):
"""Add a token; return True iff this is the end of the program."""
# Map from token to label
ilabel = self.classify(type, value, context)
# Loop until the token is shifted; may raise exceptions
while True:
dfa, state, node = self.stack[-1]
states, first = dfa
arcs = states[state]
# Look for a state with this label
for i, newstate in arcs:
t, v = self.grammar.labels[i]
if ilabel == i:
# Look it up in the list of labels
assert t < 256
# Shift a token; we're done with it
self.shift(type, value, newstate, context)
# Pop while we are in an accept-only state
state = newstate
while states[state] == [(0, state)]:
self.pop()
if not self.stack:
# Done parsing!
return True
dfa, state, node = self.stack[-1]
states, first = dfa
# Done with this token
return False
elif t >= 256:
# See if it's a symbol and if we're in its first set
itsdfa = self.grammar.dfas[t]
itsstates, itsfirst = itsdfa
if ilabel in itsfirst:
# Push a symbol
self.push(t, self.grammar.dfas[t], newstate, context)
break # To continue the outer while loop
else:
if (0, state) in arcs:
# An accepting state, pop it and try something else
self.pop()
if not self.stack:
# Done parsing, but another token is input
raise ParseError("too much input",
type, value, context)
else:
# No success finding a transition
raise ParseError("bad input", type, value, context)
def classify(self, type, value, context):
"""Turn a token into a label. (Internal)"""
if type == token.NAME:
# Keep a listing of all used names
self.used_names.add(value)
# Check for reserved words
ilabel = self.grammar.keywords.get(value)
if ilabel is not None:
return ilabel
ilabel = self.grammar.tokens.get(type)
if ilabel is None:
raise ParseError("bad token", type, value, context)
return ilabel
def shift(self, type, value, newstate, context):
"""Shift a token. (Internal)"""
dfa, state, node = self.stack[-1]
newnode = (type, value, context, None)
newnode = self.convert(self.grammar, newnode)
if newnode is not None:
node[-1].append(newnode)
self.stack[-1] = (dfa, newstate, node)
def push(self, type, newdfa, newstate, context):
"""Push a nonterminal. (Internal)"""
dfa, state, node = self.stack[-1]
newnode = (type, None, context, [])
self.stack[-1] = (dfa, newstate, node)
self.stack.append((newdfa, 0, newnode))
def pop(self):
"""Pop a nonterminal. (Internal)"""
popdfa, popstate, popnode = self.stack.pop()
newnode = self.convert(self.grammar, popnode)
if newnode is not None:
if self.stack:
dfa, state, node = self.stack[-1]
node[-1].append(newnode)
else:
self.rootnode = newnode
self.rootnode.used_names = self.used_names
| gpl-3.0 |
AndreaCrotti/offlineimap | docs/dev-doc-src/conf.py | 11 | 6621 | # -*- coding: utf-8 -*-
#
# pyDNS documentation build configuration file, created by
# sphinx-quickstart on Tue Feb 2 10:00:47 2010.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0,os.path.abspath('../..'))
from offlineimap import __version__,__author__
# -- General configuration -----------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.todo']
autoclass_content = "both"
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'OfflineImap'
copyright = u'2002-2010, ' + __author__
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = __version__
# The full version, including alpha/beta/rc tags.
release = __version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
#unused_docs = []
# List of directories, relative to source directory, that shouldn't be searched
# for source files.
exclude_trees = []
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
add_module_names = False
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
#html_static_path = ['html']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
html_use_modindex = False
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = ''
# Output file base name for HTML help builder.
htmlhelp_basename = 'dev-doc'
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'offlineimap.tex', u'OfflineImap Documentation',
u'OfflineImap contributors', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_use_modindex = True
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'http://docs.python.org/': None}
| gpl-2.0 |
rolandmansilla/microblog | flask/lib/python2.7/site-packages/flask/ctx.py | 776 | 14266 | # -*- coding: utf-8 -*-
"""
flask.ctx
~~~~~~~~~
Implements the objects required to keep the context.
:copyright: (c) 2011 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
from __future__ import with_statement
import sys
from functools import update_wrapper
from werkzeug.exceptions import HTTPException
from .globals import _request_ctx_stack, _app_ctx_stack
from .module import blueprint_is_module
from .signals import appcontext_pushed, appcontext_popped
class _AppCtxGlobals(object):
"""A plain object."""
def get(self, name, default=None):
return self.__dict__.get(name, default)
def __contains__(self, item):
return item in self.__dict__
def __iter__(self):
return iter(self.__dict__)
def __repr__(self):
top = _app_ctx_stack.top
if top is not None:
return '<flask.g of %r>' % top.app.name
return object.__repr__(self)
def after_this_request(f):
"""Executes a function after this request. This is useful to modify
response objects. The function is passed the response object and has
to return the same or a new one.
Example::
@app.route('/')
def index():
@after_this_request
def add_header(response):
response.headers['X-Foo'] = 'Parachute'
return response
return 'Hello World!'
This is more useful if a function other than the view function wants to
modify a response. For instance think of a decorator that wants to add
some headers without converting the return value into a response object.
.. versionadded:: 0.9
"""
_request_ctx_stack.top._after_request_functions.append(f)
return f
def copy_current_request_context(f):
"""A helper function that decorates a function to retain the current
request context. This is useful when working with greenlets. The moment
the function is decorated a copy of the request context is created and
then pushed when the function is called.
Example::
import gevent
from flask import copy_current_request_context
@app.route('/')
def index():
@copy_current_request_context
def do_some_work():
# do some work here, it can access flask.request like you
# would otherwise in the view function.
...
gevent.spawn(do_some_work)
return 'Regular response'
.. versionadded:: 0.10
"""
top = _request_ctx_stack.top
if top is None:
raise RuntimeError('This decorator can only be used at local scopes '
'when a request context is on the stack. For instance within '
'view functions.')
reqctx = top.copy()
def wrapper(*args, **kwargs):
with reqctx:
return f(*args, **kwargs)
return update_wrapper(wrapper, f)
def has_request_context():
"""If you have code that wants to test if a request context is there or
not this function can be used. For instance, you may want to take advantage
of request information if the request object is available, but fail
silently if it is unavailable.
::
class User(db.Model):
def __init__(self, username, remote_addr=None):
self.username = username
if remote_addr is None and has_request_context():
remote_addr = request.remote_addr
self.remote_addr = remote_addr
Alternatively you can also just test any of the context bound objects
(such as :class:`request` or :class:`g` for truthness)::
class User(db.Model):
def __init__(self, username, remote_addr=None):
self.username = username
if remote_addr is None and request:
remote_addr = request.remote_addr
self.remote_addr = remote_addr
.. versionadded:: 0.7
"""
return _request_ctx_stack.top is not None
def has_app_context():
"""Works like :func:`has_request_context` but for the application
context. You can also just do a boolean check on the
:data:`current_app` object instead.
.. versionadded:: 0.9
"""
return _app_ctx_stack.top is not None
class AppContext(object):
"""The application context binds an application object implicitly
to the current thread or greenlet, similar to how the
:class:`RequestContext` binds request information. The application
context is also implicitly created if a request context is created
but the application is not on top of the individual application
context.
"""
def __init__(self, app):
self.app = app
self.url_adapter = app.create_url_adapter(None)
self.g = app.app_ctx_globals_class()
# Like request context, app contexts can be pushed multiple times
# but there a basic "refcount" is enough to track them.
self._refcnt = 0
def push(self):
"""Binds the app context to the current context."""
self._refcnt += 1
_app_ctx_stack.push(self)
appcontext_pushed.send(self.app)
def pop(self, exc=None):
"""Pops the app context."""
self._refcnt -= 1
if self._refcnt <= 0:
if exc is None:
exc = sys.exc_info()[1]
self.app.do_teardown_appcontext(exc)
rv = _app_ctx_stack.pop()
assert rv is self, 'Popped wrong app context. (%r instead of %r)' \
% (rv, self)
appcontext_popped.send(self.app)
def __enter__(self):
self.push()
return self
def __exit__(self, exc_type, exc_value, tb):
self.pop(exc_value)
class RequestContext(object):
"""The request context contains all request relevant information. It is
created at the beginning of the request and pushed to the
`_request_ctx_stack` and removed at the end of it. It will create the
URL adapter and request object for the WSGI environment provided.
Do not attempt to use this class directly, instead use
:meth:`~flask.Flask.test_request_context` and
:meth:`~flask.Flask.request_context` to create this object.
When the request context is popped, it will evaluate all the
functions registered on the application for teardown execution
(:meth:`~flask.Flask.teardown_request`).
The request context is automatically popped at the end of the request
for you. In debug mode the request context is kept around if
exceptions happen so that interactive debuggers have a chance to
introspect the data. With 0.4 this can also be forced for requests
that did not fail and outside of `DEBUG` mode. By setting
``'flask._preserve_context'`` to `True` on the WSGI environment the
context will not pop itself at the end of the request. This is used by
the :meth:`~flask.Flask.test_client` for example to implement the
deferred cleanup functionality.
You might find this helpful for unittests where you need the
information from the context local around for a little longer. Make
sure to properly :meth:`~werkzeug.LocalStack.pop` the stack yourself in
that situation, otherwise your unittests will leak memory.
"""
def __init__(self, app, environ, request=None):
self.app = app
if request is None:
request = app.request_class(environ)
self.request = request
self.url_adapter = app.create_url_adapter(self.request)
self.flashes = None
self.session = None
# Request contexts can be pushed multiple times and interleaved with
# other request contexts. Now only if the last level is popped we
# get rid of them. Additionally if an application context is missing
# one is created implicitly so for each level we add this information
self._implicit_app_ctx_stack = []
# indicator if the context was preserved. Next time another context
# is pushed the preserved context is popped.
self.preserved = False
# remembers the exception for pop if there is one in case the context
# preservation kicks in.
self._preserved_exc = None
# Functions that should be executed after the request on the response
# object. These will be called before the regular "after_request"
# functions.
self._after_request_functions = []
self.match_request()
# XXX: Support for deprecated functionality. This is going away with
# Flask 1.0
blueprint = self.request.blueprint
if blueprint is not None:
# better safe than sorry, we don't want to break code that
# already worked
bp = app.blueprints.get(blueprint)
if bp is not None and blueprint_is_module(bp):
self.request._is_old_module = True
def _get_g(self):
return _app_ctx_stack.top.g
def _set_g(self, value):
_app_ctx_stack.top.g = value
g = property(_get_g, _set_g)
del _get_g, _set_g
def copy(self):
"""Creates a copy of this request context with the same request object.
This can be used to move a request context to a different greenlet.
Because the actual request object is the same this cannot be used to
move a request context to a different thread unless access to the
request object is locked.
.. versionadded:: 0.10
"""
return self.__class__(self.app,
environ=self.request.environ,
request=self.request
)
def match_request(self):
"""Can be overridden by a subclass to hook into the matching
of the request.
"""
try:
url_rule, self.request.view_args = \
self.url_adapter.match(return_rule=True)
self.request.url_rule = url_rule
except HTTPException as e:
self.request.routing_exception = e
def push(self):
"""Binds the request context to the current context."""
# If an exception occurs in debug mode or if context preservation is
# activated under exception situations exactly one context stays
# on the stack. The rationale is that you want to access that
# information under debug situations. However if someone forgets to
# pop that context again we want to make sure that on the next push
# it's invalidated, otherwise we run at risk that something leaks
# memory. This is usually only a problem in testsuite since this
# functionality is not active in production environments.
top = _request_ctx_stack.top
if top is not None and top.preserved:
top.pop(top._preserved_exc)
# Before we push the request context we have to ensure that there
# is an application context.
app_ctx = _app_ctx_stack.top
if app_ctx is None or app_ctx.app != self.app:
app_ctx = self.app.app_context()
app_ctx.push()
self._implicit_app_ctx_stack.append(app_ctx)
else:
self._implicit_app_ctx_stack.append(None)
_request_ctx_stack.push(self)
# Open the session at the moment that the request context is
# available. This allows a custom open_session method to use the
# request context (e.g. code that access database information
# stored on `g` instead of the appcontext).
self.session = self.app.open_session(self.request)
if self.session is None:
self.session = self.app.make_null_session()
def pop(self, exc=None):
"""Pops the request context and unbinds it by doing that. This will
also trigger the execution of functions registered by the
:meth:`~flask.Flask.teardown_request` decorator.
.. versionchanged:: 0.9
Added the `exc` argument.
"""
app_ctx = self._implicit_app_ctx_stack.pop()
clear_request = False
if not self._implicit_app_ctx_stack:
self.preserved = False
self._preserved_exc = None
if exc is None:
exc = sys.exc_info()[1]
self.app.do_teardown_request(exc)
# If this interpreter supports clearing the exception information
# we do that now. This will only go into effect on Python 2.x,
# on 3.x it disappears automatically at the end of the exception
# stack.
if hasattr(sys, 'exc_clear'):
sys.exc_clear()
request_close = getattr(self.request, 'close', None)
if request_close is not None:
request_close()
clear_request = True
rv = _request_ctx_stack.pop()
assert rv is self, 'Popped wrong request context. (%r instead of %r)' \
% (rv, self)
# get rid of circular dependencies at the end of the request
# so that we don't require the GC to be active.
if clear_request:
rv.request.environ['werkzeug.request'] = None
# Get rid of the app as well if necessary.
if app_ctx is not None:
app_ctx.pop(exc)
def auto_pop(self, exc):
if self.request.environ.get('flask._preserve_context') or \
(exc is not None and self.app.preserve_context_on_exception):
self.preserved = True
self._preserved_exc = exc
else:
self.pop(exc)
def __enter__(self):
self.push()
return self
def __exit__(self, exc_type, exc_value, tb):
# do not pop the request stack if we are in debug mode and an
# exception happened. This will allow the debugger to still
# access the request object in the interactive shell. Furthermore
# the context can be force kept alive for the test client.
# See flask.testing for how this works.
self.auto_pop(exc_value)
def __repr__(self):
return '<%s \'%s\' [%s] of %s>' % (
self.__class__.__name__,
self.request.url,
self.request.method,
self.app.name,
)
| bsd-3-clause |
jaysonkelly/Marlin | buildroot/share/scripts/createTemperatureLookupMarlin.py | 89 | 6252 | #!/usr/bin/python
"""Thermistor Value Lookup Table Generator
Generates lookup to temperature values for use in a microcontroller in C format based on:
http://en.wikipedia.org/wiki/Steinhart-Hart_equation
The main use is for Arduino programs that read data from the circuit board described here:
http://reprap.org/wiki/Temperature_Sensor_v2.0
Usage: python createTemperatureLookup.py [options]
Options:
-h, --help show this help
--rp=... pull-up resistor
--t1=ttt:rrr low temperature temperature:resistance point (around 25 degC)
--t2=ttt:rrr middle temperature temperature:resistance point (around 150 degC)
--t3=ttt:rrr high temperature temperature:resistance point (around 250 degC)
--num-temps=... the number of temperature points to calculate (default: 36)
"""
from math import *
import sys
import getopt
"Constants"
ZERO = 273.15 # zero point of Kelvin scale
VADC = 5 # ADC voltage
VCC = 5 # supply voltage
ARES = pow(2,10) # 10 Bit ADC resolution
VSTEP = VADC / ARES # ADC voltage resolution
TMIN = 0 # lowest temperature in table
TMAX = 350 # highest temperature in table
class Thermistor:
"Class to do the thermistor maths"
def __init__(self, rp, t1, r1, t2, r2, t3, r3):
l1 = log(r1)
l2 = log(r2)
l3 = log(r3)
y1 = 1.0 / (t1 + ZERO) # adjust scale
y2 = 1.0 / (t2 + ZERO)
y3 = 1.0 / (t3 + ZERO)
x = (y2 - y1) / (l2 - l1)
y = (y3 - y1) / (l3 - l1)
c = (y - x) / ((l3 - l2) * (l1 + l2 + l3))
b = x - c * (l1**2 + l2**2 + l1*l2)
a = y1 - (b + l1**2 *c)*l1
if c < 0:
print "//////////////////////////////////////////////////////////////////////////////////////"
print "// WARNING: negative coefficient 'c'! Something may be wrong with the measurements! //"
print "//////////////////////////////////////////////////////////////////////////////////////"
c = -c
self.c1 = a # Steinhart-Hart coefficients
self.c2 = b
self.c3 = c
self.rp = rp # pull-up resistance
def resol(self, adc):
"Convert ADC reading into a resolution"
res = self.temp(adc)-self.temp(adc+1)
return res
def voltage(self, adc):
"Convert ADC reading into a Voltage"
return adc * VSTEP # convert the 10 bit ADC value to a voltage
def resist(self, adc):
"Convert ADC reading into a resistance in Ohms"
r = self.rp * self.voltage(adc) / (VCC - self.voltage(adc)) # resistance of thermistor
return r
def temp(self, adc):
"Convert ADC reading into a temperature in Celcius"
l = log(self.resist(adc))
Tinv = self.c1 + self.c2*l + self.c3* l**3 # inverse temperature
return (1/Tinv) - ZERO # temperature
def adc(self, temp):
"Convert temperature into a ADC reading"
x = (self.c1 - (1.0 / (temp+ZERO))) / (2*self.c3)
y = sqrt((self.c2 / (3*self.c3))**3 + x**2)
r = exp((y-x)**(1.0/3) - (y+x)**(1.0/3))
return (r / (self.rp + r)) * ARES
def main(argv):
"Default values"
t1 = 25 # low temperature in Kelvin (25 degC)
r1 = 100000 # resistance at low temperature (10 kOhm)
t2 = 150 # middle temperature in Kelvin (150 degC)
r2 = 1641.9 # resistance at middle temperature (1.6 KOhm)
t3 = 250 # high temperature in Kelvin (250 degC)
r3 = 226.15 # resistance at high temperature (226.15 Ohm)
rp = 4700; # pull-up resistor (4.7 kOhm)
num_temps = 36; # number of entries for look-up table
try:
opts, args = getopt.getopt(argv, "h", ["help", "rp=", "t1=", "t2=", "t3=", "num-temps="])
except getopt.GetoptError as err:
print str(err)
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ("-h", "--help"):
usage()
sys.exit()
elif opt == "--rp":
rp = int(arg)
elif opt == "--t1":
arg = arg.split(':')
t1 = float(arg[0])
r1 = float(arg[1])
elif opt == "--t2":
arg = arg.split(':')
t2 = float(arg[0])
r2 = float(arg[1])
elif opt == "--t3":
arg = arg.split(':')
t3 = float(arg[0])
r3 = float(arg[1])
elif opt == "--num-temps":
num_temps = int(arg)
t = Thermistor(rp, t1, r1, t2, r2, t3, r3)
increment = int((ARES-1)/(num_temps-1));
step = (TMIN-TMAX) / (num_temps-1)
low_bound = t.temp(ARES-1);
up_bound = t.temp(1);
min_temp = int(TMIN if TMIN > low_bound else low_bound)
max_temp = int(TMAX if TMAX < up_bound else up_bound)
temps = range(max_temp, TMIN+step, step);
print "// Thermistor lookup table for Marlin"
print "// ./createTemperatureLookupMarlin.py --rp=%s --t1=%s:%s --t2=%s:%s --t3=%s:%s --num-temps=%s" % (rp, t1, r1, t2, r2, t3, r3, num_temps)
print "// Steinhart-Hart Coefficients: a=%.15g, b=%.15g, c=%.15g " % (t.c1, t.c2, t.c3)
print "// Theoretical limits of termistor: %.2f to %.2f degC" % (low_bound, up_bound)
print
print "#define NUMTEMPS %s" % (len(temps))
print "const short temptable[NUMTEMPS][2] PROGMEM = {"
for temp in temps:
adc = t.adc(temp)
print " { (short) (%7.2f * OVERSAMPLENR ), %4s }%s // v=%.3f\tr=%.3f\tres=%.3f degC/count" % (adc , temp, \
',' if temp != temps[-1] else ' ', \
t.voltage(adc), \
t.resist( adc), \
t.resol( adc) \
)
print "};"
def usage():
print __doc__
if __name__ == "__main__":
main(sys.argv[1:])
| gpl-3.0 |
tanghaibao/jcvi | jcvi/projects/vanilla.py | 1 | 11915 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Plotting scripts for the vanilla genome paper.
"""
import logging
import sys
from jcvi.apps.base import ActionDispatcher, OptionParser
from jcvi.compara.synteny import AnchorFile, check_beds
from jcvi.formats.base import get_number
from jcvi.formats.bed import Bed
from jcvi.graphics.base import normalize_axes, panel_labels, plt, savefig
from jcvi.graphics.glyph import TextCircle
from jcvi.graphics.synteny import Synteny, draw_gene_legend
def main():
actions = (
# Chromosome painting since WGD
("ancestral", "paint 14 chromosomes following alpha WGD (requires data)"),
# main figures in text
("ploidy", "plot vanilla synteny (requires data)"),
# Composite phylogeny - tree and ks
("phylogeny", "create a composite figure with tree and ks"),
("tree", "create a separate figure with tree"),
("ks", "create a separate figure with ks"),
# Composite synteny - wgd and microsynteny
("synteny", "create a composite figure with wgd and microsynteny"),
("wgd", "create separate figures with wgd"),
("microsynteny", "create separate figures with microsynteny"),
)
p = ActionDispatcher(actions)
p.dispatch(globals())
def phylogeny(args):
"""
%prog phylogeny treefile ks.layout
Create a composite figure with (A) tree and (B) ks.
"""
from jcvi.graphics.tree import parse_tree, LeafInfoFile, WGDInfoFile, draw_tree
p = OptionParser(phylogeny.__doc__)
opts, args, iopts = p.set_image_options(args, figsize="10x12")
(datafile, layoutfile) = args
logging.debug("Load tree file `{0}`".format(datafile))
t, hpd = parse_tree(datafile)
fig = plt.figure(1, (iopts.w, iopts.h))
root = fig.add_axes([0, 0, 1, 1])
ax1 = fig.add_axes([0, 0.4, 1, 0.6])
ax2 = fig.add_axes([0.12, 0.065, 0.8, 0.3])
margin, rmargin = 0.1, 0.2 # Left and right margin
leafinfo = LeafInfoFile("leafinfo.csv").cache
wgdinfo = WGDInfoFile("wgdinfo.csv").cache
outgroup = "ginkgo"
# Panel A
draw_tree(
ax1,
t,
hpd=hpd,
margin=margin,
rmargin=rmargin,
supportcolor=None,
internal=False,
outgroup=outgroup,
reroot=False,
leafinfo=leafinfo,
wgdinfo=wgdinfo,
geoscale=True,
)
from jcvi.apps.ks import Layout, KsPlot, KsFile
# Panel B
ks_min = 0.0
ks_max = 3.0
bins = 60
fill = False
layout = Layout(layoutfile)
print(layout, file=sys.stderr)
kp = KsPlot(ax2, ks_max, bins, legendp="upper right")
for lo in layout:
data = KsFile(lo.ksfile)
data = [x.ng_ks for x in data]
data = [x for x in data if ks_min <= x <= ks_max]
kp.add_data(
data,
lo.components,
label=lo.label,
color=lo.color,
marker=lo.marker,
fill=fill,
fitted=False,
kde=True,
)
kp.draw(filename=None)
normalize_axes([root, ax1])
labels = ((0.05, 0.95, "A"), (0.05, 0.4, "B"))
panel_labels(root, labels)
image_name = "phylogeny.pdf"
savefig(image_name, dpi=iopts.dpi, iopts=iopts)
def tree(args):
"""
%prog tree treefile
Create a tree figure.
"""
from jcvi.graphics.tree import parse_tree, LeafInfoFile, WGDInfoFile, draw_tree
p = OptionParser(tree.__doc__)
opts, args, iopts = p.set_image_options(args, figsize="10x8")
(datafile,) = args
logging.debug("Load tree file `{0}`".format(datafile))
t, hpd = parse_tree(datafile)
fig = plt.figure(1, (iopts.w, iopts.h))
ax1 = fig.add_axes([0, 0, 1, 1])
margin, rmargin = 0.1, 0.2 # Left and right margin
leafinfo = LeafInfoFile("leafinfo.csv").cache
wgdinfo = WGDInfoFile("wgdinfo.csv").cache
outgroup = "ginkgo"
# Panel A
draw_tree(
ax1,
t,
hpd=hpd,
margin=margin,
rmargin=rmargin,
supportcolor=None,
internal=False,
outgroup=outgroup,
reroot=False,
leafinfo=leafinfo,
wgdinfo=wgdinfo,
geoscale=True,
)
normalize_axes([ax1])
image_name = "tree.pdf"
savefig(image_name, dpi=iopts.dpi, iopts=iopts)
def ks(args):
"""
%prog ks ks.layout
Create a ks figure.
"""
p = OptionParser(ks.__doc__)
opts, args, iopts = p.set_image_options(args, figsize="10x4")
(layoutfile,) = args
from jcvi.apps.ks import Layout, KsPlot, KsFile
fig = plt.figure(1, (iopts.w, iopts.h))
ax2 = fig.add_axes([0.12, 0.12, 0.8, 0.8])
# Panel B
ks_min = 0.0
ks_max = 3.0
bins = 60
fill = False
layout = Layout(layoutfile)
print(layout, file=sys.stderr)
kp = KsPlot(ax2, ks_max, bins, legendp="upper right")
for lo in layout:
data = KsFile(lo.ksfile)
data = [x.ng_ks for x in data]
data = [x for x in data if ks_min <= x <= ks_max]
kp.add_data(
data,
lo.components,
label=lo.label,
color=lo.color,
marker=lo.marker,
fill=fill,
fitted=False,
kde=True,
)
kp.draw(filename=None)
image_name = "ks.pdf"
savefig(image_name, dpi=iopts.dpi, iopts=iopts)
def synteny(args):
"""
%prog synteny vplanifoliaA_blocks.bed vplanifoliaA.sizes \
b1.blocks all.bed b1.layout
Create a composite figure with (A) wgd and (B) microsynteny.
"""
from jcvi.graphics.chromosome import draw_chromosomes
p = OptionParser(synteny.__doc__)
opts, args, iopts = p.set_image_options(args, figsize="12x12")
(bedfile, sizesfile, blocksfile, allbedfile, blockslayout) = args
fig = plt.figure(1, (iopts.w, iopts.h))
root = fig.add_axes([0, 0, 1, 1])
ax1 = fig.add_axes([0, 0.5, 1, 0.5])
ax2 = fig.add_axes([0.02, 0, 0.98, 0.5])
# Panel A
title = r"Genome duplication $\alpha^{O}$ event in $\textit{Vanilla}$"
draw_chromosomes(
ax1,
bedfile,
sizes=sizesfile,
iopts=iopts,
mergedist=200000,
winsize=50000,
imagemap=False,
gauge=True,
legend=False,
title=title,
)
# Panel B
draw_ploidy(fig, ax2, blocksfile, allbedfile, blockslayout)
normalize_axes([root, ax1, ax2])
labels = ((0.05, 0.95, "A"), (0.05, 0.5, "B"))
panel_labels(root, labels)
image_name = "synteny.pdf"
savefig(image_name, dpi=iopts.dpi, iopts=iopts)
def wgd(args):
"""
%prog wgd vplanifoliaA_blocks.bed vplanifoliaA.sizes
Create a wgd figure.
"""
from jcvi.graphics.chromosome import draw_chromosomes
p = OptionParser(synteny.__doc__)
opts, args, iopts = p.set_image_options(args, figsize="8x5")
(bedfile, sizesfile) = args
fig = plt.figure(1, (iopts.w, iopts.h))
ax1 = fig.add_axes([0, 0, 1, 1])
title = r"Genome duplication $\alpha^{O}$ event in $\textit{Vanilla}$"
draw_chromosomes(
ax1,
bedfile,
sizes=sizesfile,
iopts=iopts,
mergedist=200000,
winsize=50000,
imagemap=False,
gauge=True,
legend=False,
title=title,
)
normalize_axes([ax1])
image_name = "wgd.pdf"
savefig(image_name, dpi=iopts.dpi, iopts=iopts)
def microsynteny(args):
"""
%prog microsynteny b1.blocks all.bed b1.layout
Create a microsynteny figure.
"""
p = OptionParser(synteny.__doc__)
opts, args, iopts = p.set_image_options(args, figsize="12x6")
(blocksfile, allbedfile, blockslayout) = args
fig = plt.figure(1, (iopts.w, iopts.h))
ax2 = fig.add_axes([0, 0, 1, 1])
draw_ploidy(fig, ax2, blocksfile, allbedfile, blockslayout)
normalize_axes([ax2])
image_name = "microsynteny.pdf"
savefig(image_name, dpi=iopts.dpi, iopts=iopts)
def ancestral(args):
"""
%prog ancestral vplanifoliaA.vplanifoliaA.anchors > vplanifoliaA_blocks.bed
Paint 14 chromosomes following alpha WGD.
"""
p = OptionParser(ancestral.__doc__)
p.set_beds()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
(anchorsfile,) = args
qbed, sbed, qorder, sorder, is_self = check_beds(anchorsfile, p, opts)
# We focus on the following chromosome pairs
target_pairs = {
(1, 1),
(1, 6),
(1, 8),
(1, 13),
(2, 4),
(3, 12),
(3, 14),
(5, 6),
(5, 8),
(7, 9),
(7, 11),
(9, 10),
(10, 11),
}
def get_target(achr, bchr):
if "chr" not in achr and "chr" not in bchr:
return None
achr, bchr = get_number(achr), get_number(bchr)
if achr > bchr:
achr, bchr = bchr, achr
if (achr, bchr) in target_pairs:
return achr, bchr
return None
def build_bedline(astart, aend, target_pair):
# target_name = "{:02d}-{:02d}".format(*target_pair)
target_name = [str(x) for x in target_pair if x in (1, 2, 3, 5, 7, 10)][0]
return "\t".join(
str(x) for x in (astart.seqid, astart.start, aend.end, target_name)
)
# Iterate through the blocks, store any regions that has hits to one of the
# target_pairs
ac = AnchorFile(anchorsfile)
blocks = ac.blocks
outbed = Bed()
for i, block in enumerate(blocks):
a, b, scores = zip(*block)
a = [qorder[x] for x in a]
b = [sorder[x] for x in b]
astart, aend = min(a)[1], max(a)[1]
bstart, bend = min(b)[1], max(b)[1]
# Now convert to BED lines with new accn
achr, bchr = astart.seqid, bstart.seqid
target = get_target(achr, bchr)
if target is None:
continue
outbed.add(build_bedline(astart, aend, target))
outbed.add(build_bedline(bstart, bend, target))
outbed.print_to_file(sorted=True)
def ploidy(args):
"""
%prog ploidy b1.blocks all.bed b1.layout
Build a figure that illustrates the WGD history of the vanilla genome.
"""
p = OptionParser(ploidy.__doc__)
opts, args, iopts = p.set_image_options(args, figsize="12x6")
if len(args) != 3:
sys.exit(not p.print_help())
blocksfile, bedfile, blockslayout = args
fig = plt.figure(1, (iopts.w, iopts.h))
root = fig.add_axes([0, 0, 1, 1])
draw_ploidy(fig, root, blocksfile, bedfile, blockslayout)
root.set_xlim(0, 1)
root.set_ylim(0, 1)
root.set_axis_off()
pf = "vanilla-karyotype"
image_name = pf + "." + iopts.format
savefig(image_name, dpi=iopts.dpi, iopts=iopts)
def draw_ploidy(fig, root, blocksfile, bedfile, blockslayout):
switchidsfile = "switch.ids"
Synteny(
fig,
root,
blocksfile,
bedfile,
blockslayout,
scalebar=True,
switch=switchidsfile,
)
# Legend showing the orientation of the genes
draw_gene_legend(root, 0.2, 0.3, 0.53)
# WGD labels
radius = 0.025
tau_color = "#bebada"
alpha_color = "#bc80bd"
label_color = "k"
pad = 0.05
for y in (0.74 + 1.5 * pad, 0.26 - 1.5 * pad):
TextCircle(
root,
0.25,
y,
r"$\alpha^{O}$",
radius=radius,
fc=alpha_color,
color=label_color,
fontweight="bold",
)
TextCircle(
root,
0.75,
y,
r"$\alpha^{O}$",
radius=radius,
fc=alpha_color,
color=label_color,
fontweight="bold",
)
for y in (0.74 + 3 * pad, 0.26 - 3 * pad):
TextCircle(
root, 0.5, y, r"$\tau$", radius=radius, fc=tau_color, color=label_color
)
if __name__ == "__main__":
main()
| bsd-2-clause |
TNosredna/CouchPotatoServer | libs/requests/packages/charade/euckrprober.py | 2931 | 1675 | ######################## BEGIN LICENSE BLOCK ########################
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Mark Pilgrim - port to Python
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
from .mbcharsetprober import MultiByteCharSetProber
from .codingstatemachine import CodingStateMachine
from .chardistribution import EUCKRDistributionAnalysis
from .mbcssm import EUCKRSMModel
class EUCKRProber(MultiByteCharSetProber):
def __init__(self):
MultiByteCharSetProber.__init__(self)
self._mCodingSM = CodingStateMachine(EUCKRSMModel)
self._mDistributionAnalyzer = EUCKRDistributionAnalysis()
self.reset()
def get_charset_name(self):
return "EUC-KR"
| gpl-3.0 |
xuegang/gpdb | src/test/tinc/tincrepo/mpp/gpdb/tests/storage/walrepl/gpstart/test_gpstart.py | 9 | 8432 | """
Copyright (C) 2004-2015 Pivotal Software, Inc. All rights reserved.
This program and the accompanying materials are made available under
the terms of the 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 socket
from time import sleep
import unittest2 as unittest
import tinctest
from gppylib.commands.base import Command
from mpp.models import MPPTestCase
from mpp.lib.PSQL import PSQL
from mpp.gpdb.tests.storage.walrepl.lib.verify import StandbyVerify
from mpp.gpdb.tests.storage.walrepl.gpinitstandby import GpinitStandby
from mpp.gpdb.tests.storage.walrepl.lib.pg_util import GpUtility
from mpp.gpdb.tests.storage.walrepl.gpactivatestandby import GpactivateStandby
class GpstartTestCase(MPPTestCase):
'''
testcase for gpstart
gpstart may return status code 1 as well as 0 in the success case. The
difference is whether it produces WARNING or not, but here we don't care.
'''
origin_mdd = os.environ.get('MASTER_DATA_DIRECTORY')
def __init__(self,methodName):
self.gputil = GpUtility()
self.stdby = StandbyVerify()
super(GpstartTestCase,self).__init__(methodName)
def setUp(self):
self.gputil.check_and_start_gpdb()
stdby_presence = self.gputil.check_standby_presence()
# We should forcibly recreate standby, as it might has been promoted.
if stdby_presence:
self.gputil.remove_standby()
self.gputil.install_standby()
def tearDown(self):
self.gputil.remove_standby()
"""
Gpstart test cases in recovery mode
"""
def test_gpstart_from_master(self):
"""
tag
"""
self.gputil.check_and_stop_gpdb()
(rc, stdout) = self.gputil.run('gpstart -a ')
self.assertIn(rc, (0, 1))
self.assertTrue(self.gputil.gpstart_and_verify())
sleep(2)
self.assertTrue(self.stdby.check_gp_segment_config(),'standby master not cofigured')
self.assertTrue(self.stdby.check_pg_stat_replication(),'standby not in replication status')
self.assertTrue(self.stdby.check_standby_processes(), 'standby processes not running')
(rc, output) = self.gputil.run(command = 'ps -ef|grep "wal sender "|grep -v grep')
self.assertIsNotNone(output)
def test_gpstart_master_only(self):
"""
tag
"""
self.gputil.check_and_stop_gpdb()
(rc, stdout) = self.gputil.run('export GPSTART_INTERNAL_MASTER_ONLY=1; '
'gpstart -a -m ')
self.assertIn(rc, (0, 1))
self.assertTrue(self.gputil.gpstart_and_verify())
(rc,output) = self.gputil.run('PGDATABASE=template1 '
"PGOPTIONS='-c gp_session_role=utility' "
'psql')
self.assertEqual(rc, 0)
(rc, output) = self.gputil.run('psql template1')
# should fail due to master only mode
self.assertEqual(rc, 2)
self.gputil.run('gpstop -a -m')
self.gputil.run('gpstart -a')
def test_gpstart_restricted_mode_master(self):
"""Test -R option with standby."""
self.gputil.check_and_stop_gpdb()
(rc, stdout) = self.gputil.run('gpstart -a -R')
self.assertIn(rc, (0, 1))
self.assertTrue(self.gputil.gpstart_and_verify())
(rc,output) = self.gputil.run(command = 'psql template1')
self.assertIn(rc, (0, 1))
self.gputil.run('gpstop -ar')
def test_gpstart_master_w_timeout(self):
"""Test -t option with standby."""
self.gputil.check_and_stop_gpdb()
(rc, output) = self.gputil.run('gpstart -a -t 30')
self.assertIn(rc, (0, 1))
self.assertTrue(self.gputil.gpstart_and_verify())
self.gputil.run('gpstop -ar')
def test_gpstart_no_standby(self):
"""Test -y with standby configured."""
self.gputil.check_and_stop_gpdb()
(rc, stdout) = self.gputil.run('gpstart -a -y')
self.assertIn(rc, (0, 1))
self.assertTrue(self.gputil.gpstart_and_verify())
self.assertFalse(self.stdby.check_standby_processes(),
'gpstart without standby failed, standby was running')
self.gputil.run('gpstop -ar')
def test_gpstart_wo_standby(self):
"""Test -y without standby configured."""
self.gputil.remove_standby()
self.gputil.check_and_stop_gpdb()
(rc, stdout) = self.gputil.run('gpstart -a -y')
self.assertIn(rc, (0, 1))
self.assertTrue(self.gputil.gpstart_and_verify())
self.assertFalse(self.stdby.check_standby_processes(), 'standby processes presented')
self.gputil.run('gpstop -ar')
"""
Gpstart, test case in failover mode
"""
def test_gpstart_master_only_after_failover(self):
"""
for test purpose, failing back to old master should
remove standby from primary after activate standby
"""
tinctest.logger.info("start master only with -m option after failover")
activatestdby = GpactivateStandby()
standby_host = activatestdby.get_current_standby()
standby_mdd = activatestdby.get_standby_dd()
standby_port = activatestdby.get_standby_port()
activatestdby.activate()
self.stdby._run_remote_command(standby_host,command = 'gpstop -a')
stdout = self.stdby._run_remote_command(standby_host,command = 'export GPSTART_INTERNAL_MASTER_ONLY=1; gpstart -a -m')
self.assertNotRegexpMatches(stdout,"ERROR","Start master only after failover failed")
self.assertTrue(self.gputil.gpstart_and_verify(master_dd = standby_mdd, host = standby_host))
self.stdby._run_remote_command(standby_host,command = 'gpstop -a -m')
self.gputil.run(command = 'gpstop -ar')
self.gputil.failback_to_original_master(self.origin_mdd, standby_host, standby_mdd, standby_port)
def test_gpstart_master_after_failover(self):
"""
failover, start from new master, then recover the cluster back to
have the old master active.
"""
tinctest.logger.info("failover, and run gpstart master test")
self.gputil.check_and_start_gpdb()
activatestdby = GpactivateStandby()
standby_host = activatestdby.get_current_standby()
standby_mdd = activatestdby.get_standby_dd()
standby_port = activatestdby.get_standby_port()
activatestdby.activate()
self.stdby._run_remote_command(standby_host, command = 'gpstop -a')
stdout = self.stdby._run_remote_command(standby_host,command = 'gpstart -a')
self.assertNotRegexpMatches(stdout,"FATAL","ERROR")
self.assertTrue(self.gputil.gpstart_and_verify(master_dd = standby_mdd, host = standby_host))
self.gputil.failback_to_original_master(self.origin_mdd, standby_host, standby_mdd, standby_port)
def test_gpstart_original_master_after_promote(self):
"""
failover, start from new master, then recover the cluster back to
have the old master active.
"""
tinctest.logger.info("activate and run gpstart for original master")
activatestdby = GpactivateStandby()
standby_host = activatestdby.get_current_standby()
standby_mdd = activatestdby.get_standby_dd()
standby_port = activatestdby.get_standby_port()
activatestdby.activate()
(rc, stdout) = self.gputil.run('gpstart -a -v')
self.gputil.run('pg_controldata %s' % self.origin_mdd)
self.stdby._run_remote_command(standby_host, command = 'pg_controldata %s' % standby_mdd)
self.assertNotEqual(rc, 0)
# This below error message comes from gpstart product code (if its modified change it here as well.)
self.assertRegexpMatches(stdout,"Standby activated, this node no more can act as master.")
self.gputil.failback_to_original_master(self.origin_mdd, standby_host, standby_mdd, standby_port)
| apache-2.0 |
floraXiao/gooderp_addons | buy/wizard/buy_order_track_wizard.py | 6 | 4873 | # -*- coding: utf-8 -*-
from datetime import date
from odoo import models, fields, api
from odoo.exceptions import UserError
class BuyOrderTrackWizard(models.TransientModel):
_name = 'buy.order.track.wizard'
_description = u'采购订单跟踪表向导'
@api.model
def _default_date_start(self):
return self.env.user.company_id.start_date
@api.model
def _default_date_end(self):
return date.today()
date_start = fields.Date(u'开始日期', default=_default_date_start,
help=u'报表汇总的开始日期,默认为公司启用日期')
date_end = fields.Date(u'结束日期', default=_default_date_end,
help=u'报表汇总的结束日期,默认为当前日期')
partner_id = fields.Many2one('partner', u'供应商',
help=u'只统计选定的供应商')
goods_id = fields.Many2one('goods', u'商品',
help=u'只统计选定的商品')
order_id = fields.Many2one('buy.order', u'订单号',
help=u'只统计选定的订单号')
warehouse_dest_id = fields.Many2one('warehouse', u'仓库',
help=u'只统计选定的仓库')
company_id = fields.Many2one(
'res.company',
string=u'公司',
change_default=True,
default=lambda self: self.env['res.company']._company_default_get())
def _get_domain(self):
'''返回wizard界面上条件'''
domain = [
('order_id.date', '>=', self.date_start),
('order_id.date', '<=', self.date_end)
]
if self.goods_id:
domain.append(('goods_id', '=', self.goods_id.id))
if self.partner_id:
domain.append(('order_id.partner_id', '=', self.partner_id.id))
if self.order_id:
domain.append(('order_id.id', '=', self.order_id.id))
if self.warehouse_dest_id:
domain.append(('order_id.warehouse_dest_id',
'=', self.warehouse_dest_id.id))
return domain
def _get_wh_in_date(self, line):
'''对于一个buy order line,返回一个入库日期'''
wh_in_date = None
move_line = self.env['wh.move.line']
wh_move_line = move_line.search([
('buy_line_id', '=', line.id),
('state', '=', 'done')
])
if len(wh_move_line) > 1: # 如果是分批入库,则入库单明细行上的buy_line_id相同
wh_in_date = wh_move_line[0].date
else:
wh_in_date = wh_move_line.date
return wh_in_date
def _prepare_track_line(self, line, qty, amount, qty_not_in):
'''返回跟踪表明细行(非小计行)'''
return {
'goods_code': line.goods_id.code,
'goods_id': line.goods_id.id,
'attribute': line.attribute_id.name,
'uom': line.uom_id.name,
'date': line.order_id.date,
'order_name': line.order_id.name,
'partner_id': line.order_id.partner_id.id,
'warehouse_dest_id': line.order_id.warehouse_dest_id.id,
'goods_state': line.order_id.goods_state,
'qty': qty,
'amount': amount,
'qty_not_in': qty_not_in,
'planned_date': line.order_id.planned_date,
'wh_in_date': self._get_wh_in_date(line), # 入库日期
'note': line.note,
'type': line.order_id.type,
}
@api.multi
def button_ok(self):
self.ensure_one()
res = []
if self.date_end < self.date_start:
raise UserError(u'开始日期不能大于结束日期!')
buy_order_line = self.env['buy.order.line']
for line in buy_order_line.search(self._get_domain(), order='goods_id'):
is_buy = line.order_id.type == 'buy' and 1 or -1 # 是否购货订单
# 以下分别为明细行上数量、采购额、未入库数量,退货时均取反
qty = is_buy * line.quantity
amount = is_buy * line.subtotal
qty_not_in = is_buy * (line.quantity - line.quantity_in)
# 创建跟踪表明细行(非小计行)
track = self.env['buy.order.track'].create(
self._prepare_track_line(line, qty, amount, qty_not_in))
res.append(track.id)
view = self.env.ref('buy.buy_order_track_tree')
return {
'name': u'采购订单跟踪表',
'view_type': 'form',
'view_mode': 'tree',
'view_id': False,
'views': [(view.id, 'tree')],
'res_model': 'buy.order.track',
'type': 'ir.actions.act_window',
'domain': [('id', 'in', res)],
'limit': 65535,
}
| agpl-3.0 |
octavioturra/aritial | google_appengine/google/appengine/tools/dev_appserver_upload.py | 5 | 10654 | #!/usr/bin/env python
#
# Copyright 2007 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.
#
"""Helper CGI for POST uploads.
Utility library contains the main logic behind simulating the blobstore
uploading mechanism.
Contents:
GenerateBlobKey: Function for generation unique blob-keys.
UploadCGIHandler: Main CGI handler class for post uploads.
"""
import base64
import cStringIO
import datetime
import md5
import random
import time
from google.appengine.api import datastore
from google.appengine.api import datastore_errors
from google.appengine.api.blobstore import blobstore
try:
from email.mime import base
from email.mime import multipart
from email import generator
except ImportError:
from email import Generator as generator
from email import MIMEBase as base
from email import MIMEMultipart as multipart
STRIPPED_HEADERS = frozenset(('content-length',
'content-md5',
'content-type',
))
class Error(Exception):
"""Base class for upload processing errors."""
class InvalidMIMETypeFormatError(Error):
"""MIME type was formatted incorrectly."""
def GenerateBlobKey(time_func=time.time, random_func=random.random):
"""Generate a unique BlobKey.
BlobKey is generated using the current time stamp combined with a random
number. The two values are subject to an md5 digest and base64 url-safe
encoded. The new key is checked against the possibility of existence within
the datastore and the random number is regenerated until there is no match.
Args:
time_func: Function used for generating the timestamp. Used for
dependency injection. Allows for predictable results during tests.
Must return a floating point UTC timestamp.
random_func: Function used for generating the random number. Used for
dependency injection. Allows for predictable results during tests.
Returns:
String version of BlobKey that is unique within the BlobInfo datastore.
None if there are too many name conflicts.
"""
timestamp = str(time_func())
tries = 0
while tries < 10:
number = str(random_func())
digester = md5.md5()
digester.update(timestamp)
digester.update(number)
blob_key = base64.urlsafe_b64encode(digester.digest())
datastore_key = datastore.Key.from_path(blobstore.BLOB_INFO_KIND,
blob_key,
namespace='')
try:
datastore.Get(datastore_key)
tries += 1
except datastore_errors.EntityNotFoundError:
return blob_key
return None
def _SplitMIMEType(mime_type):
"""Split MIME-type in to main and sub type.
Args:
mime_type: full MIME type string.
Returns:
(main, sub):
main: Main part of mime type (application, image, text, etc).
sub: Subtype part of mime type (pdf, png, html, etc).
Raises:
InvalidMIMETypeFormatError: If form item has incorrectly formatted MIME
type.
"""
if mime_type:
mime_type_array = mime_type.split('/')
if len(mime_type_array) == 1:
raise InvalidMIMETypeFormatError('Missing MIME sub-type.')
elif len(mime_type_array) == 2:
main_type, sub_type = mime_type_array
if not(main_type and sub_type):
raise InvalidMIMETypeFormatError(
'Incorrectly formatted MIME type: %s' % mime_type)
return main_type, sub_type
else:
raise InvalidMIMETypeFormatError(
'Incorrectly formatted MIME type: %s' % mime_type)
else:
return 'application', 'octet-stream'
class UploadCGIHandler(object):
"""Class used for handling an upload post.
The main interface to this class is the UploadCGI method. This will recieve
the upload form, store the blobs contained in the post and rewrite the blobs
to contain BlobKeys instead of blobs.
"""
def __init__(self,
blob_storage,
generate_blob_key=GenerateBlobKey,
now_func=datetime.datetime.now):
"""Constructor.
Args:
blob_storage: BlobStorage instance where actual blobs are stored.
generate_blob_key: Function used for generating unique blob keys.
now_func: Function that returns the current timestamp.
"""
self.__blob_storage = blob_storage
self.__generate_blob_key = generate_blob_key
self.__now_func = now_func
def StoreBlob(self, form_item, creation):
"""Store form-item to blob storage.
Args:
form_item: FieldStorage instance that represents a specific form field.
This instance should have a non-empty filename attribute, meaning that
it is an uploaded blob rather than a normal form field.
creation: Timestamp to associate with new blobs creation time. This
parameter is provided so that all blobs in the same upload form can have
the same creation date.
Returns:
datastore.Entity('__BlobInfo__') associated with the upload.
"""
main_type, sub_type = _SplitMIMEType(form_item.type)
blob_key = self.__generate_blob_key()
self.__blob_storage.StoreBlob(blob_key, form_item.file)
content_type_formatter = base.MIMEBase(main_type, sub_type,
**form_item.type_options)
blob_entity = datastore.Entity('__BlobInfo__',
name=str(blob_key),
namespace='')
blob_entity['content_type'] = (
content_type_formatter['content-type'].decode('utf-8'))
blob_entity['creation'] = creation
blob_entity['filename'] = form_item.filename.decode('utf-8')
form_item.file.seek(0, 2)
size = form_item.file.tell()
form_item.file.seek(0)
blob_entity['size'] = size
datastore.Put(blob_entity)
return blob_entity
def _GenerateMIMEMessage(self, form, boundary=None):
"""Generate a new post from original form.
Also responsible for storing blobs in the datastore.
Args:
form: Instance of cgi.FieldStorage representing the whole form
derived from original post data.
boundary: Boundary to use for resulting form. Used only in tests so
that the boundary is always consistent.
Returns:
A MIMEMultipart instance representing the new HTTP post which should be
forwarded to the developers actual CGI handler. DO NOT use the return
value of this method to generate a string unless you know what you're
doing and properly handle folding whitespace (from rfc822) properly.
"""
message = multipart.MIMEMultipart('form-data', boundary)
for name, value in form.headers.items():
if name.lower() not in STRIPPED_HEADERS:
message.add_header(name, value)
def IterateForm():
"""Flattens form in to single sequence of cgi.FieldStorage instances.
The resulting cgi.FieldStorage objects are a little bit irregular in
their structure. A single name can have mulitple sub-items. In this
case, the root FieldStorage object has a list associated with that field
name. Otherwise, the root FieldStorage object just refers to a single
nested instance.
Lists of FieldStorage instances occur when a form has multiple values
for the same name.
Yields:
cgi.FieldStorage irrespective of their nesting level.
"""
for key in sorted(form):
form_item = form[key]
if isinstance(form_item, list):
for list_item in form_item:
yield list_item
else:
yield form_item
creation = self.__now_func()
for form_item in IterateForm():
disposition_parameters = {'name': form_item.name}
if form_item.filename is None:
variable = base.MIMEBase('text', 'plain')
variable.set_payload(form_item.value)
else:
if not form_item.filename:
continue
disposition_parameters['filename'] = form_item.filename
main_type, sub_type = _SplitMIMEType(form_item.type)
blob_entity = self.StoreBlob(form_item, creation)
variable = base.MIMEBase('message',
'external-body',
access_type=blobstore.BLOB_KEY_HEADER,
blob_key=blob_entity.key().name())
form_item.file.seek(0, 2)
content_length = form_item.file.tell()
form_item.file.seek(0)
external = base.MIMEBase(main_type,
sub_type,
**form_item.type_options)
headers = dict(form_item.headers)
headers['Content-Length'] = str(content_length)
headers[blobstore.UPLOAD_INFO_CREATION_HEADER] = (
blobstore._format_creation(creation))
for key, value in headers.iteritems():
external.add_header(key, value)
external_disposition_parameters = dict(disposition_parameters)
external_disposition_parameters['filename'] = form_item.filename
if not external.get('Content-Disposition'):
external.add_header('Content-Disposition',
'form-data',
**external_disposition_parameters)
variable.set_payload([external])
variable.add_header('Content-Disposition',
'form-data',
**disposition_parameters)
message.attach(variable)
return message
def GenerateMIMEMessageString(self, form, boundary=None):
"""Generate a new post string from original form.
Args:
form: Instance of cgi.FieldStorage representing the whole form
derived from original post data.
boundary: Boundary to use for resulting form. Used only in tests so
that the boundary is always consistent.
Returns:
A string rendering of a MIMEMultipart instance.
"""
message = self._GenerateMIMEMessage(form, boundary=boundary)
message_out = cStringIO.StringIO()
gen = generator.Generator(message_out, maxheaderlen=0)
gen.flatten(message, unixfrom=False)
return message_out.getvalue()
| apache-2.0 |
ovidiu-beldie/closure-linter-tweaked | closure_linter/scopeutil.py | 84 | 5414 | #!/usr/bin/env python
#
# Copyright 2012 The Closure Linter 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.
"""Tools to match goog.scope alias statements."""
# Allow non-Google copyright
# pylint: disable=g-bad-file-header
__author__ = ('[email protected] (Nathan Naze)')
import itertools
from closure_linter import ecmametadatapass
from closure_linter import tokenutil
from closure_linter.javascripttokens import JavaScriptTokenType
def IsGoogScopeBlock(context):
"""Whether the given context is a goog.scope block.
This function only checks that the block is a function block inside
a goog.scope() call.
TODO(nnaze): Implement goog.scope checks that verify the call is
in the root context and contains only a single function literal.
Args:
context: An EcmaContext of type block.
Returns:
Whether the context is a goog.scope block.
"""
if context.type != ecmametadatapass.EcmaContext.BLOCK:
return False
if not _IsFunctionLiteralBlock(context):
return False
# Check that this function is contained by a group
# of form "goog.scope(...)".
parent = context.parent
if parent and parent.type is ecmametadatapass.EcmaContext.GROUP:
last_code_token = parent.start_token.metadata.last_code
if (last_code_token and
last_code_token.type is JavaScriptTokenType.IDENTIFIER and
last_code_token.string == 'goog.scope'):
return True
return False
def _IsFunctionLiteralBlock(block_context):
"""Check if a context is a function literal block (without parameters).
Example function literal block: 'function() {}'
Args:
block_context: An EcmaContext of type block.
Returns:
Whether this context is a function literal block.
"""
previous_code_tokens_iter = itertools.ifilter(
lambda token: token not in JavaScriptTokenType.NON_CODE_TYPES,
reversed(block_context.start_token))
# Ignore the current token
next(previous_code_tokens_iter, None)
# Grab the previous three tokens and put them in correct order.
previous_code_tokens = list(itertools.islice(previous_code_tokens_iter, 3))
previous_code_tokens.reverse()
# There aren't three previous tokens.
if len(previous_code_tokens) is not 3:
return False
# Check that the previous three code tokens are "function ()"
previous_code_token_types = [token.type for token in previous_code_tokens]
if (previous_code_token_types == [
JavaScriptTokenType.FUNCTION_DECLARATION,
JavaScriptTokenType.START_PARAMETERS,
JavaScriptTokenType.END_PARAMETERS]):
return True
return False
def IsInClosurizedNamespace(symbol, closurized_namespaces):
"""Match a goog.scope alias.
Args:
symbol: An identifier like 'goog.events.Event'.
closurized_namespaces: Iterable of valid Closurized namespaces (strings).
Returns:
True if symbol is an identifier in a Closurized namespace, otherwise False.
"""
for ns in closurized_namespaces:
if symbol.startswith(ns + '.'):
return True
return False
def MatchAlias(context):
"""Match an alias statement (some identifier assigned to a variable).
Example alias: var MyClass = proj.longNamespace.MyClass.
Args:
context: An EcmaContext of type EcmaContext.VAR.
Returns:
If a valid alias, returns a tuple of alias and symbol, otherwise None.
"""
if context.type != ecmametadatapass.EcmaContext.VAR:
return
# The var's parent is a STATEMENT, which should be directly below goog.scope.
if not IsGoogScopeBlock(context.parent.parent):
return
# Get the tokens in this statement.
if context.start_token and context.end_token:
statement_tokens = tokenutil.GetTokenRange(context.start_token,
context.end_token)
else:
return
# And now just those tokens that are actually code.
is_non_code_type = lambda t: t.type not in JavaScriptTokenType.NON_CODE_TYPES
code_tokens = filter(is_non_code_type, statement_tokens)
# This section identifies statements of the alias form "var alias = symbol".
# Pop off the semicolon if present.
if code_tokens and code_tokens[-1].IsType(JavaScriptTokenType.SEMICOLON):
code_tokens.pop()
if len(code_tokens) < 4:
return
# Verify that this is of the form "var lvalue = identifier;".
# The identifier may span multiple lines and could be multiple tokens.
if (code_tokens[0].IsKeyword('var') and
code_tokens[1].IsType(JavaScriptTokenType.SIMPLE_LVALUE) and
code_tokens[2].IsOperator('=') and
all(t.IsType(JavaScriptTokenType.IDENTIFIER) for t in code_tokens[3:])):
alias, symbol = code_tokens[1], code_tokens[3]
# Mark both tokens as an alias definition to avoid counting them as usages.
alias.metadata.is_alias_definition = True
symbol.metadata.is_alias_definition = True
return alias.string, tokenutil.GetIdentifierForToken(symbol)
| apache-2.0 |
VasuAgrawal/tartanHacks2015 | site/flask/lib/python2.7/site-packages/pbr/tests/test_version.py | 41 | 1137 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Red Hat, Inc.
# Copyright 2012-2013 Hewlett-Packard Development Company, L.P.
#
# 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.
from pbr.tests import base
from pbr import version
class DeferredVersionTestCase(base.BaseTestCase):
def test_cached_version(self):
class MyVersionInfo(version.VersionInfo):
def _get_version_from_pkg_resources(self):
return "5.5.5.5"
deferred_string = MyVersionInfo("openstack").\
cached_version_string()
self.assertEqual("5.5.5.5", deferred_string)
| mit |
dataxu/ansible | lib/ansible/modules/network/f5/bigip_virtual_server.py | 25 | 53942 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017 F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: bigip_virtual_server
short_description: Manage LTM virtual servers on a BIG-IP
description:
- Manage LTM virtual servers on a BIG-IP.
version_added: "2.1"
options:
state:
description:
- The virtual server state. If C(absent), delete the virtual server
if it exists. C(present) creates the virtual server and enable it.
If C(enabled), enable the virtual server if it exists. If C(disabled),
create the virtual server if needed, and set state to C(disabled).
default: present
choices:
- present
- absent
- enabled
- disabled
name:
description:
- Virtual server name.
required: True
aliases:
- vs
destination:
description:
- Destination IP of the virtual server.
- Required when C(state) is C(present) and virtual server does not exist.
required: True
aliases:
- address
- ip
source:
description:
- Specifies an IP address or network from which the virtual server accepts traffic.
- The virtual server accepts clients only from one of these IP addresses.
- For this setting to function effectively, specify a value other than 0.0.0.0/0 or ::/0
(that is, any/0, any6/0).
- In order to maximize utility of this setting, specify the most specific address
prefixes covering all customer addresses and no others.
- Specify the IP address in Classless Inter-Domain Routing (CIDR) format; address/prefix,
where the prefix length is in bits. For example, for IPv4, 10.0.0.1/32 or 10.0.0.0/24,
and for IPv6, ffe1::0020/64 or 2001:ed8:77b5:2:10:10:100:42/64.
version_added: 2.5
port:
description:
- Port of the virtual server. Required when C(state) is C(present)
and virtual server does not exist.
- If you do not want to specify a particular port, use the value C(0).
The result is that the virtual server will listen on any port.
profiles:
description:
- List of profiles (HTTP, ClientSSL, ServerSSL, etc) to apply to both sides
of the connection (client-side and server-side).
- If you only want to apply a particular profile to the client-side of
the connection, specify C(client-side) for the profile's C(context).
- If you only want to apply a particular profile to the server-side of
the connection, specify C(server-side) for the profile's C(context).
- If C(context) is not provided, it will default to C(all).
suboptions:
name:
description:
- Name of the profile.
- If this is not specified, then it is assumed that the profile item is
only a name of a profile.
- This must be specified if a context is specified.
required: false
context:
description:
- The side of the connection on which the profile should be applied.
choices:
- all
- server-side
- client-side
default: all
aliases:
- all_profiles
irules:
version_added: "2.2"
description:
- List of rules to be applied in priority order.
- If you want to remove existing iRules, specify a single empty value; C("").
See the documentation for an example.
aliases:
- all_rules
enabled_vlans:
version_added: "2.2"
description:
- List of VLANs to be enabled. When a VLAN named C(all) is used, all
VLANs will be allowed. VLANs can be specified with or without the
leading partition. If the partition is not specified in the VLAN,
then the C(partition) option of this module will be used.
- This parameter is mutually exclusive with the C(disabled_vlans) parameter.
disabled_vlans:
version_added: 2.5
description:
- List of VLANs to be disabled. If the partition is not specified in the VLAN,
then the C(partition) option of this module will be used.
- This parameter is mutually exclusive with the C(enabled_vlans) parameters.
pool:
description:
- Default pool for the virtual server.
- If you want to remove the existing pool, specify an empty value; C("").
See the documentation for an example.
policies:
description:
- Specifies the policies for the virtual server
aliases:
- all_policies
snat:
description:
- Source network address policy.
required: false
choices:
- None
- Automap
- Name of a SNAT pool (eg "/Common/snat_pool_name") to enable SNAT
with the specific pool
default_persistence_profile:
description:
- Default Profile which manages the session persistence.
- If you want to remove the existing default persistence profile, specify an
empty value; C(""). See the documentation for an example.
description:
description:
- Virtual server description.
fallback_persistence_profile:
description:
- Specifies the persistence profile you want the system to use if it
cannot use the specified default persistence profile.
- If you want to remove the existing fallback persistence profile, specify an
empty value; C(""). See the documentation for an example.
version_added: 2.3
partition:
description:
- Device partition to manage resources on.
default: Common
version_added: 2.5
metadata:
description:
- Arbitrary key/value pairs that you can attach to a pool. This is useful in
situations where you might want to annotate a virtual to me managed by Ansible.
- Key names will be stored as strings; this includes names that are numbers.
- Values for all of the keys will be stored as strings; this includes values
that are numbers.
- Data will be persisted, not ephemeral.
version_added: 2.5
notes:
- Requires BIG-IP software version >= 11
- Requires the netaddr Python package on the host. This is as easy as pip
install netaddr.
requirements:
- netaddr
extends_documentation_fragment: f5
author:
- Tim Rupp (@caphrim007)
'''
EXAMPLES = r'''
- name: Modify Port of the Virtual Server
bigip_virtual_server:
server: lb.mydomain.net
user: admin
password: secret
state: present
partition: Common
name: my-virtual-server
port: 8080
delegate_to: localhost
- name: Delete virtual server
bigip_virtual_server:
server: lb.mydomain.net
user: admin
password: secret
state: absent
partition: Common
name: my-virtual-server
delegate_to: localhost
- name: Add virtual server
bigip_virtual_server:
server: lb.mydomain.net
user: admin
password: secret
state: present
partition: Common
name: my-virtual-server
destination: 10.10.10.10
port: 443
pool: my-pool
snat: Automap
description: Test Virtual Server
profiles:
- http
- fix
- name: clientssl
context: server-side
- name: ilx
context: client-side
policies:
- my-ltm-policy-for-asm
- ltm-uri-policy
- ltm-policy-2
- ltm-policy-3
enabled_vlans:
- /Common/vlan2
delegate_to: localhost
- name: Add FastL4 virtual server
bigip_virtual_server:
destination: 1.1.1.1
name: fastl4_vs
port: 80
profiles:
- fastL4
state: present
- name: Add iRules to the Virtual Server
bigip_virtual_server:
server: lb.mydomain.net
user: admin
password: secret
name: my-virtual-server
irules:
- irule1
- irule2
delegate_to: localhost
- name: Remove one iRule from the Virtual Server
bigip_virtual_server:
server: lb.mydomain.net
user: admin
password: secret
name: my-virtual-server
irules:
- irule2
delegate_to: localhost
- name: Remove all iRules from the Virtual Server
bigip_virtual_server:
server: lb.mydomain.net
user: admin
password: secret
name: my-virtual-server
irules: ""
delegate_to: localhost
- name: Remove pool from the Virtual Server
bigip_virtual_server:
server: lb.mydomain.net
user: admin
password: secret
name: my-virtual-server
pool: ""
delegate_to: localhost
- name: Add metadata to virtual
bigip_pool:
server: lb.mydomain.com
user: admin
password: secret
state: absent
name: my-pool
partition: Common
metadata:
ansible: 2.4
updated_at: 2017-12-20T17:50:46Z
delegate_to: localhost
'''
RETURN = r'''
description:
description: New description of the virtual server.
returned: changed
type: string
sample: This is my description
default_persistence_profile:
description: Default persistence profile set on the virtual server.
returned: changed
type: string
sample: /Common/dest_addr
destination:
description: Destination of the virtual server.
returned: changed
type: string
sample: 1.1.1.1
disabled:
description: Whether the virtual server is disabled, or not.
returned: changed
type: bool
sample: True
disabled_vlans:
description: List of VLANs that the virtual is disabled for.
returned: changed
type: list
sample: ['/Common/vlan1', '/Common/vlan2']
enabled:
description: Whether the virtual server is enabled, or not.
returned: changed
type: bool
sample: False
enabled_vlans:
description: List of VLANs that the virtual is enabled for.
returned: changed
type: list
sample: ['/Common/vlan5', '/Common/vlan6']
fallback_persistence_profile:
description: Fallback persistence profile set on the virtual server.
returned: changed
type: string
sample: /Common/source_addr
irules:
description: iRules set on the virtual server.
returned: changed
type: list
sample: ['/Common/irule1', '/Common/irule2']
pool:
description: Pool that the virtual server is attached to.
returned: changed
type: string
sample: /Common/my-pool
policies:
description: List of policies attached to the virtual.
returned: changed
type: list
sample: ['/Common/policy1', '/Common/policy2']
port:
description: Port that the virtual server is configured to listen on.
returned: changed
type: int
sample: 80
profiles:
description: List of profiles set on the virtual server.
returned: changed
type: list
sample: [{'name': 'tcp', 'context': 'server-side'}, {'name': 'tcp-legacy', 'context': 'client-side'}]
snat:
description: SNAT setting of the virtual server.
returned: changed
type: string
sample: Automap
source:
description: Source address, in CIDR form, set on the virtual server.
returned: changed
type: string
sample: 1.2.3.4/32
metadata:
description: The new value of the virtual.
returned: changed
type: dict
sample: {'key1': 'foo', 'key2': 'bar'}
'''
import re
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.basic import env_fallback
from ansible.module_utils.six import iteritems
from collections import namedtuple
try:
# Sideband repository used for dev
from library.module_utils.network.f5.bigip import HAS_F5SDK
from library.module_utils.network.f5.bigip import F5Client
from library.module_utils.network.f5.common import F5ModuleError
from library.module_utils.network.f5.common import AnsibleF5Parameters
from library.module_utils.network.f5.common import cleanup_tokens
from library.module_utils.network.f5.common import fqdn_name
from library.module_utils.network.f5.common import f5_argument_spec
try:
from library.module_utils.network.f5.common import iControlUnexpectedHTTPError
except ImportError:
HAS_F5SDK = False
HAS_DEVEL_IMPORTS = True
except ImportError:
# Upstream Ansible
from ansible.module_utils.network.f5.bigip import HAS_F5SDK
from ansible.module_utils.network.f5.bigip import F5Client
from ansible.module_utils.network.f5.common import F5ModuleError
from ansible.module_utils.network.f5.common import AnsibleF5Parameters
from ansible.module_utils.network.f5.common import cleanup_tokens
from ansible.module_utils.network.f5.common import fqdn_name
from ansible.module_utils.network.f5.common import f5_argument_spec
try:
from ansible.module_utils.network.f5.common import iControlUnexpectedHTTPError
except ImportError:
HAS_F5SDK = False
try:
import netaddr
HAS_NETADDR = True
except ImportError:
HAS_NETADDR = False
class Parameters(AnsibleF5Parameters):
api_map = {
'sourceAddressTranslation': 'snat',
'fallbackPersistence': 'fallback_persistence_profile',
'persist': 'default_persistence_profile',
'vlansEnabled': 'vlans_enabled',
'vlansDisabled': 'vlans_disabled',
'profilesReference': 'profiles',
'policiesReference': 'policies',
'rules': 'irules'
}
api_attributes = [
'description',
'destination',
'disabled',
'enabled',
'fallbackPersistence',
'metadata',
'persist',
'policies',
'pool',
'profiles',
'rules',
'source',
'sourceAddressTranslation',
'vlans',
'vlansEnabled',
'vlansDisabled',
]
updatables = [
'description',
'default_persistence_profile',
'destination',
'disabled_vlans',
'enabled',
'enabled_vlans',
'fallback_persistence_profile',
'irules',
'metadata',
'pool',
'policies',
'port',
'profiles',
'snat',
'source'
]
returnables = [
'description',
'default_persistence_profile',
'destination',
'disabled',
'disabled_vlans',
'enabled',
'enabled_vlans',
'fallback_persistence_profile',
'irules',
'metadata',
'pool',
'policies',
'port',
'profiles',
'snat',
'source',
'vlans',
'vlans_enabled',
'vlans_disabled'
]
profiles_mutex = [
'sip', 'sipsession', 'iiop', 'rtsp', 'http', 'diameter',
'diametersession', 'radius', 'ftp', 'tftp', 'dns', 'pptp', 'fix'
]
def to_return(self):
result = {}
for returnable in self.returnables:
try:
result[returnable] = getattr(self, returnable)
except Exception as ex:
pass
result = self._filter_params(result)
return result
def _fqdn_name(self, value):
if value is not None and not value.startswith('/'):
return '/{0}/{1}'.format(self.partition, value)
return value
def is_valid_ip(self, value):
try:
netaddr.IPAddress(value)
return True
except (netaddr.core.AddrFormatError, ValueError):
return False
def _format_port_for_destination(self, ip, port):
addr = netaddr.IPAddress(ip)
if addr.version == 6:
if port == 0:
result = '.any'
else:
result = '.{0}'.format(port)
else:
result = ':{0}'.format(port)
return result
def _format_destination(self, address, port, route_domain):
if port is None:
if route_domain is None:
result = '{0}'.format(
self._fqdn_name(address)
)
else:
result = '{0}%{1}'.format(
self._fqdn_name(address),
route_domain
)
else:
port = self._format_port_for_destination(address, port)
if route_domain is None:
result = '{0}{1}'.format(
self._fqdn_name(address),
port
)
else:
result = '{0}%{1}{2}'.format(
self._fqdn_name(address),
route_domain,
port
)
return result
class ApiParameters(Parameters):
@property
def destination(self):
if self._values['destination'] is None:
return None
destination = self.destination_tuple
result = self._format_destination(destination.ip, destination.port, destination.route_domain)
return result
@property
def source(self):
if self._values['source'] is None:
return None
try:
addr = netaddr.IPNetwork(self._values['source'])
result = '{0}/{1}'.format(str(addr.ip), addr.prefixlen)
return result
except netaddr.core.AddrFormatError:
raise F5ModuleError(
"The source IP address must be specified in CIDR format: address/prefix"
)
@property
def destination_tuple(self):
Destination = namedtuple('Destination', ['ip', 'port', 'route_domain'])
# Remove the partition
if self._values['destination'] is None:
result = Destination(ip=None, port=None, route_domain=None)
return result
destination = re.sub(r'^/[a-zA-Z0-9_.-]+/', '', self._values['destination'])
if self.is_valid_ip(destination):
result = Destination(
ip=destination,
port=None,
route_domain=None
)
return result
# Covers the following examples
#
# /Common/2700:bc00:1f10:101::6%2.80
# 2700:bc00:1f10:101::6%2.80
# 1.1.1.1%2:80
# /Common/1.1.1.1%2:80
# /Common/2700:bc00:1f10:101::6%2.any
#
pattern = r'(?P<ip>[^%]+)%(?P<route_domain>[0-9]+)[:.](?P<port>[0-9]+|any)'
matches = re.search(pattern, destination)
if matches:
try:
port = int(matches.group('port'))
except ValueError:
# Can be a port of "any". This only happens with IPv6
port = matches.group('port')
if port == 'any':
port = 0
ip = matches.group('ip')
if not self.is_valid_ip(ip):
raise F5ModuleError(
"The provided destination is not a valid IP address"
)
result = Destination(
ip=matches.group('ip'),
port=port,
route_domain=int(matches.group('route_domain'))
)
return result
pattern = r'(?P<ip>[^%]+)%(?P<route_domain>[0-9]+)'
matches = re.search(pattern, destination)
if matches:
ip = matches.group('ip')
if not self.is_valid_ip(ip):
raise F5ModuleError(
"The provided destination is not a valid IP address"
)
result = Destination(
ip=matches.group('ip'),
port=None,
route_domain=int(matches.group('route_domain'))
)
return result
parts = destination.split('.')
if len(parts) == 4:
# IPv4
ip, port = destination.split(':')
if not self.is_valid_ip(ip):
raise F5ModuleError(
"The provided destination is not a valid IP address"
)
result = Destination(
ip=ip,
port=int(port),
route_domain=None
)
return result
elif len(parts) == 2:
# IPv6
ip, port = destination.split('.')
try:
port = int(port)
except ValueError:
# Can be a port of "any". This only happens with IPv6
if port == 'any':
port = 0
if not self.is_valid_ip(ip):
raise F5ModuleError(
"The provided destination is not a valid IP address"
)
result = Destination(
ip=ip,
port=port,
route_domain=None
)
return result
else:
result = Destination(ip=None, port=None, route_domain=None)
return result
@property
def port(self):
destination = self.destination_tuple
self._values['port'] = destination.port
return destination.port
@property
def route_domain(self):
destination = self.destination_tuple
self._values['route_domain'] = destination.route_domain
return destination.route_domain
@property
def profiles(self):
if 'items' not in self._values['profiles']:
return None
result = []
for item in self._values['profiles']['items']:
context = item['context']
name = item['name']
if context in ['all', 'serverside', 'clientside']:
result.append(dict(name=name, context=context, fullPath=item['fullPath']))
else:
raise F5ModuleError(
"Unknown profile context found: '{0}'".format(context)
)
return result
@property
def policies(self):
if 'items' not in self._values['policies']:
return None
result = []
for item in self._values['policies']['items']:
name = item['name']
partition = item['partition']
result.append(dict(name=name, partition=partition))
return result
@property
def default_persistence_profile(self):
if self._values['default_persistence_profile'] is None:
return None
# These persistence profiles are always lists when we get them
# from the REST API even though there can only be one. We'll
# make it a list again when we get to the Difference engine.
return self._values['default_persistence_profile'][0]
@property
def enabled(self):
if 'enabled' in self._values:
return True
else:
return False
@property
def disabled(self):
if 'disabled' in self._values:
return True
return False
@property
def metadata(self):
if self._values['metadata'] is None:
return None
result = []
for md in self._values['metadata']:
tmp = dict(name=str(md['name']))
if 'value' in md:
tmp['value'] = str(md['value'])
else:
tmp['value'] = ''
result.append(tmp)
return result
class ModuleParameters(Parameters):
def _handle_profile_context(self, tmp):
if 'context' not in tmp:
tmp['context'] = 'all'
else:
if 'name' not in tmp:
raise F5ModuleError(
"A profile name must be specified when a context is specified."
)
tmp['context'] = tmp['context'].replace('server-side', 'serverside')
tmp['context'] = tmp['context'].replace('client-side', 'clientside')
def _handle_clientssl_profile_nuances(self, profile):
if profile['name'] != 'clientssl':
return
if profile['context'] != 'clientside':
profile['context'] = 'clientside'
@property
def destination(self):
addr = self._values['destination'].split("%")[0]
if not self.is_valid_ip(addr):
raise F5ModuleError(
"The provided destination is not a valid IP address"
)
result = self._format_destination(addr, self.port, self.route_domain)
return result
@property
def destination_tuple(self):
Destination = namedtuple('Destination', ['ip', 'port', 'route_domain'])
if self._values['destination'] is None:
result = Destination(ip=None, port=None, route_domain=None)
return result
addr = self._values['destination'].split("%")[0]
result = Destination(ip=addr, port=self.port, route_domain=self.route_domain)
return result
@property
def source(self):
if self._values['source'] is None:
return None
try:
addr = netaddr.IPNetwork(self._values['source'])
result = '{0}/{1}'.format(str(addr.ip), addr.prefixlen)
return result
except netaddr.core.AddrFormatError:
raise F5ModuleError(
"The source IP address must be specified in CIDR format: address/prefix"
)
@property
def port(self):
if self._values['port'] is None:
return None
if self._values['port'] in ['*', 'any']:
return 0
self._check_port()
return int(self._values['port'])
def _check_port(self):
try:
port = int(self._values['port'])
except ValueError:
raise F5ModuleError(
"The specified port was not a valid integer"
)
if 0 <= port <= 65535:
return port
raise F5ModuleError(
"Valid ports must be in range 0 - 65535"
)
@property
def irules(self):
results = []
if self._values['irules'] is None:
return None
if len(self._values['irules']) == 1 and self._values['irules'][0] == '':
return ''
for irule in self._values['irules']:
result = self._fqdn_name(irule)
results.append(result)
return results
@property
def profiles(self):
if self._values['profiles'] is None:
return None
if len(self._values['profiles']) == 1 and self._values['profiles'][0] == '':
return ''
result = []
for profile in self._values['profiles']:
tmp = dict()
if isinstance(profile, dict):
tmp.update(profile)
self._handle_profile_context(tmp)
if 'name' not in profile:
tmp['name'] = profile
tmp['fullPath'] = self._fqdn_name(tmp['name'])
self._handle_clientssl_profile_nuances(tmp)
else:
tmp['name'] = profile
tmp['context'] = 'all'
tmp['fullPath'] = self._fqdn_name(tmp['name'])
self._handle_clientssl_profile_nuances(tmp)
result.append(tmp)
mutually_exclusive = [x['name'] for x in result if x in self.profiles_mutex]
if len(mutually_exclusive) > 1:
raise F5ModuleError(
"Profiles {0} are mutually exclusive".format(
', '.join(self.profiles_mutex).strip()
)
)
return result
@property
def policies(self):
if self._values['policies'] is None:
return None
if len(self._values['policies']) == 1 and self._values['policies'][0] == '':
return ''
result = []
policies = [self._fqdn_name(p) for p in self._values['policies']]
policies = set(policies)
for policy in policies:
parts = policy.split('/')
if len(parts) != 3:
raise F5ModuleError(
"The specified policy '{0}' is malformed".format(policy)
)
tmp = dict(
name=parts[2],
partition=parts[1]
)
result.append(tmp)
return result
@property
def pool(self):
if self._values['pool'] is None:
return None
if self._values['pool'] == '':
return ''
return self._fqdn_name(self._values['pool'])
@property
def vlans_enabled(self):
if self._values['enabled_vlans'] is None:
return None
elif self._values['vlans_enabled'] is False:
# This is a special case for "all" enabled VLANs
return False
if self._values['disabled_vlans'] is None:
return True
return False
@property
def vlans_disabled(self):
if self._values['disabled_vlans'] is None:
return None
elif self._values['vlans_disabled'] is True:
# This is a special case for "all" enabled VLANs
return True
elif self._values['enabled_vlans'] is None:
return True
return False
@property
def enabled_vlans(self):
if self._values['enabled_vlans'] is None:
return None
elif any(x.lower() for x in self._values['enabled_vlans'] if x.lower() in ['all', '*']):
result = [self._fqdn_name('all')]
if result[0].endswith('/all'):
if self._values['__warnings'] is None:
self._values['__warnings'] = []
self._values['__warnings'].append(
dict(
msg="Usage of the 'ALL' value for 'enabled_vlans' parameter is deprecated. Use '*' instead",
version='2.5'
)
)
return result
results = list(set([self._fqdn_name(x) for x in self._values['enabled_vlans']]))
results.sort()
return results
@property
def disabled_vlans(self):
if self._values['disabled_vlans'] is None:
return None
elif any(x.lower() for x in self._values['disabled_vlans'] if x.lower() in ['all', '*']):
raise F5ModuleError(
"You cannot disable all VLANs. You must name them individually."
)
results = list(set([self._fqdn_name(x) for x in self._values['disabled_vlans']]))
results.sort()
return results
@property
def vlans(self):
disabled = self.disabled_vlans
if disabled:
return self.disabled_vlans
return self.enabled_vlans
@property
def state(self):
if self._values['state'] == 'present':
return 'enabled'
return self._values['state']
@property
def snat(self):
if self._values['snat'] is None:
return None
lowercase = self._values['snat'].lower()
if lowercase in ['automap', 'none']:
return dict(type=lowercase)
snat_pool = self._fqdn_name(self._values['snat'])
return dict(pool=snat_pool, type='snat')
@property
def default_persistence_profile(self):
if self._values['default_persistence_profile'] is None:
return None
if self._values['default_persistence_profile'] == '':
return ''
profile = self._fqdn_name(self._values['default_persistence_profile'])
parts = profile.split('/')
if len(parts) != 3:
raise F5ModuleError(
"The specified 'default_persistence_profile' is malformed"
)
result = dict(
name=parts[2],
partition=parts[1]
)
return result
@property
def fallback_persistence_profile(self):
if self._values['fallback_persistence_profile'] is None:
return None
if self._values['fallback_persistence_profile'] == '':
return ''
result = self._fqdn_name(self._values['fallback_persistence_profile'])
return result
@property
def enabled(self):
if self._values['state'] == 'enabled':
return True
elif self._values['state'] == 'disabled':
return False
else:
return None
@property
def disabled(self):
if self._values['state'] == 'enabled':
return False
elif self._values['state'] == 'disabled':
return True
else:
return None
@property
def metadata(self):
if self._values['metadata'] is None:
return None
if self._values['metadata'] == '':
return []
result = []
try:
for k, v in iteritems(self._values['metadata']):
tmp = dict(name=str(k))
if v:
tmp['value'] = str(v)
else:
tmp['value'] = ''
result.append(tmp)
except AttributeError:
raise F5ModuleError(
"The 'metadata' parameter must be a dictionary of key/value pairs."
)
return result
class Changes(Parameters):
pass
class UsableChanges(Changes):
@property
def vlans(self):
if self._values['vlans'] is None:
return None
elif len(self._values['vlans']) == 0:
return []
elif any(x for x in self._values['vlans'] if x.lower() in ['/common/all', 'all']):
return []
return self._values['vlans']
class ReportableChanges(Changes):
@property
def snat(self):
if self._values['snat'] is None:
return None
result = self._values['snat'].get('type', None)
if result == 'automap':
return 'Automap'
elif result == 'none':
return 'none'
result = self._values['snat'].get('pool', None)
return result
@property
def destination(self):
params = ApiParameters(params=dict(destination=self._values['destination']))
result = params.destination_tuple.ip
return result
@property
def port(self):
params = ApiParameters(params=dict(destination=self._values['destination']))
result = params.destination_tuple.port
return result
@property
def default_persistence_profile(self):
if len(self._values['default_persistence_profile']) == 0:
return []
profile = self._values['default_persistence_profile'][0]
result = '/{0}/{1}'.format(profile['partition'], profile['name'])
return result
@property
def policies(self):
if len(self._values['policies']) == 0:
return []
result = ['/{0}/{1}'.format(x['partition'], x['name']) for x in self._values['policies']]
return result
@property
def enabled_vlans(self):
if len(self._values['vlans']) == 0 and self._values['vlans_disabled'] is True:
return 'all'
elif len(self._values['vlans']) > 0 and self._values['vlans_enabled'] is True:
return self._values['vlans']
@property
def disabled_vlans(self):
if len(self._values['vlans']) > 0 and self._values['vlans_disabled'] is True:
return self._values['vlans']
class Difference(object):
def __init__(self, want, have=None):
self.have = have
self.want = want
def compare(self, param):
try:
result = getattr(self, param)
return result
except AttributeError:
result = self.__default(param)
return result
def __default(self, param):
attr1 = getattr(self.want, param)
try:
attr2 = getattr(self.have, param)
if attr1 != attr2:
return attr1
except AttributeError:
return attr1
def to_tuple(self, items):
result = []
for x in items:
tmp = [(str(k), str(v)) for k, v in iteritems(x)]
result += tmp
return result
def _diff_complex_items(self, want, have):
if want == [] and have is None:
return None
if want is None:
return None
w = self.to_tuple(want)
h = self.to_tuple(have)
if set(w).issubset(set(h)):
return None
else:
return want
def _update_vlan_status(self, result):
if self.want.vlans_disabled is not None:
if self.want.vlans_disabled != self.have.vlans_disabled:
result['vlans_disabled'] = self.want.vlans_disabled
result['vlans_enabled'] = not self.want.vlans_disabled
elif self.want.vlans_enabled is not None:
if any(x.lower().endswith('/all') for x in self.want.vlans):
if self.have.vlans_enabled is True:
result['vlans_disabled'] = True
result['vlans_enabled'] = False
elif self.want.vlans_enabled != self.have.vlans_enabled:
result['vlans_disabled'] = not self.want.vlans_enabled
result['vlans_enabled'] = self.want.vlans_enabled
@property
def destination(self):
addr_tuple = [self.want.destination, self.want.port, self.want.route_domain]
if all(x for x in addr_tuple if x is None):
return None
have = self.have.destination_tuple
if self.want.port is None:
self.want.update({'port': have.port})
if self.want.route_domain is None:
self.want.update({'route_domain': have.route_domain})
if self.want.destination_tuple.ip is None:
address = have.ip
else:
address = self.want.destination_tuple.ip
want = self.want._format_destination(address, self.want.port, self.want.route_domain)
if want != self.have.destination:
return self.want._fqdn_name(want)
@property
def source(self):
if self.want.source is None:
return None
want = netaddr.IPNetwork(self.want.source)
have = netaddr.IPNetwork(self.have.destination_tuple.ip)
if want.version != have.version:
raise F5ModuleError(
"The source and destination addresses for the virtual server must be be the same type (IPv4 or IPv6)."
)
if self.want.source != self.have.source:
return self.want.source
@property
def vlans(self):
if self.want.vlans is None:
return None
elif self.want.vlans == [] and self.have.vlans is None:
return None
elif self.want.vlans == self.have.vlans:
return None
# Specifically looking for /all because the vlans return value will be
# an FQDN list. This means that "all" will be returned as "/partition/all",
# ex, /Common/all.
#
# We do not want to accidentally match values that would end with the word
# "all", like "vlansall". Therefore we look for the forward slash because this
# is a path delimiter.
elif any(x.lower().endswith('/all') for x in self.want.vlans):
if self.have.vlans is None:
return None
else:
return []
else:
return self.want.vlans
@property
def enabled_vlans(self):
return self.vlan_status
@property
def disabled_vlans(self):
return self.vlan_status
@property
def vlan_status(self):
result = dict()
vlans = self.vlans
if vlans is not None:
result['vlans'] = vlans
self._update_vlan_status(result)
return result
@property
def port(self):
result = self.destination
if result is not None:
return dict(
destination=result
)
@property
def profiles(self):
if self.want.profiles is None:
return None
if self.want.profiles == '' and len(self.have.profiles) > 0:
have = set([(p['name'], p['context'], p['fullPath']) for p in self.have.profiles])
if len(self.have.profiles) == 1:
if not any(x[0] in ['tcp', 'udp', 'sctp'] for x in have):
return []
else:
return None
else:
return []
if self.want.profiles == '' and len(self.have.profiles) == 0:
return None
want = set([(p['name'], p['context'], p['fullPath']) for p in self.want.profiles])
have = set([(p['name'], p['context'], p['fullPath']) for p in self.have.profiles])
if len(have) == 0:
return self.want.profiles
elif len(have) == 1:
if want != have:
return self.want.profiles
else:
if not any(x[0] == 'tcp' for x in want):
have = set([x for x in have if x[0] != 'tcp'])
if not any(x[0] == 'udp' for x in want):
have = set([x for x in have if x[0] != 'udp'])
if not any(x[0] == 'sctp' for x in want):
have = set([x for x in have if x[0] != 'sctp'])
want = set([(p[2], p[1]) for p in want])
have = set([(p[2], p[1]) for p in have])
if want != have:
return self.want.profiles
@property
def fallback_persistence_profile(self):
if self.want.fallback_persistence_profile is None:
return None
if self.want.fallback_persistence_profile == '' and self.have.fallback_persistence_profile is not None:
return ""
if self.want.fallback_persistence_profile == '' and self.have.fallback_persistence_profile is None:
return None
if self.want.fallback_persistence_profile != self.have.fallback_persistence_profile:
return self.want.fallback_persistence_profile
@property
def default_persistence_profile(self):
if self.want.default_persistence_profile is None:
return None
if self.want.default_persistence_profile == '' and self.have.default_persistence_profile is not None:
return []
if self.want.default_persistence_profile == '' and self.have.default_persistence_profile is None:
return None
if self.have.default_persistence_profile is None:
return [self.want.default_persistence_profile]
w_name = self.want.default_persistence_profile.get('name', None)
w_partition = self.want.default_persistence_profile.get('partition', None)
h_name = self.have.default_persistence_profile.get('name', None)
h_partition = self.have.default_persistence_profile.get('partition', None)
if w_name != h_name or w_partition != h_partition:
return [self.want.default_persistence_profile]
@property
def policies(self):
if self.want.policies is None:
return None
if self.want.policies == '' and self.have.policies is None:
return None
if self.want.policies == '' and len(self.have.policies) > 0:
return []
if not self.have.policies:
return self.want.policies
want = set([(p['name'], p['partition']) for p in self.want.policies])
have = set([(p['name'], p['partition']) for p in self.have.policies])
if not want == have:
return self.want.policies
@property
def snat(self):
if self.want.snat is None:
return None
if self.want.snat['type'] != self.have.snat['type']:
result = dict(snat=self.want.snat)
return result
if self.want.snat.get('pool', None) is None:
return None
if self.want.snat['pool'] != self.have.snat['pool']:
result = dict(snat=self.want.snat)
return result
@property
def enabled(self):
if self.want.state == 'enabled' and self.have.disabled:
result = dict(
enabled=True,
disabled=False
)
return result
elif self.want.state == 'disabled' and self.have.enabled:
result = dict(
enabled=False,
disabled=True
)
return result
@property
def irules(self):
if self.want.irules is None:
return None
if self.want.irules == '' and len(self.have.irules) > 0:
return []
if self.want.irules == '' and len(self.have.irules) == 0:
return None
if sorted(set(self.want.irules)) != sorted(set(self.have.irules)):
return self.want.irules
@property
def pool(self):
if self.want.pool is None:
return None
if self.want.pool == '' and self.have.pool is not None:
return ""
if self.want.pool == '' and self.have.pool is None:
return None
if self.want.pool != self.have.pool:
return self.want.pool
@property
def metadata(self):
if self.want.metadata is None:
return None
elif len(self.want.metadata) == 0 and self.have.metadata is None:
return None
elif len(self.want.metadata) == 0:
return []
elif self.have.metadata is None:
return self.want.metadata
result = self._diff_complex_items(self.want.metadata, self.have.metadata)
return result
class ModuleManager(object):
def __init__(self, *args, **kwargs):
self.module = kwargs.get('module', None)
self.client = kwargs.get('client', None)
self.have = ApiParameters()
self.want = ModuleParameters(client=self.client, params=self.module.params)
self.changes = UsableChanges()
def exec_module(self):
changed = False
result = dict()
state = self.want.state
try:
if state in ['present', 'enabled', 'disabled']:
changed = self.present()
elif state == "absent":
changed = self.absent()
except iControlUnexpectedHTTPError as e:
raise F5ModuleError(str(e))
reportable = ReportableChanges(params=self.changes.to_return())
changes = reportable.to_return()
result.update(**changes)
result.update(dict(changed=changed))
self._announce_deprecations(result)
return result
def _announce_deprecations(self, result):
warnings = result.pop('__warnings', [])
for warning in warnings:
self.module.deprecate(
msg=warning['msg'],
version=warning['version']
)
def present(self):
if self.exists():
return self.update()
else:
return self.create()
def absent(self):
if self.exists():
return self.remove()
return False
def update(self):
self.have = self.read_current_from_device()
if not self.should_update():
return False
if self.module.check_mode:
return True
self.update_on_device()
return True
def should_update(self):
result = self._update_changed_options()
if result:
return True
return False
def remove(self):
if self.module.check_mode:
return True
self.remove_from_device()
if self.exists():
raise F5ModuleError("Failed to delete the resource")
return True
def get_reportable_changes(self):
result = ReportableChanges(params=self.changes.to_return())
return result
def _set_changed_options(self):
changed = {}
for key in Parameters.returnables:
if getattr(self.want, key) is not None:
changed[key] = getattr(self.want, key)
if changed:
self.changes = UsableChanges(params=changed)
def _update_changed_options(self):
diff = Difference(self.want, self.have)
updatables = Parameters.updatables
changed = dict()
for k in updatables:
change = diff.compare(k)
if change is None:
continue
else:
if isinstance(change, dict):
changed.update(change)
else:
changed[k] = change
if changed:
self.changes = UsableChanges(params=changed)
return True
return False
def exists(self):
result = self.client.api.tm.ltm.virtuals.virtual.exists(
name=self.want.name,
partition=self.want.partition
)
return result
def create(self):
required_resources = ['destination', 'port']
self._set_changed_options()
# This must be changed back to a list to make a valid REST API
# value. The module manipulates this as a normal dictionary
if self.want.default_persistence_profile is not None:
self.want.update({'default_persistence_profile': [self.want.default_persistence_profile]})
if self.want.destination is None:
raise F5ModuleError(
"'destination' must be specified when creating a virtual server"
)
if all(getattr(self.want, v) is None for v in required_resources):
raise F5ModuleError(
"You must specify both of " + ', '.join(required_resources)
)
if self.want.enabled_vlans is not None:
if any(x for x in self.want.enabled_vlans if x.lower() in ['/common/all', 'all']):
self.want.update(
dict(
enabled_vlans=[],
vlans_disabled=True,
vlans_enabled=False
)
)
if self.want.source and self.want.destination:
want = netaddr.IPNetwork(self.want.source)
have = netaddr.IPNetwork(self.want.destination_tuple.ip)
if want.version != have.version:
raise F5ModuleError(
"The source and destination addresses for the virtual server must be be the same type (IPv4 or IPv6)."
)
if self.module.check_mode:
return True
self.create_on_device()
return True
def update_on_device(self):
params = self.changes.api_params()
resource = self.client.api.tm.ltm.virtuals.virtual.load(
name=self.want.name,
partition=self.want.partition
)
resource.modify(**params)
def read_current_from_device(self):
result = self.client.api.tm.ltm.virtuals.virtual.load(
name=self.want.name,
partition=self.want.partition,
requests_params=dict(
params=dict(
expandSubcollections='true'
)
)
)
params = result.attrs
params.update(dict(kind=result.to_dict().get('kind', None)))
result = ApiParameters(params=params)
return result
def create_on_device(self):
params = self.want.api_params()
self.client.api.tm.ltm.virtuals.virtual.create(
name=self.want.name,
partition=self.want.partition,
**params
)
def remove_from_device(self):
resource = self.client.api.tm.ltm.virtuals.virtual.load(
name=self.want.name,
partition=self.want.partition
)
if resource:
resource.delete()
class ArgumentSpec(object):
def __init__(self):
self.supports_check_mode = True
argument_spec = dict(
state=dict(
default='present',
choices=['present', 'absent', 'disabled', 'enabled']
),
name=dict(
required=True,
aliases=['vs']
),
destination=dict(
aliases=['address', 'ip']
),
port=dict(
type='int'
),
profiles=dict(
type='list',
aliases=['all_profiles'],
options=dict(
name=dict(required=False),
context=dict(default='all', choices=['all', 'server-side', 'client-side'])
)
),
policies=dict(
type='list',
aliases=['all_policies']
),
irules=dict(
type='list',
aliases=['all_rules']
),
enabled_vlans=dict(
type='list'
),
disabled_vlans=dict(
type='list'
),
pool=dict(),
description=dict(),
snat=dict(),
default_persistence_profile=dict(),
fallback_persistence_profile=dict(),
source=dict(),
metadata=dict(type='raw'),
partition=dict(
default='Common',
fallback=(env_fallback, ['F5_PARTITION'])
)
)
self.argument_spec = {}
self.argument_spec.update(f5_argument_spec)
self.argument_spec.update(argument_spec)
self.mutually_exclusive = [
['enabled_vlans', 'disabled_vlans']
]
def main():
spec = ArgumentSpec()
module = AnsibleModule(
argument_spec=spec.argument_spec,
supports_check_mode=spec.supports_check_mode,
mutually_exclusive=spec.mutually_exclusive
)
if not HAS_F5SDK:
module.fail_json(msg="The python f5-sdk module is required")
if not HAS_NETADDR:
module.fail_json(msg="The python netaddr module is required")
try:
client = F5Client(**module.params)
mm = ModuleManager(module=module, client=client)
results = mm.exec_module()
cleanup_tokens(client)
module.exit_json(**results)
except F5ModuleError as ex:
cleanup_tokens(client)
module.fail_json(msg=str(ex))
if __name__ == '__main__':
main()
| gpl-3.0 |
RichIsMyName/PicklingToolsRepo | PythonModule/ptools/xmldumper_defs.py | 3 | 3487 |
# Options for dictionaries -> XML
# If XML attributes are being folded up, then you may
# want to prepend a special character to distinguish attributes
# from nested tags: an underscore is the usual default. If
# you don't want a prepend char, use XML_DUMP_NO_PREPEND option
XML_PREPEND_CHAR = '_'
# When dumping, by DEFAULT the keys that start with _ become
# attributes (this is called "unfolding"). You may want to keep
# those keys as tags. Consider:
#
# { 'top': { '_a':'1', '_b': 2 }}
#
# DEFAULT behavior, this becomes:
# <top a="1" b="2"></top> This moves the _names to attributes
#
# But, you may want all _ keys to stay as tags: that's the purpose of this opt
# <top> <_a>1</_a> <_b>2</b> </top>
XML_DUMP_PREPEND_KEYS_AS_TAGS = 0x100
# Any value that is simple (i.e., contains no nested
# content) will be placed in the attributes bin:
# For examples:
# { 'top': { 'x':'1', 'y': 2 }} -> <top x="1" y="2"></top>
XML_DUMP_SIMPLE_TAGS_AS_ATTRIBUTES = 0x200
# By default, everything dumps as strings (without quotes), but those things
# that are strings lose their "stringedness", which means
# they can't be "evaled" on the way back in. This option makes
# Vals that are strings dump with quotes.
XML_DUMP_STRINGS_AS_STRINGS = 0x400
# Like XML_DUMP_STRINGS_AS_STRINGS, but this one ONLY
# dumps strings with quotes if it thinks Eval will return
# something else. For example in { 's': '123' } : '123' is
# a STRING, not a number. When evalled with an XMLLoader
# with XML_LOAD_EVAL_CONTENT flag, that will become a number.
XML_DUMP_STRINGS_BEST_GUESS = 0x800
# Show nesting when you dump: like "prettyPrint": basically, it shows
# nesting
XML_DUMP_PRETTY = 0x1000
# Arrays of POD (plain old data: ints, real, complex, etc) can
# dump as huge lists: By default they just dump with one tag
# and then a list of numbers. If you set this option, they dump
# as a true XML list (<data>1.0/<data><data>2.0</data> ...)
# which is very expensive, but is easier to use with other
# tools (spreadsheets that support lists, etc.).
XML_DUMP_POD_LIST_AS_XML_LIST = 0x2000
# When dumping an empty tag, what do you want it to be?
# I.e., what is <empty></empty>
# Normally (DEFAULT) this is an empty dictionary 'empty': {}
# If you want that to be empty content, as in an empty string,
# set this option: 'empty': ""
# NOTE: You don't need this option if you are using
# XML_DUMP_STRINGS_AS_STRINGS or XML_DUMP_STRINGS_BEST_GUESS
XML_DUMP_PREFER_EMPTY_STRINGS = 0x4000
# When dumping dictionaries in order, a dict BY DEFAULT prints
# out the keys in sorted/alphabetic order and BY DEFAULT an OrderedDict
# prints out in the OrderedDict order. The "unnatural" order
# for a dict is to print out in "random" order (but probably slightly
# faster). The "unnatural" order for an OrderedDict is sorted
# (because normally we use an OrderedDict because we WANTS its
# notion of order)
XML_DUMP_UNNATURAL_ORDER = 0x8000
# Even though illegal XML, allow element names starting with Digits:
# when it does see a starting digit, it turns it into an _digit
# so that it is still legal XML
XML_TAGS_ACCEPTS_DIGITS = 0x80
# Allows digits as starting XML tags, even though illegal XML.
# This preserves the number as a tag.
XML_DIGITS_AS_TAGS = 0x80000
# When dumping XML, the default is to NOT have the XML header
# <?xml version="1.0">: Specifying this option will always make that
# the header always precedes all content
XML_STRICT_HDR = 0x10000
| bsd-3-clause |
cwacek/python-jsonschema-objects | python_jsonschema_objects/wrapper_types.py | 1 | 11522 | import collections
import logging
import six
from python_jsonschema_objects import util
from python_jsonschema_objects.validators import registry, ValidationError
from python_jsonschema_objects.util import lazy_format as fmt
logger = logging.getLogger(__name__)
class ArrayWrapper(collections.abc.MutableSequence):
"""A wrapper for array-like structures.
This implements all of the array like behavior that one would want,
with a dirty-tracking mechanism to avoid constant validation costs.
"""
@property
def strict(self):
return getattr(self, "_strict_", False)
def __len__(self):
return len(self.data)
def mark_or_revalidate(self):
if self.strict:
self.validate()
else:
self._dirty = True
def __delitem__(self, index):
self.data.pop(index)
self.mark_or_revalidate()
def insert(self, index, value):
self.data.insert(index, value)
self.mark_or_revalidate()
def __setitem__(self, index, value):
self.data[index] = value
self.mark_or_revalidate()
def __getitem__(self, idx):
return self.typed_elems[idx]
def __eq__(self, other):
if isinstance(other, ArrayWrapper):
return self.for_json() == other.for_json()
else:
return self.for_json() == other
def __init__(self, ary):
"""Initialize a wrapper for the array
Args:
ary: (list-like, or ArrayWrapper)
"""
""" Marks whether or not the underlying array has been modified """
self._dirty = True
""" Holds a typed copy of the array """
self._typed = None
if isinstance(ary, (list, tuple, collections.abc.Sequence)):
self.data = ary
else:
raise TypeError("Invalid value given to array validator: {0}".format(ary))
logger.debug(fmt("Initializing ArrayWrapper {} with {}", self, ary))
@property
def typed_elems(self):
logger.debug(fmt("Accessing typed_elems of ArrayWrapper {} ", self))
if self._typed is None or self._dirty is True:
self.validate()
return self._typed
def __repr__(self):
return "<%s=%s>" % (self.__class__.__name__, str(self.data))
@classmethod
def from_json(cls, jsonmsg):
import json
msg = json.loads(jsonmsg)
obj = cls(msg)
obj.validate()
return obj
def serialize(self):
enc = util.ProtocolJSONEncoder()
return enc.encode(self.typed_elems)
def for_json(self):
from python_jsonschema_objects import classbuilder
out = []
for item in self.typed_elems:
if isinstance(
item,
(classbuilder.ProtocolBase, classbuilder.LiteralValue, ArrayWrapper),
):
out.append(item.for_json())
else:
out.append(item)
return out
def validate(self):
if self.strict or self._dirty:
self.validate_items()
self.validate_length()
self.validate_uniqueness()
return True
def validate_uniqueness(self):
if getattr(self, "uniqueItems", False) is True:
testset = set(repr(item) for item in self.data)
if len(testset) != len(self.data):
raise ValidationError(
"{0} has duplicate elements, but uniqueness required".format(
self.data
)
)
def validate_length(self):
if getattr(self, "minItems", None) is not None:
if len(self.data) < self.minItems:
raise ValidationError(
"{1} has too few elements. Wanted {0}.".format(
self.minItems, self.data
)
)
if getattr(self, "maxItems", None) is not None:
if len(self.data) > self.maxItems:
raise ValidationError(
"{1} has too many elements. Wanted {0}.".format(
self.maxItems, self.data
)
)
def validate_items(self):
"""Validates the items in the backing array, including
performing type validation.
Sets the _typed property and clears the dirty flag as a side effect
Returns:
The typed array
"""
logger.debug(fmt("Validating {}", self))
from python_jsonschema_objects import classbuilder
if self.__itemtype__ is None:
return
type_checks = self.__itemtype__
if not isinstance(type_checks, (tuple, list)):
# we were given items = {'type': 'blah'} ; thus ensure the type for all data.
type_checks = [type_checks] * len(self.data)
elif len(type_checks) > len(self.data):
raise ValidationError(
"{1} does not have sufficient elements to validate against {0}".format(
self.__itemtype__, self.data
)
)
typed_elems = []
for elem, typ in zip(self.data, type_checks):
if isinstance(typ, dict):
for param, paramval in six.iteritems(typ):
validator = registry(param)
if validator is not None:
validator(paramval, elem, typ)
typed_elems.append(elem)
elif util.safe_issubclass(typ, classbuilder.LiteralValue):
val = typ(elem)
val.validate()
typed_elems.append(val)
elif util.safe_issubclass(typ, classbuilder.ProtocolBase):
if not isinstance(elem, typ):
try:
if isinstance(
elem, (six.string_types, six.integer_types, float)
):
val = typ(elem)
else:
val = typ(**util.coerce_for_expansion(elem))
except TypeError as e:
raise ValidationError(
"'{0}' is not a valid value for '{1}': {2}".format(
elem, typ, e
)
)
else:
val = elem
val.validate()
typed_elems.append(val)
elif util.safe_issubclass(typ, ArrayWrapper):
val = typ(elem)
val.validate()
typed_elems.append(val)
elif isinstance(typ, (classbuilder.TypeProxy, classbuilder.TypeRef)):
try:
if isinstance(elem, (six.string_types, six.integer_types, float)):
val = typ(elem)
else:
val = typ(**util.coerce_for_expansion(elem))
except TypeError as e:
raise ValidationError(
"'{0}' is not a valid value for '{1}': {2}".format(elem, typ, e)
)
else:
val.validate()
typed_elems.append(val)
self._dirty = False
self._typed = typed_elems
return typed_elems
@staticmethod
def create(name, item_constraint=None, **addl_constraints):
"""Create an array validator based on the passed in constraints.
If item_constraint is a tuple, it is assumed that tuple validation
is being performed. If it is a class or dictionary, list validation
will be performed. Classes are assumed to be subclasses of ProtocolBase,
while dictionaries are expected to be basic types ('string', 'number', ...).
addl_constraints is expected to be key-value pairs of any of the other
constraints permitted by JSON Schema v4.
"""
logger.debug(
fmt(
"Constructing ArrayValidator with {} and {}",
item_constraint,
addl_constraints,
)
)
from python_jsonschema_objects import classbuilder
klassbuilder = addl_constraints.pop(
"classbuilder", None
) # type: python_jsonschema_objects.classbuilder.ClassBuilder
props = {}
if item_constraint is not None:
if isinstance(item_constraint, (tuple, list)):
for i, elem in enumerate(item_constraint):
isdict = isinstance(elem, (dict,))
isklass = isinstance(elem, type) and util.safe_issubclass(
elem, (classbuilder.ProtocolBase, classbuilder.LiteralValue)
)
if not any([isdict, isklass]):
raise TypeError(
"Item constraint (position {0}) is not a schema".format(i)
)
elif isinstance(
item_constraint, (classbuilder.TypeProxy, classbuilder.TypeRef)
):
pass
elif util.safe_issubclass(item_constraint, ArrayWrapper):
pass
else:
isdict = isinstance(item_constraint, (dict,))
isklass = isinstance(item_constraint, type) and util.safe_issubclass(
item_constraint,
(classbuilder.ProtocolBase, classbuilder.LiteralValue),
)
if not any([isdict, isklass]):
raise TypeError("Item constraint is not a schema")
if isdict and "$ref" in item_constraint:
if klassbuilder is None:
raise TypeError(
"Cannot resolve {0} without classbuilder".format(
item_constraint["$ref"]
)
)
item_constraint = klassbuilder.resolve_type(
item_constraint["$ref"], name
)
elif isdict and item_constraint.get("type") == "array":
# We need to create a sub-array validator.
item_constraint = ArrayWrapper.create(
name + "#sub",
item_constraint=item_constraint["items"],
addl_constraints=item_constraint,
)
elif isdict and "oneOf" in item_constraint:
# We need to create a TypeProxy validator
uri = "{0}_{1}".format(name, "<anonymous_list_type>")
type_array = klassbuilder.construct_objects(
item_constraint["oneOf"], uri
)
item_constraint = classbuilder.TypeProxy(type_array)
elif isdict and item_constraint.get("type") == "object":
""" We need to create a ProtocolBase object for this anonymous definition"""
uri = "{0}_{1}".format(name, "<anonymous_list_type>")
item_constraint = klassbuilder.construct(uri, item_constraint)
props["__itemtype__"] = item_constraint
strict = addl_constraints.pop("strict", False)
props["_strict_"] = strict
props.update(addl_constraints)
validator = type(str(name), (ArrayWrapper,), props)
return validator
| mit |
0x0all/scikit-learn | examples/plot_multioutput_face_completion.py | 330 | 3019 | """
==============================================
Face completion with a multi-output estimators
==============================================
This example shows the use of multi-output estimator to complete images.
The goal is to predict the lower half of a face given its upper half.
The first column of images shows true faces. The next columns illustrate
how extremely randomized trees, k nearest neighbors, linear
regression and ridge regression complete the lower half of those faces.
"""
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_olivetti_faces
from sklearn.utils.validation import check_random_state
from sklearn.ensemble import ExtraTreesRegressor
from sklearn.neighbors import KNeighborsRegressor
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import RidgeCV
# Load the faces datasets
data = fetch_olivetti_faces()
targets = data.target
data = data.images.reshape((len(data.images), -1))
train = data[targets < 30]
test = data[targets >= 30] # Test on independent people
# Test on a subset of people
n_faces = 5
rng = check_random_state(4)
face_ids = rng.randint(test.shape[0], size=(n_faces, ))
test = test[face_ids, :]
n_pixels = data.shape[1]
X_train = train[:, :np.ceil(0.5 * n_pixels)] # Upper half of the faces
y_train = train[:, np.floor(0.5 * n_pixels):] # Lower half of the faces
X_test = test[:, :np.ceil(0.5 * n_pixels)]
y_test = test[:, np.floor(0.5 * n_pixels):]
# Fit estimators
ESTIMATORS = {
"Extra trees": ExtraTreesRegressor(n_estimators=10, max_features=32,
random_state=0),
"K-nn": KNeighborsRegressor(),
"Linear regression": LinearRegression(),
"Ridge": RidgeCV(),
}
y_test_predict = dict()
for name, estimator in ESTIMATORS.items():
estimator.fit(X_train, y_train)
y_test_predict[name] = estimator.predict(X_test)
# Plot the completed faces
image_shape = (64, 64)
n_cols = 1 + len(ESTIMATORS)
plt.figure(figsize=(2. * n_cols, 2.26 * n_faces))
plt.suptitle("Face completion with multi-output estimators", size=16)
for i in range(n_faces):
true_face = np.hstack((X_test[i], y_test[i]))
if i:
sub = plt.subplot(n_faces, n_cols, i * n_cols + 1)
else:
sub = plt.subplot(n_faces, n_cols, i * n_cols + 1,
title="true faces")
sub.axis("off")
sub.imshow(true_face.reshape(image_shape),
cmap=plt.cm.gray,
interpolation="nearest")
for j, est in enumerate(sorted(ESTIMATORS)):
completed_face = np.hstack((X_test[i], y_test_predict[est][i]))
if i:
sub = plt.subplot(n_faces, n_cols, i * n_cols + 2 + j)
else:
sub = plt.subplot(n_faces, n_cols, i * n_cols + 2 + j,
title=est)
sub.axis("off")
sub.imshow(completed_face.reshape(image_shape),
cmap=plt.cm.gray,
interpolation="nearest")
plt.show()
| bsd-3-clause |
cloud9209/cloud9209_flask | lib/bs4/tests/test_lxml.py | 273 | 2965 | """Tests to ensure that the lxml tree builder generates good trees."""
import re
import warnings
try:
import lxml.etree
LXML_PRESENT = True
LXML_VERSION = lxml.etree.LXML_VERSION
except ImportError, e:
LXML_PRESENT = False
LXML_VERSION = (0,)
if LXML_PRESENT:
from bs4.builder import LXMLTreeBuilder, LXMLTreeBuilderForXML
from bs4 import (
BeautifulSoup,
BeautifulStoneSoup,
)
from bs4.element import Comment, Doctype, SoupStrainer
from bs4.testing import skipIf
from bs4.tests import test_htmlparser
from bs4.testing import (
HTMLTreeBuilderSmokeTest,
XMLTreeBuilderSmokeTest,
SoupTest,
skipIf,
)
@skipIf(
not LXML_PRESENT,
"lxml seems not to be present, not testing its tree builder.")
class LXMLTreeBuilderSmokeTest(SoupTest, HTMLTreeBuilderSmokeTest):
"""See ``HTMLTreeBuilderSmokeTest``."""
@property
def default_builder(self):
return LXMLTreeBuilder()
def test_out_of_range_entity(self):
self.assertSoupEquals(
"<p>foo�bar</p>", "<p>foobar</p>")
self.assertSoupEquals(
"<p>foo�bar</p>", "<p>foobar</p>")
self.assertSoupEquals(
"<p>foo�bar</p>", "<p>foobar</p>")
# In lxml < 2.3.5, an empty doctype causes a segfault. Skip this
# test if an old version of lxml is installed.
@skipIf(
not LXML_PRESENT or LXML_VERSION < (2,3,5,0),
"Skipping doctype test for old version of lxml to avoid segfault.")
def test_empty_doctype(self):
soup = self.soup("<!DOCTYPE>")
doctype = soup.contents[0]
self.assertEqual("", doctype.strip())
def test_beautifulstonesoup_is_xml_parser(self):
# Make sure that the deprecated BSS class uses an xml builder
# if one is installed.
with warnings.catch_warnings(record=True) as w:
soup = BeautifulStoneSoup("<b />")
self.assertEqual(u"<b/>", unicode(soup.b))
self.assertTrue("BeautifulStoneSoup class is deprecated" in str(w[0].message))
def test_real_xhtml_document(self):
"""lxml strips the XML definition from an XHTML doc, which is fine."""
markup = b"""<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>Hello.</title></head>
<body>Goodbye.</body>
</html>"""
soup = self.soup(markup)
self.assertEqual(
soup.encode("utf-8").replace(b"\n", b''),
markup.replace(b'\n', b'').replace(
b'<?xml version="1.0" encoding="utf-8"?>', b''))
@skipIf(
not LXML_PRESENT,
"lxml seems not to be present, not testing its XML tree builder.")
class LXMLXMLTreeBuilderSmokeTest(SoupTest, XMLTreeBuilderSmokeTest):
"""See ``HTMLTreeBuilderSmokeTest``."""
@property
def default_builder(self):
return LXMLTreeBuilderForXML()
| apache-2.0 |
franciscogmm/FinancialAnalysisUsingNLPandMachineLearning | SentimentAnalysis - Polarity - Domain Specific Lexicon.py | 1 | 2667 | import csv
import pandas as pd
import nltk
from nltk import FreqDist,ngrams
from nltk.corpus import stopwords
import string
from os import listdir
from os.path import isfile, join
def ngram_list(file,n):
f = open(file,'rU')
raw = f.read()
raw = raw.replace('\n',' ')
#raw = raw.decode('utf8')
#raw = raw.decode("utf-8", 'ignore')
ngramz = ngrams(raw.split(),n)
return ngramz
def IsNotNull(value):
return value is not None and len(value) > 0
mypath = '/Users/francis/Documents/FORDHAM/2nd Term/Text Analytics/' #path where files are located
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
dict_p = []
f = open('positive.txt', 'r')
for line in f:
t = line.strip().lower()
if IsNotNull(t):
dict_p.append(t)
f.close
dict_n = []
f = open('negative.txt', 'r')
for line in f:
t = line.strip().lower()
if IsNotNull(t):
dict_n.append(t)
f.close
totallist = []
rowlist = []
qa = 0
qb = 0
counti = 0
for i in onlyfiles:
if i.endswith('.txt'):
# get code
j = i.replace('.txt','')
# string filename
file = mypath + str(i)
print i
f = open(file,'rU')
raw = f.read()
#print type(raw)
raw = [w.translate(None, string.punctuation) for w in raw]
raw = ''.join(raw)
raw = raw.replace('\n','')
raw = raw.replace(' ','')
#print raw
qa = 0
qb = 0
for word in dict_p:
if word in raw:
qa += 1
for word in dict_n:
if word in raw:
qb += 1
qc = qa - qb
if qc > 0:
sentiment = 'POSITIVE'
elif qc == 0:
sentiment = 'NEUTRAL'
else:
sentiment = 'NEGATIVE'
rowlist.append(i)
rowlist.append(qa)
rowlist.append(qb)
rowlist.append(qc)
rowlist.append(sentiment)
print counti
counti += 1
totallist.append(rowlist)
rowlist = []
else:
pass
labels = ('file', 'P', 'N', 'NET', 'SENTIMENT')
df = pd.DataFrame.from_records(totallist, columns = labels)
df.to_csv('oursentiment.csv', index = False)
#print dict_p
# allbigrams.append(ngram_list(file,2))
# print i + ' BIGRAM - OK'
# alltrigrams.append(ngram_list(file,3))
# print i + ' TRIGRAM - OK'
# allfourgrams.append(ngram_list(file,4))
# print i + ' FOURGRAM - OK'
# allfivegrams.append(ngram_list(file,5))
# print i + ' TRIGRAM - OK'
# allsixgrams.append(ngram_list(file,6))
# print i + ' SIXGRAM - OK'
# allsevengrams.append(ngram_list(file,7))
# print i + ' SEVENGRAM - OK'
# alleightgrams.append(ngram_list(file,8))
# print i + ' EIGHTGRAM - OK' | mit |
oihane/server-tools | auth_dynamic_groups/model/res_users.py | 14 | 2115 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2013 Therp BV (<http://therp.nl>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.models import Model
from openerp.modules.registry import RegistryManager
from openerp import SUPERUSER_ID
class res_users(Model):
_inherit = 'res.users'
def _login(self, db, login, password):
uid = super(res_users, self)._login(db, login, password)
if uid:
self.update_dynamic_groups(uid, db)
return uid
def update_dynamic_groups(self, uid, db):
pool = RegistryManager.get(db)
cr = pool._db.cursor()
user = pool.get('res.users').browse(cr, SUPERUSER_ID, uid)
groups_obj = pool.get('res.groups')
user.write(
{
'groups_id': [
(4, dynamic_group.id)
if dynamic_group.eval_dynamic_group_condition(uid=uid)
else (3, dynamic_group.id)
for dynamic_group in groups_obj.browse(
cr, SUPERUSER_ID,
groups_obj.search(cr, SUPERUSER_ID,
[('is_dynamic', '=', True)]))
],
})
cr.commit()
cr.close()
| agpl-3.0 |
DocBO/mubosym | mubosym/simple_tire_model_interface.py | 2 | 8005 | # -*- coding: utf-8 -*-
"""
simple_tire_model_interface
===========================
Created on Wed May 27 18:02:53 2015
@author: oliver
"""
import sys
from sympy import lambdify, symbols
import numpy as np
b = [1.5,0.,1100.,0.,300.,0.,0.,0.,-2.,0.,0.,0.,0.,0.]
a = [1.4,0.,1100.,1100.,10.,0.,0.,-2.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.]
def Pacejka_F_long(Fz, slip):
"""
longitudinal force
:param (float) Fz: Force in vertical direction in N
:param (float) slip: relative slip fraction (0..1)
"""
if Fz == 0:
return 0.
slip = slip*100.0
Fz = Fz/1000.0
C = b[0]
D = Fz*(b[1]*Fz+b[2])
BCD = (Fz*(b[3]*Fz+b[4]))*np.exp(-b[5]*Fz)
B = BCD/(C*D)
H = b[9]*Fz+b[10]
V = b[11]*Fz+b[12]
E = ((b[6]*Fz*Fz)+b[7]*Fz+b[8])*(1-(b[13]*np.sign(slip+H)))
Bx1 = B*(slip+H)
Fx = D*np.sin(C*np.arctan(Bx1-E*(Bx1-np.arctan(Bx1))))+V
return Fx
def Pacejka_F_lat(Fz, alpha, camber):
"""
lateral force
:param (float) Fz: Force in vertical direction in N
:param (float) alpha: slip angle in rad
:param (float) camber: camber angle in rad
"""
if Fz == 0:
return 0.
alpha = alpha * 180.0/np.pi
camber = camber * 180.0/np.pi
Fz = Fz/1000.0
C = a[0]
D = Fz*(a[1]*Fz+a[2])*(1-a[15]*np.power(camber,2))
BCD = a[3]*np.sin(np.arctan(Fz/a[4])*2)*(1-a[5]*np.fabs(camber))
B = BCD/(C*D)
H = a[8]*Fz+a[9]+a[10]*camber
V = a[11]*Fz+a[12]+(a[13]*Fz+a[14])*camber*Fz
E = (a[6]*Fz+a[7])*(1-(a[16]*camber+a[17])*np.sign(alpha+H))
Bx1 = B*(alpha+H)
Fy = D*np.sin(C*np.arctan(Bx1-E*(Bx1-np.arctan(Bx1))))+V
return Fy
class simple_tire_model():
"""
A one body force model consists of:
* coordinate trafo generalized coords -> body coordinates (denoted list of) including pos, vel, orientation, and omega
* force calculator given as a python function with input according to our interface
* some preparation function: lambdifier to include symbolic functions into lambdas
"""
def __init__(self, paras = []):
# setup parameters
self.t = 0.
self.D = 200000.
self.gamma = 200.0
self.y0 = 0.0
self.C_side = 4500.0
self.C_align = 200.0
self.C_slip = 300.0
self.R_tire = 0.33
self.trafo = []
self.F_max = 4500.0
self.gamma_torque = 2.0
self.max_p = 100.0
self.tau = 0.1
self.signals = []
self.signals_values = []
def set_coordinate_trafo(self, tr):
"""
Input function for the coordinate trafo expressions (sympy).
:param tr: the transformation expressions as given in the mbs setup for the body
"""
self.trafo = tr
def set_subs_dicts(self, subs_dicts):
for sd in subs_dicts:
for ii in range(len(self.trafo)):
self.trafo[ii] = self.trafo[ii].subs(sd)
for ii in range(len(self.signals)):
self.signals[ii] = self.signals[ii].subs(sd)
def add_signal(self, expr):
self.signals.append(expr)
def lambdify_trafo(self, generalized_coords):
"""
This is the core function to lambdify the coordinate trafos in general
the trafos must be explicitely set via set_coordinate_trafo called from MBSCore (see therein)
:param generalized_coords: the generalized coords (symbols) of the final mbs setup (called in kaneify)
"""
if len(self.trafo) < 12:
print("call set_coordinate_trafo first")
sys.exit(0)
# for ii in range(12):
# print ii, self.trafo[ii]
t = symbols('t')
self.lam_t = lambdify(generalized_coords, t)
self.lam_x = lambdify(generalized_coords, self.trafo[0])
self.lam_y = lambdify(generalized_coords, self.trafo[1])
self.lam_z = lambdify(generalized_coords, self.trafo[2])
self.lam_nx = lambdify(generalized_coords, self.trafo[3])
self.lam_ny = lambdify(generalized_coords, self.trafo[4])
self.lam_nz = lambdify(generalized_coords, self.trafo[5])
self.lam_x_pt = lambdify(generalized_coords, self.trafo[6])
self.lam_y_pt = lambdify(generalized_coords, self.trafo[7])
self.lam_z_pt = lambdify(generalized_coords, self.trafo[8])
self.lam_omega_x = lambdify(generalized_coords, self.trafo[9])
self.lam_omega_y = lambdify(generalized_coords, self.trafo[10])
self.lam_omega_z = lambdify(generalized_coords, self.trafo[11])
self.lam_signals = [ lambdify(generalized_coords, expr) for expr in self.signals]
def trafo_lam(self, w):
"""
Just for reference all coordinate trafos as lambdas (not used at the moment).
:param w: the generalized coords (float numbers) of the final mbs setup
"""
return [self.lam_t(*w), self.lam_x(*w), self.lam_y(*w), self.lam_z(*w), \
self.lam_nx(*w), self.lam_ny(*w), self.lam_nz(*w), \
self.lam_x_pt(*w), self.lam_y_pt(*w), self.lam_z_pt(*w), \
self.lam_omega_x(*w), self.lam_omega_y(*w), self.lam_omega_z(*w)]
def force_lam(self, w):
"""
The model force/torque via lambdified expressions, input parameter here is always the full state vecor t,q,u.
Output is the force/toque via the model calc-function the nested input for the calc routine is fully possible written out:
* self.lam_t, self.lam_x, self.lam_y, self.lam_z,
* self.lam_nx, self.lam_ny, self.lam_nz,
* self.lam_x_pt, self.lam_y_pt, self.lam_z_pt,
* self.lam_omega_x self.lam_omega_y, self.lam_omega_z
but can be reduced to a subset
:param w: the generalized coords (float numbers) of the final mbs setup, The order has to be equal the one in calc.
"""
self.signals_values = [x(*w) for x in self.lam_signals]
return self._calc([ self.lam_t(*w), self.lam_y(*w), \
self.lam_x_pt(*w), self.lam_y_pt(*w), self.lam_z_pt(*w),\
self.lam_omega_z(*w) ] )
def _calc(self, inp):
"""
The python function which connects some external model calculation with the mbs model
e.g. tire-model, rail model. It is only called internally by force_lam.
* input list inp are some relevant model coordinates (out of 12 possible): [ x, y, z, nx, ny, nz, x_pt, y_pt, z_pt, omega_x, omega_y, omega_z ] = inp
* output list is force in cartesian coord. world and torque cartesian coord. world
:param inp: the subset of all possible coord. of one body (see list), here expected as float numbers. The order has to be equal the one in force_lam
"""
signals = self.signals_values
[ t, y , x_pt, y_pt, z_pt, omega_z ] = inp
#print "SSSig: ",signals
eps = 5.0e-1
#preset values
F_x = 0.
F_y = 0.
F_z = 0.
T_x = 0.
T_y = 0.
T_z = 0.
#vertical reaction force
if y<0:
F_y = -self.D*(y-self.y0) - self.gamma*y_pt
else:
F_y = 0.
#side slip angle
alpha = np.arctan2(z_pt,(x_pt+eps)) #in the tire carrier frame
#slip
slip = (omega_z * self.R_tire + x_pt)/np.abs(x_pt+eps)
#######################################################
# Pacejka - Model:
F_z = - Pacejka_F_lat(F_y, alpha, 0.)
F_x = - Pacejka_F_long(F_y, slip)
T_z = F_x * self.R_tire - self.gamma_torque * omega_z
#print F_y
#self.oz += 1./10.*delta_t * T_z
return [F_x, F_y, F_z, T_x, T_y, T_z], [F_x, F_y, F_z, T_z, 1e+2*slip, 180/np.pi*alpha]
def get_signal_length(self):
return 6
| mit |
mdaif/olympia | apps/landfill/tests/test_categories.py | 15 | 1025 | # -*- coding: utf-8 -*-
from nose.tools import eq_, ok_
import amo
import amo.tests
from addons.models import Category
from constants.applications import APPS
from landfill.categories import generate_categories
class CategoriesTests(amo.tests.TestCase):
def test_categories_themes_generation(self):
data = generate_categories()
eq_(len(data), Category.objects.all().count())
eq_(len(data), 15)
def test_categories_themes_translations(self):
with self.activate(locale='es'):
data = generate_categories()
ok_(unicode(data[0].name).startswith(u'(español) '))
def test_categories_addons_generation(self):
data = generate_categories(APPS['android'])
eq_(len(data), Category.objects.all().count())
eq_(len(data), 10)
def test_categories_addons_translations(self):
with self.activate(locale='es'):
data = generate_categories(APPS['android'])
ok_(unicode(data[0].name).startswith(u'(español) '))
| bsd-3-clause |
alex/raven | raven/handlers/logging.py | 3 | 4470 | """
raven.handlers.logging
~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import datetime
import logging
import sys
import traceback
from raven.base import Client
from raven.utils.encoding import to_string
from raven.utils.stacks import iter_stack_frames
class SentryHandler(logging.Handler, object):
def __init__(self, *args, **kwargs):
client = kwargs.get('client_cls', Client)
if len(args) == 1:
arg = args[0]
if isinstance(arg, basestring):
self.client = client(dsn=arg)
elif isinstance(arg, Client):
self.client = arg
else:
raise ValueError('The first argument to %s must be either a Client instance or a DSN, got %r instead.' % (
self.__class__.__name__,
arg,
))
elif 'client' in kwargs:
self.client = kwargs['client']
elif len(args) == 2 and not kwargs:
servers, key = args
self.client = client(servers=servers, key=key)
else:
self.client = client(*args, **kwargs)
logging.Handler.__init__(self)
def emit(self, record):
# from sentry.client.middleware import SentryLogMiddleware
# # Fetch the request from a threadlocal variable, if available
# request = getattr(SentryLogMiddleware.thread, 'request', None)
self.format(record)
# Avoid typical config issues by overriding loggers behavior
if record.name.startswith('sentry.errors'):
print >> sys.stderr, to_string(record.message)
return
try:
return self._emit(record)
except Exception:
print >> sys.stderr, "Top level Sentry exception caught - failed creating log record"
print >> sys.stderr, to_string(record.msg)
print >> sys.stderr, to_string(traceback.format_exc())
try:
self.client.capture('Exception')
except Exception:
pass
def _emit(self, record, **kwargs):
data = {}
for k, v in record.__dict__.iteritems():
if '.' not in k and k not in ('culprit',):
continue
data[k] = v
stack = getattr(record, 'stack', None)
if stack is True:
stack = iter_stack_frames()
if stack:
frames = []
started = False
last_mod = ''
for item in stack:
if isinstance(item, (list, tuple)):
frame, lineno = item
else:
frame, lineno = item, item.f_lineno
if not started:
f_globals = getattr(frame, 'f_globals', {})
module_name = f_globals.get('__name__', '')
if last_mod.startswith('logging') and not module_name.startswith('logging'):
started = True
else:
last_mod = module_name
continue
frames.append((frame, lineno))
stack = frames
extra = getattr(record, 'data', {})
# Add in all of the data from the record that we aren't already capturing
for k in record.__dict__.keys():
if k in ('stack', 'name', 'args', 'msg', 'levelno', 'exc_text', 'exc_info', 'data', 'created', 'levelname', 'msecs', 'relativeCreated'):
continue
if k.startswith('_'):
continue
extra[k] = record.__dict__[k]
date = datetime.datetime.utcfromtimestamp(record.created)
# If there's no exception being processed, exc_info may be a 3-tuple of None
# http://docs.python.org/library/sys.html#sys.exc_info
if record.exc_info and all(record.exc_info):
handler = self.client.get_handler('raven.events.Exception')
data.update(handler.capture(exc_info=record.exc_info))
data['checksum'] = handler.get_hash(data)
data['level'] = record.levelno
data['logger'] = record.name
return self.client.capture('Message', message=record.msg, params=record.args,
stack=stack, data=data, extra=extra,
date=date, **kwargs)
| bsd-3-clause |
timokoola/finnkinotxt | botocore/vendored/requests/packages/urllib3/poolmanager.py | 678 | 9406 | import logging
try: # Python 3
from urllib.parse import urljoin
except ImportError:
from urlparse import urljoin
from ._collections import RecentlyUsedContainer
from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool
from .connectionpool import port_by_scheme
from .exceptions import LocationValueError, MaxRetryError
from .request import RequestMethods
from .util.url import parse_url
from .util.retry import Retry
__all__ = ['PoolManager', 'ProxyManager', 'proxy_from_url']
pool_classes_by_scheme = {
'http': HTTPConnectionPool,
'https': HTTPSConnectionPool,
}
log = logging.getLogger(__name__)
SSL_KEYWORDS = ('key_file', 'cert_file', 'cert_reqs', 'ca_certs',
'ssl_version')
class PoolManager(RequestMethods):
"""
Allows for arbitrary requests while transparently keeping track of
necessary connection pools for you.
:param num_pools:
Number of connection pools to cache before discarding the least
recently used pool.
:param headers:
Headers to include with all requests, unless other headers are given
explicitly.
:param \**connection_pool_kw:
Additional parameters are used to create fresh
:class:`urllib3.connectionpool.ConnectionPool` instances.
Example::
>>> manager = PoolManager(num_pools=2)
>>> r = manager.request('GET', 'http://google.com/')
>>> r = manager.request('GET', 'http://google.com/mail')
>>> r = manager.request('GET', 'http://yahoo.com/')
>>> len(manager.pools)
2
"""
proxy = None
def __init__(self, num_pools=10, headers=None, **connection_pool_kw):
RequestMethods.__init__(self, headers)
self.connection_pool_kw = connection_pool_kw
self.pools = RecentlyUsedContainer(num_pools,
dispose_func=lambda p: p.close())
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.clear()
# Return False to re-raise any potential exceptions
return False
def _new_pool(self, scheme, host, port):
"""
Create a new :class:`ConnectionPool` based on host, port and scheme.
This method is used to actually create the connection pools handed out
by :meth:`connection_from_url` and companion methods. It is intended
to be overridden for customization.
"""
pool_cls = pool_classes_by_scheme[scheme]
kwargs = self.connection_pool_kw
if scheme == 'http':
kwargs = self.connection_pool_kw.copy()
for kw in SSL_KEYWORDS:
kwargs.pop(kw, None)
return pool_cls(host, port, **kwargs)
def clear(self):
"""
Empty our store of pools and direct them all to close.
This will not affect in-flight connections, but they will not be
re-used after completion.
"""
self.pools.clear()
def connection_from_host(self, host, port=None, scheme='http'):
"""
Get a :class:`ConnectionPool` based on the host, port, and scheme.
If ``port`` isn't given, it will be derived from the ``scheme`` using
``urllib3.connectionpool.port_by_scheme``.
"""
if not host:
raise LocationValueError("No host specified.")
scheme = scheme or 'http'
port = port or port_by_scheme.get(scheme, 80)
pool_key = (scheme, host, port)
with self.pools.lock:
# If the scheme, host, or port doesn't match existing open
# connections, open a new ConnectionPool.
pool = self.pools.get(pool_key)
if pool:
return pool
# Make a fresh ConnectionPool of the desired type
pool = self._new_pool(scheme, host, port)
self.pools[pool_key] = pool
return pool
def connection_from_url(self, url):
"""
Similar to :func:`urllib3.connectionpool.connection_from_url` but
doesn't pass any additional parameters to the
:class:`urllib3.connectionpool.ConnectionPool` constructor.
Additional parameters are taken from the :class:`.PoolManager`
constructor.
"""
u = parse_url(url)
return self.connection_from_host(u.host, port=u.port, scheme=u.scheme)
def urlopen(self, method, url, redirect=True, **kw):
"""
Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen`
with custom cross-host redirect logic and only sends the request-uri
portion of the ``url``.
The given ``url`` parameter must be absolute, such that an appropriate
:class:`urllib3.connectionpool.ConnectionPool` can be chosen for it.
"""
u = parse_url(url)
conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme)
kw['assert_same_host'] = False
kw['redirect'] = False
if 'headers' not in kw:
kw['headers'] = self.headers
if self.proxy is not None and u.scheme == "http":
response = conn.urlopen(method, url, **kw)
else:
response = conn.urlopen(method, u.request_uri, **kw)
redirect_location = redirect and response.get_redirect_location()
if not redirect_location:
return response
# Support relative URLs for redirecting.
redirect_location = urljoin(url, redirect_location)
# RFC 7231, Section 6.4.4
if response.status == 303:
method = 'GET'
retries = kw.get('retries')
if not isinstance(retries, Retry):
retries = Retry.from_int(retries, redirect=redirect)
try:
retries = retries.increment(method, url, response=response, _pool=conn)
except MaxRetryError:
if retries.raise_on_redirect:
raise
return response
kw['retries'] = retries
kw['redirect'] = redirect
log.info("Redirecting %s -> %s" % (url, redirect_location))
return self.urlopen(method, redirect_location, **kw)
class ProxyManager(PoolManager):
"""
Behaves just like :class:`PoolManager`, but sends all requests through
the defined proxy, using the CONNECT method for HTTPS URLs.
:param proxy_url:
The URL of the proxy to be used.
:param proxy_headers:
A dictionary contaning headers that will be sent to the proxy. In case
of HTTP they are being sent with each request, while in the
HTTPS/CONNECT case they are sent only once. Could be used for proxy
authentication.
Example:
>>> proxy = urllib3.ProxyManager('http://localhost:3128/')
>>> r1 = proxy.request('GET', 'http://google.com/')
>>> r2 = proxy.request('GET', 'http://httpbin.org/')
>>> len(proxy.pools)
1
>>> r3 = proxy.request('GET', 'https://httpbin.org/')
>>> r4 = proxy.request('GET', 'https://twitter.com/')
>>> len(proxy.pools)
3
"""
def __init__(self, proxy_url, num_pools=10, headers=None,
proxy_headers=None, **connection_pool_kw):
if isinstance(proxy_url, HTTPConnectionPool):
proxy_url = '%s://%s:%i' % (proxy_url.scheme, proxy_url.host,
proxy_url.port)
proxy = parse_url(proxy_url)
if not proxy.port:
port = port_by_scheme.get(proxy.scheme, 80)
proxy = proxy._replace(port=port)
assert proxy.scheme in ("http", "https"), \
'Not supported proxy scheme %s' % proxy.scheme
self.proxy = proxy
self.proxy_headers = proxy_headers or {}
connection_pool_kw['_proxy'] = self.proxy
connection_pool_kw['_proxy_headers'] = self.proxy_headers
super(ProxyManager, self).__init__(
num_pools, headers, **connection_pool_kw)
def connection_from_host(self, host, port=None, scheme='http'):
if scheme == "https":
return super(ProxyManager, self).connection_from_host(
host, port, scheme)
return super(ProxyManager, self).connection_from_host(
self.proxy.host, self.proxy.port, self.proxy.scheme)
def _set_proxy_headers(self, url, headers=None):
"""
Sets headers needed by proxies: specifically, the Accept and Host
headers. Only sets headers not provided by the user.
"""
headers_ = {'Accept': '*/*'}
netloc = parse_url(url).netloc
if netloc:
headers_['Host'] = netloc
if headers:
headers_.update(headers)
return headers_
def urlopen(self, method, url, redirect=True, **kw):
"Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute."
u = parse_url(url)
if u.scheme == "http":
# For proxied HTTPS requests, httplib sets the necessary headers
# on the CONNECT to the proxy. For HTTP, we'll definitely
# need to set 'Host' at the very least.
headers = kw.get('headers', self.headers)
kw['headers'] = self._set_proxy_headers(url, headers)
return super(ProxyManager, self).urlopen(method, url, redirect=redirect, **kw)
def proxy_from_url(url, **kw):
return ProxyManager(proxy_url=url, **kw)
| apache-2.0 |
sassoftware/mint | mint/django_rest/rbuilder/querysets/views/v1/views.py | 1 | 8001 | #!/usr/bin/python
#
# Copyright (c) SAS Institute 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.
#
from django import http
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from mint.django_rest.deco import return_xml, requires, access, xObjRequires
from mint.django_rest.rbuilder import service
# from mint.django_rest.rbuilder.querysets import models
from mint.django_rest.rbuilder.rbac.rbacauth import rbac, manual_rbac
from mint.django_rest.rbuilder.errors import PermissionDenied
from mint.django_rest.rbuilder.rbac.manager.rbacmanager import \
READSET, MODSETDEF
def rbac_can_read_queryset(view, request, query_set_id, *args, **kwargs):
obj = view.mgr.getQuerySet(query_set_id)
if obj.is_public:
# existance of querysets like "All Systems", etc, are not stealthed.
# but may vary in size depending on the user accessing them's permissions
# (ReadMember) on their contents.
return True
user = view.mgr.getSessionInfo().user[0]
ok = view.mgr.userHasRbacPermission(user, obj, READSET)
return ok
def rbac_can_write_queryset(view, request, query_set_id, *args, **kwargs):
obj = view.mgr.getQuerySet(query_set_id)
user = view.mgr.getSessionInfo().user[0]
return view.mgr.userHasRbacPermission(user, obj, MODSETDEF)
class BaseQuerySetService(service.BaseService):
pass
class QuerySetsService(BaseQuerySetService):
# rbac is handled semimanually for this function -- show only
# querysets that we have permission to see
# but don't use full rbac code, because that is implemented using querysets
# and is too meta.
@access.authenticated
@return_xml
def rest_GET(self, request):
user = request._authUser
querysets = self.mgr.getQuerySets()
return self.mgr.filterRbacQuerysets(user, querysets, request)
# not used above, but still needed by load_from_href and other
# functions
def get(self):
return self.mgr.getQuerySets()
@access.admin
@requires('query_set', load=True, save=True)
@return_xml
def rest_POST(self, request, query_set):
return self.mgr.addQuerySet(query_set, request._authUser)
class QuerySetService(BaseQuerySetService):
# rbac is handled semimanually for this function -- show only
# querysets that we have permission to see
# but don't use full rbac code, because that is implemented using querysets
# and is too meta.
@rbac(manual_rbac)
@return_xml
def rest_GET(self, request, query_set_id):
user = request._authUser
queryset = self.mgr.getQuerySet(query_set_id)
if not queryset.is_public and not self.mgr.userHasRbacPermission(
user, queryset, READSET, request
):
raise PermissionDenied()
return queryset
# not used above, but still needed by load_from_href and other
# functions
def get(self, query_set_id):
return self.mgr.getQuerySet(query_set_id)
@access.admin
@requires('query_set')
@return_xml
def rest_PUT(self, request, query_set_id, query_set):
oldQuerySet = self.mgr.getQuerySet(query_set_id)
if oldQuerySet.pk != query_set.pk:
raise PermissionDenied(msg='Attempting to reassign ID')
return self.mgr.updateQuerySet(query_set, request._authUser)
@access.admin
def rest_DELETE(self, request, query_set_id):
querySet = self.mgr.getQuerySet(query_set_id)
self.mgr.deleteQuerySet(querySet)
response = http.HttpResponse(status=204)
return response
class QuerySetAllResultService(BaseQuerySetService):
@access.authenticated
@return_xml
def rest_GET(self, request, query_set_id):
return self.mgr.getQuerySetAllResult(query_set_id, for_user=request._authUser)
class QuerySetUniverseResultService(BaseQuerySetService):
'''the parent queryset of all objects of a given type'''
@access.authenticated
@return_xml
def rest_GET(self, request, query_set_id):
self.mgr.getQuerySetUniverseSet(query_set_id)
url = reverse('QuerySetAllResult', args=[query_set_id])
return HttpResponseRedirect(url)
class QuerySetChosenResultService(BaseQuerySetService):
@access.authenticated
@return_xml
def rest_GET(self, request, query_set_id):
return self.mgr.getQuerySetChosenResult(query_set_id, for_user=request._authUser)
@rbac(rbac_can_write_queryset)
# TODO: source fromc onstant somewhere
@requires(['systems', 'users', 'images', 'targets', 'project_branch_stages', 'projects', 'grants', 'roles'])
@return_xml
def rest_PUT(self, request, query_set_id, *args, **kwargs):
resources = kwargs.items()[0][1]
return self.mgr.addQuerySetChosen(query_set_id, resources, request._authUser)
@rbac(rbac_can_write_queryset)
# TODO: source fromc onstant somewhere
@requires(['system', 'user', 'image', 'target', 'project_branch_stage', 'project_branch', 'project', 'grant', 'role'])
@return_xml
def rest_POST(self, request, query_set_id, *args, **kwargs):
resource = kwargs.items()[0][1]
self.mgr.updateQuerySetChosen(query_set_id, resource, request._authUser)
return resource
@rbac(rbac_can_write_queryset)
# TODO: source fromc onstant somewhere
@requires(['system', 'user', 'image', 'target', 'project_branch_stage', 'project_branch', 'project', 'grant', 'role'])
@return_xml
def rest_DELETE(self, request, query_set_id, *args, **kwargs):
resource = kwargs.items()[0][1]
return self.mgr.deleteQuerySetChosen(query_set_id, resource, request._authUser)
class QuerySetFilteredResultService(BaseQuerySetService):
@access.authenticated
@return_xml
def rest_GET(self, request, query_set_id):
return self.mgr.getQuerySetFilteredResult(query_set_id, for_user=request._authUser)
class QuerySetChildResultService(BaseQuerySetService):
@access.authenticated
@return_xml
def rest_GET(self, request, query_set_id):
if rbac_can_read_queryset(self, request, query_set_id):
return self.mgr.getQuerySetChildResult(query_set_id)
else:
return self.mgr.getQuerySetChildResult(query_set_id, for_user=request._authUser)
# this is not expected to be our final API for removing child members
# but serves as a temporary one in case someone needs it. Deleting
# the queryset is not an option to clear it out because associated
# grants would be purged.
@rbac(rbac_can_write_queryset)
@requires('query_set')
@return_xml
def rest_DELETE(self, request, query_set_id, query_set):
return self.mgr.deleteQuerySetChild(query_set_id, query_set, for_user=request._authUser)
class QuerySetJobsService(BaseQuerySetService):
# no way to list running jobs at the moment
# since all jobs run immediately
@rbac(rbac_can_read_queryset)
@xObjRequires('job')
def rest_POST(self, request, query_set_id, job):
'''launch a job on this queryset'''
queryset = self.mgr.getQuerySet(query_set_id)
self.mgr.scheduleQuerySetJobAction(
queryset, job
)
return http.HttpResponse(status=200)
class QuerySetFilterDescriptorService(BaseQuerySetService):
# @access.authenticated
@return_xml
def rest_GET(self, request, query_set_id=None):
return self.mgr.getQuerySetFilterDescriptor(query_set_id)
| apache-2.0 |
dneg/cortex | python/IECoreMaya/TransformationMatrixParameterUI.py | 12 | 5608 | ##########################################################################
#
# Copyright (c) 2010, Image Engine Design 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 Image Engine Design nor the names of any
# other contributors to this software 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.
#
##########################################################################
from __future__ import with_statement
import maya.cmds
import IECore
import IECoreMaya
## The UI for the TransformationMatrixParameter supports the following
## userData()
##
## - "visibleFields" IECore.StringVectorData, A list of fields to
## display in the UI. Possible values are (D marks a default):
## "translate" D
## "rotate", D
## "scale" D
## "shear" D
## "rotatePivot",
## "rotatePivotTranslation",
## "scalePivot"
## "scalePivotTranslation"
class TransformationMatrixParameterUI( IECoreMaya.ParameterUI ) :
_allFields = ( "translate", "rotate", "scale", "shear", "scalePivot", "scalePivotTranslation", "rotatePivot", "rotatePivotTranslation" )
def __init__( self, node, parameter, **kw ) :
self._outerColumn = maya.cmds.columnLayout( adj=True )
IECoreMaya.ParameterUI.__init__( self, node, parameter, self._outerColumn, **kw )
maya.cmds.rowLayout( numberOfColumns=2, parent=self._outerColumn )
self._label = maya.cmds.text(
label = self.label(),
font = "tinyBoldLabelFont",
align = "right",
annotation = self.description()
)
self._manip = maya.cmds.button( label="Manipulate" )
maya.cmds.setParent("..")
maya.cmds.setParent("..")
self._fields = {}
self.__kw = kw.copy()
self.replace( self.node(), self.parameter )
def replace( self, node, parameter ) :
IECoreMaya.ParameterUI.replace( self, node, parameter )
currentParent = maya.cmds.setParent( query=True )
visibleFields = IECore.StringVectorData( ( "translate", "rotate", "scale", "shear" ) )
with IECore.IgnoredExceptions( KeyError ) :
userDataFields = parameter.userData()["UI"]["visibleFields"]
visibleFields = []
for u in userDataFields :
if u not in TransformationMatrixParameterUI._allFields:
IECore.msg(
IECore.Msg.Level.Warning,
"TransformationMatrixParameterUI",
"Invalid field '%s' requested in UI userData for '%s'. Available fields are %s."
% ( u, parameter.name, TransformationMatrixParameterUI._allFields )
)
continue
visibleFields.append( u )
for f in self._fields.keys() :
if f not in visibleFields :
maya.cmds.deleteUI( self._fields[f][0] )
del self._fields[f]
fnPH = IECoreMaya.FnParameterisedHolder( node )
baseName = fnPH.parameterPlugPath( parameter )
self._addPopupMenu( parentUI=self._label, attributeName=baseName )
for f in visibleFields :
if f not in self._fields :
layout = maya.cmds.rowLayout(
numberOfColumns = 4,
parent = self._outerColumn,
columnWidth4 = [ IECoreMaya.ParameterUI.textColumnWidthIndex, IECoreMaya.ParameterUI.singleWidgetWidthIndex, IECoreMaya.ParameterUI.singleWidgetWidthIndex, IECoreMaya.ParameterUI.singleWidgetWidthIndex ]
)
maya.cmds.text( label=f, font="smallPlainLabelFont", align="right" )
self._fields[f] = ( layout, maya.cmds.floatField(), maya.cmds.floatField(), maya.cmds.floatField() )
maya.cmds.connectControl( self._fields[f][1], "%s%s%i" % ( baseName, f, 0 ) )
maya.cmds.connectControl( self._fields[f][2], "%s%s%i" % ( baseName, f, 1 ) )
maya.cmds.connectControl( self._fields[f][3], "%s%s%i" % ( baseName, f, 2 ) )
maya.cmds.button(
self._manip,
edit = True,
# The manip is currently only registered for float types
visible = isinstance( parameter, IECore.TransformationMatrixfParameter ),
command = self._createCallback( IECore.curry( IECoreMaya.ManipulatorUI.manipulateParameter, node, parameter ) )
)
maya.cmds.setParent( currentParent )
IECoreMaya.ParameterUI.registerUI( IECore.TypeId.TransformationMatrixfParameter, TransformationMatrixParameterUI )
IECoreMaya.ParameterUI.registerUI( IECore.TypeId.TransformationMatrixdParameter, TransformationMatrixParameterUI )
| bsd-3-clause |
simonpatrick/bite-project | deps/gdata-python-client/tests/gdata_tests/client_smoke_test.py | 39 | 1743 | #!/usr/bin/env python
#
# Copyright (C) 2010 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.
# This module is used for version 2 of the Google Data APIs.
__author__ = '[email protected] (Jeff Scudder)'
import unittest
import gdata.test_config as conf
import gdata.analytics.client
import gdata.apps.emailsettings.client
import gdata.blogger.client
import gdata.spreadsheets.client
import gdata.calendar_resource.client
import gdata.contacts.client
import gdata.docs.client
import gdata.projecthosting.client
import gdata.sites.client
class ClientSmokeTest(unittest.TestCase):
def test_check_auth_client_classes(self):
conf.check_clients_with_auth(self, (
gdata.analytics.client.AnalyticsClient,
gdata.apps.emailsettings.client.EmailSettingsClient,
gdata.blogger.client.BloggerClient,
gdata.spreadsheets.client.SpreadsheetsClient,
gdata.calendar_resource.client.CalendarResourceClient,
gdata.contacts.client.ContactsClient,
gdata.docs.client.DocsClient,
gdata.projecthosting.client.ProjectHostingClient,
gdata.sites.client.SitesClient
))
def suite():
return conf.build_suite([ClientSmokeTest])
if __name__ == '__main__':
unittest.main()
| apache-2.0 |
msabramo/ansible | lib/ansible/modules/cloud/google/gcdns_record.py | 49 | 28445 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015 CallFire Inc.
#
# This file is part of Ansible.
#
# 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/>.
################################################################################
# Documentation
################################################################################
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: gcdns_record
short_description: Creates or removes resource records in Google Cloud DNS
description:
- Creates or removes resource records in Google Cloud DNS.
version_added: "2.2"
author: "William Albert (@walbert947)"
requirements:
- "python >= 2.6"
- "apache-libcloud >= 0.19.0"
options:
state:
description:
- Whether the given resource record should or should not be present.
required: false
choices: ["present", "absent"]
default: "present"
record:
description:
- The fully-qualified domain name of the resource record.
required: true
aliases: ['name']
zone:
description:
- The DNS domain name of the zone (e.g., example.com).
- One of either I(zone) or I(zone_id) must be specified as an
option, or the module will fail.
- If both I(zone) and I(zone_id) are specifed, I(zone_id) will be
used.
required: false
zone_id:
description:
- The Google Cloud ID of the zone (e.g., example-com).
- One of either I(zone) or I(zone_id) must be specified as an
option, or the module will fail.
- These usually take the form of domain names with the dots replaced
with dashes. A zone ID will never have any dots in it.
- I(zone_id) can be faster than I(zone) in projects with a large
number of zones.
- If both I(zone) and I(zone_id) are specifed, I(zone_id) will be
used.
required: false
type:
description:
- The type of resource record to add.
required: true
choices: [ 'A', 'AAAA', 'CNAME', 'SRV', 'TXT', 'SOA', 'NS', 'MX', 'SPF', 'PTR' ]
record_data:
description:
- The record_data to use for the resource record.
- I(record_data) must be specified if I(state) is C(present) or
I(overwrite) is C(True), or the module will fail.
- Valid record_data vary based on the record's I(type). In addition,
resource records that contain a DNS domain name in the value
field (e.g., CNAME, PTR, SRV, .etc) MUST include a trailing dot
in the value.
- Individual string record_data for TXT records must be enclosed in
double quotes.
- For resource records that have the same name but different
record_data (e.g., multiple A records), they must be defined as
multiple list entries in a single record.
required: false
aliases: ['value']
ttl:
description:
- The amount of time in seconds that a resource record will remain
cached by a caching resolver.
required: false
default: 300
overwrite:
description:
- Whether an attempt to overwrite an existing record should succeed
or fail. The behavior of this option depends on I(state).
- If I(state) is C(present) and I(overwrite) is C(True), this
module will replace an existing resource record of the same name
with the provided I(record_data). If I(state) is C(present) and
I(overwrite) is C(False), this module will fail if there is an
existing resource record with the same name and type, but
different resource data.
- If I(state) is C(absent) and I(overwrite) is C(True), this
module will remove the given resource record unconditionally.
If I(state) is C(absent) and I(overwrite) is C(False), this
module will fail if the provided record_data do not match exactly
with the existing resource record's record_data.
required: false
choices: [True, False]
default: False
service_account_email:
description:
- The e-mail address for a service account with access to Google
Cloud DNS.
required: false
default: null
pem_file:
description:
- The path to the PEM file associated with the service account
email.
- This option is deprecated and may be removed in a future release.
Use I(credentials_file) instead.
required: false
default: null
credentials_file:
description:
- The path to the JSON file associated with the service account
email.
required: false
default: null
project_id:
description:
- The Google Cloud Platform project ID to use.
required: false
default: null
notes:
- See also M(gcdns_zone).
- This modules's underlying library does not support in-place updates for
DNS resource records. Instead, resource records are quickly deleted and
recreated.
- SOA records are technically supported, but their functionality is limited
to verifying that a zone's existing SOA record matches a pre-determined
value. The SOA record cannot be updated.
- Root NS records cannot be updated.
- NAPTR records are not supported.
'''
EXAMPLES = '''
# Create an A record.
- gcdns_record:
record: 'www1.example.com'
zone: 'example.com'
type: A
value: '1.2.3.4'
# Update an existing record.
- gcdns_record:
record: 'www1.example.com'
zone: 'example.com'
type: A
overwrite: true
value: '5.6.7.8'
# Remove an A record.
- gcdns_record:
record: 'www1.example.com'
zone_id: 'example-com'
state: absent
type: A
value: '5.6.7.8'
# Create a CNAME record.
- gcdns_record:
record: 'www.example.com'
zone_id: 'example-com'
type: CNAME
value: 'www.example.com.' # Note the trailing dot
# Create an MX record with a custom TTL.
- gcdns_record:
record: 'example.com'
zone: 'example.com'
type: MX
ttl: 3600
value: '10 mail.example.com.' # Note the trailing dot
# Create multiple A records with the same name.
- gcdns_record:
record: 'api.example.com'
zone_id: 'example-com'
type: A
record_data:
- '192.0.2.23'
- '10.4.5.6'
- '198.51.100.5'
- '203.0.113.10'
# Change the value of an existing record with multiple record_data.
- gcdns_record:
record: 'api.example.com'
zone: 'example.com'
type: A
overwrite: true
record_data: # WARNING: All values in a record will be replaced
- '192.0.2.23'
- '192.0.2.42' # The changed record
- '198.51.100.5'
- '203.0.113.10'
# Safely remove a multi-line record.
- gcdns_record:
record: 'api.example.com'
zone_id: 'example-com'
state: absent
type: A
record_data: # NOTE: All of the values must match exactly
- '192.0.2.23'
- '192.0.2.42'
- '198.51.100.5'
- '203.0.113.10'
# Unconditionally remove a record.
- gcdns_record:
record: 'api.example.com'
zone_id: 'example-com'
state: absent
overwrite: true # overwrite is true, so no values are needed
type: A
# Create an AAAA record
- gcdns_record:
record: 'www1.example.com'
zone: 'example.com'
type: AAAA
value: 'fd00:db8::1'
# Create a PTR record
- gcdns_record:
record: '10.5.168.192.in-addr.arpa'
zone: '5.168.192.in-addr.arpa'
type: PTR
value: 'api.example.com.' # Note the trailing dot.
# Create an NS record
- gcdns_record:
record: 'subdomain.example.com'
zone: 'example.com'
type: NS
ttl: 21600
record_data:
- 'ns-cloud-d1.googledomains.com.' # Note the trailing dots on values
- 'ns-cloud-d2.googledomains.com.'
- 'ns-cloud-d3.googledomains.com.'
- 'ns-cloud-d4.googledomains.com.'
# Create a TXT record
- gcdns_record:
record: 'example.com'
zone_id: 'example-com'
type: TXT
record_data:
- '"v=spf1 include:_spf.google.com -all"' # A single-string TXT value
- '"hello " "world"' # A multi-string TXT value
'''
RETURN = '''
overwrite:
description: Whether to the module was allowed to overwrite the record
returned: success
type: boolean
sample: True
record:
description: Fully-qualified domain name of the resource record
returned: success
type: string
sample: mail.example.com.
state:
description: Whether the record is present or absent
returned: success
type: string
sample: present
ttl:
description: The time-to-live of the resource record
returned: success
type: int
sample: 300
type:
description: The type of the resource record
returned: success
type: string
sample: A
record_data:
description: The resource record values
returned: success
type: list
sample: ['5.6.7.8', '9.10.11.12']
zone:
description: The dns name of the zone
returned: success
type: string
sample: example.com.
zone_id:
description: The Google Cloud DNS ID of the zone
returned: success
type: string
sample: example-com
'''
################################################################################
# Imports
################################################################################
import socket
from distutils.version import LooseVersion
try:
from libcloud import __version__ as LIBCLOUD_VERSION
from libcloud.common.google import InvalidRequestError
from libcloud.common.types import LibcloudError
from libcloud.dns.types import Provider
from libcloud.dns.types import RecordDoesNotExistError
from libcloud.dns.types import ZoneDoesNotExistError
HAS_LIBCLOUD = True
except ImportError:
HAS_LIBCLOUD = False
################################################################################
# Constants
################################################################################
# Apache libcloud 0.19.0 was the first to contain the non-beta Google Cloud DNS
# v1 API. Earlier versions contained the beta v1 API, which has since been
# deprecated and decommissioned.
MINIMUM_LIBCLOUD_VERSION = '0.19.0'
# The libcloud Google Cloud DNS provider.
PROVIDER = Provider.GOOGLE
# The records that libcloud's Google Cloud DNS provider supports.
#
# Libcloud has a RECORD_TYPE_MAP dictionary in the provider that also contains
# this information and is the authoritative source on which records are
# supported, but accessing the dictionary requires creating a Google Cloud DNS
# driver object, which is done in a helper module.
#
# I'm hard-coding the supported record types here, because they (hopefully!)
# shouldn't change much, and it allows me to use it as a "choices" parameter
# in an AnsibleModule argument_spec.
SUPPORTED_RECORD_TYPES = [ 'A', 'AAAA', 'CNAME', 'SRV', 'TXT', 'SOA', 'NS', 'MX', 'SPF', 'PTR' ]
################################################################################
# Functions
################################################################################
def create_record(module, gcdns, zone, record):
"""Creates or overwrites a resource record."""
overwrite = module.boolean(module.params['overwrite'])
record_name = module.params['record']
record_type = module.params['type']
ttl = module.params['ttl']
record_data = module.params['record_data']
data = dict(ttl=ttl, rrdatas=record_data)
# Google Cloud DNS wants the trailing dot on all DNS names.
if record_name[-1] != '.':
record_name = record_name + '.'
# If we found a record, we need to check if the values match.
if record is not None:
# If the record matches, we obviously don't have to change anything.
if _records_match(record.data['ttl'], record.data['rrdatas'], ttl, record_data):
return False
# The record doesn't match, so we need to check if we can overwrite it.
if not overwrite:
module.fail_json(
msg = 'cannot overwrite existing record, overwrite protection enabled',
changed = False
)
# The record either doesn't exist, or it exists and we can overwrite it.
if record is None and not module.check_mode:
# There's no existing record, so we'll just create it.
try:
gcdns.create_record(record_name, zone, record_type, data)
except InvalidRequestError as error:
if error.code == 'invalid':
# The resource record name and type are valid by themselves, but
# not when combined (e.g., an 'A' record with "www.example.com"
# as its value).
module.fail_json(
msg = 'value is invalid for the given type: ' +
"%s, got value: %s" % (record_type, record_data),
changed = False
)
elif error.code == 'cnameResourceRecordSetConflict':
# We're attempting to create a CNAME resource record when we
# already have another type of resource record with the name
# domain name.
module.fail_json(
msg = "non-CNAME resource record already exists: %s" % record_name,
changed = False
)
else:
# The error is something else that we don't know how to handle,
# so we'll just re-raise the exception.
raise
elif record is not None and not module.check_mode:
# The Google provider in libcloud doesn't support updating a record in
# place, so if the record already exists, we need to delete it and
# recreate it using the new information.
gcdns.delete_record(record)
try:
gcdns.create_record(record_name, zone, record_type, data)
except InvalidRequestError:
# Something blew up when creating the record. This will usually be a
# result of invalid value data in the new record. Unfortunately, we
# already changed the state of the record by deleting the old one,
# so we'll try to roll back before failing out.
try:
gcdns.create_record(record.name, record.zone, record.type, record.data)
module.fail_json(
msg = 'error updating record, the original record was restored',
changed = False
)
except LibcloudError:
# We deleted the old record, couldn't create the new record, and
# couldn't roll back. That really sucks. We'll dump the original
# record to the failure output so the user can resore it if
# necessary.
module.fail_json(
msg = 'error updating record, and could not restore original record, ' +
"original name: %s " % record.name +
"original zone: %s " % record.zone +
"original type: %s " % record.type +
"original data: %s" % record.data,
changed = True)
return True
def remove_record(module, gcdns, record):
"""Remove a resource record."""
overwrite = module.boolean(module.params['overwrite'])
ttl = module.params['ttl']
record_data = module.params['record_data']
# If there is no record, we're obviously done.
if record is None:
return False
# If there is an existing record, do our values match the values of the
# existing record?
if not overwrite:
if not _records_match(record.data['ttl'], record.data['rrdatas'], ttl, record_data):
module.fail_json(
msg = 'cannot delete due to non-matching ttl or record_data: ' +
"ttl: %d, record_data: %s " % (ttl, record_data) +
"original ttl: %d, original record_data: %s" % (record.data['ttl'], record.data['rrdatas']),
changed = False
)
# If we got to this point, we're okay to delete the record.
if not module.check_mode:
gcdns.delete_record(record)
return True
def _get_record(gcdns, zone, record_type, record_name):
"""Gets the record object for a given FQDN."""
# The record ID is a combination of its type and FQDN. For example, the
# ID of an A record for www.example.com would be 'A:www.example.com.'
record_id = "%s:%s" % (record_type, record_name)
try:
return gcdns.get_record(zone.id, record_id)
except RecordDoesNotExistError:
return None
def _get_zone(gcdns, zone_name, zone_id):
"""Gets the zone object for a given domain name."""
if zone_id is not None:
try:
return gcdns.get_zone(zone_id)
except ZoneDoesNotExistError:
return None
# To create a zone, we need to supply a domain name. However, to delete a
# zone, we need to supply a zone ID. Zone ID's are often based on domain
# names, but that's not guaranteed, so we'll iterate through the list of
# zones to see if we can find a matching domain name.
available_zones = gcdns.iterate_zones()
found_zone = None
for zone in available_zones:
if zone.domain == zone_name:
found_zone = zone
break
return found_zone
def _records_match(old_ttl, old_record_data, new_ttl, new_record_data):
"""Checks to see if original and new TTL and values match."""
matches = True
if old_ttl != new_ttl:
matches = False
if old_record_data != new_record_data:
matches = False
return matches
def _sanity_check(module):
"""Run sanity checks that don't depend on info from the zone/record."""
overwrite = module.params['overwrite']
record_name = module.params['record']
record_type = module.params['type']
state = module.params['state']
ttl = module.params['ttl']
record_data = module.params['record_data']
# Apache libcloud needs to be installed and at least the minimum version.
if not HAS_LIBCLOUD:
module.fail_json(
msg = 'This module requires Apache libcloud %s or greater' % MINIMUM_LIBCLOUD_VERSION,
changed = False
)
elif LooseVersion(LIBCLOUD_VERSION) < MINIMUM_LIBCLOUD_VERSION:
module.fail_json(
msg = 'This module requires Apache libcloud %s or greater' % MINIMUM_LIBCLOUD_VERSION,
changed = False
)
# A negative TTL is not permitted (how would they even work?!).
if ttl < 0:
module.fail_json(
msg = 'TTL cannot be less than zero, got: %d' % ttl,
changed = False
)
# Deleting SOA records is not permitted.
if record_type == 'SOA' and state == 'absent':
module.fail_json(msg='cannot delete SOA records', changed=False)
# Updating SOA records is not permitted.
if record_type == 'SOA' and state == 'present' and overwrite:
module.fail_json(msg='cannot update SOA records', changed=False)
# Some sanity checks depend on what value was supplied.
if record_data is not None and (state == 'present' or not overwrite):
# A records must contain valid IPv4 addresses.
if record_type == 'A':
for value in record_data:
try:
socket.inet_aton(value)
except socket.error:
module.fail_json(
msg = 'invalid A record value, got: %s' % value,
changed = False
)
# AAAA records must contain valid IPv6 addresses.
if record_type == 'AAAA':
for value in record_data:
try:
socket.inet_pton(socket.AF_INET6, value)
except socket.error:
module.fail_json(
msg = 'invalid AAAA record value, got: %s' % value,
changed = False
)
# CNAME and SOA records can't have multiple values.
if record_type in ['CNAME', 'SOA'] and len(record_data) > 1:
module.fail_json(
msg = 'CNAME or SOA records cannot have more than one value, ' +
"got: %s" % record_data,
changed = False
)
# Google Cloud DNS does not support wildcard NS records.
if record_type == 'NS' and record_name[0] == '*':
module.fail_json(
msg = "wildcard NS records not allowed, got: %s" % record_name,
changed = False
)
# Values for txt records must begin and end with a double quote.
if record_type == 'TXT':
for value in record_data:
if value[0] != '"' and value[-1] != '"':
module.fail_json(
msg = 'TXT record_data must be enclosed in double quotes, ' +
'got: %s' % value,
changed = False
)
def _additional_sanity_checks(module, zone):
"""Run input sanity checks that depend on info from the zone/record."""
overwrite = module.params['overwrite']
record_name = module.params['record']
record_type = module.params['type']
state = module.params['state']
# CNAME records are not allowed to have the same name as the root domain.
if record_type == 'CNAME' and record_name == zone.domain:
module.fail_json(
msg = 'CNAME records cannot match the zone name',
changed = False
)
# The root domain must always have an NS record.
if record_type == 'NS' and record_name == zone.domain and state == 'absent':
module.fail_json(
msg = 'cannot delete root NS records',
changed = False
)
# Updating NS records with the name as the root domain is not allowed
# because libcloud does not support in-place updates and root domain NS
# records cannot be removed.
if record_type == 'NS' and record_name == zone.domain and overwrite:
module.fail_json(
msg = 'cannot update existing root NS records',
changed = False
)
# SOA records with names that don't match the root domain are not permitted
# (and wouldn't make sense anyway).
if record_type == 'SOA' and record_name != zone.domain:
module.fail_json(
msg = 'non-root SOA records are not permitted, got: %s' % record_name,
changed = False
)
################################################################################
# Main
################################################################################
def main():
"""Main function"""
module = AnsibleModule(
argument_spec = dict(
state = dict(default='present', choices=['present', 'absent'], type='str'),
record = dict(required=True, aliases=['name'], type='str'),
zone = dict(type='str'),
zone_id = dict(type='str'),
type = dict(required=True, choices=SUPPORTED_RECORD_TYPES, type='str'),
record_data = dict(aliases=['value'], type='list'),
ttl = dict(default=300, type='int'),
overwrite = dict(default=False, type='bool'),
service_account_email = dict(type='str'),
pem_file = dict(type='path'),
credentials_file = dict(type='path'),
project_id = dict(type='str')
),
required_if = [
('state', 'present', ['record_data']),
('overwrite', False, ['record_data'])
],
required_one_of = [['zone', 'zone_id']],
supports_check_mode = True
)
_sanity_check(module)
record_name = module.params['record']
record_type = module.params['type']
state = module.params['state']
ttl = module.params['ttl']
zone_name = module.params['zone']
zone_id = module.params['zone_id']
json_output = dict(
state = state,
record = record_name,
zone = zone_name,
zone_id = zone_id,
type = record_type,
record_data = module.params['record_data'],
ttl = ttl,
overwrite = module.boolean(module.params['overwrite'])
)
# Google Cloud DNS wants the trailing dot on all DNS names.
if zone_name is not None and zone_name[-1] != '.':
zone_name = zone_name + '.'
if record_name[-1] != '.':
record_name = record_name + '.'
# Build a connection object that we can use to connect with Google Cloud
# DNS.
gcdns = gcdns_connect(module, provider=PROVIDER)
# We need to check that the zone we're creating a record for actually
# exists.
zone = _get_zone(gcdns, zone_name, zone_id)
if zone is None and zone_name is not None:
module.fail_json(
msg = 'zone name was not found: %s' % zone_name,
changed = False
)
elif zone is None and zone_id is not None:
module.fail_json(
msg = 'zone id was not found: %s' % zone_id,
changed = False
)
# Populate the returns with the actual zone information.
json_output['zone'] = zone.domain
json_output['zone_id'] = zone.id
# We also need to check if the record we want to create or remove actually
# exists.
try:
record = _get_record(gcdns, zone, record_type, record_name)
except InvalidRequestError:
# We gave Google Cloud DNS an invalid DNS record name.
module.fail_json(
msg = 'record name is invalid: %s' % record_name,
changed = False
)
_additional_sanity_checks(module, zone)
diff = dict()
# Build the 'before' diff
if record is None:
diff['before'] = ''
diff['before_header'] = '<absent>'
else:
diff['before'] = dict(
record = record.data['name'],
type = record.data['type'],
record_data = record.data['rrdatas'],
ttl = record.data['ttl']
)
diff['before_header'] = "%s:%s" % (record_type, record_name)
# Create, remove, or modify the record.
if state == 'present':
diff['after'] = dict(
record = record_name,
type = record_type,
record_data = module.params['record_data'],
ttl = ttl
)
diff['after_header'] = "%s:%s" % (record_type, record_name)
changed = create_record(module, gcdns, zone, record)
elif state == 'absent':
diff['after'] = ''
diff['after_header'] = '<absent>'
changed = remove_record(module, gcdns, record)
module.exit_json(changed=changed, diff=diff, **json_output)
from ansible.module_utils.basic import *
from ansible.module_utils.gcdns import *
if __name__ == '__main__':
main()
| gpl-3.0 |
Anonymike/pasta-bot | plugins/google_broken.py | 1 | 3457 | import random
from util import hook, http, text, database, web
import re
def api_get(kind, query):
"""Use the RESTful Google Search API"""
url = 'http://ajax.googleapis.com/ajax/services/search/%s?' \
'v=1.0&safe=off'
return http.get_json(url % kind, q=query)
@hook.command('search')
@hook.command('g')
@hook.command
def google(inp,db=None,chan=None):
"""google <query> -- Returns first google search result for <query>."""
trimlength = database.get(db,'channels','trimlength','chan',chan)
if not trimlength: trimlength = 9999
parsed = api_get('web', inp)
if not 200 <= parsed['responseStatus'] < 300:
raise IOError('error searching for pages: {}: {}'.format(parsed['responseStatus'], ''))
if not parsed['responseData']['results']:
return 'No results found.'
result = parsed['responseData']['results'][0]
title = http.unescape(result['titleNoFormatting'])
content = http.unescape(result['content'])
if not content: content = "No description available."
else: content = http.html.fromstring(content.replace('\n', '')).text_content()
return u'{} -- \x02{}\x02: "{}"'.format(result['unescapedUrl'], title, content)
# @hook.command('image')
@hook.command('gis')
@hook.command('gi')
@hook.command('image')
@hook.command
def googleimage(inp):
"""gis <query> -- Returns first Google Image result for <query>."""
parsed = api_get('images', inp)
if not 200 <= parsed['responseStatus'] < 300:
raise IOError('error searching for images: {}: {}'.format(parsed['responseStatus'], ''))
if not parsed['responseData']['results']:
return 'no images found'
return random.choice(parsed['responseData']['results'][:10])['unescapedUrl']
@hook.command
def gcalc(inp):
"gcalc <term> -- Calculate <term> with Google Calc."
soup = http.get_soup('http://www.google.com/search', q=inp)
result = soup.find('span', {'class': 'cwcot'})
formula = soup.find('span', {'class': 'cwclet'})
if not result:
return "Could not calculate '{}'".format(inp)
return u"{} {}".format(formula.contents[0].strip(),result.contents[0].strip())
@hook.regex(r'^\>(.*\.(gif|GIF|jpg|JPG|jpeg|JPEG|png|PNG|tiff|TIFF|bmp|BMP))\s?(\d+)?')
@hook.command
def implying(inp):
""">laughing girls.gif <num> -- Returns first Google Image result for <query>."""
try: search = inp.group(1)
except: search = inp
try: num = int(inp.group(3))
except: num = 0
if 'http' in search: return
parsed = api_get('images', search)
if not 200 <= parsed['responseStatus'] < 300:
raise IOError('error searching for images: {}: {}'.format(parsed['responseStatus'], ''))
if not parsed['responseData']['results']:
return 'no images found'
try: return u'\x033\x02>{}\x02\x03 {}'.format(search, parsed['responseData']['results'][:10][num]['unescapedUrl'])
except: return u'\x033\x02>{}\x02\x03 {}'.format(search, parsed['responseData']['results'][:10][0]['unescapedUrl'])
#return random.choice(parsed['responseData']['results'][:10])['unescapedUrl']
@hook.command('nym')
@hook.command('littleanon')
@hook.command('gfy')
@hook.command
def lmgtfy(inp, bot=None):
"lmgtfy [phrase] - Posts a google link for the specified phrase"
link = "http://lmgtfy.com/?q=%s" % http.quote_plus(inp)
try:
return web.isgd(link)
except (web.ShortenError, http.HTTPError):
return link
| gpl-3.0 |
rhurkes/chasegame | venv/lib/python2.7/site-packages/flask/sessions.py | 428 | 13107 | # -*- coding: utf-8 -*-
"""
flask.sessions
~~~~~~~~~~~~~~
Implements cookie based sessions based on itsdangerous.
:copyright: (c) 2012 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import uuid
import hashlib
from base64 import b64encode, b64decode
from datetime import datetime
from werkzeug.http import http_date, parse_date
from werkzeug.datastructures import CallbackDict
from . import Markup, json
from ._compat import iteritems, text_type
from itsdangerous import URLSafeTimedSerializer, BadSignature
def total_seconds(td):
return td.days * 60 * 60 * 24 + td.seconds
class SessionMixin(object):
"""Expands a basic dictionary with an accessors that are expected
by Flask extensions and users for the session.
"""
def _get_permanent(self):
return self.get('_permanent', False)
def _set_permanent(self, value):
self['_permanent'] = bool(value)
#: this reflects the ``'_permanent'`` key in the dict.
permanent = property(_get_permanent, _set_permanent)
del _get_permanent, _set_permanent
#: some session backends can tell you if a session is new, but that is
#: not necessarily guaranteed. Use with caution. The default mixin
#: implementation just hardcodes `False` in.
new = False
#: for some backends this will always be `True`, but some backends will
#: default this to false and detect changes in the dictionary for as
#: long as changes do not happen on mutable structures in the session.
#: The default mixin implementation just hardcodes `True` in.
modified = True
class TaggedJSONSerializer(object):
"""A customized JSON serializer that supports a few extra types that
we take for granted when serializing (tuples, markup objects, datetime).
"""
def dumps(self, value):
def _tag(value):
if isinstance(value, tuple):
return {' t': [_tag(x) for x in value]}
elif isinstance(value, uuid.UUID):
return {' u': value.hex}
elif isinstance(value, bytes):
return {' b': b64encode(value).decode('ascii')}
elif callable(getattr(value, '__html__', None)):
return {' m': text_type(value.__html__())}
elif isinstance(value, list):
return [_tag(x) for x in value]
elif isinstance(value, datetime):
return {' d': http_date(value)}
elif isinstance(value, dict):
return dict((k, _tag(v)) for k, v in iteritems(value))
elif isinstance(value, str):
try:
return text_type(value)
except UnicodeError:
raise UnexpectedUnicodeError(u'A byte string with '
u'non-ASCII data was passed to the session system '
u'which can only store unicode strings. Consider '
u'base64 encoding your string (String was %r)' % value)
return value
return json.dumps(_tag(value), separators=(',', ':'))
def loads(self, value):
def object_hook(obj):
if len(obj) != 1:
return obj
the_key, the_value = next(iteritems(obj))
if the_key == ' t':
return tuple(the_value)
elif the_key == ' u':
return uuid.UUID(the_value)
elif the_key == ' b':
return b64decode(the_value)
elif the_key == ' m':
return Markup(the_value)
elif the_key == ' d':
return parse_date(the_value)
return obj
return json.loads(value, object_hook=object_hook)
session_json_serializer = TaggedJSONSerializer()
class SecureCookieSession(CallbackDict, SessionMixin):
"""Baseclass for sessions based on signed cookies."""
def __init__(self, initial=None):
def on_update(self):
self.modified = True
CallbackDict.__init__(self, initial, on_update)
self.modified = False
class NullSession(SecureCookieSession):
"""Class used to generate nicer error messages if sessions are not
available. Will still allow read-only access to the empty session
but fail on setting.
"""
def _fail(self, *args, **kwargs):
raise RuntimeError('the session is unavailable because no secret '
'key was set. Set the secret_key on the '
'application to something unique and secret.')
__setitem__ = __delitem__ = clear = pop = popitem = \
update = setdefault = _fail
del _fail
class SessionInterface(object):
"""The basic interface you have to implement in order to replace the
default session interface which uses werkzeug's securecookie
implementation. The only methods you have to implement are
:meth:`open_session` and :meth:`save_session`, the others have
useful defaults which you don't need to change.
The session object returned by the :meth:`open_session` method has to
provide a dictionary like interface plus the properties and methods
from the :class:`SessionMixin`. We recommend just subclassing a dict
and adding that mixin::
class Session(dict, SessionMixin):
pass
If :meth:`open_session` returns `None` Flask will call into
:meth:`make_null_session` to create a session that acts as replacement
if the session support cannot work because some requirement is not
fulfilled. The default :class:`NullSession` class that is created
will complain that the secret key was not set.
To replace the session interface on an application all you have to do
is to assign :attr:`flask.Flask.session_interface`::
app = Flask(__name__)
app.session_interface = MySessionInterface()
.. versionadded:: 0.8
"""
#: :meth:`make_null_session` will look here for the class that should
#: be created when a null session is requested. Likewise the
#: :meth:`is_null_session` method will perform a typecheck against
#: this type.
null_session_class = NullSession
#: A flag that indicates if the session interface is pickle based.
#: This can be used by flask extensions to make a decision in regards
#: to how to deal with the session object.
#:
#: .. versionadded:: 0.10
pickle_based = False
def make_null_session(self, app):
"""Creates a null session which acts as a replacement object if the
real session support could not be loaded due to a configuration
error. This mainly aids the user experience because the job of the
null session is to still support lookup without complaining but
modifications are answered with a helpful error message of what
failed.
This creates an instance of :attr:`null_session_class` by default.
"""
return self.null_session_class()
def is_null_session(self, obj):
"""Checks if a given object is a null session. Null sessions are
not asked to be saved.
This checks if the object is an instance of :attr:`null_session_class`
by default.
"""
return isinstance(obj, self.null_session_class)
def get_cookie_domain(self, app):
"""Helpful helper method that returns the cookie domain that should
be used for the session cookie if session cookies are used.
"""
if app.config['SESSION_COOKIE_DOMAIN'] is not None:
return app.config['SESSION_COOKIE_DOMAIN']
if app.config['SERVER_NAME'] is not None:
# chop of the port which is usually not supported by browsers
rv = '.' + app.config['SERVER_NAME'].rsplit(':', 1)[0]
# Google chrome does not like cookies set to .localhost, so
# we just go with no domain then. Flask documents anyways that
# cross domain cookies need a fully qualified domain name
if rv == '.localhost':
rv = None
# If we infer the cookie domain from the server name we need
# to check if we are in a subpath. In that case we can't
# set a cross domain cookie.
if rv is not None:
path = self.get_cookie_path(app)
if path != '/':
rv = rv.lstrip('.')
return rv
def get_cookie_path(self, app):
"""Returns the path for which the cookie should be valid. The
default implementation uses the value from the SESSION_COOKIE_PATH``
config var if it's set, and falls back to ``APPLICATION_ROOT`` or
uses ``/`` if it's `None`.
"""
return app.config['SESSION_COOKIE_PATH'] or \
app.config['APPLICATION_ROOT'] or '/'
def get_cookie_httponly(self, app):
"""Returns True if the session cookie should be httponly. This
currently just returns the value of the ``SESSION_COOKIE_HTTPONLY``
config var.
"""
return app.config['SESSION_COOKIE_HTTPONLY']
def get_cookie_secure(self, app):
"""Returns True if the cookie should be secure. This currently
just returns the value of the ``SESSION_COOKIE_SECURE`` setting.
"""
return app.config['SESSION_COOKIE_SECURE']
def get_expiration_time(self, app, session):
"""A helper method that returns an expiration date for the session
or `None` if the session is linked to the browser session. The
default implementation returns now + the permanent session
lifetime configured on the application.
"""
if session.permanent:
return datetime.utcnow() + app.permanent_session_lifetime
def open_session(self, app, request):
"""This method has to be implemented and must either return `None`
in case the loading failed because of a configuration error or an
instance of a session object which implements a dictionary like
interface + the methods and attributes on :class:`SessionMixin`.
"""
raise NotImplementedError()
def save_session(self, app, session, response):
"""This is called for actual sessions returned by :meth:`open_session`
at the end of the request. This is still called during a request
context so if you absolutely need access to the request you can do
that.
"""
raise NotImplementedError()
class SecureCookieSessionInterface(SessionInterface):
"""The default session interface that stores sessions in signed cookies
through the :mod:`itsdangerous` module.
"""
#: the salt that should be applied on top of the secret key for the
#: signing of cookie based sessions.
salt = 'cookie-session'
#: the hash function to use for the signature. The default is sha1
digest_method = staticmethod(hashlib.sha1)
#: the name of the itsdangerous supported key derivation. The default
#: is hmac.
key_derivation = 'hmac'
#: A python serializer for the payload. The default is a compact
#: JSON derived serializer with support for some extra Python types
#: such as datetime objects or tuples.
serializer = session_json_serializer
session_class = SecureCookieSession
def get_signing_serializer(self, app):
if not app.secret_key:
return None
signer_kwargs = dict(
key_derivation=self.key_derivation,
digest_method=self.digest_method
)
return URLSafeTimedSerializer(app.secret_key, salt=self.salt,
serializer=self.serializer,
signer_kwargs=signer_kwargs)
def open_session(self, app, request):
s = self.get_signing_serializer(app)
if s is None:
return None
val = request.cookies.get(app.session_cookie_name)
if not val:
return self.session_class()
max_age = total_seconds(app.permanent_session_lifetime)
try:
data = s.loads(val, max_age=max_age)
return self.session_class(data)
except BadSignature:
return self.session_class()
def save_session(self, app, session, response):
domain = self.get_cookie_domain(app)
path = self.get_cookie_path(app)
if not session:
if session.modified:
response.delete_cookie(app.session_cookie_name,
domain=domain, path=path)
return
httponly = self.get_cookie_httponly(app)
secure = self.get_cookie_secure(app)
expires = self.get_expiration_time(app, session)
val = self.get_signing_serializer(app).dumps(dict(session))
response.set_cookie(app.session_cookie_name, val,
expires=expires, httponly=httponly,
domain=domain, path=path, secure=secure)
from flask.debughelpers import UnexpectedUnicodeError
| mit |
aequitas/home-assistant | homeassistant/components/homematicip_cloud/sensor.py | 2 | 12041 | """Support for HomematicIP Cloud sensors."""
import logging
from homematicip.aio.device import (
AsyncBrandSwitchMeasuring, AsyncFullFlushSwitchMeasuring,
AsyncHeatingThermostat, AsyncHeatingThermostatCompact, AsyncLightSensor,
AsyncMotionDetectorIndoor, AsyncMotionDetectorOutdoor,
AsyncMotionDetectorPushButton, AsyncPlugableSwitchMeasuring,
AsyncPresenceDetectorIndoor, AsyncTemperatureHumiditySensorDisplay,
AsyncTemperatureHumiditySensorOutdoor,
AsyncTemperatureHumiditySensorWithoutDisplay, AsyncWeatherSensor,
AsyncWeatherSensorPlus, AsyncWeatherSensorPro)
from homematicip.aio.home import AsyncHome
from homematicip.base.enums import ValveState
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_ILLUMINANCE, DEVICE_CLASS_POWER,
DEVICE_CLASS_TEMPERATURE, POWER_WATT, TEMP_CELSIUS)
from homeassistant.core import HomeAssistant
from . import DOMAIN as HMIPC_DOMAIN, HMIPC_HAPID, HomematicipGenericDevice
_LOGGER = logging.getLogger(__name__)
ATTR_TEMPERATURE_OFFSET = 'temperature_offset'
ATTR_WIND_DIRECTION = 'wind_direction'
ATTR_WIND_DIRECTION_VARIATION = 'wind_direction_variation_in_degree'
async def async_setup_platform(
hass, config, async_add_entities, discovery_info=None):
"""Set up the HomematicIP Cloud sensors devices."""
pass
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry,
async_add_entities) -> None:
"""Set up the HomematicIP Cloud sensors from a config entry."""
home = hass.data[HMIPC_DOMAIN][config_entry.data[HMIPC_HAPID]].home
devices = [HomematicipAccesspointStatus(home)]
for device in home.devices:
if isinstance(device, (AsyncHeatingThermostat,
AsyncHeatingThermostatCompact)):
devices.append(HomematicipHeatingThermostat(home, device))
devices.append(HomematicipTemperatureSensor(home, device))
if isinstance(device, (AsyncTemperatureHumiditySensorDisplay,
AsyncTemperatureHumiditySensorWithoutDisplay,
AsyncTemperatureHumiditySensorOutdoor,
AsyncWeatherSensor,
AsyncWeatherSensorPlus,
AsyncWeatherSensorPro)):
devices.append(HomematicipTemperatureSensor(home, device))
devices.append(HomematicipHumiditySensor(home, device))
if isinstance(device, (AsyncLightSensor, AsyncMotionDetectorIndoor,
AsyncMotionDetectorOutdoor,
AsyncMotionDetectorPushButton,
AsyncPresenceDetectorIndoor,
AsyncWeatherSensor,
AsyncWeatherSensorPlus,
AsyncWeatherSensorPro)):
devices.append(HomematicipIlluminanceSensor(home, device))
if isinstance(device, (AsyncPlugableSwitchMeasuring,
AsyncBrandSwitchMeasuring,
AsyncFullFlushSwitchMeasuring)):
devices.append(HomematicipPowerSensor(home, device))
if isinstance(device, (AsyncWeatherSensor,
AsyncWeatherSensorPlus,
AsyncWeatherSensorPro)):
devices.append(HomematicipWindspeedSensor(home, device))
if isinstance(device, (AsyncWeatherSensorPlus,
AsyncWeatherSensorPro)):
devices.append(HomematicipTodayRainSensor(home, device))
if devices:
async_add_entities(devices)
class HomematicipAccesspointStatus(HomematicipGenericDevice):
"""Representation of an HomeMaticIP Cloud access point."""
def __init__(self, home: AsyncHome) -> None:
"""Initialize access point device."""
super().__init__(home, home)
@property
def device_info(self):
"""Return device specific attributes."""
# Adds a sensor to the existing HAP device
return {
'identifiers': {
# Serial numbers of Homematic IP device
(HMIPC_DOMAIN, self._device.id)
}
}
@property
def icon(self) -> str:
"""Return the icon of the access point device."""
return 'mdi:access-point-network'
@property
def state(self) -> float:
"""Return the state of the access point."""
return self._home.dutyCycle
@property
def available(self) -> bool:
"""Device available."""
return self._home.connected
@property
def unit_of_measurement(self) -> str:
"""Return the unit this state is expressed in."""
return '%'
class HomematicipHeatingThermostat(HomematicipGenericDevice):
"""Represenation of a HomematicIP heating thermostat device."""
def __init__(self, home: AsyncHome, device) -> None:
"""Initialize heating thermostat device."""
super().__init__(home, device, 'Heating')
@property
def icon(self) -> str:
"""Return the icon."""
if super().icon:
return super().icon
if self._device.valveState != ValveState.ADAPTION_DONE:
return 'mdi:alert'
return 'mdi:radiator'
@property
def state(self) -> int:
"""Return the state of the radiator valve."""
if self._device.valveState != ValveState.ADAPTION_DONE:
return self._device.valveState
return round(self._device.valvePosition*100)
@property
def unit_of_measurement(self) -> str:
"""Return the unit this state is expressed in."""
return '%'
class HomematicipHumiditySensor(HomematicipGenericDevice):
"""Represenation of a HomematicIP Cloud humidity device."""
def __init__(self, home: AsyncHome, device) -> None:
"""Initialize the thermometer device."""
super().__init__(home, device, 'Humidity')
@property
def device_class(self) -> str:
"""Return the device class of the sensor."""
return DEVICE_CLASS_HUMIDITY
@property
def state(self) -> int:
"""Return the state."""
return self._device.humidity
@property
def unit_of_measurement(self) -> str:
"""Return the unit this state is expressed in."""
return '%'
class HomematicipTemperatureSensor(HomematicipGenericDevice):
"""Representation of a HomematicIP Cloud thermometer device."""
def __init__(self, home: AsyncHome, device) -> None:
"""Initialize the thermometer device."""
super().__init__(home, device, 'Temperature')
@property
def device_class(self) -> str:
"""Return the device class of the sensor."""
return DEVICE_CLASS_TEMPERATURE
@property
def state(self) -> float:
"""Return the state."""
if hasattr(self._device, 'valveActualTemperature'):
return self._device.valveActualTemperature
return self._device.actualTemperature
@property
def unit_of_measurement(self) -> str:
"""Return the unit this state is expressed in."""
return TEMP_CELSIUS
@property
def device_state_attributes(self):
"""Return the state attributes of the windspeed sensor."""
attr = super().device_state_attributes
if hasattr(self._device, 'temperatureOffset') and \
self._device.temperatureOffset:
attr[ATTR_TEMPERATURE_OFFSET] = self._device.temperatureOffset
return attr
class HomematicipIlluminanceSensor(HomematicipGenericDevice):
"""Represenation of a HomematicIP Illuminance device."""
def __init__(self, home: AsyncHome, device) -> None:
"""Initialize the device."""
super().__init__(home, device, 'Illuminance')
@property
def device_class(self) -> str:
"""Return the device class of the sensor."""
return DEVICE_CLASS_ILLUMINANCE
@property
def state(self) -> float:
"""Return the state."""
if hasattr(self._device, 'averageIllumination'):
return self._device.averageIllumination
return self._device.illumination
@property
def unit_of_measurement(self) -> str:
"""Return the unit this state is expressed in."""
return 'lx'
class HomematicipPowerSensor(HomematicipGenericDevice):
"""Represenation of a HomematicIP power measuring device."""
def __init__(self, home: AsyncHome, device) -> None:
"""Initialize the device."""
super().__init__(home, device, 'Power')
@property
def device_class(self) -> str:
"""Return the device class of the sensor."""
return DEVICE_CLASS_POWER
@property
def state(self) -> float:
"""Represenation of the HomematicIP power comsumption value."""
return self._device.currentPowerConsumption
@property
def unit_of_measurement(self) -> str:
"""Return the unit this state is expressed in."""
return POWER_WATT
class HomematicipWindspeedSensor(HomematicipGenericDevice):
"""Represenation of a HomematicIP wind speed sensor."""
def __init__(self, home: AsyncHome, device) -> None:
"""Initialize the device."""
super().__init__(home, device, 'Windspeed')
@property
def state(self) -> float:
"""Represenation of the HomematicIP wind speed value."""
return self._device.windSpeed
@property
def unit_of_measurement(self) -> str:
"""Return the unit this state is expressed in."""
return 'km/h'
@property
def device_state_attributes(self):
"""Return the state attributes of the wind speed sensor."""
attr = super().device_state_attributes
if hasattr(self._device, 'windDirection') and \
self._device.windDirection:
attr[ATTR_WIND_DIRECTION] = \
_get_wind_direction(self._device.windDirection)
if hasattr(self._device, 'windDirectionVariation') and \
self._device.windDirectionVariation:
attr[ATTR_WIND_DIRECTION_VARIATION] = \
self._device.windDirectionVariation
return attr
class HomematicipTodayRainSensor(HomematicipGenericDevice):
"""Represenation of a HomematicIP rain counter of a day sensor."""
def __init__(self, home: AsyncHome, device) -> None:
"""Initialize the device."""
super().__init__(home, device, 'Today Rain')
@property
def state(self) -> float:
"""Represenation of the HomematicIP todays rain value."""
return round(self._device.todayRainCounter, 2)
@property
def unit_of_measurement(self) -> str:
"""Return the unit this state is expressed in."""
return 'mm'
def _get_wind_direction(wind_direction_degree: float) -> str:
"""Convert wind direction degree to named direction."""
if 11.25 <= wind_direction_degree < 33.75:
return 'NNE'
if 33.75 <= wind_direction_degree < 56.25:
return 'NE'
if 56.25 <= wind_direction_degree < 78.75:
return 'ENE'
if 78.75 <= wind_direction_degree < 101.25:
return 'E'
if 101.25 <= wind_direction_degree < 123.75:
return 'ESE'
if 123.75 <= wind_direction_degree < 146.25:
return 'SE'
if 146.25 <= wind_direction_degree < 168.75:
return 'SSE'
if 168.75 <= wind_direction_degree < 191.25:
return 'S'
if 191.25 <= wind_direction_degree < 213.75:
return 'SSW'
if 213.75 <= wind_direction_degree < 236.25:
return 'SW'
if 236.25 <= wind_direction_degree < 258.75:
return 'WSW'
if 258.75 <= wind_direction_degree < 281.25:
return 'W'
if 281.25 <= wind_direction_degree < 303.75:
return 'WNW'
if 303.75 <= wind_direction_degree < 326.25:
return 'NW'
if 326.25 <= wind_direction_degree < 348.75:
return 'NNW'
return 'N'
| apache-2.0 |
boshnivolo/TIY-GitHub | node_modules/node-sass/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings_test.py | 395 | 65937 | #!/usr/bin/env python
# Copyright (c) 2012 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.
"""Unit tests for the MSVSSettings.py file."""
import StringIO
import unittest
import gyp.MSVSSettings as MSVSSettings
class TestSequenceFunctions(unittest.TestCase):
def setUp(self):
self.stderr = StringIO.StringIO()
def _ExpectedWarnings(self, expected):
"""Compares recorded lines to expected warnings."""
self.stderr.seek(0)
actual = self.stderr.read().split('\n')
actual = [line for line in actual if line]
self.assertEqual(sorted(expected), sorted(actual))
def testValidateMSVSSettings_tool_names(self):
"""Tests that only MSVS tool names are allowed."""
MSVSSettings.ValidateMSVSSettings(
{'VCCLCompilerTool': {},
'VCLinkerTool': {},
'VCMIDLTool': {},
'foo': {},
'VCResourceCompilerTool': {},
'VCLibrarianTool': {},
'VCManifestTool': {},
'ClCompile': {}},
self.stderr)
self._ExpectedWarnings([
'Warning: unrecognized tool foo',
'Warning: unrecognized tool ClCompile'])
def testValidateMSVSSettings_settings(self):
"""Tests that for invalid MSVS settings."""
MSVSSettings.ValidateMSVSSettings(
{'VCCLCompilerTool': {
'AdditionalIncludeDirectories': 'folder1;folder2',
'AdditionalOptions': ['string1', 'string2'],
'AdditionalUsingDirectories': 'folder1;folder2',
'AssemblerListingLocation': 'a_file_name',
'AssemblerOutput': '0',
'BasicRuntimeChecks': '5',
'BrowseInformation': 'fdkslj',
'BrowseInformationFile': 'a_file_name',
'BufferSecurityCheck': 'true',
'CallingConvention': '-1',
'CompileAs': '1',
'DebugInformationFormat': '2',
'DefaultCharIsUnsigned': 'true',
'Detect64BitPortabilityProblems': 'true',
'DisableLanguageExtensions': 'true',
'DisableSpecificWarnings': 'string1;string2',
'EnableEnhancedInstructionSet': '1',
'EnableFiberSafeOptimizations': 'true',
'EnableFunctionLevelLinking': 'true',
'EnableIntrinsicFunctions': 'true',
'EnablePREfast': 'true',
'Enableprefast': 'bogus',
'ErrorReporting': '1',
'ExceptionHandling': '1',
'ExpandAttributedSource': 'true',
'FavorSizeOrSpeed': '1',
'FloatingPointExceptions': 'true',
'FloatingPointModel': '1',
'ForceConformanceInForLoopScope': 'true',
'ForcedIncludeFiles': 'file1;file2',
'ForcedUsingFiles': 'file1;file2',
'GeneratePreprocessedFile': '1',
'GenerateXMLDocumentationFiles': 'true',
'IgnoreStandardIncludePath': 'true',
'InlineFunctionExpansion': '1',
'KeepComments': 'true',
'MinimalRebuild': 'true',
'ObjectFile': 'a_file_name',
'OmitDefaultLibName': 'true',
'OmitFramePointers': 'true',
'OpenMP': 'true',
'Optimization': '1',
'PrecompiledHeaderFile': 'a_file_name',
'PrecompiledHeaderThrough': 'a_file_name',
'PreprocessorDefinitions': 'string1;string2',
'ProgramDataBaseFileName': 'a_file_name',
'RuntimeLibrary': '1',
'RuntimeTypeInfo': 'true',
'ShowIncludes': 'true',
'SmallerTypeCheck': 'true',
'StringPooling': 'true',
'StructMemberAlignment': '1',
'SuppressStartupBanner': 'true',
'TreatWChar_tAsBuiltInType': 'true',
'UndefineAllPreprocessorDefinitions': 'true',
'UndefinePreprocessorDefinitions': 'string1;string2',
'UseFullPaths': 'true',
'UsePrecompiledHeader': '1',
'UseUnicodeResponseFiles': 'true',
'WarnAsError': 'true',
'WarningLevel': '1',
'WholeProgramOptimization': 'true',
'XMLDocumentationFileName': 'a_file_name',
'ZZXYZ': 'bogus'},
'VCLinkerTool': {
'AdditionalDependencies': 'file1;file2',
'AdditionalDependencies_excluded': 'file3',
'AdditionalLibraryDirectories': 'folder1;folder2',
'AdditionalManifestDependencies': 'file1;file2',
'AdditionalOptions': 'a string1',
'AddModuleNamesToAssembly': 'file1;file2',
'AllowIsolation': 'true',
'AssemblyDebug': '2',
'AssemblyLinkResource': 'file1;file2',
'BaseAddress': 'a string1',
'CLRImageType': '2',
'CLRThreadAttribute': '2',
'CLRUnmanagedCodeCheck': 'true',
'DataExecutionPrevention': '2',
'DelayLoadDLLs': 'file1;file2',
'DelaySign': 'true',
'Driver': '2',
'EmbedManagedResourceFile': 'file1;file2',
'EnableCOMDATFolding': '2',
'EnableUAC': 'true',
'EntryPointSymbol': 'a string1',
'ErrorReporting': '2',
'FixedBaseAddress': '2',
'ForceSymbolReferences': 'file1;file2',
'FunctionOrder': 'a_file_name',
'GenerateDebugInformation': 'true',
'GenerateManifest': 'true',
'GenerateMapFile': 'true',
'HeapCommitSize': 'a string1',
'HeapReserveSize': 'a string1',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreDefaultLibraryNames': 'file1;file2',
'IgnoreEmbeddedIDL': 'true',
'IgnoreImportLibrary': 'true',
'ImportLibrary': 'a_file_name',
'KeyContainer': 'a_file_name',
'KeyFile': 'a_file_name',
'LargeAddressAware': '2',
'LinkIncremental': '2',
'LinkLibraryDependencies': 'true',
'LinkTimeCodeGeneration': '2',
'ManifestFile': 'a_file_name',
'MapExports': 'true',
'MapFileName': 'a_file_name',
'MergedIDLBaseFileName': 'a_file_name',
'MergeSections': 'a string1',
'MidlCommandFile': 'a_file_name',
'ModuleDefinitionFile': 'a_file_name',
'OptimizeForWindows98': '1',
'OptimizeReferences': '2',
'OutputFile': 'a_file_name',
'PerUserRedirection': 'true',
'Profile': 'true',
'ProfileGuidedDatabase': 'a_file_name',
'ProgramDatabaseFile': 'a_file_name',
'RandomizedBaseAddress': '2',
'RegisterOutput': 'true',
'ResourceOnlyDLL': 'true',
'SetChecksum': 'true',
'ShowProgress': '2',
'StackCommitSize': 'a string1',
'StackReserveSize': 'a string1',
'StripPrivateSymbols': 'a_file_name',
'SubSystem': '2',
'SupportUnloadOfDelayLoadedDLL': 'true',
'SuppressStartupBanner': 'true',
'SwapRunFromCD': 'true',
'SwapRunFromNet': 'true',
'TargetMachine': '2',
'TerminalServerAware': '2',
'TurnOffAssemblyGeneration': 'true',
'TypeLibraryFile': 'a_file_name',
'TypeLibraryResourceID': '33',
'UACExecutionLevel': '2',
'UACUIAccess': 'true',
'UseLibraryDependencyInputs': 'true',
'UseUnicodeResponseFiles': 'true',
'Version': 'a string1'},
'VCMIDLTool': {
'AdditionalIncludeDirectories': 'folder1;folder2',
'AdditionalOptions': 'a string1',
'CPreprocessOptions': 'a string1',
'DefaultCharType': '1',
'DLLDataFileName': 'a_file_name',
'EnableErrorChecks': '1',
'ErrorCheckAllocations': 'true',
'ErrorCheckBounds': 'true',
'ErrorCheckEnumRange': 'true',
'ErrorCheckRefPointers': 'true',
'ErrorCheckStubData': 'true',
'GenerateStublessProxies': 'true',
'GenerateTypeLibrary': 'true',
'HeaderFileName': 'a_file_name',
'IgnoreStandardIncludePath': 'true',
'InterfaceIdentifierFileName': 'a_file_name',
'MkTypLibCompatible': 'true',
'notgood': 'bogus',
'OutputDirectory': 'a string1',
'PreprocessorDefinitions': 'string1;string2',
'ProxyFileName': 'a_file_name',
'RedirectOutputAndErrors': 'a_file_name',
'StructMemberAlignment': '1',
'SuppressStartupBanner': 'true',
'TargetEnvironment': '1',
'TypeLibraryName': 'a_file_name',
'UndefinePreprocessorDefinitions': 'string1;string2',
'ValidateParameters': 'true',
'WarnAsError': 'true',
'WarningLevel': '1'},
'VCResourceCompilerTool': {
'AdditionalOptions': 'a string1',
'AdditionalIncludeDirectories': 'folder1;folder2',
'Culture': '1003',
'IgnoreStandardIncludePath': 'true',
'notgood2': 'bogus',
'PreprocessorDefinitions': 'string1;string2',
'ResourceOutputFileName': 'a string1',
'ShowProgress': 'true',
'SuppressStartupBanner': 'true',
'UndefinePreprocessorDefinitions': 'string1;string2'},
'VCLibrarianTool': {
'AdditionalDependencies': 'file1;file2',
'AdditionalLibraryDirectories': 'folder1;folder2',
'AdditionalOptions': 'a string1',
'ExportNamedFunctions': 'string1;string2',
'ForceSymbolReferences': 'a string1',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreSpecificDefaultLibraries': 'file1;file2',
'LinkLibraryDependencies': 'true',
'ModuleDefinitionFile': 'a_file_name',
'OutputFile': 'a_file_name',
'SuppressStartupBanner': 'true',
'UseUnicodeResponseFiles': 'true'},
'VCManifestTool': {
'AdditionalManifestFiles': 'file1;file2',
'AdditionalOptions': 'a string1',
'AssemblyIdentity': 'a string1',
'ComponentFileName': 'a_file_name',
'DependencyInformationFile': 'a_file_name',
'GenerateCatalogFiles': 'true',
'InputResourceManifests': 'a string1',
'ManifestResourceFile': 'a_file_name',
'OutputManifestFile': 'a_file_name',
'RegistrarScriptFile': 'a_file_name',
'ReplacementsFile': 'a_file_name',
'SuppressStartupBanner': 'true',
'TypeLibraryFile': 'a_file_name',
'UpdateFileHashes': 'truel',
'UpdateFileHashesSearchPath': 'a_file_name',
'UseFAT32Workaround': 'true',
'UseUnicodeResponseFiles': 'true',
'VerboseOutput': 'true'}},
self.stderr)
self._ExpectedWarnings([
'Warning: for VCCLCompilerTool/BasicRuntimeChecks, '
'index value (5) not in expected range [0, 4)',
'Warning: for VCCLCompilerTool/BrowseInformation, '
"invalid literal for int() with base 10: 'fdkslj'",
'Warning: for VCCLCompilerTool/CallingConvention, '
'index value (-1) not in expected range [0, 4)',
'Warning: for VCCLCompilerTool/DebugInformationFormat, '
'converted value for 2 not specified.',
'Warning: unrecognized setting VCCLCompilerTool/Enableprefast',
'Warning: unrecognized setting VCCLCompilerTool/ZZXYZ',
'Warning: for VCLinkerTool/TargetMachine, '
'converted value for 2 not specified.',
'Warning: unrecognized setting VCMIDLTool/notgood',
'Warning: unrecognized setting VCResourceCompilerTool/notgood2',
'Warning: for VCManifestTool/UpdateFileHashes, '
"expected bool; got 'truel'"
''])
def testValidateMSBuildSettings_settings(self):
"""Tests that for invalid MSBuild settings."""
MSVSSettings.ValidateMSBuildSettings(
{'ClCompile': {
'AdditionalIncludeDirectories': 'folder1;folder2',
'AdditionalOptions': ['string1', 'string2'],
'AdditionalUsingDirectories': 'folder1;folder2',
'AssemblerListingLocation': 'a_file_name',
'AssemblerOutput': 'NoListing',
'BasicRuntimeChecks': 'StackFrameRuntimeCheck',
'BrowseInformation': 'false',
'BrowseInformationFile': 'a_file_name',
'BufferSecurityCheck': 'true',
'BuildingInIDE': 'true',
'CallingConvention': 'Cdecl',
'CompileAs': 'CompileAsC',
'CompileAsManaged': 'Pure',
'CreateHotpatchableImage': 'true',
'DebugInformationFormat': 'ProgramDatabase',
'DisableLanguageExtensions': 'true',
'DisableSpecificWarnings': 'string1;string2',
'EnableEnhancedInstructionSet': 'StreamingSIMDExtensions',
'EnableFiberSafeOptimizations': 'true',
'EnablePREfast': 'true',
'Enableprefast': 'bogus',
'ErrorReporting': 'Prompt',
'ExceptionHandling': 'SyncCThrow',
'ExpandAttributedSource': 'true',
'FavorSizeOrSpeed': 'Neither',
'FloatingPointExceptions': 'true',
'FloatingPointModel': 'Precise',
'ForceConformanceInForLoopScope': 'true',
'ForcedIncludeFiles': 'file1;file2',
'ForcedUsingFiles': 'file1;file2',
'FunctionLevelLinking': 'false',
'GenerateXMLDocumentationFiles': 'true',
'IgnoreStandardIncludePath': 'true',
'InlineFunctionExpansion': 'OnlyExplicitInline',
'IntrinsicFunctions': 'false',
'MinimalRebuild': 'true',
'MultiProcessorCompilation': 'true',
'ObjectFileName': 'a_file_name',
'OmitDefaultLibName': 'true',
'OmitFramePointers': 'true',
'OpenMPSupport': 'true',
'Optimization': 'Disabled',
'PrecompiledHeader': 'NotUsing',
'PrecompiledHeaderFile': 'a_file_name',
'PrecompiledHeaderOutputFile': 'a_file_name',
'PreprocessKeepComments': 'true',
'PreprocessorDefinitions': 'string1;string2',
'PreprocessOutputPath': 'a string1',
'PreprocessSuppressLineNumbers': 'false',
'PreprocessToFile': 'false',
'ProcessorNumber': '33',
'ProgramDataBaseFileName': 'a_file_name',
'RuntimeLibrary': 'MultiThreaded',
'RuntimeTypeInfo': 'true',
'ShowIncludes': 'true',
'SmallerTypeCheck': 'true',
'StringPooling': 'true',
'StructMemberAlignment': '1Byte',
'SuppressStartupBanner': 'true',
'TrackerLogDirectory': 'a_folder',
'TreatSpecificWarningsAsErrors': 'string1;string2',
'TreatWarningAsError': 'true',
'TreatWChar_tAsBuiltInType': 'true',
'UndefineAllPreprocessorDefinitions': 'true',
'UndefinePreprocessorDefinitions': 'string1;string2',
'UseFullPaths': 'true',
'UseUnicodeForAssemblerListing': 'true',
'WarningLevel': 'TurnOffAllWarnings',
'WholeProgramOptimization': 'true',
'XMLDocumentationFileName': 'a_file_name',
'ZZXYZ': 'bogus'},
'Link': {
'AdditionalDependencies': 'file1;file2',
'AdditionalLibraryDirectories': 'folder1;folder2',
'AdditionalManifestDependencies': 'file1;file2',
'AdditionalOptions': 'a string1',
'AddModuleNamesToAssembly': 'file1;file2',
'AllowIsolation': 'true',
'AssemblyDebug': '',
'AssemblyLinkResource': 'file1;file2',
'BaseAddress': 'a string1',
'BuildingInIDE': 'true',
'CLRImageType': 'ForceIJWImage',
'CLRSupportLastError': 'Enabled',
'CLRThreadAttribute': 'MTAThreadingAttribute',
'CLRUnmanagedCodeCheck': 'true',
'CreateHotPatchableImage': 'X86Image',
'DataExecutionPrevention': 'false',
'DelayLoadDLLs': 'file1;file2',
'DelaySign': 'true',
'Driver': 'NotSet',
'EmbedManagedResourceFile': 'file1;file2',
'EnableCOMDATFolding': 'false',
'EnableUAC': 'true',
'EntryPointSymbol': 'a string1',
'FixedBaseAddress': 'false',
'ForceFileOutput': 'Enabled',
'ForceSymbolReferences': 'file1;file2',
'FunctionOrder': 'a_file_name',
'GenerateDebugInformation': 'true',
'GenerateMapFile': 'true',
'HeapCommitSize': 'a string1',
'HeapReserveSize': 'a string1',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreEmbeddedIDL': 'true',
'IgnoreSpecificDefaultLibraries': 'a_file_list',
'ImageHasSafeExceptionHandlers': 'true',
'ImportLibrary': 'a_file_name',
'KeyContainer': 'a_file_name',
'KeyFile': 'a_file_name',
'LargeAddressAware': 'false',
'LinkDLL': 'true',
'LinkErrorReporting': 'SendErrorReport',
'LinkStatus': 'true',
'LinkTimeCodeGeneration': 'UseLinkTimeCodeGeneration',
'ManifestFile': 'a_file_name',
'MapExports': 'true',
'MapFileName': 'a_file_name',
'MergedIDLBaseFileName': 'a_file_name',
'MergeSections': 'a string1',
'MidlCommandFile': 'a_file_name',
'MinimumRequiredVersion': 'a string1',
'ModuleDefinitionFile': 'a_file_name',
'MSDOSStubFileName': 'a_file_name',
'NoEntryPoint': 'true',
'OptimizeReferences': 'false',
'OutputFile': 'a_file_name',
'PerUserRedirection': 'true',
'PreventDllBinding': 'true',
'Profile': 'true',
'ProfileGuidedDatabase': 'a_file_name',
'ProgramDatabaseFile': 'a_file_name',
'RandomizedBaseAddress': 'false',
'RegisterOutput': 'true',
'SectionAlignment': '33',
'SetChecksum': 'true',
'ShowProgress': 'LinkVerboseREF',
'SpecifySectionAttributes': 'a string1',
'StackCommitSize': 'a string1',
'StackReserveSize': 'a string1',
'StripPrivateSymbols': 'a_file_name',
'SubSystem': 'Console',
'SupportNobindOfDelayLoadedDLL': 'true',
'SupportUnloadOfDelayLoadedDLL': 'true',
'SuppressStartupBanner': 'true',
'SwapRunFromCD': 'true',
'SwapRunFromNET': 'true',
'TargetMachine': 'MachineX86',
'TerminalServerAware': 'false',
'TrackerLogDirectory': 'a_folder',
'TreatLinkerWarningAsErrors': 'true',
'TurnOffAssemblyGeneration': 'true',
'TypeLibraryFile': 'a_file_name',
'TypeLibraryResourceID': '33',
'UACExecutionLevel': 'AsInvoker',
'UACUIAccess': 'true',
'Version': 'a string1'},
'ResourceCompile': {
'AdditionalIncludeDirectories': 'folder1;folder2',
'AdditionalOptions': 'a string1',
'Culture': '0x236',
'IgnoreStandardIncludePath': 'true',
'NullTerminateStrings': 'true',
'PreprocessorDefinitions': 'string1;string2',
'ResourceOutputFileName': 'a string1',
'ShowProgress': 'true',
'SuppressStartupBanner': 'true',
'TrackerLogDirectory': 'a_folder',
'UndefinePreprocessorDefinitions': 'string1;string2'},
'Midl': {
'AdditionalIncludeDirectories': 'folder1;folder2',
'AdditionalOptions': 'a string1',
'ApplicationConfigurationMode': 'true',
'ClientStubFile': 'a_file_name',
'CPreprocessOptions': 'a string1',
'DefaultCharType': 'Signed',
'DllDataFileName': 'a_file_name',
'EnableErrorChecks': 'EnableCustom',
'ErrorCheckAllocations': 'true',
'ErrorCheckBounds': 'true',
'ErrorCheckEnumRange': 'true',
'ErrorCheckRefPointers': 'true',
'ErrorCheckStubData': 'true',
'GenerateClientFiles': 'Stub',
'GenerateServerFiles': 'None',
'GenerateStublessProxies': 'true',
'GenerateTypeLibrary': 'true',
'HeaderFileName': 'a_file_name',
'IgnoreStandardIncludePath': 'true',
'InterfaceIdentifierFileName': 'a_file_name',
'LocaleID': '33',
'MkTypLibCompatible': 'true',
'OutputDirectory': 'a string1',
'PreprocessorDefinitions': 'string1;string2',
'ProxyFileName': 'a_file_name',
'RedirectOutputAndErrors': 'a_file_name',
'ServerStubFile': 'a_file_name',
'StructMemberAlignment': 'NotSet',
'SuppressCompilerWarnings': 'true',
'SuppressStartupBanner': 'true',
'TargetEnvironment': 'Itanium',
'TrackerLogDirectory': 'a_folder',
'TypeLibFormat': 'NewFormat',
'TypeLibraryName': 'a_file_name',
'UndefinePreprocessorDefinitions': 'string1;string2',
'ValidateAllParameters': 'true',
'WarnAsError': 'true',
'WarningLevel': '1'},
'Lib': {
'AdditionalDependencies': 'file1;file2',
'AdditionalLibraryDirectories': 'folder1;folder2',
'AdditionalOptions': 'a string1',
'DisplayLibrary': 'a string1',
'ErrorReporting': 'PromptImmediately',
'ExportNamedFunctions': 'string1;string2',
'ForceSymbolReferences': 'a string1',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreSpecificDefaultLibraries': 'file1;file2',
'LinkTimeCodeGeneration': 'true',
'MinimumRequiredVersion': 'a string1',
'ModuleDefinitionFile': 'a_file_name',
'Name': 'a_file_name',
'OutputFile': 'a_file_name',
'RemoveObjects': 'file1;file2',
'SubSystem': 'Console',
'SuppressStartupBanner': 'true',
'TargetMachine': 'MachineX86i',
'TrackerLogDirectory': 'a_folder',
'TreatLibWarningAsErrors': 'true',
'UseUnicodeResponseFiles': 'true',
'Verbose': 'true'},
'Manifest': {
'AdditionalManifestFiles': 'file1;file2',
'AdditionalOptions': 'a string1',
'AssemblyIdentity': 'a string1',
'ComponentFileName': 'a_file_name',
'EnableDPIAwareness': 'fal',
'GenerateCatalogFiles': 'truel',
'GenerateCategoryTags': 'true',
'InputResourceManifests': 'a string1',
'ManifestFromManagedAssembly': 'a_file_name',
'notgood3': 'bogus',
'OutputManifestFile': 'a_file_name',
'OutputResourceManifests': 'a string1',
'RegistrarScriptFile': 'a_file_name',
'ReplacementsFile': 'a_file_name',
'SuppressDependencyElement': 'true',
'SuppressStartupBanner': 'true',
'TrackerLogDirectory': 'a_folder',
'TypeLibraryFile': 'a_file_name',
'UpdateFileHashes': 'true',
'UpdateFileHashesSearchPath': 'a_file_name',
'VerboseOutput': 'true'},
'ProjectReference': {
'LinkLibraryDependencies': 'true',
'UseLibraryDependencyInputs': 'true'},
'ManifestResourceCompile': {
'ResourceOutputFileName': 'a_file_name'},
'': {
'EmbedManifest': 'true',
'GenerateManifest': 'true',
'IgnoreImportLibrary': 'true',
'LinkIncremental': 'false'}},
self.stderr)
self._ExpectedWarnings([
'Warning: unrecognized setting ClCompile/Enableprefast',
'Warning: unrecognized setting ClCompile/ZZXYZ',
'Warning: unrecognized setting Manifest/notgood3',
'Warning: for Manifest/GenerateCatalogFiles, '
"expected bool; got 'truel'",
'Warning: for Lib/TargetMachine, unrecognized enumerated value '
'MachineX86i',
"Warning: for Manifest/EnableDPIAwareness, expected bool; got 'fal'"])
def testConvertToMSBuildSettings_empty(self):
"""Tests an empty conversion."""
msvs_settings = {}
expected_msbuild_settings = {}
actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(
msvs_settings,
self.stderr)
self.assertEqual(expected_msbuild_settings, actual_msbuild_settings)
self._ExpectedWarnings([])
def testConvertToMSBuildSettings_minimal(self):
"""Tests a minimal conversion."""
msvs_settings = {
'VCCLCompilerTool': {
'AdditionalIncludeDirectories': 'dir1',
'AdditionalOptions': '/foo',
'BasicRuntimeChecks': '0',
},
'VCLinkerTool': {
'LinkTimeCodeGeneration': '1',
'ErrorReporting': '1',
'DataExecutionPrevention': '2',
},
}
expected_msbuild_settings = {
'ClCompile': {
'AdditionalIncludeDirectories': 'dir1',
'AdditionalOptions': '/foo',
'BasicRuntimeChecks': 'Default',
},
'Link': {
'LinkTimeCodeGeneration': 'UseLinkTimeCodeGeneration',
'LinkErrorReporting': 'PromptImmediately',
'DataExecutionPrevention': 'true',
},
}
actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(
msvs_settings,
self.stderr)
self.assertEqual(expected_msbuild_settings, actual_msbuild_settings)
self._ExpectedWarnings([])
def testConvertToMSBuildSettings_warnings(self):
"""Tests conversion that generates warnings."""
msvs_settings = {
'VCCLCompilerTool': {
'AdditionalIncludeDirectories': '1',
'AdditionalOptions': '2',
# These are incorrect values:
'BasicRuntimeChecks': '12',
'BrowseInformation': '21',
'UsePrecompiledHeader': '13',
'GeneratePreprocessedFile': '14'},
'VCLinkerTool': {
# These are incorrect values:
'Driver': '10',
'LinkTimeCodeGeneration': '31',
'ErrorReporting': '21',
'FixedBaseAddress': '6'},
'VCResourceCompilerTool': {
# Custom
'Culture': '1003'}}
expected_msbuild_settings = {
'ClCompile': {
'AdditionalIncludeDirectories': '1',
'AdditionalOptions': '2'},
'Link': {},
'ResourceCompile': {
# Custom
'Culture': '0x03eb'}}
actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(
msvs_settings,
self.stderr)
self.assertEqual(expected_msbuild_settings, actual_msbuild_settings)
self._ExpectedWarnings([
'Warning: while converting VCCLCompilerTool/BasicRuntimeChecks to '
'MSBuild, index value (12) not in expected range [0, 4)',
'Warning: while converting VCCLCompilerTool/BrowseInformation to '
'MSBuild, index value (21) not in expected range [0, 3)',
'Warning: while converting VCCLCompilerTool/UsePrecompiledHeader to '
'MSBuild, index value (13) not in expected range [0, 3)',
'Warning: while converting VCCLCompilerTool/GeneratePreprocessedFile to '
'MSBuild, value must be one of [0, 1, 2]; got 14',
'Warning: while converting VCLinkerTool/Driver to '
'MSBuild, index value (10) not in expected range [0, 4)',
'Warning: while converting VCLinkerTool/LinkTimeCodeGeneration to '
'MSBuild, index value (31) not in expected range [0, 5)',
'Warning: while converting VCLinkerTool/ErrorReporting to '
'MSBuild, index value (21) not in expected range [0, 3)',
'Warning: while converting VCLinkerTool/FixedBaseAddress to '
'MSBuild, index value (6) not in expected range [0, 3)',
])
def testConvertToMSBuildSettings_full_synthetic(self):
"""Tests conversion of all the MSBuild settings."""
msvs_settings = {
'VCCLCompilerTool': {
'AdditionalIncludeDirectories': 'folder1;folder2;folder3',
'AdditionalOptions': 'a_string',
'AdditionalUsingDirectories': 'folder1;folder2;folder3',
'AssemblerListingLocation': 'a_file_name',
'AssemblerOutput': '0',
'BasicRuntimeChecks': '1',
'BrowseInformation': '2',
'BrowseInformationFile': 'a_file_name',
'BufferSecurityCheck': 'true',
'CallingConvention': '0',
'CompileAs': '1',
'DebugInformationFormat': '4',
'DefaultCharIsUnsigned': 'true',
'Detect64BitPortabilityProblems': 'true',
'DisableLanguageExtensions': 'true',
'DisableSpecificWarnings': 'd1;d2;d3',
'EnableEnhancedInstructionSet': '0',
'EnableFiberSafeOptimizations': 'true',
'EnableFunctionLevelLinking': 'true',
'EnableIntrinsicFunctions': 'true',
'EnablePREfast': 'true',
'ErrorReporting': '1',
'ExceptionHandling': '2',
'ExpandAttributedSource': 'true',
'FavorSizeOrSpeed': '0',
'FloatingPointExceptions': 'true',
'FloatingPointModel': '1',
'ForceConformanceInForLoopScope': 'true',
'ForcedIncludeFiles': 'file1;file2;file3',
'ForcedUsingFiles': 'file1;file2;file3',
'GeneratePreprocessedFile': '1',
'GenerateXMLDocumentationFiles': 'true',
'IgnoreStandardIncludePath': 'true',
'InlineFunctionExpansion': '2',
'KeepComments': 'true',
'MinimalRebuild': 'true',
'ObjectFile': 'a_file_name',
'OmitDefaultLibName': 'true',
'OmitFramePointers': 'true',
'OpenMP': 'true',
'Optimization': '3',
'PrecompiledHeaderFile': 'a_file_name',
'PrecompiledHeaderThrough': 'a_file_name',
'PreprocessorDefinitions': 'd1;d2;d3',
'ProgramDataBaseFileName': 'a_file_name',
'RuntimeLibrary': '0',
'RuntimeTypeInfo': 'true',
'ShowIncludes': 'true',
'SmallerTypeCheck': 'true',
'StringPooling': 'true',
'StructMemberAlignment': '1',
'SuppressStartupBanner': 'true',
'TreatWChar_tAsBuiltInType': 'true',
'UndefineAllPreprocessorDefinitions': 'true',
'UndefinePreprocessorDefinitions': 'd1;d2;d3',
'UseFullPaths': 'true',
'UsePrecompiledHeader': '1',
'UseUnicodeResponseFiles': 'true',
'WarnAsError': 'true',
'WarningLevel': '2',
'WholeProgramOptimization': 'true',
'XMLDocumentationFileName': 'a_file_name'},
'VCLinkerTool': {
'AdditionalDependencies': 'file1;file2;file3',
'AdditionalLibraryDirectories': 'folder1;folder2;folder3',
'AdditionalLibraryDirectories_excluded': 'folder1;folder2;folder3',
'AdditionalManifestDependencies': 'file1;file2;file3',
'AdditionalOptions': 'a_string',
'AddModuleNamesToAssembly': 'file1;file2;file3',
'AllowIsolation': 'true',
'AssemblyDebug': '0',
'AssemblyLinkResource': 'file1;file2;file3',
'BaseAddress': 'a_string',
'CLRImageType': '1',
'CLRThreadAttribute': '2',
'CLRUnmanagedCodeCheck': 'true',
'DataExecutionPrevention': '0',
'DelayLoadDLLs': 'file1;file2;file3',
'DelaySign': 'true',
'Driver': '1',
'EmbedManagedResourceFile': 'file1;file2;file3',
'EnableCOMDATFolding': '0',
'EnableUAC': 'true',
'EntryPointSymbol': 'a_string',
'ErrorReporting': '0',
'FixedBaseAddress': '1',
'ForceSymbolReferences': 'file1;file2;file3',
'FunctionOrder': 'a_file_name',
'GenerateDebugInformation': 'true',
'GenerateManifest': 'true',
'GenerateMapFile': 'true',
'HeapCommitSize': 'a_string',
'HeapReserveSize': 'a_string',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreDefaultLibraryNames': 'file1;file2;file3',
'IgnoreEmbeddedIDL': 'true',
'IgnoreImportLibrary': 'true',
'ImportLibrary': 'a_file_name',
'KeyContainer': 'a_file_name',
'KeyFile': 'a_file_name',
'LargeAddressAware': '2',
'LinkIncremental': '1',
'LinkLibraryDependencies': 'true',
'LinkTimeCodeGeneration': '2',
'ManifestFile': 'a_file_name',
'MapExports': 'true',
'MapFileName': 'a_file_name',
'MergedIDLBaseFileName': 'a_file_name',
'MergeSections': 'a_string',
'MidlCommandFile': 'a_file_name',
'ModuleDefinitionFile': 'a_file_name',
'OptimizeForWindows98': '1',
'OptimizeReferences': '0',
'OutputFile': 'a_file_name',
'PerUserRedirection': 'true',
'Profile': 'true',
'ProfileGuidedDatabase': 'a_file_name',
'ProgramDatabaseFile': 'a_file_name',
'RandomizedBaseAddress': '1',
'RegisterOutput': 'true',
'ResourceOnlyDLL': 'true',
'SetChecksum': 'true',
'ShowProgress': '0',
'StackCommitSize': 'a_string',
'StackReserveSize': 'a_string',
'StripPrivateSymbols': 'a_file_name',
'SubSystem': '2',
'SupportUnloadOfDelayLoadedDLL': 'true',
'SuppressStartupBanner': 'true',
'SwapRunFromCD': 'true',
'SwapRunFromNet': 'true',
'TargetMachine': '3',
'TerminalServerAware': '2',
'TurnOffAssemblyGeneration': 'true',
'TypeLibraryFile': 'a_file_name',
'TypeLibraryResourceID': '33',
'UACExecutionLevel': '1',
'UACUIAccess': 'true',
'UseLibraryDependencyInputs': 'false',
'UseUnicodeResponseFiles': 'true',
'Version': 'a_string'},
'VCResourceCompilerTool': {
'AdditionalIncludeDirectories': 'folder1;folder2;folder3',
'AdditionalOptions': 'a_string',
'Culture': '1003',
'IgnoreStandardIncludePath': 'true',
'PreprocessorDefinitions': 'd1;d2;d3',
'ResourceOutputFileName': 'a_string',
'ShowProgress': 'true',
'SuppressStartupBanner': 'true',
'UndefinePreprocessorDefinitions': 'd1;d2;d3'},
'VCMIDLTool': {
'AdditionalIncludeDirectories': 'folder1;folder2;folder3',
'AdditionalOptions': 'a_string',
'CPreprocessOptions': 'a_string',
'DefaultCharType': '0',
'DLLDataFileName': 'a_file_name',
'EnableErrorChecks': '2',
'ErrorCheckAllocations': 'true',
'ErrorCheckBounds': 'true',
'ErrorCheckEnumRange': 'true',
'ErrorCheckRefPointers': 'true',
'ErrorCheckStubData': 'true',
'GenerateStublessProxies': 'true',
'GenerateTypeLibrary': 'true',
'HeaderFileName': 'a_file_name',
'IgnoreStandardIncludePath': 'true',
'InterfaceIdentifierFileName': 'a_file_name',
'MkTypLibCompatible': 'true',
'OutputDirectory': 'a_string',
'PreprocessorDefinitions': 'd1;d2;d3',
'ProxyFileName': 'a_file_name',
'RedirectOutputAndErrors': 'a_file_name',
'StructMemberAlignment': '3',
'SuppressStartupBanner': 'true',
'TargetEnvironment': '1',
'TypeLibraryName': 'a_file_name',
'UndefinePreprocessorDefinitions': 'd1;d2;d3',
'ValidateParameters': 'true',
'WarnAsError': 'true',
'WarningLevel': '4'},
'VCLibrarianTool': {
'AdditionalDependencies': 'file1;file2;file3',
'AdditionalLibraryDirectories': 'folder1;folder2;folder3',
'AdditionalLibraryDirectories_excluded': 'folder1;folder2;folder3',
'AdditionalOptions': 'a_string',
'ExportNamedFunctions': 'd1;d2;d3',
'ForceSymbolReferences': 'a_string',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreSpecificDefaultLibraries': 'file1;file2;file3',
'LinkLibraryDependencies': 'true',
'ModuleDefinitionFile': 'a_file_name',
'OutputFile': 'a_file_name',
'SuppressStartupBanner': 'true',
'UseUnicodeResponseFiles': 'true'},
'VCManifestTool': {
'AdditionalManifestFiles': 'file1;file2;file3',
'AdditionalOptions': 'a_string',
'AssemblyIdentity': 'a_string',
'ComponentFileName': 'a_file_name',
'DependencyInformationFile': 'a_file_name',
'EmbedManifest': 'true',
'GenerateCatalogFiles': 'true',
'InputResourceManifests': 'a_string',
'ManifestResourceFile': 'my_name',
'OutputManifestFile': 'a_file_name',
'RegistrarScriptFile': 'a_file_name',
'ReplacementsFile': 'a_file_name',
'SuppressStartupBanner': 'true',
'TypeLibraryFile': 'a_file_name',
'UpdateFileHashes': 'true',
'UpdateFileHashesSearchPath': 'a_file_name',
'UseFAT32Workaround': 'true',
'UseUnicodeResponseFiles': 'true',
'VerboseOutput': 'true'}}
expected_msbuild_settings = {
'ClCompile': {
'AdditionalIncludeDirectories': 'folder1;folder2;folder3',
'AdditionalOptions': 'a_string /J',
'AdditionalUsingDirectories': 'folder1;folder2;folder3',
'AssemblerListingLocation': 'a_file_name',
'AssemblerOutput': 'NoListing',
'BasicRuntimeChecks': 'StackFrameRuntimeCheck',
'BrowseInformation': 'true',
'BrowseInformationFile': 'a_file_name',
'BufferSecurityCheck': 'true',
'CallingConvention': 'Cdecl',
'CompileAs': 'CompileAsC',
'DebugInformationFormat': 'EditAndContinue',
'DisableLanguageExtensions': 'true',
'DisableSpecificWarnings': 'd1;d2;d3',
'EnableEnhancedInstructionSet': 'NotSet',
'EnableFiberSafeOptimizations': 'true',
'EnablePREfast': 'true',
'ErrorReporting': 'Prompt',
'ExceptionHandling': 'Async',
'ExpandAttributedSource': 'true',
'FavorSizeOrSpeed': 'Neither',
'FloatingPointExceptions': 'true',
'FloatingPointModel': 'Strict',
'ForceConformanceInForLoopScope': 'true',
'ForcedIncludeFiles': 'file1;file2;file3',
'ForcedUsingFiles': 'file1;file2;file3',
'FunctionLevelLinking': 'true',
'GenerateXMLDocumentationFiles': 'true',
'IgnoreStandardIncludePath': 'true',
'InlineFunctionExpansion': 'AnySuitable',
'IntrinsicFunctions': 'true',
'MinimalRebuild': 'true',
'ObjectFileName': 'a_file_name',
'OmitDefaultLibName': 'true',
'OmitFramePointers': 'true',
'OpenMPSupport': 'true',
'Optimization': 'Full',
'PrecompiledHeader': 'Create',
'PrecompiledHeaderFile': 'a_file_name',
'PrecompiledHeaderOutputFile': 'a_file_name',
'PreprocessKeepComments': 'true',
'PreprocessorDefinitions': 'd1;d2;d3',
'PreprocessSuppressLineNumbers': 'false',
'PreprocessToFile': 'true',
'ProgramDataBaseFileName': 'a_file_name',
'RuntimeLibrary': 'MultiThreaded',
'RuntimeTypeInfo': 'true',
'ShowIncludes': 'true',
'SmallerTypeCheck': 'true',
'StringPooling': 'true',
'StructMemberAlignment': '1Byte',
'SuppressStartupBanner': 'true',
'TreatWarningAsError': 'true',
'TreatWChar_tAsBuiltInType': 'true',
'UndefineAllPreprocessorDefinitions': 'true',
'UndefinePreprocessorDefinitions': 'd1;d2;d3',
'UseFullPaths': 'true',
'WarningLevel': 'Level2',
'WholeProgramOptimization': 'true',
'XMLDocumentationFileName': 'a_file_name'},
'Link': {
'AdditionalDependencies': 'file1;file2;file3',
'AdditionalLibraryDirectories': 'folder1;folder2;folder3',
'AdditionalManifestDependencies': 'file1;file2;file3',
'AdditionalOptions': 'a_string',
'AddModuleNamesToAssembly': 'file1;file2;file3',
'AllowIsolation': 'true',
'AssemblyDebug': '',
'AssemblyLinkResource': 'file1;file2;file3',
'BaseAddress': 'a_string',
'CLRImageType': 'ForceIJWImage',
'CLRThreadAttribute': 'STAThreadingAttribute',
'CLRUnmanagedCodeCheck': 'true',
'DataExecutionPrevention': '',
'DelayLoadDLLs': 'file1;file2;file3',
'DelaySign': 'true',
'Driver': 'Driver',
'EmbedManagedResourceFile': 'file1;file2;file3',
'EnableCOMDATFolding': '',
'EnableUAC': 'true',
'EntryPointSymbol': 'a_string',
'FixedBaseAddress': 'false',
'ForceSymbolReferences': 'file1;file2;file3',
'FunctionOrder': 'a_file_name',
'GenerateDebugInformation': 'true',
'GenerateMapFile': 'true',
'HeapCommitSize': 'a_string',
'HeapReserveSize': 'a_string',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreEmbeddedIDL': 'true',
'IgnoreSpecificDefaultLibraries': 'file1;file2;file3',
'ImportLibrary': 'a_file_name',
'KeyContainer': 'a_file_name',
'KeyFile': 'a_file_name',
'LargeAddressAware': 'true',
'LinkErrorReporting': 'NoErrorReport',
'LinkTimeCodeGeneration': 'PGInstrument',
'ManifestFile': 'a_file_name',
'MapExports': 'true',
'MapFileName': 'a_file_name',
'MergedIDLBaseFileName': 'a_file_name',
'MergeSections': 'a_string',
'MidlCommandFile': 'a_file_name',
'ModuleDefinitionFile': 'a_file_name',
'NoEntryPoint': 'true',
'OptimizeReferences': '',
'OutputFile': 'a_file_name',
'PerUserRedirection': 'true',
'Profile': 'true',
'ProfileGuidedDatabase': 'a_file_name',
'ProgramDatabaseFile': 'a_file_name',
'RandomizedBaseAddress': 'false',
'RegisterOutput': 'true',
'SetChecksum': 'true',
'ShowProgress': 'NotSet',
'StackCommitSize': 'a_string',
'StackReserveSize': 'a_string',
'StripPrivateSymbols': 'a_file_name',
'SubSystem': 'Windows',
'SupportUnloadOfDelayLoadedDLL': 'true',
'SuppressStartupBanner': 'true',
'SwapRunFromCD': 'true',
'SwapRunFromNET': 'true',
'TargetMachine': 'MachineARM',
'TerminalServerAware': 'true',
'TurnOffAssemblyGeneration': 'true',
'TypeLibraryFile': 'a_file_name',
'TypeLibraryResourceID': '33',
'UACExecutionLevel': 'HighestAvailable',
'UACUIAccess': 'true',
'Version': 'a_string'},
'ResourceCompile': {
'AdditionalIncludeDirectories': 'folder1;folder2;folder3',
'AdditionalOptions': 'a_string',
'Culture': '0x03eb',
'IgnoreStandardIncludePath': 'true',
'PreprocessorDefinitions': 'd1;d2;d3',
'ResourceOutputFileName': 'a_string',
'ShowProgress': 'true',
'SuppressStartupBanner': 'true',
'UndefinePreprocessorDefinitions': 'd1;d2;d3'},
'Midl': {
'AdditionalIncludeDirectories': 'folder1;folder2;folder3',
'AdditionalOptions': 'a_string',
'CPreprocessOptions': 'a_string',
'DefaultCharType': 'Unsigned',
'DllDataFileName': 'a_file_name',
'EnableErrorChecks': 'All',
'ErrorCheckAllocations': 'true',
'ErrorCheckBounds': 'true',
'ErrorCheckEnumRange': 'true',
'ErrorCheckRefPointers': 'true',
'ErrorCheckStubData': 'true',
'GenerateStublessProxies': 'true',
'GenerateTypeLibrary': 'true',
'HeaderFileName': 'a_file_name',
'IgnoreStandardIncludePath': 'true',
'InterfaceIdentifierFileName': 'a_file_name',
'MkTypLibCompatible': 'true',
'OutputDirectory': 'a_string',
'PreprocessorDefinitions': 'd1;d2;d3',
'ProxyFileName': 'a_file_name',
'RedirectOutputAndErrors': 'a_file_name',
'StructMemberAlignment': '4',
'SuppressStartupBanner': 'true',
'TargetEnvironment': 'Win32',
'TypeLibraryName': 'a_file_name',
'UndefinePreprocessorDefinitions': 'd1;d2;d3',
'ValidateAllParameters': 'true',
'WarnAsError': 'true',
'WarningLevel': '4'},
'Lib': {
'AdditionalDependencies': 'file1;file2;file3',
'AdditionalLibraryDirectories': 'folder1;folder2;folder3',
'AdditionalOptions': 'a_string',
'ExportNamedFunctions': 'd1;d2;d3',
'ForceSymbolReferences': 'a_string',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreSpecificDefaultLibraries': 'file1;file2;file3',
'ModuleDefinitionFile': 'a_file_name',
'OutputFile': 'a_file_name',
'SuppressStartupBanner': 'true',
'UseUnicodeResponseFiles': 'true'},
'Manifest': {
'AdditionalManifestFiles': 'file1;file2;file3',
'AdditionalOptions': 'a_string',
'AssemblyIdentity': 'a_string',
'ComponentFileName': 'a_file_name',
'GenerateCatalogFiles': 'true',
'InputResourceManifests': 'a_string',
'OutputManifestFile': 'a_file_name',
'RegistrarScriptFile': 'a_file_name',
'ReplacementsFile': 'a_file_name',
'SuppressStartupBanner': 'true',
'TypeLibraryFile': 'a_file_name',
'UpdateFileHashes': 'true',
'UpdateFileHashesSearchPath': 'a_file_name',
'VerboseOutput': 'true'},
'ManifestResourceCompile': {
'ResourceOutputFileName': 'my_name'},
'ProjectReference': {
'LinkLibraryDependencies': 'true',
'UseLibraryDependencyInputs': 'false'},
'': {
'EmbedManifest': 'true',
'GenerateManifest': 'true',
'IgnoreImportLibrary': 'true',
'LinkIncremental': 'false'}}
actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(
msvs_settings,
self.stderr)
self.assertEqual(expected_msbuild_settings, actual_msbuild_settings)
self._ExpectedWarnings([])
def testConvertToMSBuildSettings_actual(self):
"""Tests the conversion of an actual project.
A VS2008 project with most of the options defined was created through the
VS2008 IDE. It was then converted to VS2010. The tool settings found in
the .vcproj and .vcxproj files were converted to the two dictionaries
msvs_settings and expected_msbuild_settings.
Note that for many settings, the VS2010 converter adds macros like
%(AdditionalIncludeDirectories) to make sure than inherited values are
included. Since the Gyp projects we generate do not use inheritance,
we removed these macros. They were:
ClCompile:
AdditionalIncludeDirectories: ';%(AdditionalIncludeDirectories)'
AdditionalOptions: ' %(AdditionalOptions)'
AdditionalUsingDirectories: ';%(AdditionalUsingDirectories)'
DisableSpecificWarnings: ';%(DisableSpecificWarnings)',
ForcedIncludeFiles: ';%(ForcedIncludeFiles)',
ForcedUsingFiles: ';%(ForcedUsingFiles)',
PreprocessorDefinitions: ';%(PreprocessorDefinitions)',
UndefinePreprocessorDefinitions:
';%(UndefinePreprocessorDefinitions)',
Link:
AdditionalDependencies: ';%(AdditionalDependencies)',
AdditionalLibraryDirectories: ';%(AdditionalLibraryDirectories)',
AdditionalManifestDependencies:
';%(AdditionalManifestDependencies)',
AdditionalOptions: ' %(AdditionalOptions)',
AddModuleNamesToAssembly: ';%(AddModuleNamesToAssembly)',
AssemblyLinkResource: ';%(AssemblyLinkResource)',
DelayLoadDLLs: ';%(DelayLoadDLLs)',
EmbedManagedResourceFile: ';%(EmbedManagedResourceFile)',
ForceSymbolReferences: ';%(ForceSymbolReferences)',
IgnoreSpecificDefaultLibraries:
';%(IgnoreSpecificDefaultLibraries)',
ResourceCompile:
AdditionalIncludeDirectories: ';%(AdditionalIncludeDirectories)',
AdditionalOptions: ' %(AdditionalOptions)',
PreprocessorDefinitions: ';%(PreprocessorDefinitions)',
Manifest:
AdditionalManifestFiles: ';%(AdditionalManifestFiles)',
AdditionalOptions: ' %(AdditionalOptions)',
InputResourceManifests: ';%(InputResourceManifests)',
"""
msvs_settings = {
'VCCLCompilerTool': {
'AdditionalIncludeDirectories': 'dir1',
'AdditionalOptions': '/more',
'AdditionalUsingDirectories': 'test',
'AssemblerListingLocation': '$(IntDir)\\a',
'AssemblerOutput': '1',
'BasicRuntimeChecks': '3',
'BrowseInformation': '1',
'BrowseInformationFile': '$(IntDir)\\e',
'BufferSecurityCheck': 'false',
'CallingConvention': '1',
'CompileAs': '1',
'DebugInformationFormat': '4',
'DefaultCharIsUnsigned': 'true',
'Detect64BitPortabilityProblems': 'true',
'DisableLanguageExtensions': 'true',
'DisableSpecificWarnings': 'abc',
'EnableEnhancedInstructionSet': '1',
'EnableFiberSafeOptimizations': 'true',
'EnableFunctionLevelLinking': 'true',
'EnableIntrinsicFunctions': 'true',
'EnablePREfast': 'true',
'ErrorReporting': '2',
'ExceptionHandling': '2',
'ExpandAttributedSource': 'true',
'FavorSizeOrSpeed': '2',
'FloatingPointExceptions': 'true',
'FloatingPointModel': '1',
'ForceConformanceInForLoopScope': 'false',
'ForcedIncludeFiles': 'def',
'ForcedUsingFiles': 'ge',
'GeneratePreprocessedFile': '2',
'GenerateXMLDocumentationFiles': 'true',
'IgnoreStandardIncludePath': 'true',
'InlineFunctionExpansion': '1',
'KeepComments': 'true',
'MinimalRebuild': 'true',
'ObjectFile': '$(IntDir)\\b',
'OmitDefaultLibName': 'true',
'OmitFramePointers': 'true',
'OpenMP': 'true',
'Optimization': '3',
'PrecompiledHeaderFile': '$(IntDir)\\$(TargetName).pche',
'PrecompiledHeaderThrough': 'StdAfx.hd',
'PreprocessorDefinitions': 'WIN32;_DEBUG;_CONSOLE',
'ProgramDataBaseFileName': '$(IntDir)\\vc90b.pdb',
'RuntimeLibrary': '3',
'RuntimeTypeInfo': 'false',
'ShowIncludes': 'true',
'SmallerTypeCheck': 'true',
'StringPooling': 'true',
'StructMemberAlignment': '3',
'SuppressStartupBanner': 'false',
'TreatWChar_tAsBuiltInType': 'false',
'UndefineAllPreprocessorDefinitions': 'true',
'UndefinePreprocessorDefinitions': 'wer',
'UseFullPaths': 'true',
'UsePrecompiledHeader': '0',
'UseUnicodeResponseFiles': 'false',
'WarnAsError': 'true',
'WarningLevel': '3',
'WholeProgramOptimization': 'true',
'XMLDocumentationFileName': '$(IntDir)\\c'},
'VCLinkerTool': {
'AdditionalDependencies': 'zx',
'AdditionalLibraryDirectories': 'asd',
'AdditionalManifestDependencies': 's2',
'AdditionalOptions': '/mor2',
'AddModuleNamesToAssembly': 'd1',
'AllowIsolation': 'false',
'AssemblyDebug': '1',
'AssemblyLinkResource': 'd5',
'BaseAddress': '23423',
'CLRImageType': '3',
'CLRThreadAttribute': '1',
'CLRUnmanagedCodeCheck': 'true',
'DataExecutionPrevention': '0',
'DelayLoadDLLs': 'd4',
'DelaySign': 'true',
'Driver': '2',
'EmbedManagedResourceFile': 'd2',
'EnableCOMDATFolding': '1',
'EnableUAC': 'false',
'EntryPointSymbol': 'f5',
'ErrorReporting': '2',
'FixedBaseAddress': '1',
'ForceSymbolReferences': 'd3',
'FunctionOrder': 'fssdfsd',
'GenerateDebugInformation': 'true',
'GenerateManifest': 'false',
'GenerateMapFile': 'true',
'HeapCommitSize': '13',
'HeapReserveSize': '12',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreDefaultLibraryNames': 'flob;flok',
'IgnoreEmbeddedIDL': 'true',
'IgnoreImportLibrary': 'true',
'ImportLibrary': 'f4',
'KeyContainer': 'f7',
'KeyFile': 'f6',
'LargeAddressAware': '2',
'LinkIncremental': '0',
'LinkLibraryDependencies': 'false',
'LinkTimeCodeGeneration': '1',
'ManifestFile':
'$(IntDir)\\$(TargetFileName).2intermediate.manifest',
'MapExports': 'true',
'MapFileName': 'd5',
'MergedIDLBaseFileName': 'f2',
'MergeSections': 'f5',
'MidlCommandFile': 'f1',
'ModuleDefinitionFile': 'sdsd',
'OptimizeForWindows98': '2',
'OptimizeReferences': '2',
'OutputFile': '$(OutDir)\\$(ProjectName)2.exe',
'PerUserRedirection': 'true',
'Profile': 'true',
'ProfileGuidedDatabase': '$(TargetDir)$(TargetName).pgdd',
'ProgramDatabaseFile': 'Flob.pdb',
'RandomizedBaseAddress': '1',
'RegisterOutput': 'true',
'ResourceOnlyDLL': 'true',
'SetChecksum': 'false',
'ShowProgress': '1',
'StackCommitSize': '15',
'StackReserveSize': '14',
'StripPrivateSymbols': 'd3',
'SubSystem': '1',
'SupportUnloadOfDelayLoadedDLL': 'true',
'SuppressStartupBanner': 'false',
'SwapRunFromCD': 'true',
'SwapRunFromNet': 'true',
'TargetMachine': '1',
'TerminalServerAware': '1',
'TurnOffAssemblyGeneration': 'true',
'TypeLibraryFile': 'f3',
'TypeLibraryResourceID': '12',
'UACExecutionLevel': '2',
'UACUIAccess': 'true',
'UseLibraryDependencyInputs': 'true',
'UseUnicodeResponseFiles': 'false',
'Version': '333'},
'VCResourceCompilerTool': {
'AdditionalIncludeDirectories': 'f3',
'AdditionalOptions': '/more3',
'Culture': '3084',
'IgnoreStandardIncludePath': 'true',
'PreprocessorDefinitions': '_UNICODE;UNICODE2',
'ResourceOutputFileName': '$(IntDir)/$(InputName)3.res',
'ShowProgress': 'true'},
'VCManifestTool': {
'AdditionalManifestFiles': 'sfsdfsd',
'AdditionalOptions': 'afdsdafsd',
'AssemblyIdentity': 'sddfdsadfsa',
'ComponentFileName': 'fsdfds',
'DependencyInformationFile': '$(IntDir)\\mt.depdfd',
'EmbedManifest': 'false',
'GenerateCatalogFiles': 'true',
'InputResourceManifests': 'asfsfdafs',
'ManifestResourceFile':
'$(IntDir)\\$(TargetFileName).embed.manifest.resfdsf',
'OutputManifestFile': '$(TargetPath).manifestdfs',
'RegistrarScriptFile': 'sdfsfd',
'ReplacementsFile': 'sdffsd',
'SuppressStartupBanner': 'false',
'TypeLibraryFile': 'sfsd',
'UpdateFileHashes': 'true',
'UpdateFileHashesSearchPath': 'sfsd',
'UseFAT32Workaround': 'true',
'UseUnicodeResponseFiles': 'false',
'VerboseOutput': 'true'}}
expected_msbuild_settings = {
'ClCompile': {
'AdditionalIncludeDirectories': 'dir1',
'AdditionalOptions': '/more /J',
'AdditionalUsingDirectories': 'test',
'AssemblerListingLocation': '$(IntDir)a',
'AssemblerOutput': 'AssemblyCode',
'BasicRuntimeChecks': 'EnableFastChecks',
'BrowseInformation': 'true',
'BrowseInformationFile': '$(IntDir)e',
'BufferSecurityCheck': 'false',
'CallingConvention': 'FastCall',
'CompileAs': 'CompileAsC',
'DebugInformationFormat': 'EditAndContinue',
'DisableLanguageExtensions': 'true',
'DisableSpecificWarnings': 'abc',
'EnableEnhancedInstructionSet': 'StreamingSIMDExtensions',
'EnableFiberSafeOptimizations': 'true',
'EnablePREfast': 'true',
'ErrorReporting': 'Queue',
'ExceptionHandling': 'Async',
'ExpandAttributedSource': 'true',
'FavorSizeOrSpeed': 'Size',
'FloatingPointExceptions': 'true',
'FloatingPointModel': 'Strict',
'ForceConformanceInForLoopScope': 'false',
'ForcedIncludeFiles': 'def',
'ForcedUsingFiles': 'ge',
'FunctionLevelLinking': 'true',
'GenerateXMLDocumentationFiles': 'true',
'IgnoreStandardIncludePath': 'true',
'InlineFunctionExpansion': 'OnlyExplicitInline',
'IntrinsicFunctions': 'true',
'MinimalRebuild': 'true',
'ObjectFileName': '$(IntDir)b',
'OmitDefaultLibName': 'true',
'OmitFramePointers': 'true',
'OpenMPSupport': 'true',
'Optimization': 'Full',
'PrecompiledHeader': 'NotUsing', # Actual conversion gives ''
'PrecompiledHeaderFile': 'StdAfx.hd',
'PrecompiledHeaderOutputFile': '$(IntDir)$(TargetName).pche',
'PreprocessKeepComments': 'true',
'PreprocessorDefinitions': 'WIN32;_DEBUG;_CONSOLE',
'PreprocessSuppressLineNumbers': 'true',
'PreprocessToFile': 'true',
'ProgramDataBaseFileName': '$(IntDir)vc90b.pdb',
'RuntimeLibrary': 'MultiThreadedDebugDLL',
'RuntimeTypeInfo': 'false',
'ShowIncludes': 'true',
'SmallerTypeCheck': 'true',
'StringPooling': 'true',
'StructMemberAlignment': '4Bytes',
'SuppressStartupBanner': 'false',
'TreatWarningAsError': 'true',
'TreatWChar_tAsBuiltInType': 'false',
'UndefineAllPreprocessorDefinitions': 'true',
'UndefinePreprocessorDefinitions': 'wer',
'UseFullPaths': 'true',
'WarningLevel': 'Level3',
'WholeProgramOptimization': 'true',
'XMLDocumentationFileName': '$(IntDir)c'},
'Link': {
'AdditionalDependencies': 'zx',
'AdditionalLibraryDirectories': 'asd',
'AdditionalManifestDependencies': 's2',
'AdditionalOptions': '/mor2',
'AddModuleNamesToAssembly': 'd1',
'AllowIsolation': 'false',
'AssemblyDebug': 'true',
'AssemblyLinkResource': 'd5',
'BaseAddress': '23423',
'CLRImageType': 'ForceSafeILImage',
'CLRThreadAttribute': 'MTAThreadingAttribute',
'CLRUnmanagedCodeCheck': 'true',
'DataExecutionPrevention': '',
'DelayLoadDLLs': 'd4',
'DelaySign': 'true',
'Driver': 'UpOnly',
'EmbedManagedResourceFile': 'd2',
'EnableCOMDATFolding': 'false',
'EnableUAC': 'false',
'EntryPointSymbol': 'f5',
'FixedBaseAddress': 'false',
'ForceSymbolReferences': 'd3',
'FunctionOrder': 'fssdfsd',
'GenerateDebugInformation': 'true',
'GenerateMapFile': 'true',
'HeapCommitSize': '13',
'HeapReserveSize': '12',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreEmbeddedIDL': 'true',
'IgnoreSpecificDefaultLibraries': 'flob;flok',
'ImportLibrary': 'f4',
'KeyContainer': 'f7',
'KeyFile': 'f6',
'LargeAddressAware': 'true',
'LinkErrorReporting': 'QueueForNextLogin',
'LinkTimeCodeGeneration': 'UseLinkTimeCodeGeneration',
'ManifestFile': '$(IntDir)$(TargetFileName).2intermediate.manifest',
'MapExports': 'true',
'MapFileName': 'd5',
'MergedIDLBaseFileName': 'f2',
'MergeSections': 'f5',
'MidlCommandFile': 'f1',
'ModuleDefinitionFile': 'sdsd',
'NoEntryPoint': 'true',
'OptimizeReferences': 'true',
'OutputFile': '$(OutDir)$(ProjectName)2.exe',
'PerUserRedirection': 'true',
'Profile': 'true',
'ProfileGuidedDatabase': '$(TargetDir)$(TargetName).pgdd',
'ProgramDatabaseFile': 'Flob.pdb',
'RandomizedBaseAddress': 'false',
'RegisterOutput': 'true',
'SetChecksum': 'false',
'ShowProgress': 'LinkVerbose',
'StackCommitSize': '15',
'StackReserveSize': '14',
'StripPrivateSymbols': 'd3',
'SubSystem': 'Console',
'SupportUnloadOfDelayLoadedDLL': 'true',
'SuppressStartupBanner': 'false',
'SwapRunFromCD': 'true',
'SwapRunFromNET': 'true',
'TargetMachine': 'MachineX86',
'TerminalServerAware': 'false',
'TurnOffAssemblyGeneration': 'true',
'TypeLibraryFile': 'f3',
'TypeLibraryResourceID': '12',
'UACExecutionLevel': 'RequireAdministrator',
'UACUIAccess': 'true',
'Version': '333'},
'ResourceCompile': {
'AdditionalIncludeDirectories': 'f3',
'AdditionalOptions': '/more3',
'Culture': '0x0c0c',
'IgnoreStandardIncludePath': 'true',
'PreprocessorDefinitions': '_UNICODE;UNICODE2',
'ResourceOutputFileName': '$(IntDir)%(Filename)3.res',
'ShowProgress': 'true'},
'Manifest': {
'AdditionalManifestFiles': 'sfsdfsd',
'AdditionalOptions': 'afdsdafsd',
'AssemblyIdentity': 'sddfdsadfsa',
'ComponentFileName': 'fsdfds',
'GenerateCatalogFiles': 'true',
'InputResourceManifests': 'asfsfdafs',
'OutputManifestFile': '$(TargetPath).manifestdfs',
'RegistrarScriptFile': 'sdfsfd',
'ReplacementsFile': 'sdffsd',
'SuppressStartupBanner': 'false',
'TypeLibraryFile': 'sfsd',
'UpdateFileHashes': 'true',
'UpdateFileHashesSearchPath': 'sfsd',
'VerboseOutput': 'true'},
'ProjectReference': {
'LinkLibraryDependencies': 'false',
'UseLibraryDependencyInputs': 'true'},
'': {
'EmbedManifest': 'false',
'GenerateManifest': 'false',
'IgnoreImportLibrary': 'true',
'LinkIncremental': ''
},
'ManifestResourceCompile': {
'ResourceOutputFileName':
'$(IntDir)$(TargetFileName).embed.manifest.resfdsf'}
}
actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(
msvs_settings,
self.stderr)
self.assertEqual(expected_msbuild_settings, actual_msbuild_settings)
self._ExpectedWarnings([])
if __name__ == '__main__':
unittest.main()
| mit |
vhaupert/mitmproxy | test/pathod/tservers.py | 4 | 3619 | import os
import tempfile
import re
import shutil
import requests
import io
import urllib
from mitmproxy.net import tcp
from mitmproxy.utils import data
from pathod import language
from pathod import pathoc
from pathod import pathod
from pathod import test
from pathod.pathod import CA_CERT_NAME
cdata = data.Data(__name__)
def treader(bytes):
"""
Construct a tcp.Read object from bytes.
"""
fp = io.BytesIO(bytes)
return tcp.Reader(fp)
class DaemonTests:
nohang = False
ssl = False
timeout = None
hexdump = False
ssloptions = None
nocraft = False
explain = True
@classmethod
def setup_class(cls):
opts = cls.ssloptions or {}
cls.confdir = tempfile.mkdtemp()
opts["confdir"] = cls.confdir
so = pathod.SSLOptions(**opts)
cls.d = test.Daemon(
staticdir=cdata.path("data"),
anchors=[
(re.compile("/anchor/.*"), "202:da")
],
ssl=cls.ssl,
ssloptions=so,
sizelimit=1 * 1024 * 1024,
nohang=cls.nohang,
timeout=cls.timeout,
hexdump=cls.hexdump,
nocraft=cls.nocraft,
logreq=True,
logresp=True,
explain=cls.explain
)
@classmethod
def teardown_class(cls):
cls.d.shutdown()
shutil.rmtree(cls.confdir)
def teardown(self):
self.d.wait_for_silence()
self.d.clear_log()
def _getpath(self, path, params=None):
scheme = "https" if self.ssl else "http"
resp = requests.get(
"%s://localhost:%s/%s" % (
scheme,
self.d.port,
path
),
verify=os.path.join(self.d.thread.server.ssloptions.confdir, CA_CERT_NAME),
params=params
)
return resp
def getpath(self, path, params=None):
logfp = io.StringIO()
c = pathoc.Pathoc(
("localhost", self.d.port),
ssl=self.ssl,
fp=logfp,
)
with c.connect():
if params:
path = path + "?" + urllib.parse.urlencode(params)
resp = c.request("get:%s" % path)
return resp
def get(self, spec):
logfp = io.StringIO()
c = pathoc.Pathoc(
("localhost", self.d.port),
ssl=self.ssl,
fp=logfp,
)
with c.connect():
resp = c.request(
"get:/p/%s" % urllib.parse.quote(spec)
)
return resp
def pathoc(
self,
specs,
timeout=None,
connect_to=None,
ssl=None,
ws_read_limit=None,
use_http2=False,
):
"""
Returns a (messages, text log) tuple.
"""
if ssl is None:
ssl = self.ssl
logfp = io.StringIO()
c = pathoc.Pathoc(
("localhost", self.d.port),
ssl=ssl,
ws_read_limit=ws_read_limit,
timeout=timeout,
fp=logfp,
use_http2=use_http2,
)
with c.connect(connect_to):
ret = []
for i in specs:
resp = c.request(i)
if resp:
ret.append(resp)
for frm in c.wait():
ret.append(frm)
c.stop()
return ret, logfp.getvalue()
def render(r, settings=language.Settings()):
r = r.resolve(settings)
s = io.BytesIO()
assert language.serve(r, s, settings)
return s.getvalue()
| mit |
doduytrung/odoo-8.0 | addons/project_timesheet/__openerp__.py | 260 | 2151 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Bill Time on Tasks',
'version': '1.0',
'category': 'Project Management',
'description': """
Synchronization of project task work entries with timesheet entries.
====================================================================
This module lets you transfer the entries under tasks defined for Project
Management to the Timesheet line entries for particular date and particular user
with the effect of creating, editing and deleting either ways.
""",
'author': 'OpenERP SA',
'website': 'https://www.odoo.com/page/project-management',
'depends': ['resource', 'project', 'hr_timesheet_sheet', 'hr_timesheet_invoice', 'account_analytic_analysis', 'procurement'],
'data': [
'security/ir.model.access.csv',
'security/project_timesheet_security.xml',
'report/task_report_view.xml',
'project_timesheet_view.xml',
],
'demo': ['project_timesheet_demo.xml'],
'test': [
'test/worktask_entry_to_timesheetline_entry.yml',
'test/work_timesheet.yml',
],
'installable': True,
'auto_install': True,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
enthought/traitsgui | enthought/pyface/message_dialog.py | 3 | 1716 | #------------------------------------------------------------------------------
# Copyright (c) 2005, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in enthought/LICENSE.txt and may be redistributed only
# under the conditions described in the aforementioned license. The license
# is also available online at http://www.enthought.com/licenses/BSD.txt
# Thanks for using Enthought open source!
#
# Author: Enthought, Inc.
# Description: <Enthought pyface package component>
#------------------------------------------------------------------------------
""" The implementation of a dialog that displays a message. """
# Convenience functions.
def information(parent, message, title='Information'):
""" Convenience function to show an information message dialog. """
dialog = MessageDialog(
parent=parent, message=message, title=title, severity='information'
)
dialog.open()
return
def warning(parent, message, title='Warning'):
""" Convenience function to show a warning message dialog. """
dialog = MessageDialog(
parent=parent, message=message, title=title, severity='warning'
)
dialog.open()
return
def error(parent, message, title='Error'):
""" Convenience function to show an error message dialog. """
dialog = MessageDialog(
parent=parent, message=message, title=title, severity='error'
)
dialog.open()
return
# Import the toolkit specific version.
from toolkit import toolkit_object
MessageDialog = toolkit_object('message_dialog:MessageDialog')
#### EOF ######################################################################
| bsd-3-clause |
Asquera/bigcouch | couchjs/scons/scons-local-2.0.1/SCons/Tool/sunf90.py | 61 | 2180 | """SCons.Tool.sunf90
Tool-specific initialization for sunf90, the Sun Studio F90 compiler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# 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,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following 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 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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.
#
__revision__ = "src/engine/SCons/Tool/sunf90.py 5134 2010/08/16 23:02:40 bdeegan"
import SCons.Util
from FortranCommon import add_all_to_env
compilers = ['sunf90', 'f90']
def generate(env):
"""Add Builders and construction variables for sun f90 compiler to an
Environment."""
add_all_to_env(env)
fcomp = env.Detect(compilers) or 'f90'
env['FORTRAN'] = fcomp
env['F90'] = fcomp
env['SHFORTRAN'] = '$FORTRAN'
env['SHF90'] = '$F90'
env['SHFORTRANFLAGS'] = SCons.Util.CLVar('$FORTRANFLAGS -KPIC')
env['SHF90FLAGS'] = SCons.Util.CLVar('$F90FLAGS -KPIC')
def exists(env):
return env.Detect(compilers)
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| apache-2.0 |
rally12/deep-learning | language-translation/problem_unittests.py | 98 | 13080 | import numpy as np
import tensorflow as tf
import itertools
import collections
import helper
def _print_success_message():
print('Tests Passed')
def test_text_to_ids(text_to_ids):
test_source_text = 'new jersey is sometimes quiet during autumn , and it is snowy in april .\nthe united states is usually chilly during july , and it is usually freezing in november .\ncalifornia is usually quiet during march , and it is usually hot in june .\nthe united states is sometimes mild during june , and it is cold in september .'
test_target_text = 'new jersey est parfois calme pendant l\' automne , et il est neigeux en avril .\nles états-unis est généralement froid en juillet , et il gèle habituellement en novembre .\ncalifornia est généralement calme en mars , et il est généralement chaud en juin .\nles états-unis est parfois légère en juin , et il fait froid en septembre .'
test_source_text = test_source_text.lower()
test_target_text = test_target_text.lower()
source_vocab_to_int, source_int_to_vocab = helper.create_lookup_tables(test_source_text)
target_vocab_to_int, target_int_to_vocab = helper.create_lookup_tables(test_target_text)
test_source_id_seq, test_target_id_seq = text_to_ids(test_source_text, test_target_text, source_vocab_to_int, target_vocab_to_int)
assert len(test_source_id_seq) == len(test_source_text.split('\n')),\
'source_id_text has wrong length, it should be {}.'.format(len(test_source_text.split('\n')))
assert len(test_target_id_seq) == len(test_target_text.split('\n')), \
'target_id_text has wrong length, it should be {}.'.format(len(test_target_text.split('\n')))
target_not_iter = [type(x) for x in test_source_id_seq if not isinstance(x, collections.Iterable)]
assert not target_not_iter,\
'Element in source_id_text is not iteratable. Found type {}'.format(target_not_iter[0])
target_not_iter = [type(x) for x in test_target_id_seq if not isinstance(x, collections.Iterable)]
assert not target_not_iter, \
'Element in target_id_text is not iteratable. Found type {}'.format(target_not_iter[0])
source_changed_length = [(words, word_ids)
for words, word_ids in zip(test_source_text.split('\n'), test_source_id_seq)
if len(words.split()) != len(word_ids)]
assert not source_changed_length,\
'Source text changed in size from {} word(s) to {} id(s): {}'.format(
len(source_changed_length[0][0].split()), len(source_changed_length[0][1]), source_changed_length[0][1])
target_missing_end = [word_ids for word_ids in test_target_id_seq if word_ids[-1] != target_vocab_to_int['<EOS>']]
assert not target_missing_end,\
'Missing <EOS> id at the end of {}'.format(target_missing_end[0])
target_bad_size = [(words.split(), word_ids)
for words, word_ids in zip(test_target_text.split('\n'), test_target_id_seq)
if len(word_ids) != len(words.split()) + 1]
assert not target_bad_size,\
'Target text incorrect size. {} should be length {}'.format(
target_bad_size[0][1], len(target_bad_size[0][0]) + 1)
source_bad_id = [(word, word_id)
for word, word_id in zip(
[word for sentence in test_source_text.split('\n') for word in sentence.split()],
itertools.chain.from_iterable(test_source_id_seq))
if source_vocab_to_int[word] != word_id]
assert not source_bad_id,\
'Source word incorrectly converted from {} to id {}.'.format(source_bad_id[0][0], source_bad_id[0][1])
target_bad_id = [(word, word_id)
for word, word_id in zip(
[word for sentence in test_target_text.split('\n') for word in sentence.split()],
[word_id for word_ids in test_target_id_seq for word_id in word_ids[:-1]])
if target_vocab_to_int[word] != word_id]
assert not target_bad_id,\
'Target word incorrectly converted from {} to id {}.'.format(target_bad_id[0][0], target_bad_id[0][1])
_print_success_message()
def test_model_inputs(model_inputs):
with tf.Graph().as_default():
input_data, targets, lr, keep_prob = model_inputs()
# Check type
assert input_data.op.type == 'Placeholder',\
'Input is not a Placeholder.'
assert targets.op.type == 'Placeholder',\
'Targets is not a Placeholder.'
assert lr.op.type == 'Placeholder',\
'Learning Rate is not a Placeholder.'
assert keep_prob.op.type == 'Placeholder', \
'Keep Probability is not a Placeholder.'
# Check name
assert input_data.name == 'input:0',\
'Input has bad name. Found name {}'.format(input_data.name)
assert keep_prob.name == 'keep_prob:0', \
'Keep Probability has bad name. Found name {}'.format(keep_prob.name)
assert tf.assert_rank(input_data, 2, message='Input data has wrong rank')
assert tf.assert_rank(targets, 2, message='Targets has wrong rank')
assert tf.assert_rank(lr, 0, message='Learning Rate has wrong rank')
assert tf.assert_rank(keep_prob, 0, message='Keep Probability has wrong rank')
_print_success_message()
def test_encoding_layer(encoding_layer):
rnn_size = 512
batch_size = 64
num_layers = 3
with tf.Graph().as_default():
rnn_inputs = tf.placeholder(tf.float32, [batch_size, 22, 1000])
keep_prob = tf.placeholder(tf.float32)
states = encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob)
assert len(states) == num_layers,\
'Found {} state(s). It should be {} states.'.format(len(states), num_layers)
bad_types = [type(state) for state in states if not isinstance(state, tf.contrib.rnn.LSTMStateTuple)]
assert not bad_types,\
'Found wrong type: {}'.format(bad_types[0])
bad_shapes = [state_tensor.get_shape()
for state in states
for state_tensor in state
if state_tensor.get_shape().as_list() not in [[None, rnn_size], [batch_size, rnn_size]]]
assert not bad_shapes,\
'Found wrong shape: {}'.format(bad_shapes[0])
_print_success_message()
def test_decoding_layer(decoding_layer):
batch_size = 64
vocab_size = 1000
embedding_size = 200
sequence_length = 22
rnn_size = 512
num_layers = 3
target_vocab_to_int = {'<EOS>': 1, '<GO>': 3}
with tf.Graph().as_default():
dec_embed_input = tf.placeholder(tf.float32, [batch_size, 22, embedding_size])
dec_embeddings = tf.placeholder(tf.float32, [vocab_size, embedding_size])
keep_prob = tf.placeholder(tf.float32)
state = tf.contrib.rnn.LSTMStateTuple(
tf.placeholder(tf.float32, [None, rnn_size]),
tf.placeholder(tf.float32, [None, rnn_size]))
encoder_state = (state, state, state)
train_output, inf_output = decoding_layer(dec_embed_input, dec_embeddings, encoder_state, vocab_size,
sequence_length, rnn_size, num_layers, target_vocab_to_int, keep_prob)
assert isinstance(train_output, tf.Tensor),\
'Train Logits is wrong type: {}'.format(type(train_output))
assert isinstance(inf_output, tf.Tensor), \
'Inference Logits is wrong type: {}'.format(type(inf_output))
assert train_output.get_shape().as_list() == [batch_size, None, vocab_size],\
'Train Logits is the wrong shape: {}'.format(train_output.get_shape())
assert inf_output.get_shape().as_list() == [None, None, vocab_size], \
'Inference Logits is the wrong shape: {}'.format(inf_output.get_shape())
_print_success_message()
def test_seq2seq_model(seq2seq_model):
batch_size = 64
target_vocab_size = 300
sequence_length = 22
rnn_size = 512
num_layers = 3
target_vocab_to_int = {'<EOS>': 1, '<GO>': 3}
with tf.Graph().as_default():
input_data = tf.placeholder(tf.int32, [64, 22])
target_data = tf.placeholder(tf.int32, [64, 22])
keep_prob = tf.placeholder(tf.float32)
train_output, inf_output = seq2seq_model(input_data, target_data, keep_prob, batch_size, sequence_length,
200, target_vocab_size, 64, 80, rnn_size, num_layers, target_vocab_to_int)
assert isinstance(train_output, tf.Tensor),\
'Train Logits is wrong type: {}'.format(type(train_output))
assert isinstance(inf_output, tf.Tensor), \
'Inference Logits is wrong type: {}'.format(type(inf_output))
assert train_output.get_shape().as_list() == [batch_size, None, target_vocab_size],\
'Train Logits is the wrong shape: {}'.format(train_output.get_shape())
assert inf_output.get_shape().as_list() == [None, None, target_vocab_size], \
'Inference Logits is the wrong shape: {}'.format(inf_output.get_shape())
_print_success_message()
def test_sentence_to_seq(sentence_to_seq):
sentence = 'this is a test sentence'
vocab_to_int = {'<PAD>': 0, '<EOS>': 1, '<UNK>': 2, 'this': 3, 'is': 6, 'a': 5, 'sentence': 4}
output = sentence_to_seq(sentence, vocab_to_int)
assert len(output) == 5,\
'Wrong length. Found a length of {}'.format(len(output))
assert output[3] == 2,\
'Missing <UNK> id.'
assert np.array_equal(output, [3, 6, 5, 2, 4]),\
'Incorrect ouput. Found {}'.format(output)
_print_success_message()
def test_process_decoding_input(process_decoding_input):
batch_size = 2
seq_length = 3
target_vocab_to_int = {'<GO>': 3}
with tf.Graph().as_default():
target_data = tf.placeholder(tf.int32, [batch_size, seq_length])
dec_input = process_decoding_input(target_data, target_vocab_to_int, batch_size)
assert dec_input.get_shape() == (batch_size, seq_length),\
'Wrong shape returned. Found {}'.format(dec_input.get_shape())
test_target_data = [[10, 20, 30], [40, 18, 23]]
with tf.Session() as sess:
test_dec_input = sess.run(dec_input, {target_data: test_target_data})
assert test_dec_input[0][0] == target_vocab_to_int['<GO>'] and\
test_dec_input[1][0] == target_vocab_to_int['<GO>'],\
'Missing GO Id.'
_print_success_message()
def test_decoding_layer_train(decoding_layer_train):
batch_size = 64
vocab_size = 1000
embedding_size = 200
sequence_length = 22
rnn_size = 512
num_layers = 3
with tf.Graph().as_default():
with tf.variable_scope("decoding") as decoding_scope:
dec_cell = tf.contrib.rnn.MultiRNNCell([tf.contrib.rnn.BasicLSTMCell(rnn_size)] * num_layers)
output_fn = lambda x: tf.contrib.layers.fully_connected(x, vocab_size, None, scope=decoding_scope)
dec_embed_input = tf.placeholder(tf.float32, [batch_size, 22, embedding_size])
keep_prob = tf.placeholder(tf.float32)
state = tf.contrib.rnn.LSTMStateTuple(
tf.placeholder(tf.float32, [None, rnn_size]),
tf.placeholder(tf.float32, [None, rnn_size]))
encoder_state = (state, state, state)
train_logits = decoding_layer_train(encoder_state, dec_cell, dec_embed_input, sequence_length,
decoding_scope, output_fn, keep_prob)
assert train_logits.get_shape().as_list() == [batch_size, None, vocab_size], \
'Wrong shape returned. Found {}'.format(train_logits.get_shape())
_print_success_message()
def test_decoding_layer_infer(decoding_layer_infer):
vocab_size = 1000
sequence_length = 22
embedding_size = 200
rnn_size = 512
num_layers = 3
with tf.Graph().as_default():
with tf.variable_scope("decoding") as decoding_scope:
dec_cell = tf.contrib.rnn.MultiRNNCell([tf.contrib.rnn.BasicLSTMCell(rnn_size)] * num_layers)
output_fn = lambda x: tf.contrib.layers.fully_connected(x, vocab_size, None, scope=decoding_scope)
dec_embeddings = tf.placeholder(tf.float32, [vocab_size, embedding_size])
keep_prob = tf.placeholder(tf.float32)
state = tf.contrib.rnn.LSTMStateTuple(
tf.placeholder(tf.float32, [None, rnn_size]),
tf.placeholder(tf.float32, [None, rnn_size]))
encoder_state = (state, state, state)
infer_logits = decoding_layer_infer(encoder_state, dec_cell, dec_embeddings, 10, 20,
sequence_length, vocab_size, decoding_scope, output_fn, keep_prob)
assert infer_logits.get_shape().as_list() == [None, None, vocab_size], \
'Wrong shape returned. Found {}'.format(infer_logits.get_shape())
_print_success_message()
| mit |
earshel/PokeyPyManager | POGOProtos/Networking/Responses/CollectDailyDefenderBonusResponse_pb2.py | 16 | 5285 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: POGOProtos/Networking/Responses/CollectDailyDefenderBonusResponse.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='POGOProtos/Networking/Responses/CollectDailyDefenderBonusResponse.proto',
package='POGOProtos.Networking.Responses',
syntax='proto3',
serialized_pb=_b('\nGPOGOProtos/Networking/Responses/CollectDailyDefenderBonusResponse.proto\x12\x1fPOGOProtos.Networking.Responses\"\x97\x02\n!CollectDailyDefenderBonusResponse\x12Y\n\x06result\x18\x01 \x01(\x0e\x32I.POGOProtos.Networking.Responses.CollectDailyDefenderBonusResponse.Result\x12\x15\n\rcurrency_type\x18\x02 \x03(\t\x12\x18\n\x10\x63urrency_awarded\x18\x03 \x03(\x05\x12\x17\n\x0f\x64\x65\x66\x65nders_count\x18\x04 \x01(\x05\"M\n\x06Result\x12\t\n\x05UNSET\x10\x00\x12\x0b\n\x07SUCCESS\x10\x01\x12\x0b\n\x07\x46\x41ILURE\x10\x02\x12\x0c\n\x08TOO_SOON\x10\x03\x12\x10\n\x0cNO_DEFENDERS\x10\x04\x62\x06proto3')
)
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
_COLLECTDAILYDEFENDERBONUSRESPONSE_RESULT = _descriptor.EnumDescriptor(
name='Result',
full_name='POGOProtos.Networking.Responses.CollectDailyDefenderBonusResponse.Result',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='UNSET', index=0, number=0,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='SUCCESS', index=1, number=1,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='FAILURE', index=2, number=2,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='TOO_SOON', index=3, number=3,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='NO_DEFENDERS', index=4, number=4,
options=None,
type=None),
],
containing_type=None,
options=None,
serialized_start=311,
serialized_end=388,
)
_sym_db.RegisterEnumDescriptor(_COLLECTDAILYDEFENDERBONUSRESPONSE_RESULT)
_COLLECTDAILYDEFENDERBONUSRESPONSE = _descriptor.Descriptor(
name='CollectDailyDefenderBonusResponse',
full_name='POGOProtos.Networking.Responses.CollectDailyDefenderBonusResponse',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='result', full_name='POGOProtos.Networking.Responses.CollectDailyDefenderBonusResponse.result', index=0,
number=1, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='currency_type', full_name='POGOProtos.Networking.Responses.CollectDailyDefenderBonusResponse.currency_type', index=1,
number=2, type=9, cpp_type=9, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='currency_awarded', full_name='POGOProtos.Networking.Responses.CollectDailyDefenderBonusResponse.currency_awarded', index=2,
number=3, type=5, cpp_type=1, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='defenders_count', full_name='POGOProtos.Networking.Responses.CollectDailyDefenderBonusResponse.defenders_count', index=3,
number=4, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
_COLLECTDAILYDEFENDERBONUSRESPONSE_RESULT,
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=109,
serialized_end=388,
)
_COLLECTDAILYDEFENDERBONUSRESPONSE.fields_by_name['result'].enum_type = _COLLECTDAILYDEFENDERBONUSRESPONSE_RESULT
_COLLECTDAILYDEFENDERBONUSRESPONSE_RESULT.containing_type = _COLLECTDAILYDEFENDERBONUSRESPONSE
DESCRIPTOR.message_types_by_name['CollectDailyDefenderBonusResponse'] = _COLLECTDAILYDEFENDERBONUSRESPONSE
CollectDailyDefenderBonusResponse = _reflection.GeneratedProtocolMessageType('CollectDailyDefenderBonusResponse', (_message.Message,), dict(
DESCRIPTOR = _COLLECTDAILYDEFENDERBONUSRESPONSE,
__module__ = 'POGOProtos.Networking.Responses.CollectDailyDefenderBonusResponse_pb2'
# @@protoc_insertion_point(class_scope:POGOProtos.Networking.Responses.CollectDailyDefenderBonusResponse)
))
_sym_db.RegisterMessage(CollectDailyDefenderBonusResponse)
# @@protoc_insertion_point(module_scope)
| mit |
LeeKamentsky/CellProfiler | cellprofiler/modules/tests/test_identifyprimaryobjects.py | 2 | 158497 | """test_identifyprimautomatic.py: test the IdentifyPrimAutomatic module
CellProfiler is distributed under the GNU General Public License.
See the accompanying file LICENSE for details.
Copyright (c) 2003-2009 Massachusetts Institute of Technology
Copyright (c) 2009-2015 Broad Institute
All rights reserved.
Please see the AUTHORS file for credits.
Website: http://www.cellprofiler.org
"""
import os
import base64
import unittest
import numpy as np
import scipy.ndimage
import tempfile
import StringIO
import zlib
import cellprofiler.modules.identifyprimaryobjects as ID
import cellprofiler.modules.identify as I
import cellprofiler.cpmath.threshold as T
from cellprofiler.modules.injectimage import InjectImage
import cellprofiler.settings
import cellprofiler.cpimage as cpi
import cellprofiler.objects as cpo
import cellprofiler.measurements as cpmeas
import cellprofiler.pipeline
from cellprofiler.workspace import Workspace
from cellprofiler.modules.tests import read_example_image
IMAGE_NAME = "my_image"
OBJECTS_NAME = "my_objects"
BINARY_IMAGE_NAME = "binary_image"
MASKING_OBJECTS_NAME = "masking_objects"
MEASUREMENT_NAME = "my_measurement"
class test_IdentifyPrimaryObjects(unittest.TestCase):
def load_error_handler(self, caller, event):
if isinstance(event, cellprofiler.pipeline.LoadExceptionEvent):
self.fail(event.error.message)
def make_workspace(self, image,
mask = None,
labels = None,
binary_image = None):
'''Make a workspace and IdentifyPrimaryObjects module
image - the intensity image for thresholding
mask - if present, the "don't analyze" mask of the intensity image
labels - if thresholding per-object, the labels matrix needed
binary_image - if thresholding using a binary image, the image
'''
module = ID.IdentifyPrimaryObjects()
module.module_num = 1
module.image_name.value = IMAGE_NAME
module.object_name.value = OBJECTS_NAME
module.binary_image.value = BINARY_IMAGE_NAME
module.masking_objects.value = MASKING_OBJECTS_NAME
pipeline = cellprofiler.pipeline.Pipeline()
pipeline.add_module(module)
m = cpmeas.Measurements()
cpimage = cpi.Image(image, mask = mask)
m.add(IMAGE_NAME, cpimage)
if binary_image is not None:
m.add(BINARY_IMAGE_NAME, cpi.Image(binary_image))
object_set = cpo.ObjectSet()
if labels is not None:
o = cpo.Objects()
o.segmented = labels
object_set.add_objects(o, MASKING_OBJECTS_NAME)
workspace = cellprofiler.workspace.Workspace(
pipeline, module, m, object_set, m, None)
return workspace, module
def test_00_00_init(self):
x = ID.IdentifyPrimaryObjects()
def test_02_000_test_zero_objects(self):
x = ID.IdentifyPrimaryObjects()
x.object_name.value = "my_object"
x.image_name.value = "my_image"
x.threshold_range.min =.1
x.threshold_range.max = 1
x.watershed_method.value = ID.WA_NONE
img = np.zeros((25,25))
image = cpi.Image(img)
image_set_list = cpi.ImageSetList()
image_set = image_set_list.get_image_set(0)
image_set.providers.append(cpi.VanillaImageProvider("my_image",image))
object_set = cpo.ObjectSet()
measurements = cpmeas.Measurements()
pipeline = cellprofiler.pipeline.Pipeline()
x.run(Workspace(pipeline,x,image_set,object_set,measurements,None))
self.assertEqual(len(object_set.object_names),1)
self.assertTrue("my_object" in object_set.object_names)
objects = object_set.get_objects("my_object")
segmented = objects.segmented
self.assertTrue(np.all(segmented == 0))
self.assertTrue("Image" in measurements.get_object_names())
self.assertTrue("my_object" in measurements.get_object_names())
self.assertTrue("Threshold_FinalThreshold_my_object" in measurements.get_feature_names("Image"))
self.assertTrue("Count_my_object" in measurements.get_feature_names("Image"))
count = measurements.get_current_measurement("Image","Count_my_object")
self.assertEqual(count,0)
self.assertTrue("Location_Center_X" in measurements.get_feature_names("my_object"))
location_center_x = measurements.get_current_measurement("my_object","Location_Center_X")
self.assertTrue(isinstance(location_center_x,np.ndarray))
self.assertEqual(np.product(location_center_x.shape),0)
self.assertTrue("Location_Center_Y" in measurements.get_feature_names("my_object"))
location_center_y = measurements.get_current_measurement("my_object","Location_Center_Y")
self.assertTrue(isinstance(location_center_y,np.ndarray))
self.assertEqual(np.product(location_center_y.shape),0)
def test_02_001_test_zero_objects_wa_in_lo_in(self):
x = ID.IdentifyPrimaryObjects()
x.object_name.value = "my_object"
x.image_name.value = "my_image"
x.threshold_range.min = .1
x.threshold_range.max = 1
x.watershed_method.value = ID.WA_INTENSITY
x.unclump_method.value = ID.UN_INTENSITY
img = np.zeros((25,25))
image = cpi.Image(img)
image_set_list = cpi.ImageSetList()
image_set = image_set_list.get_image_set(0)
image_set.providers.append(cpi.VanillaImageProvider("my_image",image))
object_set = cpo.ObjectSet()
measurements = cpmeas.Measurements()
pipeline = cellprofiler.pipeline.Pipeline()
x.run(Workspace(pipeline,x,image_set,object_set,measurements,None))
self.assertEqual(len(object_set.object_names),1)
self.assertTrue("my_object" in object_set.object_names)
objects = object_set.get_objects("my_object")
segmented = objects.segmented
self.assertTrue(np.all(segmented == 0))
def test_02_002_test_zero_objects_wa_di_lo_in(self):
x = ID.IdentifyPrimaryObjects()
x.object_name.value = "my_object"
x.image_name.value = "my_image"
x.threshold_range.min = .1
x.threshold_range.max = 1
x.watershed_method.value = ID.WA_SHAPE
x.unclump_method.value = ID.UN_INTENSITY
img = np.zeros((25,25))
image = cpi.Image(img)
image_set_list = cpi.ImageSetList()
image_set = image_set_list.get_image_set(0)
image_set.providers.append(cpi.VanillaImageProvider("my_image",image))
object_set = cpo.ObjectSet()
measurements = cpmeas.Measurements()
pipeline = cellprofiler.pipeline.Pipeline()
x.run(Workspace(pipeline,x,image_set,object_set,measurements,None))
self.assertEqual(len(object_set.object_names),1)
self.assertTrue("my_object" in object_set.object_names)
objects = object_set.get_objects("my_object")
segmented = objects.segmented
self.assertTrue(np.all(segmented == 0))
def test_02_003_test_zero_objects_wa_in_lo_sh(self):
x = ID.IdentifyPrimaryObjects()
x.object_name.value = "my_object"
x.image_name.value = "my_image"
x.threshold_range.min = .1
x.threshold_range.max = 1
x.watershed_method.value = ID.WA_INTENSITY
x.unclump_method.value = ID.UN_SHAPE
img = np.zeros((25,25))
image = cpi.Image(img)
image_set_list = cpi.ImageSetList()
image_set = image_set_list.get_image_set(0)
image_set.providers.append(cpi.VanillaImageProvider("my_image",image))
object_set = cpo.ObjectSet()
measurements = cpmeas.Measurements()
pipeline = cellprofiler.pipeline.Pipeline()
x.run(Workspace(pipeline,x,image_set,object_set,measurements,None))
self.assertEqual(len(object_set.object_names),1)
self.assertTrue("my_object" in object_set.object_names)
objects = object_set.get_objects("my_object")
segmented = objects.segmented
self.assertTrue(np.all(segmented == 0))
def test_02_004_test_zero_objects_wa_di_lo_sh(self):
x = ID.IdentifyPrimaryObjects()
x.object_name.value = "my_object"
x.image_name.value = "my_image"
x.threshold_range.min = .1
x.threshold_range.max = 1
x.watershed_method.value = ID.WA_SHAPE
x.unclump_method.value = ID.UN_SHAPE
img = np.zeros((25,25))
image = cpi.Image(img)
image_set_list = cpi.ImageSetList()
image_set = image_set_list.get_image_set(0)
image_set.providers.append(cpi.VanillaImageProvider("my_image",image))
object_set = cpo.ObjectSet()
measurements = cpmeas.Measurements()
pipeline = cellprofiler.pipeline.Pipeline()
x.run(Workspace(pipeline,x,image_set,object_set,measurements,None))
self.assertEqual(len(object_set.object_names),1)
self.assertTrue("my_object" in object_set.object_names)
objects = object_set.get_objects("my_object")
segmented = objects.segmented
self.assertTrue(np.all(segmented == 0))
def test_02_01_test_one_object(self):
x = ID.IdentifyPrimaryObjects()
x.object_name.value = "my_object"
x.image_name.value = "my_image"
x.exclude_size.value = False
x.watershed_method.value = ID.WA_NONE
x.threshold_scope.value = I.TS_GLOBAL
x.threshold_method.value = T.TM_OTSU
x.threshold_smoothing_choice.value = I.TSM_NONE
img = one_cell_image()
image = cpi.Image(img)
image_set_list = cpi.ImageSetList()
image_set = image_set_list.get_image_set(0)
image_set.providers.append(cpi.VanillaImageProvider("my_image",image))
object_set = cpo.ObjectSet()
measurements = cpmeas.Measurements()
pipeline = cellprofiler.pipeline.Pipeline()
x.run(Workspace(pipeline,x,image_set,object_set,measurements,None))
self.assertEqual(len(object_set.object_names),1)
self.assertTrue("my_object" in object_set.object_names)
objects = object_set.get_objects("my_object")
segmented = objects.segmented
self.assertTrue(np.all(segmented[img>0] == 1))
self.assertTrue(np.all(img[segmented==1] > 0))
self.assertTrue("Image" in measurements.get_object_names())
self.assertTrue("my_object" in measurements.get_object_names())
self.assertTrue("Threshold_FinalThreshold_my_object" in measurements.get_feature_names("Image"))
threshold = measurements.get_current_measurement("Image","Threshold_FinalThreshold_my_object")
self.assertTrue(threshold < .5)
self.assertTrue("Count_my_object" in measurements.get_feature_names("Image"))
count = measurements.get_current_measurement("Image","Count_my_object")
self.assertEqual(count,1)
self.assertTrue("Location_Center_Y" in measurements.get_feature_names("my_object"))
location_center_y = measurements.get_current_measurement("my_object","Location_Center_Y")
self.assertTrue(isinstance(location_center_y,np.ndarray))
self.assertEqual(np.product(location_center_y.shape),1)
self.assertTrue(location_center_y[0]>8)
self.assertTrue(location_center_y[0]<12)
self.assertTrue("Location_Center_X" in measurements.get_feature_names("my_object"))
location_center_x = measurements.get_current_measurement("my_object","Location_Center_X")
self.assertTrue(isinstance(location_center_x,np.ndarray))
self.assertEqual(np.product(location_center_x.shape),1)
self.assertTrue(location_center_x[0]>13)
self.assertTrue(location_center_x[0]<16)
columns = x.get_measurement_columns(pipeline)
for object_name in (cpmeas.IMAGE, "my_object"):
ocolumns =[x for x in columns if x[0] == object_name]
features = measurements.get_feature_names(object_name)
self.assertEqual(len(ocolumns), len(features))
self.assertTrue(all([column[1] in features for column in ocolumns]))
def test_02_02_test_two_objects(self):
x = ID.IdentifyPrimaryObjects()
x.object_name.value = "my_object"
x.image_name.value = "my_image"
x.exclude_size.value = False
x.watershed_method.value = ID.WA_NONE
x.threshold_scope.value = I.TS_GLOBAL
x.threshold_method.value = T.TM_OTSU
x.threshold_smoothing_choice.value = I.TSM_NONE
img = two_cell_image()
image = cpi.Image(img)
image_set_list = cpi.ImageSetList()
image_set = image_set_list.get_image_set(0)
image_set.providers.append(cpi.VanillaImageProvider("my_image",image))
object_set = cpo.ObjectSet()
measurements = cpmeas.Measurements()
pipeline = cellprofiler.pipeline.Pipeline()
x.run(Workspace(pipeline,x,image_set,object_set,measurements,None))
self.assertEqual(len(object_set.object_names),1)
self.assertTrue("my_object" in object_set.object_names)
objects = object_set.get_objects("my_object")
self.assertTrue("Image" in measurements.get_object_names())
self.assertTrue("my_object" in measurements.get_object_names())
self.assertTrue("Threshold_FinalThreshold_my_object" in measurements.get_feature_names("Image"))
threshold = measurements.get_current_measurement("Image","Threshold_FinalThreshold_my_object")
self.assertTrue(threshold < .6)
self.assertTrue("Count_my_object" in measurements.get_feature_names("Image"))
count = measurements.get_current_measurement("Image","Count_my_object")
self.assertEqual(count,2)
self.assertTrue("Location_Center_Y" in measurements.get_feature_names("my_object"))
location_center_y = measurements.get_current_measurement("my_object","Location_Center_Y")
self.assertTrue(isinstance(location_center_y,np.ndarray))
self.assertEqual(np.product(location_center_y.shape),2)
self.assertTrue(location_center_y[0]>8)
self.assertTrue(location_center_y[0]<12)
self.assertTrue(location_center_y[1]>28)
self.assertTrue(location_center_y[1]<32)
self.assertTrue("Location_Center_Y" in measurements.get_feature_names("my_object"))
location_center_x = measurements.get_current_measurement("my_object","Location_Center_X")
self.assertTrue(isinstance(location_center_x,np.ndarray))
self.assertEqual(np.product(location_center_x.shape),2)
self.assertTrue(location_center_x[0]>33)
self.assertTrue(location_center_x[0]<37)
self.assertTrue(location_center_x[1]>13)
self.assertTrue(location_center_x[1]<16)
def test_02_03_test_threshold_range(self):
x = ID.IdentifyPrimaryObjects()
x.object_name.value = "my_object"
x.image_name.value = "my_image"
x.threshold_range.min = .7
x.threshold_range.max = 1
x.threshold_correction_factor.value = .95
x.threshold_scope.value = I.TS_GLOBAL
x.threshold_method.value = I.TM_MCT
x.exclude_size.value = False
x.watershed_method.value = ID.WA_NONE
img = two_cell_image()
image = cpi.Image(img)
image_set_list = cpi.ImageSetList()
image_set = image_set_list.get_image_set(0)
image_set.providers.append(cpi.VanillaImageProvider("my_image",image))
object_set = cpo.ObjectSet()
measurements = cpmeas.Measurements()
pipeline = cellprofiler.pipeline.Pipeline()
x.run(Workspace(pipeline,x,image_set,object_set,measurements,None))
self.assertEqual(len(object_set.object_names),1)
self.assertTrue("my_object" in object_set.object_names)
objects = object_set.get_objects("my_object")
self.assertTrue("Image" in measurements.get_object_names())
self.assertTrue("my_object" in measurements.get_object_names())
self.assertTrue("Threshold_FinalThreshold_my_object" in measurements.get_feature_names("Image"))
threshold = measurements.get_current_measurement("Image","Threshold_FinalThreshold_my_object")
self.assertTrue(threshold < .8)
self.assertTrue(threshold > .6)
self.assertTrue("Count_my_object" in measurements.get_feature_names("Image"))
count = measurements.get_current_measurement("Image","Count_my_object")
self.assertEqual(count,1)
self.assertTrue("Location_Center_Y" in measurements.get_feature_names("my_object"))
location_center_y = measurements.get_current_measurement("my_object","Location_Center_Y")
self.assertTrue(isinstance(location_center_y,np.ndarray))
self.assertEqual(np.product(location_center_y.shape),1)
self.assertTrue(location_center_y[0]>8)
self.assertTrue(location_center_y[0]<12)
self.assertTrue("Location_Center_X" in measurements.get_feature_names("my_object"))
location_center_x = measurements.get_current_measurement("my_object","Location_Center_X")
self.assertTrue(isinstance(location_center_x,np.ndarray))
self.assertEqual(np.product(location_center_x.shape),1)
self.assertTrue(location_center_x[0]>33)
self.assertTrue(location_center_x[0]<36)
def test_02_04_fill_holes(self):
x = ID.IdentifyPrimaryObjects()
x.object_name.value = "my_object"
x.image_name.value = "my_image"
x.exclude_size.value = False
x.fill_holes.value = True
x.watershed_method.value = ID.WA_NONE
x.threshold_scope.value = I.TS_GLOBAL
x.threshold_method.value = T.TM_OTSU
x.threshold_smoothing_choice.value = I.TSM_NONE
img = np.zeros((40,40))
draw_circle(img, (10,10), 7, .5)
draw_circle(img, (30,30), 7, .5)
img[10,10] = 0
img[30,30] = 0
image = cpi.Image(img)
image_set_list = cpi.ImageSetList()
image_set = image_set_list.get_image_set(0)
image_set.providers.append(cpi.VanillaImageProvider("my_image",image))
object_set = cpo.ObjectSet()
measurements = cpmeas.Measurements()
pipeline = cellprofiler.pipeline.Pipeline()
x.run(Workspace(pipeline,x,image_set,object_set,measurements,None))
objects = object_set.get_objects("my_object")
self.assertTrue(objects.segmented[10,10] > 0)
self.assertTrue(objects.segmented[30,30] > 0)
def test_02_05_dont_fill_holes(self):
x = ID.IdentifyPrimaryObjects()
x.object_name.value = "my_object"
x.image_name.value = "my_image"
x.threshold_range.min = .7
x.threshold_range.max = 1
x.exclude_size.value = False
x.fill_holes.value = False
x.smoothing_filter_size.value = 0
x.automatic_smoothing.value = False
x.watershed_method.value = ID.WA_NONE
img = np.zeros((40,40))
draw_circle(img, (10,10), 7, .5)
draw_circle(img, (30,30), 7, .5)
img[10,10] = 0
img[30,30] = 0
image = cpi.Image(img)
image_set_list = cpi.ImageSetList()
image_set = image_set_list.get_image_set(0)
image_set.providers.append(cpi.VanillaImageProvider("my_image",image))
object_set = cpo.ObjectSet()
measurements = cpmeas.Measurements()
pipeline = cellprofiler.pipeline.Pipeline()
x.run(Workspace(pipeline,x,image_set,object_set,measurements,None))
objects = object_set.get_objects("my_object")
self.assertTrue(objects.segmented[10,10] == 0)
self.assertTrue(objects.segmented[30,30] == 0)
def test_02_05_01_fill_holes_within_holes(self):
'Regression test of img-1431'
x = ID.IdentifyPrimaryObjects()
x.object_name.value = "my_object"
x.image_name.value = "my_image"
x.size_range.min = 1
x.size_range.max = 2
x.exclude_size.value = False
x.fill_holes.value = ID.FH_DECLUMP
x.watershed_method.value = ID.WA_NONE
x.threshold_scope.value = I.TS_GLOBAL
x.threshold_method.value = T.TM_OTSU
x.threshold_smoothing_choice.value = I.TSM_NONE
img = np.zeros((40,40))
draw_circle(img, (20,20), 10, .5)
draw_circle(img, (20,20), 4, 0)
img[20,20] = 1
image = cpi.Image(img)
image_set_list = cpi.ImageSetList()
image_set = image_set_list.get_image_set(0)
image_set.providers.append(cpi.VanillaImageProvider("my_image",image))
object_set = cpo.ObjectSet()
measurements = cpmeas.Measurements()
pipeline = cellprofiler.pipeline.Pipeline()
x.run(Workspace(pipeline,x,image_set,object_set,measurements,None))
objects = object_set.get_objects("my_object")
self.assertTrue(objects.segmented[20,20] == 1)
self.assertTrue(objects.segmented[22,20] == 1)
self.assertTrue(objects.segmented[26,20] == 1)
def test_02_06_test_watershed_shape_shape(self):
"""Identify by local_maxima:shape & intensity:shape
Create an object whose intensity is high near the middle
but has an hourglass shape, then segment it using shape/shape
"""
x = ID.IdentifyPrimaryObjects()
x.image_name.value = "my_image"
x.object_name.value = "my_object"
x.exclude_size.value = False
x.size_range.value = (2,10)
x.fill_holes.value = False
x.maxima_suppression_size.value = 3
x.automatic_suppression.value = False
x.unclump_method.value = ID.UN_SHAPE
x.watershed_method.value = ID.WA_SHAPE
x.threshold_scope.value = I.TS_GLOBAL
x.threshold_method.value = T.TM_OTSU
x.threshold_smoothing_choice.value = I.TSM_NONE
img = np.array([[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0,.5,.5,.5,.5,.5,.5, 0, 0, 0, 0, 0],
[ 0, 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0, 0,.6,.6,.6,.6,.6,.6,.6,.6,.6,.6, 0, 0, 0],
[ 0, 0, 0, 0,.7,.7,.7,.7,.7,.7,.7,.7, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0,.8,.9, 1, 1,.9,.8, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0,.7,.7,.7,.7,.7,.7,.7,.7, 0, 0, 0, 0],
[ 0, 0, 0,.6,.6,.6,.6,.6,.6,.6,.6,.6,.6, 0, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0, 0],
[ 0, 0, 0, 0, 0,.5,.5,.5,.5,.5,.5, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
])
image = cpi.Image(img)
image_set_list = cpi.ImageSetList()
image_set = image_set_list.get_image_set(0)
image_set.providers.append(cpi.VanillaImageProvider("my_image",image))
object_set = cpo.ObjectSet()
measurements = cpmeas.Measurements()
pipeline = cellprofiler.pipeline.Pipeline()
x.run(Workspace(pipeline,x,image_set,object_set,measurements,None))
objects = object_set.get_objects("my_object")
self.assertEqual(np.max(objects.segmented),2)
def test_02_07_test_watershed_shape_intensity(self):
"""Identify by local_maxima:shape & watershed:intensity
Create an object with an hourglass shape to get two maxima, but
set the intensities so that one maximum gets the middle portion
"""
x = ID.IdentifyPrimaryObjects()
x.image_name.value = "my_image"
x.object_name.value = "my_object"
x.exclude_size.value = False
x.size_range.value = (2,10)
x.fill_holes.value = False
x.maxima_suppression_size.value = 3
x.automatic_suppression.value = False
x.unclump_method.value = ID.UN_SHAPE
x.watershed_method.value = ID.WA_INTENSITY
x.threshold_scope.value = I.TS_GLOBAL
x.threshold_method.value = T.TM_OTSU
x.threshold_smoothing_choice.value = I.TSM_NONE
img = np.array([[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0,.5,.5,.5,.5,.5,.5, 0, 0, 0, 0, 0],
[ 0, 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0, 0],
[ 0, 0, 0, 0,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0,.5,.5,.5,.5,.5,.5, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0, 0, 0],
[ 0, 0, 0,.4,.4,.4,.5,.5,.5,.4,.4,.4,.4, 0, 0, 0],
[ 0, 0,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4, 0, 0],
[ 0, 0,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4, 0, 0],
[ 0, 0,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4, 0, 0],
[ 0, 0,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4, 0, 0],
[ 0, 0, 0,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4, 0, 0, 0],
[ 0, 0, 0, 0, 0,.4,.4,.4,.4,.4,.4, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
])
image = cpi.Image(img)
image_set_list = cpi.ImageSetList()
image_set = image_set_list.get_image_set(0)
image_set.providers.append(cpi.VanillaImageProvider("my_image",image))
object_set = cpo.ObjectSet()
measurements = cpmeas.Measurements()
pipeline = cellprofiler.pipeline.Pipeline()
x.run(Workspace(pipeline,x,image_set,object_set,measurements,None))
objects = object_set.get_objects("my_object")
self.assertEqual(np.max(objects.segmented),2)
self.assertEqual(objects.segmented[7,11],objects.segmented[7,4])
def test_02_08_test_watershed_intensity_distance_single(self):
"""Identify by local_maxima:intensity & watershed:shape - one object
Create an object with an hourglass shape and a peak in the middle.
It should be segmented into a single object.
"""
x = ID.IdentifyPrimaryObjects()
x.image_name.value = "my_image"
x.object_name.value = "my_object"
x.exclude_size.value = False
x.size_range.value = (4,10)
x.fill_holes.value = False
x.maxima_suppression_size.value = 3.6
x.automatic_suppression.value = False
x.unclump_method.value = ID.UN_INTENSITY
x.watershed_method.value = ID.WA_SHAPE
x.threshold_scope.value = I.TS_GLOBAL
x.threshold_method.value = T.TM_OTSU
x.threshold_smoothing_choice.value = I.TSM_NONE
img = np.array([[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0,.5,.5,.5,.5,.5,.5, 0, 0, 0, 0, 0],
[ 0, 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.6,.6,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0, 0,.5,.5,.5,.6,.7,.7,.6,.5,.5,.5, 0, 0, 0],
[ 0, 0, 0, 0,.5,.6,.7,.8,.8,.7,.6,.5, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0,.7,.8,.9,.9,.8,.7, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0,.5,.6,.7,.8,.8,.7,.6,.5, 0, 0, 0, 0],
[ 0, 0, 0,.5,.5,.5,.6,.7,.7,.6,.5,.5,.5, 0, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.6,.6,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0, 0],
[ 0, 0, 0, 0, 0,.5,.5,.5,.5,.5,.5, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
])
# We do a little blur here so that there's some monotonic decrease
# from the central peak
img = scipy.ndimage.gaussian_filter(img, .25, mode='constant')
image = cpi.Image(img)
image_set_list = cpi.ImageSetList()
image_set = image_set_list.get_image_set(0)
image_set.providers.append(cpi.VanillaImageProvider("my_image",image))
object_set = cpo.ObjectSet()
measurements = cpmeas.Measurements()
pipeline = cellprofiler.pipeline.Pipeline()
x.run(Workspace(pipeline,x,image_set,object_set,measurements,None))
objects = object_set.get_objects("my_object")
self.assertEqual(np.max(objects.segmented),1)
def test_02_08_test_watershed_intensity_distance_triple(self):
"""Identify by local_maxima:intensity & watershed:shape - 3 objects w/o filter
Create an object with an hourglass shape and a peak in the middle.
It should be segmented into a single object.
"""
x = ID.IdentifyPrimaryObjects()
x.image_name.value = "my_image"
x.object_name.value = "my_object"
x.exclude_size.value = False
x.size_range.value = (2,10)
x.fill_holes.value = False
x.smoothing_filter_size.value = 0
x.automatic_smoothing.value = False
x.maxima_suppression_size.value = 7.1
x.automatic_suppression.value = False
x.unclump_method.value = ID.UN_INTENSITY
x.watershed_method.value = ID.WA_SHAPE
x.threshold_scope.value = I.TS_GLOBAL
x.threshold_method.value = T.TM_OTSU
x.threshold_smoothing_choice.value = I.TSM_NONE
img = np.array([[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0,.5,.5,.5,.5,.5,.5, 0, 0, 0, 0, 0],
[ 0, 0, 0,.5,.5,.5,.5,.8,.8,.5,.5,.5,.5, 0, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.6,.6,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0, 0,.5,.5,.5,.6,.7,.7,.6,.5,.5,.5, 0, 0, 0],
[ 0, 0, 0, 0,.5,.6,.7,.8,.8,.7,.6,.5, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0,.7,.8,.9,.9,.8,.7, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0,.5,.6,.7,.8,.8,.7,.6,.5, 0, 0, 0, 0],
[ 0, 0, 0,.5,.5,.5,.6,.7,.7,.6,.5,.5,.5, 0, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.6,.6,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0, 0,.5,.5,.5,.5,.8,.8,.5,.5,.5,.5, 0, 0, 0],
[ 0, 0, 0, 0, 0,.5,.5,.5,.5,.5,.5, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
])
image = cpi.Image(img)
image_set_list = cpi.ImageSetList()
image_set = image_set_list.get_image_set(0)
image_set.providers.append(cpi.VanillaImageProvider("my_image",image))
object_set = cpo.ObjectSet()
measurements = cpmeas.Measurements()
pipeline = cellprofiler.pipeline.Pipeline()
x.run(Workspace(pipeline,x,image_set,object_set,measurements,None))
objects = object_set.get_objects("my_object")
self.assertEqual(np.max(objects.segmented),3)
def test_02_09_test_watershed_intensity_distance_filter(self):
"""Identify by local_maxima:intensity & watershed:shape - filtered
Create an object with an hourglass shape and a peak in the middle.
It should be segmented into a single object.
"""
x = ID.IdentifyPrimaryObjects()
x.image_name.value = "my_image"
x.object_name.value = "my_object"
x.exclude_size.value = False
x.size_range.value = (2,10)
x.fill_holes.value = False
x.smoothing_filter_size.value = 1
x.automatic_smoothing.value = 1
x.maxima_suppression_size.value = 3.6
x.automatic_suppression.value = False
x.unclump_method.value = ID.UN_INTENSITY
x.watershed_method.value = ID.WA_SHAPE
x.threshold_scope.value = I.TS_GLOBAL
x.threshold_method.value = T.TM_OTSU
x.threshold_smoothing_choice.value = I.TSM_NONE
img = np.array([[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0,.5,.5,.5,.5,.5,.5, 0, 0, 0, 0, 0],
[ 0, 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.6,.6,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0, 0,.5,.5,.5,.6,.7,.7,.6,.5,.5,.5, 0, 0, 0],
[ 0, 0, 0, 0,.5,.6,.7,.8,.8,.7,.6,.5, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0,.7,.8,.9,.9,.8,.7, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0,.5,.6,.7,.8,.8,.7,.6,.5, 0, 0, 0, 0],
[ 0, 0, 0,.5,.5,.5,.6,.7,.7,.6,.5,.5,.5, 0, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.6,.6,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0, 0],
[ 0, 0, 0, 0, 0,.5,.5,.5,.5,.5,.5, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
])
image = cpi.Image(img)
image_set_list = cpi.ImageSetList()
image_set = image_set_list.get_image_set(0)
image_set.providers.append(cpi.VanillaImageProvider("my_image",image))
object_set = cpo.ObjectSet()
measurements = cpmeas.Measurements()
pipeline = cellprofiler.pipeline.Pipeline()
x.run(Workspace(pipeline,x,image_set,object_set,measurements,None))
objects = object_set.get_objects("my_object")
self.assertEqual(np.max(objects.segmented),1)
def test_02_10_test_watershed_intensity_distance_double(self):
"""Identify by local_maxima:intensity & watershed:shape - two objects
Create an object with an hourglass shape and peaks in the top and
bottom, but with a distribution of values that's skewed so that,
by intensity, one of the images occupies the middle. The middle
should be shared because the watershed is done using the distance
transform.
"""
x = ID.IdentifyPrimaryObjects()
x.image_name.value = "my_image"
x.object_name.value = "my_object"
x.exclude_size.value = False
x.size_range.value = (2,10)
x.fill_holes.value = False
x.smoothing_filter_size.value = 0
x.automatic_smoothing.value = 0
x.maxima_suppression_size.value = 3.6
x.automatic_suppression.value = False
x.unclump_method.value = ID.UN_INTENSITY
x.watershed_method.value = ID.WA_SHAPE
img = np.array([[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0,.5,.5,.5,.5,.5,.5, 0, 0, 0, 0, 0],
[ 0, 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.9,.9,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0, 0],
[ 0, 0, 0, 0,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0,.5,.5,.5,.5,.5,.5, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0, 0, 0],
[ 0, 0, 0,.4,.4,.4,.5,.5,.5,.4,.4,.4,.4, 0, 0, 0],
[ 0, 0,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4, 0, 0],
[ 0, 0,.4,.4,.4,.4,.4,.9,.9,.4,.4,.4,.4,.4, 0, 0],
[ 0, 0,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4, 0, 0],
[ 0, 0,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4, 0, 0],
[ 0, 0, 0,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4, 0, 0, 0],
[ 0, 0, 0, 0, 0,.4,.4,.4,.4,.4,.4, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
])
# We do a little blur here so that there's some monotonic decrease
# from the central peak
img = scipy.ndimage.gaussian_filter(img, .5, mode='constant')
image = cpi.Image(img)
image_set_list = cpi.ImageSetList()
image_set = image_set_list.get_image_set(0)
image_set.providers.append(cpi.VanillaImageProvider("my_image",image))
object_set = cpo.ObjectSet()
measurements = cpmeas.Measurements()
pipeline = cellprofiler.pipeline.Pipeline()
x.run(Workspace(pipeline,x,image_set,object_set,measurements,None))
objects = object_set.get_objects("my_object")
self.assertEqual(np.max(objects.segmented),2)
self.assertNotEqual(objects.segmented[12,7],objects.segmented[4,7])
def test_02_11_propagate(self):
"""Test the propagate unclump method"""
x = ID.IdentifyPrimaryObjects()
x.image_name.value = "my_image"
x.object_name.value = "my_object"
x.exclude_size.value = False
x.size_range.value = (2,10)
x.fill_holes.value = False
x.smoothing_filter_size.value = 0
x.automatic_smoothing.value = 0
x.maxima_suppression_size.value = 7
x.automatic_suppression.value = False
x.manual_threshold.value = .3
x.unclump_method.value = ID.UN_INTENSITY
x.watershed_method.value = ID.WA_PROPAGATE
x.threshold_scope.value = I.TS_MANUAL
x.threshold_smoothing_choice.value = I.TSM_NONE
img = np.array([[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0,.5,.5,.5,.5,.5,.5, 0, 0, 0, 0, 0],
[ 0, 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0,.5,.5,.5,.5,.5,.9,.9,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0,.5,.5,.5,.5, 0, 0, 0, 0, 0, 0, 0,.5, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,.5, 0, 0],
[ 0, 0, 0, 0, 0, 0,.5,.5,.5,.5,.5,.5,.5,.5, 0, 0],
[ 0, 0, 0, 0, 0,.5,.5,.5,.5, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0,.5,.5,.5,.5,.5, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0,.4,.4,.4,.5,.5,.5,.4,.4,.4,.4, 0, 0, 0],
[ 0, 0,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4, 0, 0],
[ 0, 0,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4, 0, 0],
[ 0, 0,.4,.4,.4,.4,.4,.9,.9,.4,.4,.4,.4,.4, 0, 0],
[ 0, 0,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4, 0, 0],
[ 0, 0, 0,.4,.4,.4,.4,.4,.4,.4,.4,.4,.4, 0, 0, 0],
[ 0, 0, 0, 0, 0,.4,.4,.4,.4,.4,.4, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
])
# We do a little blur here so that there's some monotonic decrease
# from the central peak
img = scipy.ndimage.gaussian_filter(img, .5, mode='constant')
image = cpi.Image(img)
image_set_list = cpi.ImageSetList()
image_set = image_set_list.get_image_set(0)
image_set.providers.append(cpi.VanillaImageProvider("my_image",image))
object_set = cpo.ObjectSet()
measurements = cpmeas.Measurements()
pipeline = cellprofiler.pipeline.Pipeline()
x.run(Workspace(pipeline,x,image_set,object_set,measurements,None))
objects = object_set.get_objects("my_object")
self.assertEqual(np.max(objects.segmented),2)
# This point has a closer "crow-fly" distance to the upper object
# but should be in the lower one because of the serpentine path
self.assertEqual(objects.segmented[14,9],objects.segmented[9,9])
def test_02_12_fly(self):
'''Run identify on the fly image'''
data = r"""CellProfiler Pipeline: http://www.cellprofiler.org
Version:1
SVNRevision:9722
IdentifyPrimaryObjects:[module_num:1|svn_version:\'9633\'|variable_revision_number:6|show_window:True|notes:\x5B\x5D]
Select the input image:CropBlue
Name the primary objects to be identified:Nuclei
Typical diameter of objects, in pixel units (Min,Max):15,40
Discard objects outside the diameter range?:Yes
Try to merge too small objects with nearby larger objects?:No
Discard objects touching the border of the image?:Yes
Select the thresholding method:MoG Global
Threshold correction factor:1.6
Lower and upper bounds on threshold:0,1
Approximate fraction of image covered by objects?:0.2
Method to distinguish clumped objects:Intensity
Method to draw dividing lines between clumped objects:Intensity
Size of smoothing filter:10
Suppress local maxima that are closer than this minimum allowed distance:5
Speed up by using lower-resolution image to find local maxima?:Yes
Name the outline image:None
Fill holes in identified objects?:Yes
Automatically calculate size of smoothing filter?:Yes
Automatically calculate minimum allowed distance between local maxima?:Yes
Manual threshold:0.0
Select binary image:MoG Global
Retain outlines of the identified objects?:No
Automatically calculate the threshold using the Otsu method?:Yes
Enter Laplacian of Gaussian threshold:.5
Two-class or three-class thresholding?:Two classes
Minimize the weighted variance or the entropy?:Weighted variance
Assign pixels in the middle intensity class to the foreground or the background?:Foreground
Automatically calculate the size of objects for the Laplacian of Gaussian filter?:Yes
Enter LoG filter diameter:5
Handling of objects if excessive number of objects identified:Continue
Maximum number of objects:500
"""
pipeline = cellprofiler.pipeline.Pipeline()
def callback(pipeline, event):
self.assertFalse(isinstance(event, (cellprofiler.pipeline.RunExceptionEvent,
cellprofiler.pipeline.LoadExceptionEvent)))
pipeline.add_listener(callback)
pipeline.load(StringIO.StringIO(data))
x = pipeline.modules()[0]
self.assertTrue(isinstance(x, ID.IdentifyPrimaryObjects))
img = fly_image()[300:600,300:600]
image = cpi.Image(img)
#
# Make sure it runs both regular and with reduced image
#
for min_size in (9, 15):
#
# Exercise clumping / declumping options
#
x.size_range.min = min_size
for unclump_method in (ID.UN_INTENSITY, ID.UN_SHAPE, ID.UN_LOG):
x.unclump_method.value = unclump_method
for watershed_method in (ID.WA_INTENSITY, ID.WA_SHAPE, ID.WA_PROPAGATE):
x.watershed_method.value = watershed_method
image_set_list = cpi.ImageSetList()
image_set = image_set_list.get_image_set(0)
image_set.add(x.image_name.value, image)
object_set = cpo.ObjectSet()
measurements = cpmeas.Measurements()
x.run(Workspace(pipeline,x,image_set,object_set,measurements,None))
def test_02_13_maxima_suppression_zero(self):
# Regression test for issue #877
# if maxima_suppression_size = 1 or 0, use a 4-connected structuring
# element.
#
img = np.array(
[[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, .1, 0, 0, .1, 0, 0, .1, 0, 0],
[ 0, .1, 0, 0, 0, .2, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, .1, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
expected = np.array(
[[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 1, 0, 0, 2, 0, 0, 3, 0, 0],
[ 0, 1, 0, 0, 0, 2, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 4, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
for distance in (0, 1):
x = ID.IdentifyPrimaryObjects()
x.image_name.value = "my_image"
x.object_name.value = "my_object"
x.exclude_size.value = False
x.size_range.value = (2,10)
x.fill_holes.value = False
x.smoothing_filter_size.value = 0
x.automatic_smoothing.value = 0
x.maxima_suppression_size.value = distance
x.automatic_suppression.value = False
x.manual_threshold.value = .05
x.unclump_method.value = ID.UN_INTENSITY
x.watershed_method.value = ID.WA_INTENSITY
x.threshold_scope.value = I.TS_MANUAL
x.threshold_smoothing_choice.value = I.TSM_NONE
pipeline = cellprofiler.pipeline.Pipeline()
x.module_num = 1
pipeline.add_module(x)
object_set = cpo.ObjectSet()
measurements = cpmeas.Measurements()
measurements.add(x.image_name.value, cpi.Image(img))
x.run(Workspace(pipeline, x, measurements, object_set, measurements,
None))
output = object_set.get_objects(x.object_name.value)
self.assertEqual(output.count, 4)
self.assertTrue(np.all(output.segmented[expected == 0] == 0))
self.assertEqual(len(np.unique(output.segmented[expected == 1])), 1)
def test_02_14_automatic(self):
# Regression test of issue 1071 - automatic should yield same
# threshold regardless of manual parameters
#
r = np.random.RandomState()
r.seed(214)
image = r.uniform(size = (20, 20))
workspace, module = self.make_workspace(image)
assert isinstance(module, ID.IdentifyPrimaryObjects)
module.threshold_scope.value = I.TS_AUTOMATIC
module.run(workspace)
m = workspace.measurements
orig_threshold = m[cpmeas.IMAGE, I.FF_FINAL_THRESHOLD % OBJECTS_NAME]
workspace, module = self.make_workspace(image)
module.threshold_scope.value = I.TS_AUTOMATIC
module.threshold_method.value = I.TM_OTSU
module.threshold_smoothing_choice.value = I.TSM_MANUAL
module.threshold_smoothing_scale.value = 100
module.threshold_correction_factor.value = .1
module.threshold_range.min = .8
module.threshold_range.max = .81
module.run(workspace)
m = workspace.measurements
threshold = m[cpmeas.IMAGE, I.FF_FINAL_THRESHOLD % OBJECTS_NAME]
self.assertEqual(threshold, orig_threshold)
def test_04_01_load_matlab_12(self):
"""Test loading a Matlab version 12 IdentifyPrimAutomatic pipeline
"""
old_r12_file = 'TUFUTEFCIDUuMCBNQVQtZmlsZSwgUGxhdGZvcm06IFBDV0lOLCBDcmVhdGVkIG9uOiBXZWQgRGVjIDMxIDExOjQxOjUxIDIwMDggICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAABSU0PAAAAuAEAAHicxVRdT8IwFO3GWEQNEYmJvu3RB2K2xAcfNTFRHgQihujjBoXUbC3ZWgM++TP8Of4Uf4ot7LMSNqfgTZpx7u45p/eytg4AMGsA6Py5w5cKllENsZJaAvchpQhPgirQwHGY/+BrYPvIdlw4sF0GAxBHlG/jMXmYT+NXd2TEXNixvXQxjw7zHOgH3XFEDF/30Ay6ffQKQTaisnv4ggJEcMgP9eVs7Euo5Fvn61NL5qCsmEMzlRf1lyCp11bU76bqD0J8TQxMqMECmOhc5Ojoko6+mNPQhagYvyrxBbbM1rkZ+ps5/EqGXwFPfHZFeGqGp4IO+Z1f3rz3pD4F7tKAGTcucWw3nneev5LRUYBVck5myyrE0zI8DZhnplWk35rUr8BtTCEOEJ2H+f/WuWKUeDZFww3obOo7Knpu/0pn2+fvTVl/zzVS+bJ9Is+ewIlP2DTRuc3RaUg6AhPnGQ7pQshAeASnqX1t+5m3/0Np/wITRl2E4bcGhN4MrP8f0vdQEf8jyV/g9ghiisbzno+89BmSvx89x1/lv5oreGXvzyJ++yV4Gme+nyx5jz+c7+ma+iii/BfqTY0Q'
pipeline = cellprofiler.modules.tests.load_pipeline(self, old_r12_file)
pipeline.add_listener(self.load_error_handler)
self.assertEqual(len(pipeline.modules()),1)
module = pipeline.module(1)
self.assertTrue(isinstance(module,ID.IdentifyPrimaryObjects))
self.assertTrue(module.threshold_algorithm,T.TM_OTSU)
self.assertTrue(module.threshold_modifier,T.TM_GLOBAL)
self.assertAlmostEqual(float(module.object_fraction.value),.01)
self.assertEqual(module.object_name.value,"Nuclei")
self.assertEqual(module.image_name.value,"Do not use")
self.assertTrue(module.exclude_size.value)
self.assertEqual(module.fill_holes.value, ID.FH_THRESHOLDING)
self.assertTrue(module.exclude_border_objects.value)
self.assertTrue(module.automatic_smoothing.value)
self.assertTrue(module.automatic_suppression.value)
self.assertFalse(module.merge_objects.value)
self.assertTrue(module.image_name == cellprofiler.settings.DO_NOT_USE)
self.assertFalse(module.should_save_outlines.value)
self.assertEqual(module.save_outlines.value, "None")
self.assertAlmostEqual(module.threshold_range.min, 0)
self.assertAlmostEqual(module.threshold_range.max, 1)
self.assertAlmostEqual(module.threshold_correction_factor.value, 1)
self.assertEqual(module.watershed_method.value, "Intensity")
self.assertEqual(module.unclump_method.value, "Intensity")
self.assertAlmostEqual(module.maxima_suppression_size.value, 5)
def test_04_001_load_matlab_regression(self):
'''A regression test on a pipeline that misloaded the outlines variable'''
data = ('eJzzdQzxcXRSMNUzUPB1DNFNy8xJ1VEIyEksScsvyrVSCHAO9/TTUX'
'AuSk0sSU1RyM+zUvDNz1PwKs1TMLBQMDS1MjayMjJTMDIwsFQgGTAw'
'evryMzAwbGNiYKiY8zbCMf+ygUjZpWVaOVrJzJ3O/JZFEsqiMhabMj'
'mUNi5Luqyiopf3SqxZOrwzeOsfqTo29zqpwtlL+m5KXed9zRexac3z'
'Pd9/7j1/Xt8viqHhpjCD1MkbPrs4p531SnV+EbPPpedhgkjkAr55Sz'
'/vn1zH68zzmyXWWWgxxxPd2eXNintn+X9yFy8REL7SmhxomXm34o57'
'4hNe48NfCvnPC+w8Yi+gsc3nrfCsRxyXFbb6f3x6syb21JLSaM/63d'
'sfHZxQsUL1r8eM+BfNU+v+st3jY/nbvCV+oWT1xzy22rR+xc/7i+aY'
'q1r4crafjutwT+e8qvVtWsr5p8ZMze8zZfw6a/cmxLM/X24bnnq3bY'
've9N0b/QXCHq9Xvbm9qFo/jYW9hrv8aPxxy7q3DFstvqlW68UfmOnb'
'biZ3+KLS0tACOS+LGLvlZQ4zZd1fHgy4eT6KcTmbnbrLq2MPfQM9Ht'
'y56yqTxnicJXbV9PORcm9m/V/1U/vwzckFO95s1Nh2X/hWu8rxlbfW'
'G9X1MPUxWll/cr6n/nxH8IfkyxZxmrdO/nw5x2Ju7JPjzEBn5x0IEE'
'g0E/9z8hi/akW/qo3e44SG5RUCzpvWtE5sCN9av+ury/H+yzMuPmHt'
'r+W1f7LH8mZTf2ndiwe9Thb9NR4TGjbn7v0d/l77avGCV+15dSvuJZ'
'f85Ig75PUtMVrO6Hfn1n9yutcac1/fWpTR4yTlv+r4Sbe5u9x+359w'
'XqyhLOjxhZRmi/xd6RdTlz2Re1VXv+ZRzK7S2/vMVfasSa1YlqDeH/'
'qzNP7x5aM/5c/fPVJ8//imqiKOrj2FkTb/kxwFC2cfe1savu7/rtJP'
'yq3M4TtWrDzyOeTQw03WDoyHD1fqH0n+2Lfo0XVlzv7TL8sz/jnpnl'
'afyW88ka9/zdp9/max52+Z//9VH5gW7l+6b8veb+e/Fd2NT9hcW7/P'
'zT67fOl/9tZZsgEA6Ux4DA==')
pipeline = cellprofiler.pipeline.Pipeline()
pipeline.load(StringIO.StringIO(zlib.decompress(base64.b64decode(data))))
self.assertEqual(len(pipeline.modules()),3)
module = pipeline.modules()[1]
self.assertTrue(isinstance(module, ID.IdentifyPrimaryObjects))
self.assertTrue(module.should_save_outlines.value)
self.assertEqual(module.save_outlines.value, "NucleiOutlines")
def test_04_02_load_v1(self):
file = 'TUFUTEFCIDUuMCBNQVQtZmlsZSBQbGF0Zm9ybTogbnQsIENyZWF0ZWQgb246IE1vbiBBcHIgMDYgMTI6MzQ6MjQgMjAwOQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABSU0OAAAAoA0AAAYAAAAIAAAAAgAAAAAAAAAFAAAACAAAAAEAAAABAAAAAQAAAAgAAABTZXR0aW5ncwUABAAYAAAAAQAAAMAAAABWYXJpYWJsZVZhbHVlcwAAAAAAAAAAAABWYXJpYWJsZUluZm9UeXBlcwAAAAAAAABNb2R1bGVOYW1lcwAAAAAAAAAAAAAAAABOdW1iZXJzT2ZWYXJpYWJsZXMAAAAAAABQaXhlbFNpemUAAAAAAAAAAAAAAAAAAABWYXJpYWJsZVJldmlzaW9uTnVtYmVycwBNb2R1bGVSZXZpc2lvbk51bWJlcnMAAABNb2R1bGVOb3RlcwAAAAAAAAAAAAAAAAAOAAAAYAUAAAYAAAAIAAAAAQAAAAAAAAAFAAAACAAAAAEAAAAWAAAAAQAAAAAAAAAOAAAAMAAAAAYAAAAIAAAABAAAAAAAAAAFAAAACAAAAAEAAAAEAAAAAQAAAAAAAAAQAAQATm9uZQ4AAAA4AAAABgAAAAgAAAAEAAAAAAAAAAUAAAAIAAAAAQAAAAYAAAABAAAAAAAAABAAAAAGAAAATnVjbGVpAAAOAAAAOAAAAAYAAAAIAAAABAAAAAAAAAAFAAAACAAAAAEAAAAFAAAAAQAAAAAAAAAQAAAABQAAADEwLDQwAAAADgAAADAAAAAGAAAACAAAAAQAAAAAAAAABQAAAAgAAAABAAAAAwAAAAEAAAAAAAAAEAADAFllcwAOAAAAMAAAAAYAAAAIAAAABAAAAAAAAAAFAAAACAAAAAEAAAACAAAAAQAAAAAAAAAQAAIATm8AAA4AAAAwAAAABgAAAAgAAAAEAAAAAAAAAAUAAAAIAAAAAQAAAAMAAAABAAAAAAAAABAAAwBZZXMADgAAAEAAAAAGAAAACAAAAAQAAAAAAAAABQAAAAgAAAABAAAACwAAAAEAAAAAAAAAEAAAAAsAAABPdHN1IEdsb2JhbAAAAAAADgAAADAAAAAGAAAACAAAAAQAAAAAAAAABQAAAAgAAAABAAAAAQAAAAEAAAAAAAAAEAABADEAAAAOAAAASAAAAAYAAAAIAAAABAAAAAAAAAAFAAAACAAAAAEAAAARAAAAAQAAAAAAAAAQAAAAEQAAADAuMDAwMDAwLDEuMDAwMDAwAAAAAAAAAA4AAAAwAAAABgAAAAgAAAAEAAAAAAAAAAUAAAAIAAAAAQAAAAQAAAABAAAAAAAAABAABAAwLjAxDgAAAEAAAAAGAAAACAAAAAQAAAAAAAAABQAAAAgAAAABAAAACQAAAAEAAAAAAAAAEAAAAAkAAABJbnRlbnNpdHkAAAAAAAAADgAAAEAAAAAGAAAACAAAAAQAAAAAAAAABQAAAAgAAAABAAAACQAAAAEAAAAAAAAAEAAAAAkAAABJbnRlbnNpdHkAAAAAAAAADgAAADAAAAAGAAAACAAAAAQAAAAAAAAABQAAAAgAAAABAAAAAgAAAAEAAAAAAAAAEAACADEwAAAOAAAAMAAAAAYAAAAIAAAABAAAAAAAAAAFAAAACAAAAAEAAAABAAAAAQAAAAAAAAAQAAEANwAAAA4AAAAwAAAABgAAAAgAAAAEAAAAAAAAAAUAAAAIAAAAAQAAAAMAAAABAAAAAAAAABAAAwBZZXMADgAAAEAAAAAGAAAACAAAAAQAAAAAAAAABQAAAAgAAAABAAAACgAAAAEAAAAAAAAAEAAAAAoAAABEbyBub3QgdXNlAAAAAAAADgAAADAAAAAGAAAACAAAAAQAAAAAAAAABQAAAAgAAAABAAAAAwAAAAEAAAAAAAAAEAADAFllcwAOAAAAMAAAAAYAAAAIAAAABAAAAAAAAAAFAAAACAAAAAEAAAADAAAAAQAAAAAAAAAQAAMAWWVzAA4AAAAwAAAABgAAAAgAAAAEAAAAAAAAAAUAAAAIAAAAAQAAAAMAAAABAAAAAAAAABAAAwBZZXMADgAAADAAAAAGAAAACAAAAAQAAAAAAAAABQAAAAgAAAABAAAAAwAAAAEAAAAAAAAAEAADADAuMAAOAAAAMAAAAAYAAAAIAAAABAAAAAAAAAAFAAAACAAAAAEAAAAEAAAAAQAAAAAAAAAQAAQATm9uZQ4AAAAwAAAABgAAAAgAAAAEAAAAAAAAAAUAAAAIAAAAAQAAAAIAAAABAAAAAAAAABAAAgBObwAADgAAAEgFAAAGAAAACAAAAAEAAAAAAAAABQAAAAgAAAABAAAAFgAAAAEAAAAAAAAADgAAAEAAAAAGAAAACAAAAAQAAAAAAAAABQAAAAgAAAABAAAACgAAAAEAAAAAAAAAEAAAAAoAAABpbWFnZWdyb3VwAAAAAAAADgAAAEgAAAAGAAAACAAAAAQAAAAAAAAABQAAAAgAAAABAAAAEQAAAAEAAAAAAAAAEAAAABEAAABvYmplY3Rncm91cCBpbmRlcAAAAAAAAAAOAAAAMAAAAAYAAAAIAAAABgAAAAAAAAAFAAAACAAAAAAAAAAAAAAAAQAAAAAAAAAJAAAAAAAAAA4AAAAwAAAABgAAAAgAAAAGAAAAAAAAAAUAAAAIAAAAAAAAAAAAAAABAAAAAAAAAAkAAAAAAAAADgAAADAAAAAGAAAACAAAAAYAAAAAAAAABQAAAAgAAAAAAAAAAAAAAAEAAAAAAAAACQAAAAAAAAAOAAAAMAAAAAYAAAAIAAAABgAAAAAAAAAFAAAACAAAAAAAAAAAAAAAAQAAAAAAAAAJAAAAAAAAAA4AAAAwAAAABgAAAAgAAAAGAAAAAAAAAAUAAAAIAAAAAAAAAAAAAAABAAAAAAAAAAkAAAAAAAAADgAAADAAAAAGAAAACAAAAAYAAAAAAAAABQAAAAgAAAAAAAAAAAAAAAEAAAAAAAAACQAAAAAAAAAOAAAAMAAAAAYAAAAIAAAABgAAAAAAAAAFAAAACAAAAAAAAAAAAAAAAQAAAAAAAAAJAAAAAAAAAA4AAAAwAAAABgAAAAgAAAAGAAAAAAAAAAUAAAAIAAAAAAAAAAAAAAABAAAAAAAAAAkAAAAAAAAADgAAADAAAAAGAAAACAAAAAYAAAAAAAAABQAAAAgAAAAAAAAAAAAAAAEAAAAAAAAACQAAAAAAAAAOAAAAMAAAAAYAAAAIAAAABgAAAAAAAAAFAAAACAAAAAAAAAAAAAAAAQAAAAAAAAAJAAAAAAAAAA4AAAAwAAAABgAAAAgAAAAGAAAAAAAAAAUAAAAIAAAAAAAAAAAAAAABAAAAAAAAAAkAAAAAAAAADgAAADAAAAAGAAAACAAAAAYAAAAAAAAABQAAAAgAAAAAAAAAAAAAAAEAAAAAAAAACQAAAAAAAAAOAAAAMAAAAAYAAAAIAAAABgAAAAAAAAAFAAAACAAAAAAAAAAAAAAAAQAAAAAAAAAJAAAAAAAAAA4AAABIAAAABgAAAAgAAAAEAAAAAAAAAAUAAAAIAAAAAQAAABIAAAABAAAAAAAAABAAAAASAAAAb3V0bGluZWdyb3VwIGluZGVwAAAAAAAADgAAADAAAAAGAAAACAAAAAYAAAAAAAAABQAAAAgAAAAAAAAAAAAAAAEAAAAAAAAACQAAAAAAAAAOAAAAMAAAAAYAAAAIAAAABgAAAAAAAAAFAAAACAAAAAAAAAAAAAAAAQAAAAAAAAAJAAAAAAAAAA4AAAAwAAAABgAAAAgAAAAGAAAAAAAAAAUAAAAIAAAAAAAAAAAAAAABAAAAAAAAAAkAAAAAAAAADgAAADAAAAAGAAAACAAAAAYAAAAAAAAABQAAAAgAAAAAAAAAAAAAAAEAAAAAAAAACQAAAAAAAAAOAAAAQAAAAAYAAAAIAAAABAAAAAAAAAAFAAAACAAAAAEAAAAKAAAAAQAAAAAAAAAQAAAACgAAAGltYWdlZ3JvdXAAAAAAAAAOAAAAMAAAAAYAAAAIAAAABgAAAAAAAAAFAAAACAAAAAAAAAAAAAAAAQAAAAAAAAAJAAAAAAAAAA4AAACgAAAABgAAAAgAAAABAAAAAAAAAAUAAAAIAAAAAQAAAAEAAAABAAAAAAAAAA4AAABwAAAABgAAAAgAAAAEAAAAAAAAAAUAAAAIAAAAAQAAAEAAAAABAAAAAAAAABAAAABAAAAAY2VsbHByb2ZpbGVyLm1vZHVsZXMuaWRlbnRpZnlwcmltYXV0b21hdGljLklkZW50aWZ5UHJpbUF1dG9tYXRpYw4AAAAwAAAABgAAAAgAAAAJAAAAAAAAAAUAAAAIAAAAAQAAAAEAAAABAAAAAAAAAAIAAQAWAAAADgAAADAAAAAGAAAACAAAAAYAAAAAAAAABQAAAAAAAAABAAAAAAAAAAkAAAAIAAAAAAAAAAAA8D8OAAAAMAAAAAYAAAAIAAAACQAAAAAAAAAFAAAACAAAAAEAAAABAAAAAQAAAAAAAAACAAEAAQAAAA4AAAAwAAAABgAAAAgAAAALAAAAAAAAAAUAAAAIAAAAAQAAAAEAAAABAAAAAAAAAAQAAgAAAAAADgAAAFgAAAAGAAAACAAAAAEAAAAAAAAABQAAAAgAAAABAAAAAQAAAAEAAAAAAAAADgAAACgAAAAGAAAACAAAAAEAAAAAAAAABQAAAAgAAAAAAAAAAQAAAAEAAAAAAAAA'
pipeline = cellprofiler.modules.tests.load_pipeline(self,file)
pipeline.add_listener(self.load_error_handler)
self.assertEqual(len(pipeline.modules()),1)
module = pipeline.module(1)
self.assertTrue(isinstance(module,ID.IdentifyPrimaryObjects))
self.assertEqual(module.threshold_algorithm,T.TM_OTSU)
self.assertEqual(module.threshold_modifier,T.TM_GLOBAL)
self.assertTrue(module.image_name == 'None')
def test_04_03_load_v3(self):
data = ('eJztWVtP2zAUTktBMMbG9rJJaJIfYWurpIAGaAI6uku3tlTQcRFim9'
'u6rSfXrhKH0U1Ie9zP2k/aT1gc0jY1l4T0IpgaFKXn5HznO+f4Ehtn'
'k4VM8jVYjqsgmyzEKpggkCeQV5heXwOUR8GWjiBHZcDoGsgyCj6YFK'
'grQEusLS6taQmQUNVVJdgVSmcfWI+DZ4oyYT0nrTvsvBp35JDrFvIu'
'4hzTqjGuRJSnjv6Pde9BHcMiQXuQmMjoULT0aVphhWaj/SrLyiZBOV'
'h3G1tXzqwXkW5sV1pA53UenyKyi38gKYWW2Q46wQZm1ME7/mVtm5dx'
'iVfUoTHTqUNIqoOoy5xLL+zfKx37yCV1e+Syn3VkTMv4BJdNSACuw2'
'o7CuFP9fA31uVvTEnlkjZu0wM3K8Uh7gI65bE3p7DEQR3yUk34WfHw'
'MyH5EXLOLBGE/cUf6sKHlEUnby/ecYlXyJoaXVJ7wKczmU/ZgHU/tF'
'rNDy7chQsrOeaP7yqcV397IuUp5BSqQJNwkBadDaSwjkqc6c2+5T0h'
'4VpXCzflPP3002kpfiFvc8ME7wgrQtL2M6j2knFaXO2JL8j8oMZV+4'
'pqzg9X/bz6+aTkT8hbNUgpIgk/eUS68BERizbIeWlKilfIacoRNTBv'
'uvK+6byiKf76W7/45brlGEVBxrmmnvP98sB9lOIW8uf5jfwrsXBA6/'
'EXC1+EtI8I2WHf14+SsfzxQkuzxYhZp+tHamz1+KcWTZydG+9iC2kr'
'FwLX/aWDq3ngVqT4hSxiOERQdwJbOluICZW14OE1R5dwdCnY7Ghu4z'
'x2T8pPyCkGKOPANFDHT1D+Yec74uvmUy/5LvSTz8980k8+P+uU/6v9'
'lgc6/meU7vEv5EJNRwiUCDQMe83fC3+QdcU+wtWa2EaeiA0TLSGXv2'
'HOg2+Zjqo6M2m54+fg/s32XcOM196kiYAbvfMHaTdW/Gat2O0AgLV3'
'RI0+1GGEG+FGuN5xmy6c3/+7dOaT8+F8l/Id4W4Hzus78ljp7ndCZi'
'YnmKILH5K7lPcIN9z5a9DroRFuhBsGbjJ09f5C3v8K+6/K9ePiudI9'
'LoRcQoQ0dCbO7/R43T5kMuKEwfL5KU88Y/1Muw587PMmD55NiWfzKh'
'5cRpTjSrOhW2wmZ3XIcSmedrR5S5tsaeU6Tl3C665H2Pp7OHd9/eW6'
'd9rj70YQvvDYRb5pD1zEqaDA/VZu1t7z19i3cgtq/w8+vUjz')
fd = StringIO.StringIO(zlib.decompress(base64.b64decode(data)))
pipeline = cellprofiler.pipeline.Pipeline()
pipeline.add_listener(self.load_error_handler)
pipeline.load(fd)
self.assertEqual(len(pipeline.modules()),2)
module = pipeline.modules()[1]
self.assertTrue(isinstance(module,ID.IdentifyPrimaryObjects))
self.assertTrue(module.threshold_algorithm,T.TM_OTSU)
self.assertTrue(module.threshold_modifier,T.TM_GLOBAL)
self.assertEqual(module.two_class_otsu.value, I.O_THREE_CLASS)
self.assertEqual(module.use_weighted_variance.value,
I.O_WEIGHTED_VARIANCE)
self.assertEqual(module.assign_middle_to_foreground.value,
I.O_FOREGROUND)
def test_04_04_load_v4(self):
data = ('eJztWd1u0zAUdrtu2piGBjdwM+RLhLYo2VYxekPLyqCo7SZWhrjDTd3WyLWr'
'xJlWnoBLHolLHodHIO6SNvG6JUvaiaGkitLj+Dvf+bFP7KRRadUrb2BR02Gj'
'0trpEorhCUWiy61BCTKxDQ8tjATuQM5K8Mgi8IND4e4+NIolQy/t7cFdXX8F'
'kh25WuOhe/n5DIAV97rqnnnv1rIn5wKnlE+xEIT17GVQAE+99l/ueYYsgtoU'
'nyHqYHtK4bfXWJe3RsPJrQbvOBQ30SDY2T2azqCNLfu46wO92yfkAtNT8h0r'
'LvjdPuJzYhPOPLynX22d8HKh8Mo4/N6YxiGnxEHGZSvQLvu/B9P+hRlxexTo'
'v+nJhHXIOek4iEIyQL2JFVKfHqFvKaRvCVSblTGuHIHbVOyQZwtfiJ23F8gU'
'cICE2Zd6DiL0rCh6pNx0TIpJPPtzIXwO7Hl+R/EuK7xSNvTtfT0Fvlavf2ok'
'jPsXN2txcPkQLg+aPB7fdbio8fZE8VPKVdxFDhWwJgcbrBILm4Jbo7n5vaLg'
'/MPHrXnXOON0XbFfysfCduA7ytuITvQsKl8qztD0VHxJ6oOu6eNj2/D+BOK3'
'KL8LIVxB2mDEmVerIGy/lA/7iDFMd+Pke03BS7nGBGY2EaMUfseti/PiV+ua'
'EROnznNDj4dT89XkDCex82VMO5PyzWs8+nzlCNwDEM6nlKscMi6gY3sLhzT1'
'667rZcYX5tNn1ON58sUZ5/Pki7M++L/yV1zo+mEDhOe/lFt9C2NoUmTb47V2'
'Gv4kz/PPmPT6cvt2LjcqzMQBfYuKw6w6eMQt3LO4wzrp+f+1caY+14oe7uCW'
'+7m7zMd48ycTMkzPn2Rc8vY3dycwNgC6e1I8nEMcMlyGy3D3D1cO4OK+P5rW'
'r8vycZ/8zXDJniOPQXgcSJk7ghKGrzxI7pPfGe5u68mi10MZLsNluPS41dz1'
'+yf1/YXs/zXAM2vevwDheS9lE1M6tLj87mlpg/HHOVujHHUuv45pdfdvLfCh'
'TPIMI3jKCk/5Oh7SwUyQ7mhouWyO4AMkiKnVvNYTt7Xit6pxXJvBG4xH3v1t'
'bt0cfzXu03z8eZ2Eb6lwlW89AlfwIihxP8Dt8v38hv6+b0n7/wXQ1Cms')
pipeline = cellprofiler.pipeline.Pipeline()
def callback(caller,event):
self.assertFalse(
isinstance(event, cellprofiler.pipeline.LoadExceptionEvent))
pipeline.add_listener(callback)
pipeline.load(
StringIO.StringIO(zlib.decompress(base64.b64decode(data))))
self.assertEqual(len(pipeline.modules()),2)
module = pipeline.modules()[1]
self.assertTrue(isinstance(module,ID.IdentifyPrimaryObjects))
self.assertTrue(module.threshold_algorithm,T.TM_OTSU)
self.assertTrue(module.threshold_modifier,T.TM_GLOBAL)
self.assertEqual(module.two_class_otsu.value, I.O_THREE_CLASS)
self.assertEqual(module.use_weighted_variance.value,
I.O_WEIGHTED_VARIANCE)
self.assertEqual(module.assign_middle_to_foreground.value,
I.O_FOREGROUND)
def test_04_05_load_v5(self):
data = r"""CellProfiler Pipeline: http://www.cellprofiler.org
Version:1
SVNRevision:9008
LoadImages:[module_num:1|svn_version:\'8947\'|variable_revision_number:4|show_window:True|notes:\x5B\x5D]
What type of files are you loading?:individual images
How do you want to load these files?:Text-Exact match
How many images are there in each group?:3
Type the text that the excluded images have in common:Do not use
Analyze all subfolders within the selected folder?:No
Image location:Default Image Folder
Enter the full path to the images:
Do you want to check image sets for missing or duplicate files?:Yes
Do you want to group image sets by metadata?:No
Do you want to exclude certain files?:No
What metadata fields do you want to group by?:
Type the text that these images have in common (case-sensitive):
What do you want to call this image in CellProfiler?:DNA
What is the position of this image in each group?:1
Do you want to extract metadata from the file name, the subfolder path or both?:None
Type the regular expression that finds metadata in the file name\x3A:^(?P<Plate>.*)_(?P<Well>\x5BA-P\x5D\x5B0-9\x5D{2})_s(?P<Site>\x5B0-9\x5D)
Type the regular expression that finds metadata in the subfolder path\x3A:.*\x5B\\\\/\x5D(?P<Date>.*)\x5B\\\\/\x5D(?P<Run>.*)$
IdentifyPrimaryObjects:[module_num:2|svn_version:\'8981\'|variable_revision_number:5|show_window:True|notes:\x5B\x5D]
Select the input image:DNA
Name the identified primary objects:MyObjects
Typical diameter of objects, in pixel units (Min,Max)\x3A:12,42
Discard objects outside the diameter range?:Yes
Try to merge too small objects with nearby larger objects?:No
Discard objects touching the border of the image?:Yes
Select the thresholding method:RobustBackground Global
Threshold correction factor:1.2
Lower and upper bounds on threshold\x3A:0.1,0.6
Approximate fraction of image covered by objects?:0.01
Method to distinguish clumped objects:Shape
Method to draw dividing lines between clumped objects:Distance
Size of smoothing filter\x3A:10
Suppress local maxima within this distance\x3A:7
Speed up by using lower-resolution image to find local maxima?:Yes
Name the outline image:MyOutlines
Fill holes in identified objects?:Yes
Automatically calculate size of smoothing filter?:Yes
Automatically calculate minimum size of local maxima?:Yes
Enter manual threshold\x3A:0.0
Select binary image\x3A:MyBinaryImage
Save outlines of the identified objects?:No
Calculate the Laplacian of Gaussian threshold automatically?:Yes
Enter Laplacian of Gaussian threshold\x3A:0.5
Two-class or three-class thresholding?:Two classes
Minimize the weighted variance or the entropy?:Weighted variance
Assign pixels in the middle intensity class to the foreground or the background?:Foreground
Automatically calculate the size of objects for the Laplacian of Gaussian filter?:Yes
Enter LoG filter diameter\x3A :5
How do you want to handle images with large numbers of objects?:Truncate
Maximum # of objects\x3A:305
IdentifyPrimaryObjects:[module_num:3|svn_version:\'8981\'|variable_revision_number:5|show_window:True|notes:\x5B\x5D]
Select the input image:DNA
Name the identified primary objects:MyObjects
Typical diameter of objects, in pixel units (Min,Max)\x3A:12,42
Discard objects outside the diameter range?:No
Try to merge too small objects with nearby larger objects?:Yes
Discard objects touching the border of the image?:No
Select the thresholding method:Otsu Adaptive
Threshold correction factor:1.2
Lower and upper bounds on threshold\x3A:0.1,0.6
Approximate fraction of image covered by objects?:0.01
Method to distinguish clumped objects:Intensity
Method to draw dividing lines between clumped objects:Propagate
Size of smoothing filter\x3A:10
Suppress local maxima within this distance\x3A:7
Speed up by using lower-resolution image to find local maxima?:No
Name the outline image:MyOutlines
Fill holes in identified objects?:No
Automatically calculate size of smoothing filter?:No
Automatically calculate minimum size of local maxima?:No
Enter manual threshold\x3A:0.0
Select binary image\x3A:MyBinaryImage
Save outlines of the identified objects?:Yes
Calculate the Laplacian of Gaussian threshold automatically?:No
Enter Laplacian of Gaussian threshold\x3A:0.5
Two-class or three-class thresholding?:Three classes
Minimize the weighted variance or the entropy?:Entropy
Assign pixels in the middle intensity class to the foreground or the background?:Background
Automatically calculate the size of objects for the Laplacian of Gaussian filter?:No
Enter LoG filter diameter\x3A :5
How do you want to handle images with large numbers of objects?:Erase
Maximum # of objects\x3A:305
"""
pipeline = cellprofiler.pipeline.Pipeline()
def callback(caller,event):
self.assertFalse(
isinstance(event, cellprofiler.pipeline.LoadExceptionEvent))
pipeline.add_listener(callback)
pipeline.load(StringIO.StringIO(data))
self.assertEqual(len(pipeline.modules()),3)
module = pipeline.modules()[1]
self.assertTrue(isinstance(module, ID.IdentifyPrimaryObjects))
self.assertEqual(module.image_name, "DNA")
self.assertEqual(module.object_name, "MyObjects")
self.assertEqual(module.size_range.min, 12)
self.assertEqual(module.size_range.max, 42)
self.assertTrue(module.exclude_size)
self.assertFalse(module.merge_objects)
self.assertTrue(module.exclude_border_objects)
self.assertEqual(module.threshold_algorithm, T.TM_ROBUST_BACKGROUND)
self.assertEqual(module.threshold_modifier, T.TM_GLOBAL)
self.assertAlmostEqual(module.threshold_correction_factor.value, 1.2)
self.assertAlmostEqual(module.threshold_range.min, 0.1)
self.assertAlmostEqual(module.threshold_range.max, 0.6)
self.assertEqual(module.object_fraction.value, "0.01")
self.assertEqual(module.unclump_method, ID.UN_SHAPE)
self.assertEqual(module.watershed_method, ID.WA_SHAPE)
self.assertEqual(module.smoothing_filter_size, 10)
self.assertEqual(module.maxima_suppression_size, 7)
self.assertFalse(module.should_save_outlines)
self.assertEqual(module.save_outlines, "MyOutlines")
self.assertEqual(module.fill_holes, ID.FH_THRESHOLDING)
self.assertTrue(module.automatic_smoothing)
self.assertTrue(module.automatic_suppression)
self.assertEqual(module.manual_threshold, 0)
self.assertEqual(module.binary_image, "MyBinaryImage")
self.assertTrue(module.wants_automatic_log_threshold)
self.assertAlmostEqual(module.manual_log_threshold.value, 0.5)
self.assertEqual(module.two_class_otsu, I.O_TWO_CLASS)
self.assertEqual(module.use_weighted_variance, I.O_WEIGHTED_VARIANCE)
self.assertEqual(module.assign_middle_to_foreground, I.O_FOREGROUND)
self.assertTrue(module.wants_automatic_log_diameter)
self.assertEqual(module.log_diameter, 5)
self.assertEqual(module.limit_choice, ID.LIMIT_TRUNCATE)
self.assertEqual(module.maximum_object_count, 305)
module = pipeline.modules()[2]
self.assertTrue(isinstance(module, ID.IdentifyPrimaryObjects))
self.assertEqual(module.image_name, "DNA")
self.assertEqual(module.object_name, "MyObjects")
self.assertEqual(module.size_range.min, 12)
self.assertEqual(module.size_range.max, 42)
self.assertFalse(module.exclude_size)
self.assertTrue(module.merge_objects)
self.assertFalse(module.exclude_border_objects)
self.assertEqual(module.threshold_algorithm, T.TM_OTSU)
self.assertEqual(module.threshold_modifier, T.TM_ADAPTIVE)
self.assertAlmostEqual(module.threshold_correction_factor.value, 1.2)
self.assertAlmostEqual(module.threshold_range.min, 0.1)
self.assertAlmostEqual(module.threshold_range.max, 0.6)
self.assertEqual(module.object_fraction.value, "0.01")
self.assertEqual(module.unclump_method, ID.UN_INTENSITY)
self.assertEqual(module.watershed_method, ID.WA_PROPAGATE)
self.assertEqual(module.smoothing_filter_size, 10)
self.assertEqual(module.maxima_suppression_size, 7)
self.assertTrue(module.should_save_outlines)
self.assertEqual(module.save_outlines, "MyOutlines")
self.assertEqual(module.fill_holes, ID.FH_NEVER)
self.assertFalse(module.automatic_smoothing)
self.assertFalse(module.automatic_suppression)
self.assertEqual(module.manual_threshold, 0)
self.assertEqual(module.binary_image, "MyBinaryImage")
self.assertFalse(module.wants_automatic_log_threshold)
self.assertAlmostEqual(module.manual_log_threshold.value, 0.5)
self.assertEqual(module.two_class_otsu, I.O_THREE_CLASS)
self.assertEqual(module.use_weighted_variance, I.O_ENTROPY)
self.assertEqual(module.assign_middle_to_foreground, I.O_BACKGROUND)
self.assertFalse(module.wants_automatic_log_diameter)
self.assertEqual(module.log_diameter, 5)
self.assertEqual(module.limit_choice, ID.LIMIT_ERASE)
self.assertEqual(module.maximum_object_count, 305)
# Missing tests for versions 6-9 (!)
def test_04_10_load_v10(self):
# Sorry about this overly-long pipeline, it seemed like we need to
# revisit many of the choices.
data = r"""CellProfiler Pipeline: http://www.cellprofiler.org
Version:3
DateRevision:20130226215424
ModuleCount:11
HasImagePlaneDetails:False
Images:[module_num:1|svn_version:\'Unknown\'|variable_revision_number:1|show_window:False|notes:\x5B\x5D|batch_state:array(\x5B\x5D, dtype=uint8)|enabled:True]
:
Filter based on rules:No
Filter:or (file does contain "")
Metadata:[module_num:2|svn_version:\'Unknown\'|variable_revision_number:2|show_window:False|notes:\x5B\x5D|batch_state:array(\x5B\x5D, dtype=uint8)|enabled:True]
Extract metadata?:Yes
Extraction method count:2
Extraction method:Automatic
Source:From file name
Regular expression:^(?P<Plate>.*)_(?P<Well>\x5BA-P\x5D\x5B0-9\x5D{2})_s(?P<Site>\x5B0-9\x5D)_w(?P<ChannelNumber>\x5B0-9\x5D)
Regular expression:(?P<Date>\x5B0-9\x5D{4}_\x5B0-9\x5D{2}_\x5B0-9\x5D{2})$
Filter images:All images
:or (file does contain "")
Metadata file location\x3A:
Match file and image metadata:\x5B\x5D
Case insensitive matching:No
Extraction method:Manual
Source:From file name
Regular expression:^(?P<StackName>\x5B^.\x5D+).flex
Regular expression:(?P<Date>\x5B0-9\x5D{4}_\x5B0-9\x5D{2}_\x5B0-9\x5D{2})$
Filter images:All images
:or (file does contain "")
Metadata file location\x3A:
Match file and image metadata:\x5B\x5D
Case insensitive matching:No
NamesAndTypes:[module_num:3|svn_version:\'Unknown\'|variable_revision_number:1|show_window:False|notes:\x5B\x5D|batch_state:array(\x5B\x5D, dtype=uint8)|enabled:True]
Assignment method:Assign all images
Load as:Grayscale image
Image name:Channel0
:\x5B\x5D
Assign channels by:Order
Assignments count:1
Match this rule:or (metadata does StackName "")
Image name:DNA
Objects name:Cell
Load as:Grayscale image
Groups:[module_num:4|svn_version:\'Unknown\'|variable_revision_number:2|show_window:False|notes:\x5B\x5D|batch_state:array(\x5B\x5D, dtype=uint8)|enabled:True]
Do you want to group your images?:Yes
grouping metadata count:1
Metadata category:StackName
IdentifyPrimaryObjects:[module_num:5|svn_version:\'Unknown\'|variable_revision_number:10|show_window:True|notes:\x5B\x5D|batch_state:array(\x5B\x5D, dtype=uint8)|enabled:True]
Select the input image:Channel0
Name the primary objects to be identified:Cells
Typical diameter of objects, in pixel units (Min,Max):15,45
Discard objects outside the diameter range?:Yes
Try to merge too small objects with nearby larger objects?:No
Discard objects touching the border of the image?:Yes
Method to distinguish clumped objects:Intensity
Method to draw dividing lines between clumped objects:Intensity
Size of smoothing filter:11
Suppress local maxima that are closer than this minimum allowed distance:9
Speed up by using lower-resolution image to find local maxima?:Yes
Name the outline image:CellOutlines
Fill holes in identified objects?:Yes
Automatically calculate size of smoothing filter?:Yes
Automatically calculate minimum allowed distance between local maxima?:Yes
Retain outlines of the identified objects?:No
Automatically calculate the threshold using the Otsu method?:Yes
Enter Laplacian of Gaussian threshold:0.2
Automatically calculate the size of objects for the Laplacian of Gaussian filter?:Yes
Enter LoG filter diameter:3
Handling of objects if excessive number of objects identified:Continue
Maximum number of objects:499
Threshold setting version:1
Threshold strategy:Adaptive
Threshold method:Otsu
Smoothing for threshold:Automatic
Threshold smoothing scale:2.0
Threshold correction factor:.80
Lower and upper bounds on threshold:0.01,0.90
Approximate fraction of image covered by objects?:0.05
Manual threshold:0.03
Select the measurement to threshold with:Metadata_Threshold
Select binary image:Segmentation
Masking objects:Wells
Two-class or three-class thresholding?:Two classes
Minimize the weighted variance or the entropy?:Weighted variance
Assign pixels in the middle intensity class to the foreground or the background?:Foreground
Method to calculate adaptive window size:Image size
Size of adaptive window:12
IdentifyPrimaryObjects:[module_num:6|svn_version:\'Unknown\'|variable_revision_number:10|show_window:True|notes:\x5B\x5D|batch_state:array(\x5B\x5D, dtype=uint8)|enabled:True]
Select the input image:Channel1
Name the primary objects to be identified:Cells
Typical diameter of objects, in pixel units (Min,Max):15,45
Discard objects outside the diameter range?:No
Try to merge too small objects with nearby larger objects?:Yes
Discard objects touching the border of the image?:No
Method to distinguish clumped objects:Laplacian of Gaussian
Method to draw dividing lines between clumped objects:None
Size of smoothing filter:11
Suppress local maxima that are closer than this minimum allowed distance:9
Speed up by using lower-resolution image to find local maxima?:No
Name the outline image:CellOutlines
Fill holes in identified objects?:No
Automatically calculate size of smoothing filter?:No
Automatically calculate minimum allowed distance between local maxima?:No
Retain outlines of the identified objects?:Yes
Automatically calculate the threshold using the Otsu method?:No
Enter Laplacian of Gaussian threshold:0.2
Automatically calculate the size of objects for the Laplacian of Gaussian filter?:No
Enter LoG filter diameter:3
Handling of objects if excessive number of objects identified:Erase
Maximum number of objects:499
Threshold setting version:1
Threshold strategy:Automatic
Threshold method:MCT
Smoothing for threshold:Manual
Threshold smoothing scale:2.0
Threshold correction factor:.80
Lower and upper bounds on threshold:0.01,0.09
Approximate fraction of image covered by objects?:0.05
Manual threshold:0.03
Select the measurement to threshold with:Metadata_Threshold
Select binary image:Segmentation
Masking objects:Wells
Two-class or three-class thresholding?:Three classes
Minimize the weighted variance or the entropy?:Entropy
Assign pixels in the middle intensity class to the foreground or the background?:Background
Method to calculate adaptive window size:Custom
Size of adaptive window:12
IdentifyPrimaryObjects:[module_num:7|svn_version:\'Unknown\'|variable_revision_number:10|show_window:True|notes:\x5B\x5D|batch_state:array(\x5B\x5D, dtype=uint8)|enabled:True]
Select the input image:Channel2
Name the primary objects to be identified:Cells
Typical diameter of objects, in pixel units (Min,Max):15,45
Discard objects outside the diameter range?:No
Try to merge too small objects with nearby larger objects?:Yes
Discard objects touching the border of the image?:No
Method to distinguish clumped objects:None
Method to draw dividing lines between clumped objects:Propagate
Size of smoothing filter:11
Suppress local maxima that are closer than this minimum allowed distance:9
Speed up by using lower-resolution image to find local maxima?:No
Name the outline image:CellOutlines
Fill holes in identified objects?:No
Automatically calculate size of smoothing filter?:No
Automatically calculate minimum allowed distance between local maxima?:No
Retain outlines of the identified objects?:Yes
Automatically calculate the threshold using the Otsu method?:No
Enter Laplacian of Gaussian threshold:0.2
Automatically calculate the size of objects for the Laplacian of Gaussian filter?:No
Enter LoG filter diameter:3
Handling of objects if excessive number of objects identified:Truncate
Maximum number of objects:499
Threshold setting version:1
Threshold strategy:Binary image
Threshold method:MoG
Smoothing for threshold:No smoothing
Threshold smoothing scale:2.0
Threshold correction factor:.80
Lower and upper bounds on threshold:0.01,0.09
Approximate fraction of image covered by objects?:0.05
Manual threshold:0.03
Select the measurement to threshold with:Metadata_Threshold
Select binary image:Segmentation
Masking objects:Wells
Two-class or three-class thresholding?:Three classes
Minimize the weighted variance or the entropy?:Entropy
Assign pixels in the middle intensity class to the foreground or the background?:Background
Method to calculate adaptive window size:Custom
Size of adaptive window:12
IdentifyPrimaryObjects:[module_num:8|svn_version:\'Unknown\'|variable_revision_number:10|show_window:True|notes:\x5B\x5D|batch_state:array(\x5B\x5D, dtype=uint8)|enabled:True]
Select the input image:Channel3
Name the primary objects to be identified:Cells
Typical diameter of objects, in pixel units (Min,Max):15,45
Discard objects outside the diameter range?:No
Try to merge too small objects with nearby larger objects?:Yes
Discard objects touching the border of the image?:No
Method to distinguish clumped objects:Shape
Method to draw dividing lines between clumped objects:Shape
Size of smoothing filter:11
Suppress local maxima that are closer than this minimum allowed distance:9
Speed up by using lower-resolution image to find local maxima?:No
Name the outline image:CellOutlines
Fill holes in identified objects?:No
Automatically calculate size of smoothing filter?:No
Automatically calculate minimum allowed distance between local maxima?:No
Retain outlines of the identified objects?:Yes
Automatically calculate the threshold using the Otsu method?:No
Enter Laplacian of Gaussian threshold:0.2
Automatically calculate the size of objects for the Laplacian of Gaussian filter?:No
Enter LoG filter diameter:3
Handling of objects if excessive number of objects identified:Truncate
Maximum number of objects:499
Threshold setting version:1
Threshold strategy:Global
Threshold method:Background
Smoothing for threshold:No smoothing
Threshold smoothing scale:2.0
Threshold correction factor:.80
Lower and upper bounds on threshold:0.01,0.09
Approximate fraction of image covered by objects?:0.05
Manual threshold:0.03
Select the measurement to threshold with:Metadata_Threshold
Select binary image:Segmentation
Masking objects:Wells
Two-class or three-class thresholding?:Three classes
Minimize the weighted variance or the entropy?:Entropy
Assign pixels in the middle intensity class to the foreground or the background?:Background
Method to calculate adaptive window size:Custom
Size of adaptive window:12
IdentifyPrimaryObjects:[module_num:9|svn_version:\'Unknown\'|variable_revision_number:10|show_window:True|notes:\x5B\x5D|batch_state:array(\x5B\x5D, dtype=uint8)|enabled:True]
Select the input image:Channel4
Name the primary objects to be identified:Cells
Typical diameter of objects, in pixel units (Min,Max):15,45
Discard objects outside the diameter range?:No
Try to merge too small objects with nearby larger objects?:Yes
Discard objects touching the border of the image?:No
Method to distinguish clumped objects:Shape
Method to draw dividing lines between clumped objects:Shape
Size of smoothing filter:11
Suppress local maxima that are closer than this minimum allowed distance:9
Speed up by using lower-resolution image to find local maxima?:No
Name the outline image:CellOutlines
Fill holes in identified objects?:No
Automatically calculate size of smoothing filter?:No
Automatically calculate minimum allowed distance between local maxima?:No
Retain outlines of the identified objects?:Yes
Automatically calculate the threshold using the Otsu method?:No
Enter Laplacian of Gaussian threshold:0.2
Automatically calculate the size of objects for the Laplacian of Gaussian filter?:No
Enter LoG filter diameter:3
Handling of objects if excessive number of objects identified:Truncate
Maximum number of objects:499
Threshold setting version:1
Threshold strategy:Manual
Threshold method:Kapur
Smoothing for threshold:No smoothing
Threshold smoothing scale:2.0
Threshold correction factor:.80
Lower and upper bounds on threshold:0.01,0.09
Approximate fraction of image covered by objects?:0.05
Manual threshold:0.03
Select the measurement to threshold with:Metadata_Threshold
Select binary image:Segmentation
Masking objects:Wells
Two-class or three-class thresholding?:Three classes
Minimize the weighted variance or the entropy?:Entropy
Assign pixels in the middle intensity class to the foreground or the background?:Background
Method to calculate adaptive window size:Custom
Size of adaptive window:12
IdentifyPrimaryObjects:[module_num:10|svn_version:\'Unknown\'|variable_revision_number:10|show_window:True|notes:\x5B\x5D|batch_state:array(\x5B\x5D, dtype=uint8)|enabled:True]
Select the input image:Channel4
Name the primary objects to be identified:Cells
Typical diameter of objects, in pixel units (Min,Max):15,45
Discard objects outside the diameter range?:No
Try to merge too small objects with nearby larger objects?:Yes
Discard objects touching the border of the image?:No
Method to distinguish clumped objects:Shape
Method to draw dividing lines between clumped objects:Shape
Size of smoothing filter:11
Suppress local maxima that are closer than this minimum allowed distance:9
Speed up by using lower-resolution image to find local maxima?:No
Name the outline image:CellOutlines
Fill holes in identified objects?:No
Automatically calculate size of smoothing filter?:No
Automatically calculate minimum allowed distance between local maxima?:No
Retain outlines of the identified objects?:Yes
Automatically calculate the threshold using the Otsu method?:No
Enter Laplacian of Gaussian threshold:0.2
Automatically calculate the size of objects for the Laplacian of Gaussian filter?:No
Enter LoG filter diameter:3
Handling of objects if excessive number of objects identified:Truncate
Maximum number of objects:499
Threshold setting version:1
Threshold strategy:Measurement
Threshold method:RidlerCalvard
Smoothing for threshold:No smoothing
Threshold smoothing scale:2.0
Threshold correction factor:.80
Lower and upper bounds on threshold:0.01,0.09
Approximate fraction of image covered by objects?:0.05
Manual threshold:0.03
Select the measurement to threshold with:Metadata_Threshold
Select binary image:Segmentation
Masking objects:Wells
Two-class or three-class thresholding?:Three classes
Minimize the weighted variance or the entropy?:Entropy
Assign pixels in the middle intensity class to the foreground or the background?:Background
Method to calculate adaptive window size:Custom
Size of adaptive window:12
IdentifyPrimaryObjects:[module_num:11|svn_version:\'Unknown\'|variable_revision_number:10|show_window:True|notes:\x5B\x5D|batch_state:array(\x5B\x5D, dtype=uint8)|enabled:True]
Select the input image:Channel4
Name the primary objects to be identified:Cells
Typical diameter of objects, in pixel units (Min,Max):15,45
Discard objects outside the diameter range?:No
Try to merge too small objects with nearby larger objects?:Yes
Discard objects touching the border of the image?:No
Method to distinguish clumped objects:Shape
Method to draw dividing lines between clumped objects:Shape
Size of smoothing filter:11
Suppress local maxima that are closer than this minimum allowed distance:9
Speed up by using lower-resolution image to find local maxima?:No
Name the outline image:CellOutlines
Fill holes in identified objects?:No
Automatically calculate size of smoothing filter?:No
Automatically calculate minimum allowed distance between local maxima?:No
Retain outlines of the identified objects?:Yes
Automatically calculate the threshold using the Otsu method?:No
Enter Laplacian of Gaussian threshold:0.2
Automatically calculate the size of objects for the Laplacian of Gaussian filter?:No
Enter LoG filter diameter:3
Handling of objects if excessive number of objects identified:Truncate
Maximum number of objects:499
Threshold setting version:1
Threshold strategy:Per object
Threshold method:RobustBackground
Smoothing for threshold:No smoothing
Threshold smoothing scale:2.0
Threshold correction factor:.80
Lower and upper bounds on threshold:0.01,0.09
Approximate fraction of image covered by objects?:0.05
Manual threshold:0.03
Select the measurement to threshold with:Metadata_Threshold
Select binary image:Segmentation
Masking objects:Wells
Two-class or three-class thresholding?:Three classes
Minimize the weighted variance or the entropy?:Entropy
Assign pixels in the middle intensity class to the foreground or the background?:Background
Method to calculate adaptive window size:Custom
Size of adaptive window:12
"""
pipeline = cellprofiler.pipeline.Pipeline()
def callback(caller,event):
self.assertFalse(
isinstance(event, cellprofiler.pipeline.LoadExceptionEvent))
pipeline.add_listener(callback)
pipeline.load(StringIO.StringIO(data))
module = pipeline.modules()[4]
self.assertTrue(isinstance(module, ID.IdentifyPrimaryObjects))
self.assertEqual(module.image_name, "Channel0")
self.assertEqual(module.object_name, "Cells")
self.assertEqual(module.size_range.min, 15)
self.assertEqual(module.size_range.max, 45)
self.assertTrue(module.exclude_size)
self.assertFalse(module.merge_objects)
self.assertTrue(module.exclude_border_objects)
self.assertEqual(module.unclump_method, ID.UN_INTENSITY)
self.assertEqual(module.watershed_method, ID.WA_INTENSITY)
self.assertTrue(module.automatic_smoothing)
self.assertEqual(module.smoothing_filter_size, 11)
self.assertTrue(module.automatic_suppression)
self.assertEqual(module.maxima_suppression_size, 9)
self.assertTrue(module.low_res_maxima)
self.assertFalse(module.should_save_outlines)
self.assertEqual(module.save_outlines, "CellOutlines")
self.assertEqual(module.fill_holes, ID.FH_THRESHOLDING)
self.assertTrue(module.wants_automatic_log_threshold)
self.assertEqual(module.manual_log_threshold, .2)
self.assertTrue(module.wants_automatic_log_diameter)
self.assertEqual(module.log_diameter, 3)
self.assertEqual(module.limit_choice, ID.LIMIT_NONE)
self.assertEqual(module.maximum_object_count, 499)
#
self.assertEqual(module.threshold_scope, I.TS_ADAPTIVE)
self.assertEqual(module.threshold_method, I.TM_OTSU)
self.assertEqual(module.threshold_smoothing_choice, I.TSM_AUTOMATIC)
self.assertEqual(module.threshold_smoothing_scale, 2.0)
self.assertAlmostEqual(module.threshold_correction_factor, .80)
self.assertAlmostEqual(module.threshold_range.min, 0.01)
self.assertAlmostEqual(module.threshold_range.max, 0.90)
self.assertAlmostEqual(module.object_fraction, 0.05)
self.assertAlmostEqual(module.manual_threshold, 0.03)
self.assertEqual(module.thresholding_measurement, "Metadata_Threshold")
self.assertEqual(module.binary_image, "Segmentation")
self.assertEqual(module.masking_objects, "Wells")
self.assertEqual(module.two_class_otsu, I.O_TWO_CLASS)
self.assertEqual(module.use_weighted_variance, I.O_WEIGHTED_VARIANCE)
self.assertEqual(module.assign_middle_to_foreground, I.O_FOREGROUND)
self.assertEqual(module.adaptive_window_method, I.FI_IMAGE_SIZE)
self.assertEqual(module.adaptive_window_size, 12)
#
# Test alternate settings using subsequent instances of IDPrimary
#
module = pipeline.modules()[5]
self.assertTrue(isinstance(module, ID.IdentifyPrimaryObjects))
self.assertFalse(module.exclude_size)
self.assertTrue(module.merge_objects)
self.assertFalse(module.exclude_border_objects)
self.assertEqual(module.unclump_method, ID.UN_LOG)
self.assertEqual(module.watershed_method, ID.WA_NONE)
self.assertFalse(module.automatic_smoothing)
self.assertFalse(module.automatic_suppression)
self.assertFalse(module.low_res_maxima)
self.assertTrue(module.should_save_outlines)
self.assertEqual(module.fill_holes, ID.FH_NEVER)
self.assertFalse(module.wants_automatic_log_threshold)
self.assertFalse(module.wants_automatic_log_diameter)
self.assertEqual(module.limit_choice, ID.LIMIT_ERASE)
self.assertEqual(module.threshold_scope, I.TS_AUTOMATIC)
self.assertEqual(module.threshold_method, I.TM_MCT)
self.assertEqual(module.threshold_smoothing_choice, I.TSM_MANUAL)
self.assertEqual(module.two_class_otsu, I.O_THREE_CLASS)
self.assertEqual(module.use_weighted_variance, I.O_ENTROPY)
self.assertEqual(module.assign_middle_to_foreground, I.O_BACKGROUND)
self.assertEqual(module.adaptive_window_method, I.FI_CUSTOM)
module = pipeline.modules()[6]
self.assertTrue(isinstance(module, ID.IdentifyPrimaryObjects))
self.assertEqual(module.unclump_method, ID.UN_NONE)
self.assertEqual(module.watershed_method, ID.WA_PROPAGATE)
self.assertEqual(module.limit_choice, ID.LIMIT_TRUNCATE)
self.assertEqual(module.threshold_scope, I.TS_BINARY_IMAGE)
self.assertEqual(module.threshold_method, I.TM_MOG)
self.assertEqual(module.threshold_smoothing_choice, I.TSM_NONE)
module = pipeline.modules()[7]
self.assertTrue(isinstance(module, ID.IdentifyPrimaryObjects))
self.assertEqual(module.unclump_method, ID.UN_SHAPE)
self.assertEqual(module.watershed_method, ID.WA_SHAPE)
self.assertEqual(module.threshold_scope, I.TS_GLOBAL)
self.assertEqual(module.threshold_method, T.TM_BACKGROUND)
module = pipeline.modules()[8]
self.assertTrue(isinstance(module, ID.IdentifyPrimaryObjects))
self.assertEqual(module.threshold_scope, I.TS_MANUAL)
self.assertEqual(module.threshold_method, T.TM_KAPUR)
module = pipeline.modules()[9]
self.assertTrue(isinstance(module, ID.IdentifyPrimaryObjects))
self.assertEqual(module.threshold_scope, I.TS_MEASUREMENT)
self.assertEqual(module.threshold_method, T.TM_RIDLER_CALVARD)
module = pipeline.modules()[10]
self.assertTrue(isinstance(module, ID.IdentifyPrimaryObjects))
self.assertEqual(module.threshold_scope, I.TS_PER_OBJECT)
self.assertEqual(module.threshold_method, T.TM_ROBUST_BACKGROUND)
self.assertEqual(module.rb_custom_choice, I.RB_DEFAULT)
self.assertEqual(module.lower_outlier_fraction, .05)
self.assertEqual(module.upper_outlier_fraction, .05)
self.assertEqual(module.averaging_method, I.RB_MEAN)
self.assertEqual(module.variance_method, I.RB_SD)
self.assertEqual(module.number_of_deviations, 2)
def test_04_10_01_load_new_robust_background(self):
#
# Test custom robust background parameters.
#
data = r"""CellProfiler Pipeline: http://www.cellprofiler.org
Version:3
DateRevision:20141114191709
GitHash:d186f20
ModuleCount:3
HasImagePlaneDetails:False
IdentifyPrimaryObjects:[module_num:1|svn_version:\'Unknown\'|variable_revision_number:10|show_window:True|notes:\x5B\x5D|batch_state:array(\x5B\x5D, dtype=uint8)|enabled:True|wants_pause:False]
Select the input image:DNA
Name the primary objects to be identified:Nuclei
Typical diameter of objects, in pixel units (Min,Max):10,40
Discard objects outside the diameter range?:Yes
Try to merge too small objects with nearby larger objects?:No
Discard objects touching the border of the image?:Yes
Method to distinguish clumped objects:Intensity
Method to draw dividing lines between clumped objects:Intensity
Size of smoothing filter:10
Suppress local maxima that are closer than this minimum allowed distance:7.0
Speed up by using lower-resolution image to find local maxima?:Yes
Name the outline image:PrimaryOutlines
Fill holes in identified objects?:After both thresholding and declumping
Automatically calculate size of smoothing filter for declumping?:Yes
Automatically calculate minimum allowed distance between local maxima?:Yes
Retain outlines of the identified objects?:No
Automatically calculate the threshold using the Otsu method?:Yes
Enter Laplacian of Gaussian threshold:0.5
Automatically calculate the size of objects for the Laplacian of Gaussian filter?:Yes
Enter LoG filter diameter:5.0
Handling of objects if excessive number of objects identified:Continue
Maximum number of objects:500
Threshold setting version:2
Threshold strategy:Global
Thresholding method:RobustBackground
Select the smoothing method for thresholding:Automatic
Threshold smoothing scale:1.0
Threshold correction factor:1.0
Lower and upper bounds on threshold:0.0,1.0
Approximate fraction of image covered by objects?:0.01
Manual threshold:0.0
Select the measurement to threshold with:None
Select binary image:None
Masking objects:None
Two-class or three-class thresholding?:Two classes
Minimize the weighted variance or the entropy?:Weighted variance
Assign pixels in the middle intensity class to the foreground or the background?:Foreground
Method to calculate adaptive window size:Image size
Size of adaptive window:10
Use default parameters?:Custom
Lower outlier fraction:0.1
Upper outlier fraction:0.2
Averaging method:Mean
Variance method:Standard deviation
# of deviations:2.5
IdentifyPrimaryObjects:[module_num:2|svn_version:\'Unknown\'|variable_revision_number:10|show_window:True|notes:\x5B\x5D|batch_state:array(\x5B\x5D, dtype=uint8)|enabled:True|wants_pause:False]
Select the input image:DNA
Name the primary objects to be identified:Nuclei
Typical diameter of objects, in pixel units (Min,Max):10,40
Discard objects outside the diameter range?:Yes
Try to merge too small objects with nearby larger objects?:No
Discard objects touching the border of the image?:Yes
Method to distinguish clumped objects:Intensity
Method to draw dividing lines between clumped objects:Intensity
Size of smoothing filter:10
Suppress local maxima that are closer than this minimum allowed distance:7.0
Speed up by using lower-resolution image to find local maxima?:Yes
Name the outline image:PrimaryOutlines
Fill holes in identified objects?:After both thresholding and declumping
Automatically calculate size of smoothing filter for declumping?:Yes
Automatically calculate minimum allowed distance between local maxima?:Yes
Retain outlines of the identified objects?:No
Automatically calculate the threshold using the Otsu method?:Yes
Enter Laplacian of Gaussian threshold:0.5
Automatically calculate the size of objects for the Laplacian of Gaussian filter?:Yes
Enter LoG filter diameter:5.0
Handling of objects if excessive number of objects identified:Continue
Maximum number of objects:500
Threshold setting version:2
Threshold strategy:Global
Thresholding method:RobustBackground
Select the smoothing method for thresholding:Automatic
Threshold smoothing scale:1.0
Threshold correction factor:1.0
Lower and upper bounds on threshold:0.0,1.0
Approximate fraction of image covered by objects?:0.01
Manual threshold:0.0
Select the measurement to threshold with:None
Select binary image:None
Masking objects:None
Two-class or three-class thresholding?:Two classes
Minimize the weighted variance or the entropy?:Weighted variance
Assign pixels in the middle intensity class to the foreground or the background?:Foreground
Method to calculate adaptive window size:Image size
Size of adaptive window:10
Use default parameters?:Custom
Lower outlier fraction:0.1
Upper outlier fraction:0.2
Averaging method:Median
Variance method:Median absolute deviation
# of deviations:2.5
IdentifyPrimaryObjects:[module_num:3|svn_version:\'Unknown\'|variable_revision_number:10|show_window:True|notes:\x5B\x5D|batch_state:array(\x5B\x5D, dtype=uint8)|enabled:True|wants_pause:False]
Select the input image:DNA
Name the primary objects to be identified:Nuclei
Typical diameter of objects, in pixel units (Min,Max):10,40
Discard objects outside the diameter range?:Yes
Try to merge too small objects with nearby larger objects?:No
Discard objects touching the border of the image?:Yes
Method to distinguish clumped objects:Intensity
Method to draw dividing lines between clumped objects:Intensity
Size of smoothing filter:10
Suppress local maxima that are closer than this minimum allowed distance:7.0
Speed up by using lower-resolution image to find local maxima?:Yes
Name the outline image:PrimaryOutlines
Fill holes in identified objects?:After both thresholding and declumping
Automatically calculate size of smoothing filter for declumping?:Yes
Automatically calculate minimum allowed distance between local maxima?:Yes
Retain outlines of the identified objects?:No
Automatically calculate the threshold using the Otsu method?:Yes
Enter Laplacian of Gaussian threshold:0.5
Automatically calculate the size of objects for the Laplacian of Gaussian filter?:Yes
Enter LoG filter diameter:5.0
Handling of objects if excessive number of objects identified:Continue
Maximum number of objects:500
Threshold setting version:2
Threshold strategy:Global
Thresholding method:RobustBackground
Select the smoothing method for thresholding:Automatic
Threshold smoothing scale:1.0
Threshold correction factor:1.0
Lower and upper bounds on threshold:0.0,1.0
Approximate fraction of image covered by objects?:0.01
Manual threshold:0.0
Select the measurement to threshold with:None
Select binary image:None
Masking objects:None
Two-class or three-class thresholding?:Two classes
Minimize the weighted variance or the entropy?:Weighted variance
Assign pixels in the middle intensity class to the foreground or the background?:Foreground
Method to calculate adaptive window size:Image size
Size of adaptive window:10
Use default parameters?:Custom
Lower outlier fraction:0.1
Upper outlier fraction:0.2
Averaging method:Mode
Variance method:Median absolute deviation
# of deviations:2.5
"""
pipeline = cellprofiler.pipeline.Pipeline()
def callback(caller,event):
self.assertFalse(
isinstance(event, cellprofiler.pipeline.LoadExceptionEvent))
pipeline.add_listener(callback)
pipeline.load(StringIO.StringIO(data))
for module, averaging_method, variance_method in zip(
pipeline.modules(),
(I.RB_MEAN, I.RB_MEDIAN, I.RB_MODE),
(I.RB_SD, I.RB_MAD, I.RB_MAD)):
assert isinstance(module, ID.IdentifyPrimaryObjects)
self.assertEqual(module.lower_outlier_fraction, .1)
self.assertEqual(module.upper_outlier_fraction, .2)
self.assertEqual(module.number_of_deviations, 2.5)
self.assertEqual(module.averaging_method, averaging_method)
self.assertEqual(module.variance_method, variance_method)
def test_05_01_discard_large(self):
x = ID.IdentifyPrimaryObjects()
x.object_name.value = "my_object"
x.image_name.value = "my_image"
x.exclude_size.value = True
x.size_range.min = 10
x.size_range.max = 40
x.watershed_method.value = ID.WA_NONE
x.threshold_scope.value = I.TS_MANUAL
x.manual_threshold.value = .3
img = np.zeros((200,200))
draw_circle(img,(100,100),25,.5)
draw_circle(img,(25,25),10,.5)
image = cpi.Image(img)
image_set_list = cpi.ImageSetList()
image_set = image_set_list.get_image_set(0)
image_set.providers.append(cpi.VanillaImageProvider("my_image",image))
object_set = cpo.ObjectSet()
measurements = cpmeas.Measurements()
pipeline = cellprofiler.pipeline.Pipeline()
x.run(Workspace(pipeline,x,image_set,object_set,measurements,None))
objects = object_set.get_objects("my_object")
self.assertEqual(objects.segmented[25,25],1,"The small object was not there")
self.assertEqual(objects.segmented[100,100],0,"The large object was not filtered out")
self.assertTrue(objects.small_removed_segmented[25,25]>0,"The small object was not in the small_removed label set")
self.assertTrue(objects.small_removed_segmented[100,100]>0,"The large object was not in the small-removed label set")
self.assertTrue(objects.unedited_segmented[25,25],"The small object was not in the unedited set")
self.assertTrue(objects.unedited_segmented[100,100],"The large object was not in the unedited set")
location_center_x = measurements.get_current_measurement("my_object","Location_Center_X")
self.assertTrue(isinstance(location_center_x,np.ndarray))
self.assertEqual(np.product(location_center_x.shape),1)
def test_05_02_keep_large(self):
x = ID.IdentifyPrimaryObjects()
x.object_name.value = "my_object"
x.image_name.value = "my_image"
x.exclude_size.value = False
x.size_range.min = 10
x.size_range.max = 40
x.watershed_method.value = ID.WA_NONE
x.threshold_scope.value = I.TS_MANUAL
x.manual_threshold.value = .3
img = np.zeros((200,200))
draw_circle(img,(100,100),25,.5)
draw_circle(img,(25,25),10,.5)
image = cpi.Image(img)
image_set_list = cpi.ImageSetList()
image_set = image_set_list.get_image_set(0)
image_set.providers.append(cpi.VanillaImageProvider("my_image",image))
object_set = cpo.ObjectSet()
measurements = cpmeas.Measurements()
pipeline = cellprofiler.pipeline.Pipeline()
x.run(Workspace(pipeline,x,image_set,object_set,measurements,None))
objects = object_set.get_objects("my_object")
self.assertTrue(objects.segmented[25,25],"The small object was not there")
self.assertTrue(objects.segmented[100,100],"The large object was filtered out")
self.assertTrue(objects.unedited_segmented[25,25],"The small object was not in the unedited set")
self.assertTrue(objects.unedited_segmented[100,100],"The large object was not in the unedited set")
location_center_x = measurements.get_current_measurement("my_object","Location_Center_X")
self.assertTrue(isinstance(location_center_x,np.ndarray))
self.assertEqual(np.product(location_center_x.shape),2)
def test_05_03_discard_small(self):
x = ID.IdentifyPrimaryObjects()
x.object_name.value = "my_object"
x.image_name.value = "my_image"
x.exclude_size.value = True
x.size_range.min = 40
x.size_range.max = 60
x.watershed_method.value = ID.WA_NONE
x.threshold_scope.value = I.TS_MANUAL
x.manual_threshold.value = .3
img = np.zeros((200,200))
draw_circle(img,(100,100),25,.5)
draw_circle(img,(25,25),10,.5)
image = cpi.Image(img)
image_set_list = cpi.ImageSetList()
image_set = image_set_list.get_image_set(0)
image_set.providers.append(cpi.VanillaImageProvider("my_image",image))
object_set = cpo.ObjectSet()
measurements = cpmeas.Measurements()
pipeline = cellprofiler.pipeline.Pipeline()
x.run(Workspace(pipeline,x,image_set,object_set,measurements,None))
objects = object_set.get_objects("my_object")
self.assertEqual(objects.segmented[25,25],0,"The small object was not filtered out")
self.assertEqual(objects.segmented[100,100],1,"The large object was not present")
self.assertTrue(objects.small_removed_segmented[25,25]==0,"The small object was in the small_removed label set")
self.assertTrue(objects.small_removed_segmented[100,100]>0,"The large object was not in the small-removed label set")
self.assertTrue(objects.unedited_segmented[25,25],"The small object was not in the unedited set")
self.assertTrue(objects.unedited_segmented[100,100],"The large object was not in the unedited set")
location_center_x = measurements.get_current_measurement("my_object","Location_Center_X")
self.assertTrue(isinstance(location_center_x,np.ndarray))
self.assertEqual(np.product(location_center_x.shape),1)
def test_05_02_discard_edge(self):
x = ID.IdentifyPrimaryObjects()
x.object_name.value = "my_object"
x.image_name.value = "my_image"
x.exclude_size.value = False
x.size_range.min = 10
x.size_range.max = 40
x.watershed_method.value = ID.WA_NONE
x.threshold_scope.value = I.TS_MANUAL
x.manual_threshold.value = .3
img = np.zeros((100,100))
centers = [(50,50),(10,50),(50,10),(90,50),(50,90)]
present = [ True, False, False, False, False]
for center in centers:
draw_circle(img,center,15,.5)
image = cpi.Image(img)
image_set_list = cpi.ImageSetList()
image_set = image_set_list.get_image_set(0)
image_set.providers.append(cpi.VanillaImageProvider("my_image",image))
object_set = cpo.ObjectSet()
measurements = cpmeas.Measurements()
pipeline = cellprofiler.pipeline.Pipeline()
x.run(Workspace(pipeline,x,image_set,object_set,measurements,None))
objects = object_set.get_objects("my_object")
for center, p in zip(centers,present):
if p:
self.assertTrue(objects.segmented[center[0],center[1]] > 0)
self.assertTrue(objects.small_removed_segmented[center[0],center[1]] > 0)
else:
self.assertTrue(objects.segmented[center[0],center[1]] == 0)
self.assertTrue(objects.small_removed_segmented[center[0],center[1]] == 0)
self.assertTrue(objects.unedited_segmented[center[0],center[1]] > 0)
def test_05_03_discard_with_mask(self):
"""Check discard of objects that are on the border of a mask"""
x = ID.IdentifyPrimaryObjects()
x.object_name.value = "my_object"
x.image_name.value = "my_image"
x.exclude_size.value = False
x.size_range.min = 10
x.size_range.max = 40
x.watershed_method.value = ID.WA_NONE
x.threshold_scope.value = I.TS_MANUAL
x.manual_threshold.value = .3
img = np.zeros((200,200))
centers = [(100,100),(30,100),(100,30),(170,100),(100,170)]
present = [ True, False, False, False, False]
for center in centers:
draw_circle(img,center,15,.5)
mask = np.zeros((200,200))
mask[25:175,25:175]=1
image = cpi.Image(img,mask)
image_set_list = cpi.ImageSetList()
image_set = image_set_list.get_image_set(0)
image_set.providers.append(cpi.VanillaImageProvider("my_image",image))
object_set = cpo.ObjectSet()
measurements = cpmeas.Measurements()
pipeline = cellprofiler.pipeline.Pipeline()
x.run(Workspace(pipeline,x,image_set,object_set,measurements,None))
objects = object_set.get_objects("my_object")
for center, p in zip(centers,present):
if p:
self.assertTrue(objects.segmented[center[0],center[1]] > 0)
self.assertTrue(objects.small_removed_segmented[center[0],center[1]] > 0)
else:
self.assertTrue(objects.segmented[center[0],center[1]] == 0)
self.assertTrue(objects.small_removed_segmented[center[0],center[1]] == 0)
self.assertTrue(objects.unedited_segmented[center[0],center[1]] > 0)
def test_06_01_regression_diagonal(self):
"""Regression test - was using one-connected instead of 3-connected structuring element"""
x = ID.IdentifyPrimaryObjects()
x.object_name.value = "my_object"
x.image_name.value = "my_image"
x.exclude_size.value = False
x.smoothing_filter_size.value = 0
x.automatic_smoothing.value = False
x.watershed_method.value = ID.WA_NONE
x.threshold_scope.value = I.TS_MANUAL
x.threshold_smoothing_choice.value = I.TSM_NONE
x.manual_threshold.value = .5
img = np.zeros((10,10))
img[4,4]=1
img[5,5]=1
image = cpi.Image(img)
image_set_list = cpi.ImageSetList()
image_set = image_set_list.get_image_set(0)
image_set.providers.append(cpi.VanillaImageProvider("my_image",image))
object_set = cpo.ObjectSet()
measurements = cpmeas.Measurements()
pipeline = cellprofiler.pipeline.Pipeline()
x.run(Workspace(pipeline,x,image_set,object_set,measurements,None))
self.assertEqual(len(object_set.object_names),1)
self.assertTrue("my_object" in object_set.object_names)
objects = object_set.get_objects("my_object")
segmented = objects.segmented
self.assertTrue(np.all(segmented[img>0] == 1))
self.assertTrue(np.all(img[segmented==1] > 0))
def test_06_02_regression_adaptive_mask(self):
"""Regression test - mask all but one pixel / adaptive"""
for o_alg in (I.O_WEIGHTED_VARIANCE, I.O_ENTROPY):
x = ID.IdentifyPrimaryObjects()
x.use_weighted_variance.value = o_alg
x.object_name.value = "my_object"
x.image_name.value = "my_image"
x.exclude_size.value = False
x.threshold_scope.value = T.TM_ADAPTIVE
x.threshold_method.value = T.TM_OTSU
np.random.seed(62)
img = np.random.uniform(size=(100,100))
mask = np.zeros(img.shape, bool)
mask[-1,-1] = True
image = cpi.Image(img, mask)
image_set_list = cpi.ImageSetList()
image_set = image_set_list.get_image_set(0)
image_set.providers.append(cpi.VanillaImageProvider("my_image",image))
object_set = cpo.ObjectSet()
measurements = cpmeas.Measurements()
pipeline = cellprofiler.pipeline.Pipeline()
x.run(Workspace(pipeline,x,image_set,object_set,measurements,None))
self.assertEqual(len(object_set.object_names),1)
self.assertTrue("my_object" in object_set.object_names)
objects = object_set.get_objects("my_object")
segmented = objects.segmented
self.assertTrue(np.all(segmented == 0))
def test_07_01_adaptive_otsu_small(self):
"""Test the function, get_threshold, using Otsu adaptive / small
Use a small image (125 x 125) to break the image into four
pieces, check that the threshold is different in each block
and that there are four blocks broken at the 75 boundary
"""
np.random.seed(0)
image = np.zeros((120,110))
for i0,i1 in ((0,60),(60,120)):
for j0,j1 in ((0,55),(55,110)):
dmin = float(i0 * 2 + j0) / 500.0
dmult = 1.0-dmin
# use the sine here to get a bimodal distribution of values
r = np.random.uniform(0,np.pi*2,(60,55))
rsin = (np.sin(r) + 1) / 2
image[i0:i1,j0:j1] = dmin + rsin * dmult
workspace, x = self.make_workspace(image)
assert isinstance(x, ID.IdentifyPrimaryObjects)
x.threshold_scope.value = T.TM_ADAPTIVE
x.threshold_method.value = T.TM_OTSU
threshold, global_threshold = x.get_threshold(
cpi.Image(image), np.ones((120,110),bool), workspace)
self.assertTrue(threshold[0,0] != threshold[0,109])
self.assertTrue(threshold[0,0] != threshold[119,0])
self.assertTrue(threshold[0,0] != threshold[119,109])
def test_07_02_adaptive_otsu_big(self):
"""Test the function, get_threshold, using Otsu adaptive / big
Use a large image (525 x 525) to break the image into 100
pieces, check that the threshold is different in each block
and that boundaries occur where expected
"""
np.random.seed(0)
image = np.zeros((525,525))
blocks = []
for i in range(10):
for j in range(10):
# the following makes a pattern of thresholds where
# each square has a different threshold from its 8-connected
# neighbors
dmin = float((i % 2) * 2 + (j%2)) / 8.0
dmult = 1.0-dmin
def b(x):
return int(float(x)*52.5)
dim = ((b(i),b(i+1)),(b(j),b(j+1)))
blocks.append(dim)
((i0,i1),(j0,j1)) = dim
# use the sine here to get a bimodal distribution of values
r = np.random.uniform(0,np.pi*2,(i1-i0,j1-j0))
rsin = (np.sin(r) + 1) / 2
image[i0:i1,j0:j1] = dmin + rsin * dmult
workspace, x = self.make_workspace(image)
assert isinstance(x, ID.IdentifyPrimaryObjects)
x.threshold_scope.value = T.TM_ADAPTIVE
x.threshold_method.value = T.TM_OTSU
threshold, global_threshold = x.get_threshold(
cpi.Image(image), np.ones((525,525),bool), workspace)
def test_08_01_per_object_otsu(self):
"""Test get_threshold using Otsu per-object"""
image = np.ones((20,20)) * .08
draw_circle(image,(5,5),2,.1)
draw_circle(image,(15,15),3,.1)
draw_circle(image,(15,15),2,.2)
labels = np.zeros((20,20),int)
draw_circle(labels,(5,5),3,1)
draw_circle(labels,(15,15),3,2)
workspace, x = self.make_workspace(image, labels=labels)
x.threshold_scope.value = I.TS_PER_OBJECT
x.threshold_method.value = T.TM_OTSU
threshold, global_threshold = x.get_threshold(cpi.Image(image),
np.ones((20,20), bool),
workspace)
t1 = threshold[5,5]
t2 = threshold[15,15]
self.assertTrue(t1 < .1)
self.assertTrue(t2 > .1)
self.assertTrue(t2 < .2)
self.assertTrue(np.all(threshold[labels==1] == threshold[5,5]))
self.assertTrue(np.all(threshold[labels==2] == threshold[15,15]))
def test_08_02_per_object_otsu_run(self):
"""Test IdentifyPrimAutomatic per object through the Run function"""
image = np.ones((20,20))*0.06
draw_circle(image,(5,5),5,.05)
draw_circle(image,(5,5),2,.15)
draw_circle(image,(15,15),5,.05)
draw_circle(image,(15,15),2,.15)
image = add_noise(image, .01)
labels = np.zeros((20,20),int)
draw_circle(labels,(5,5),5,1)
draw_circle(labels,(15,15),5,2)
expected_labels = np.zeros((20,20),int)
draw_circle(expected_labels,(5,5),2,1)
draw_circle(expected_labels,(15,15),2,2)
workspace, x = self.make_workspace(image, labels = labels)
x.exclude_size.value = False
x.watershed_method.value = ID.WA_NONE
x.threshold_scope.value = I.TS_PER_OBJECT
x.threshold_method.value = T.TM_OTSU
x.threshold_correction_factor.value = 1.05
x.run(workspace)
labels = workspace.object_set.get_objects(OBJECTS_NAME).segmented
# Do a little indexing trick so we can ignore which object got
# which label
self.assertNotEqual(labels[5,5], labels[15,15])
indexes = np.array([0, labels[5,5], labels[15,15]])
self.assertTrue(np.all(indexes[labels] == expected_labels))
def test_08_03_per_objects_image_mask(self):
image = np.ones((20,20))*0.06
draw_circle(image,(5,5),5,.05)
draw_circle(image,(5,5),2,.15)
image = add_noise(image, .01)
mask = np.zeros((20,20), bool)
draw_circle(mask, (5,5), 5, 1)
expected_labels = np.zeros((20,20),int)
draw_circle(expected_labels,(5,5),2,1)
workspace, x = self.make_workspace(image, mask=mask)
x.masking_objects.value = I.O_FROM_IMAGE
x.exclude_size.value = False
x.watershed_method.value = ID.WA_NONE
x.threshold_scope.value = I.TS_PER_OBJECT
x.threshold_method.value = T.TM_OTSU
x.threshold_correction_factor.value = 1.05
x.run(workspace)
labels = workspace.object_set.get_objects(OBJECTS_NAME).segmented
self.assertTrue(np.all(labels == expected_labels))
def test_09_01_small_images(self):
"""Test mixture of gaussians thresholding with few pixels
Run MOG to see if it blows up, given 0-10 pixels"""
r = np.random.RandomState()
r.seed(91)
image = r.uniform(size=(9, 11))
ii, jj = np.mgrid[0:image.shape[0], 0:image.shape[1]]
ii, jj = ii.flatten(), jj.flatten()
for threshold_method in (T.TM_BACKGROUND, T.TM_KAPUR, T.TM_MCT,
T.TM_MOG, T.TM_OTSU, T.TM_RIDLER_CALVARD,
T.TM_ROBUST_BACKGROUND):
for i in range(11):
mask = np.zeros(image.shape, bool)
if i:
p = r.permutation(np.prod(image.shape))[:i]
mask[ii[p], jj[p]] = True
workspace, x = self.make_workspace(image, mask)
x.threshold_method.value = threshold_method
x.threshold_scope.value = I.TS_GLOBAL
l, g = x.get_threshold(cpi.Image(image), mask, workspace)
v = image[mask]
image = r.uniform(size=(9, 11))
image[mask] = v
l1, g1 = x.get_threshold(cpi.Image(image), mask, workspace)
self.assertAlmostEqual(l1, l)
def test_09_02_mog_fly(self):
"""Test mixture of gaussians thresholding on the fly image"""
image = fly_image()
workspace, x = self.make_workspace(image)
x.threshold_method.value = T.TM_MOG
x.threshold_scope.value = I.TS_GLOBAL
x.object_fraction.value = '0.10'
local_threshold,threshold = x.get_threshold(
cpi.Image(image), np.ones(image.shape,bool), workspace)
self.assertTrue(threshold > 0.036)
self.assertTrue(threshold < 0.040)
x.object_fraction.value = '0.20'
local_threshold,threshold = x.get_threshold(
cpi.Image(image), np.ones(image.shape,bool), workspace)
self.assertTrue(threshold > 0.0084)
self.assertTrue(threshold < 0.0088)
x.object_fraction.value = '0.50'
local_threshold,threshold = x.get_threshold(
cpi.Image(image), np.ones(image.shape,bool), workspace)
self.assertTrue(threshold > 0.0082)
self.assertTrue(threshold < 0.0086)
def test_10_02_test_background_fly(self):
image = fly_image()
workspace, x = self.make_workspace(image)
x.threshold_method.value = T.TM_BACKGROUND
x.threshold_scope.value = I.TS_GLOBAL
local_threshold,threshold = x.get_threshold(
cpi.Image(image), np.ones(image.shape,bool), workspace)
self.assertTrue(threshold > 0.030)
self.assertTrue(threshold < 0.032)
def test_10_03_test_background_mog(self):
'''Test the background method with a mixture of gaussian distributions'''
np.random.seed(103)
image = np.random.normal(.2, .01, size=10000)
ind = np.random.permutation(int(image.shape[0]))[:image.shape[0] / 5]
image[ind] = np.random.normal(.5, .2, size=len(ind))
image[image < 0] = 0
image[image > 1] = 1
image[0] = 0
image[1] = 1
image.shape = (100,100)
workspace, x = self.make_workspace(image)
x.threshold_method.value = T.TM_BACKGROUND
x.threshold_scope.value = I.TS_GLOBAL
local_threshold,threshold = x.get_threshold(
cpi.Image(image), np.ones(image.shape,bool), workspace)
self.assertTrue(threshold > .18 * 2)
self.assertTrue(threshold < .22 * 2)
def test_11_01_test_robust_background_fly(self):
image = fly_image()
workspace, x = self.make_workspace(image)
x.threshold_scope.value = I.TS_GLOBAL
x.threshold_method.value = T.TM_ROBUST_BACKGROUND
local_threshold,threshold = x.get_threshold(
cpi.Image(image), np.ones(image.shape,bool), workspace)
self.assertTrue(threshold > 0.054)
self.assertTrue(threshold < 0.056)
def test_12_01_test_ridler_calvard_background_fly(self):
image = fly_image()
workspace, x = self.make_workspace(image)
x.threshold_scope.value = I.TS_GLOBAL
x.threshold_method.value = T.TM_RIDLER_CALVARD
local_threshold,threshold = x.get_threshold(
cpi.Image(image), np.ones(image.shape,bool), workspace)
self.assertTrue(threshold > 0.017)
self.assertTrue(threshold < 0.019)
def test_13_01_test_kapur_background_fly(self):
image = fly_image()
workspace, x = self.make_workspace(image)
x.threshold_scope.value = I.TS_GLOBAL
x.threshold_method.value = T.TM_KAPUR
local_threshold,threshold = x.get_threshold(
cpi.Image(image), np.ones(image.shape,bool), workspace)
self.assertTrue(threshold > 0.015)
self.assertTrue(threshold < 0.020)
def test_14_01_test_manual_background(self):
"""Test manual background"""
workspace, x = self.make_workspace(np.zeros((10, 10)))
x = ID.IdentifyPrimaryObjects()
x.threshold_scope.value = T.TM_MANUAL
x.manual_threshold.value = .5
local_threshold,threshold = x.get_threshold(cpi.Image(np.zeros((10,10))),
np.ones((10,10),bool),
workspace)
self.assertTrue(threshold == .5)
self.assertTrue(threshold == .5)
def test_15_01_test_binary_background(self):
img = np.zeros((200,200),np.float32)
thresh = np.zeros((200,200),bool)
draw_circle(thresh,(100,100),50,True)
draw_circle(thresh,(25,25),20,True)
workspace, x = self.make_workspace(img, binary_image=thresh)
x.exclude_size.value = False
x.watershed_method.value = ID.WA_NONE
x.threshold_scope.value = I.TS_BINARY_IMAGE
x.run(workspace)
count_ftr = I.C_COUNT + "_" + OBJECTS_NAME
m = workspace.measurements
self.assertTrue(m.has_feature(cpmeas.IMAGE, count_ftr))
count = m.get_current_measurement(cpmeas.IMAGE, count_ftr)
self.assertEqual(count,2)
def test_16_01_get_measurement_columns(self):
'''Test the get_measurement_columns method'''
x = ID.IdentifyPrimaryObjects()
oname = "my_object"
x.object_name.value = oname
x.image_name.value = "my_image"
columns = x.get_measurement_columns(None)
expected_columns = [
(cpmeas.IMAGE, format%oname, coltype )
for format,coltype in ((I.FF_COUNT, cpmeas.COLTYPE_INTEGER),
(I.FF_FINAL_THRESHOLD, cpmeas.COLTYPE_FLOAT),
(I.FF_ORIG_THRESHOLD, cpmeas.COLTYPE_FLOAT),
(I.FF_WEIGHTED_VARIANCE, cpmeas.COLTYPE_FLOAT),
(I.FF_SUM_OF_ENTROPIES, cpmeas.COLTYPE_FLOAT))]
expected_columns += [(oname, feature, cpmeas.COLTYPE_FLOAT)
for feature in (I.M_LOCATION_CENTER_X,
I.M_LOCATION_CENTER_Y)]
expected_columns += [(oname, I.M_NUMBER_OBJECT_NUMBER, cpmeas.COLTYPE_INTEGER)]
self.assertEqual(len(columns), len(expected_columns))
for column in columns:
self.assertTrue(any(all([colval==exval for colval, exval in zip(column, expected)])
for expected in expected_columns))
def test_17_01_regression_holes(self):
'''Regression test - fill holes caused by filtered object
This was created as a regression test for the bug, IMG-191, but
didn't exercise the bug. It's a good test of watershed and filling
labeled holes in an odd case, so I'm leaving it in.
'''
#
# This array has two intensity peaks separated by a border.
# You should get two objects, one within the other.
#
pixels = np.array([[0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,2,2,2,2,2,2,2,2,0,0],
[0,0,2,2,2,2,2,2,2,2,0,0],
[0,0,2,2,2,2,2,2,2,2,0,0],
[0,0,2,1,1,1,1,1,1,2,0,0],
[0,0,2,1,2,2,2,2,1,2,0,0],
[0,0,2,1,2,9,2,2,1,2,0,0],
[0,0,2,1,2,2,2,2,1,2,0,0],
[0,0,2,1,1,1,1,1,1,2,0,0],
[0,0,2,2,2,2,2,2,2,2,0,0],
[0,0,2,2,1,2,2,2,2,2,0,0],
[0,0,2,2,1,2,2,2,2,2,0,0],
[0,0,2,2,1,2,2,2,2,2,0,0],
[0,0,2,2,2,2,2,2,2,2,0,0],
[0,0,2,2,2,2,2,2,9,9,0,0],
[0,0,2,2,2,2,2,2,9,9,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0]], float) / 10.0
expected = np.array([[0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,2,2,2,2,2,2,2,2,0,0],
[0,0,2,2,2,2,2,2,2,2,0,0],
[0,0,2,2,2,2,2,2,2,2,0,0],
[0,0,2,1,1,1,1,1,1,2,0,0],
[0,0,2,1,1,1,1,1,1,2,0,0],
[0,0,2,1,1,1,1,1,1,2,0,0],
[0,0,2,1,1,1,1,1,1,2,0,0],
[0,0,2,1,1,1,1,1,1,2,0,0],
[0,0,2,2,2,2,2,2,2,2,0,0],
[0,0,2,2,2,2,2,2,2,2,0,0],
[0,0,2,2,2,2,2,2,2,2,0,0],
[0,0,2,2,2,2,2,2,2,2,0,0],
[0,0,2,2,2,2,2,2,2,2,0,0],
[0,0,2,2,2,2,2,2,2,2,0,0],
[0,0,2,2,2,2,2,2,2,2,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0]])
mask = np.array([[0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,1,1,1,1,1,1,0,0,0],
[0,0,1,1,1,1,1,1,1,1,0,0],
[0,0,1,1,1,1,1,1,1,1,0,0],
[0,0,1,0,0,0,0,0,0,1,0,0],
[0,0,1,0,1,1,1,1,0,1,0,0],
[0,0,1,0,1,1,1,1,0,1,0,0],
[0,0,1,0,1,1,1,1,0,1,0,0],
[0,0,1,0,0,0,0,0,0,1,0,0],
[0,0,1,1,1,1,1,1,1,1,0,0],
[0,0,1,1,1,1,1,1,1,1,0,0],
[0,0,1,1,1,1,1,1,1,1,0,0],
[0,0,1,1,1,1,1,1,1,1,0,0],
[0,0,1,1,1,1,1,1,1,1,0,0],
[0,0,1,1,1,1,1,1,1,1,0,0],
[0,0,0,1,1,1,1,1,1,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0]], bool)
workspace, x = self.make_workspace(pixels)
x.exclude_size.value = True
x.size_range.min = 6
x.size_range.max = 50
x.maxima_suppression_size.value = 3
x.automatic_suppression.value = False
x.watershed_method.value = ID.WA_INTENSITY
x.threshold_scope.value = T.TM_MANUAL
x.threshold_smoothing_choice.value = I.TSM_NONE
x.manual_threshold.value = .05
x.threshold_correction_factor.value = 1
x.should_save_outlines.value = True
x.save_outlines.value = "outlines"
measurements = workspace.measurements
x.run(workspace)
my_objects = workspace.object_set.get_objects(OBJECTS_NAME)
self.assertTrue(my_objects.segmented[3,3] != 0)
if my_objects.unedited_segmented[3,3] == 2:
unedited_segmented = my_objects.unedited_segmented
else:
unedited_segmented = np.array([0,2,1])[my_objects.unedited_segmented]
self.assertTrue(np.all(unedited_segmented[mask] == expected[mask]))
outlines = workspace.image_set.get_image("outlines",
must_be_binary=True)
self.assertTrue(np.all(my_objects.segmented[outlines.pixel_data] > 0))
def test_17_02_regression_holes(self):
'''Regression test - fill holes caused by filtered object
This is the real regression test for IMG-191. The smaller object
is surrounded by pixels below threshold. This prevents filling in
the unedited case.
'''
# An update to fill_labeled_holes will remove both the filtered object
# and the hole
#
if True:
return
pixels = np.array([[0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,2,2,2,2,2,2,2,2,0,0],
[0,0,2,2,2,2,2,2,2,2,0,0],
[0,0,2,2,2,2,2,2,2,2,0,0],
[0,0,3,0,0,0,0,0,0,3,0,0],
[0,0,3,0,0,0,0,0,0,3,0,0],
[0,0,3,0,0,9,2,0,0,3,0,0],
[0,0,3,0,0,0,0,0,0,3,0,0],
[0,0,3,0,0,0,0,0,0,3,0,0],
[0,0,3,2,2,2,2,2,2,2,0,0],
[0,0,3,2,2,2,2,2,2,2,0,0],
[0,0,3,2,2,2,2,2,2,2,0,0],
[0,0,2,2,2,2,2,2,9,2,0,0],
[0,0,2,2,2,2,2,2,2,2,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0]], float) / 10.0
expected = np.array([[0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,1,1,1,1,1,1,1,1,0,0],
[0,0,1,1,1,1,1,1,1,1,0,0],
[0,0,1,1,1,1,1,1,1,1,0,0],
[0,0,1,1,1,1,1,1,1,1,0,0],
[0,0,1,1,1,1,1,1,1,1,0,0],
[0,0,1,1,1,1,1,1,1,1,0,0],
[0,0,1,1,1,1,1,1,1,1,0,0],
[0,0,1,1,1,1,1,1,1,1,0,0],
[0,0,1,1,1,1,1,1,1,1,0,0],
[0,0,1,1,1,1,1,1,1,1,0,0],
[0,0,1,1,1,1,1,1,1,1,0,0],
[0,0,1,1,1,1,1,1,1,1,0,0],
[0,0,1,1,1,1,1,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0]])
mask = np.array([[0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,1,1,1,1,1,1,0,0,0],
[0,0,1,1,1,1,1,1,1,1,0,0],
[0,0,1,1,1,1,1,1,1,1,0,0],
[0,0,1,0,0,0,0,0,0,1,0,0],
[0,0,1,0,0,0,0,0,0,1,0,0],
[0,0,1,0,0,1,1,0,0,1,0,0],
[0,0,1,0,0,0,0,0,0,1,0,0],
[0,0,1,0,0,0,0,0,0,1,0,0],
[0,0,1,1,1,1,1,1,1,1,0,0],
[0,0,1,1,1,1,1,1,1,1,0,0],
[0,0,1,1,1,1,1,1,1,1,0,0],
[0,0,1,1,1,1,1,1,1,1,0,0],
[0,0,0,1,1,1,1,1,1,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0]], bool)
image = cpi.Image(pixels)
image_set_list = cpi.ImageSetList()
image_set = image_set_list.get_image_set(0)
image_set.add("my_image", image)
object_set = cpo.ObjectSet()
x = ID.IdentifyPrimaryObjects()
x.object_name.value = "my_object"
x.image_name.value = "my_image"
x.exclude_size.value = True
x.size_range.min = 4
x.size_range.max = 50
x.maxima_suppression_size.value = 3
x.automatic_suppression.value = False
x.watershed_method.value = ID.WA_NONE
x.threshold_method.value = T.TM_MANUAL
x.manual_threshold.value = .1
x.threshold_correction_factor.value = 1
x.module_num = 1
pipeline = cellprofiler.pipeline.Pipeline()
pipeline.add_module(x)
measurements = cpmeas.Measurements()
workspace = Workspace(pipeline, x, image_set, object_set, measurements,
image_set_list)
x.run(workspace)
my_objects = object_set.get_objects("my_object")
self.assertTrue(my_objects.segmented[3,3] != 0)
self.assertTrue(np.all(my_objects.segmented[mask] == expected[mask]))
def test_18_01_truncate_objects(self):
'''Set up a limit on the # of objects and exceed it'''
for maximum_object_count in range(2,5):
pixels = np.zeros((20,21))
pixels[2:8,2:8] = .5
pixels[12:18,2:8] = .5
pixels[2:8,12:18] = .5
pixels[12:18,12:18] = .5
image = cpi.Image(pixels)
image_set_list = cpi.ImageSetList()
image_set = image_set_list.get_image_set(0)
image_set.add("my_image", image)
object_set = cpo.ObjectSet()
x = ID.IdentifyPrimaryObjects()
x.object_name.value = "my_object"
x.image_name.value = "my_image"
x.exclude_size.value = False
x.unclump_method.value = ID.UN_NONE
x.watershed_method.value = ID.WA_NONE
x.threshold_scope.value = T.TM_MANUAL
x.manual_threshold.value = .25
x.threshold_smoothing_choice.value = I.TSM_NONE
x.threshold_correction_factor.value = 1
x.limit_choice.value = ID.LIMIT_TRUNCATE
x.maximum_object_count.value = maximum_object_count
x.module_num = 1
pipeline = cellprofiler.pipeline.Pipeline()
pipeline.add_module(x)
measurements = cpmeas.Measurements()
workspace = Workspace(pipeline, x, image_set, object_set, measurements,
image_set_list)
x.run(workspace)
self.assertEqual(measurements.get_current_image_measurement(
"Count_my_object"), maximum_object_count)
my_objects = object_set.get_objects("my_object")
self.assertEqual(np.max(my_objects.segmented), maximum_object_count)
self.assertEqual(np.max(my_objects.unedited_segmented), 4)
def test_18_02_erase_objects(self):
'''Set up a limit on the # of objects and exceed it - erasing objects'''
maximum_object_count = 3
pixels = np.zeros((20,21))
pixels[2:8,2:8] = .5
pixels[12:18,2:8] = .5
pixels[2:8,12:18] = .5
pixels[12:18,12:18] = .5
image = cpi.Image(pixels)
image_set_list = cpi.ImageSetList()
image_set = image_set_list.get_image_set(0)
image_set.add("my_image", image)
object_set = cpo.ObjectSet()
x = ID.IdentifyPrimaryObjects()
x.object_name.value = "my_object"
x.image_name.value = "my_image"
x.exclude_size.value = False
x.unclump_method.value = ID.UN_NONE
x.watershed_method.value = ID.WA_NONE
x.threshold_scope.value = T.TM_MANUAL
x.threshold_smoothing_choice.value = I.TSM_NONE
x.manual_threshold.value = .25
x.threshold_correction_factor.value = 1
x.limit_choice.value = ID.LIMIT_ERASE
x.maximum_object_count.value = maximum_object_count
x.module_num = 1
pipeline = cellprofiler.pipeline.Pipeline()
pipeline.add_module(x)
measurements = cpmeas.Measurements()
workspace = Workspace(pipeline, x, image_set, object_set, measurements,
image_set_list)
x.run(workspace)
self.assertEqual(measurements.get_current_image_measurement(
"Count_my_object"), 0)
my_objects = object_set.get_objects("my_object")
self.assertTrue(np.all(my_objects.segmented == 0))
self.assertEqual(np.max(my_objects.unedited_segmented), 4)
def test_18_03_dont_erase_objects(self):
'''Ask to erase objects, but don't'''
maximum_object_count = 5
pixels = np.zeros((20,21))
pixels[2:8,2:8] = .5
pixels[12:18,2:8] = .5
pixels[2:8,12:18] = .5
pixels[12:18,12:18] = .5
image = cpi.Image(pixels)
image_set_list = cpi.ImageSetList()
image_set = image_set_list.get_image_set(0)
image_set.add("my_image", image)
object_set = cpo.ObjectSet()
x = ID.IdentifyPrimaryObjects()
x.object_name.value = "my_object"
x.image_name.value = "my_image"
x.exclude_size.value = False
x.unclump_method.value = ID.UN_NONE
x.watershed_method.value = ID.WA_NONE
x.threshold_scope.value = T.TM_MANUAL
x.threshold_smoothing_choice.value = I.TSM_NONE
x.manual_threshold.value = .25
x.threshold_correction_factor.value = 1
x.limit_choice.value = ID.LIMIT_ERASE
x.maximum_object_count.value = maximum_object_count
x.module_num = 1
pipeline = cellprofiler.pipeline.Pipeline()
pipeline.add_module(x)
measurements = cpmeas.Measurements()
workspace = Workspace(pipeline, x, image_set, object_set, measurements,
image_set_list)
x.run(workspace)
self.assertEqual(measurements.get_current_image_measurement(
"Count_my_object"), 4)
my_objects = object_set.get_objects("my_object")
self.assertEqual(np.max(my_objects.segmented), 4)
def test_19_01_threshold_by_measurement(self):
'''Set threshold based on mean image intensity'''
pixels = np.zeros((10,10))
pixels[2:6,2:6] = .5
image = cpi.Image(pixels)
image_set_list = cpi.ImageSetList()
image_set = image_set_list.get_image_set(0)
image_set.add("MyImage", image)
object_set = cpo.ObjectSet()
pipeline = cellprofiler.pipeline.Pipeline()
measurements = cpmeas.Measurements()
measurements.add_image_measurement("MeanIntensity_MyImage", np.mean(pixels))
x = ID.IdentifyPrimaryObjects()
x.object_name.value = "MyObject"
x.image_name.value = "MyImage"
x.exclude_size.value = False
x.unclump_method.value = ID.UN_NONE
x.watershed_method.value = ID.WA_NONE
x.threshold_scope.value = T.TM_MEASUREMENT
x.threshold_smoothing_choice.value = I.TSM_NONE
x.thresholding_measurement.value = "MeanIntensity_MyImage"
x.threshold_correction_factor.value = 1
x.module_num = 1
pipeline.add_module(x)
workspace = Workspace(pipeline, x, image_set, object_set, measurements,
image_set_list)
x.run(workspace)
self.assertEqual(measurements.get_current_image_measurement("Count_MyObject"),1)
self.assertEqual(measurements.get_current_image_measurement("Threshold_FinalThreshold_MyObject"),np.mean(pixels))
def test_20_01_threshold_smoothing_automatic(self):
image = np.array([[ 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, .4, .4, .4, 0, 0],
[ 0, 0, .4, .5, .4, 0, 0],
[ 0, 0, .4, .4, .4, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0]])
expected = np.array([[ 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 1, 0, 0, 0],
[ 0, 0, 1, 1, 1, 0, 0],
[ 0, 0, 0, 1, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0]])
workspace, module = self.make_workspace(image)
assert isinstance(module, ID.IdentifyPrimaryObjects)
module.exclude_size.value = False
module.unclump_method.value = ID.UN_NONE
module.watershed_method.value = ID.WA_NONE
# MCT on this image is zero, so set the threshold at .225
# with the threshold minimum (manual = no smoothing)
module.threshold_scope.value = I.TS_GLOBAL
module.threshold_method.value = T.TM_MCT
module.threshold_range.min= .225
module.threshold_smoothing_choice.value = I.TSM_AUTOMATIC
module.run(workspace)
labels = workspace.object_set.get_objects(OBJECTS_NAME).segmented
np.testing.assert_array_equal(expected, labels)
def test_20_02_threshold_smoothing_manual(self):
image = np.array([[ 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, .4, .4, .4, 0, 0],
[ 0, 0, .4, .5, .4, 0, 0],
[ 0, 0, .4, .4, .4, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0]])
expected = np.array([[ 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 1, 0, 0, 0],
[ 0, 0, 1, 1, 1, 0, 0],
[ 0, 0, 0, 1, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0]])
workspace, module = self.make_workspace(image)
assert isinstance(module, ID.IdentifyPrimaryObjects)
module.exclude_size.value = False
module.unclump_method.value = ID.UN_NONE
module.watershed_method.value = ID.WA_NONE
module.threshold_scope.value = I.TS_GLOBAL
module.threshold_method.value = T.TM_MCT
module.threshold_range.min= .125
module.threshold_smoothing_choice.value = I.TSM_MANUAL
module.threshold_smoothing_scale.value = 3
module.run(workspace)
labels = workspace.object_set.get_objects(OBJECTS_NAME).segmented
np.testing.assert_array_equal(expected, labels)
def test_20_03_threshold_no_smoothing(self):
image = np.array([[ 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, .4, .4, .4, 0, 0],
[ 0, 0, .4, .5, .4, 0, 0],
[ 0, 0, .4, .4, .4, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0]])
expected = np.array([[ 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 1, 1, 1, 0, 0],
[ 0, 0, 1, 1, 1, 0, 0],
[ 0, 0, 1, 1, 1, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0]])
for ts in I.TS_MANUAL, I.TS_MEASUREMENT:
workspace, module = self.make_workspace(image)
assert isinstance(module, ID.IdentifyPrimaryObjects)
module.exclude_size.value = False
module.unclump_method.value = ID.UN_NONE
module.watershed_method.value = ID.WA_NONE
module.threshold_scope.value = ts
module.manual_threshold.value = .125
module.thresholding_measurement.value = MEASUREMENT_NAME
workspace.measurements[cpmeas.IMAGE, MEASUREMENT_NAME] = .125
module.threshold_smoothing_choice.value = I.TSM_MANUAL
module.threshold_smoothing_scale.value = 3
module.run(workspace)
labels = workspace.object_set.get_objects(OBJECTS_NAME).segmented
np.testing.assert_array_equal(expected, labels)
def add_noise(img, fraction):
'''Add a fractional amount of noise to an image to make it look real'''
np.random.seed(0)
noise = np.random.uniform(low=1-fraction/2, high=1+fraction/2,
size=img.shape)
return img * noise
def one_cell_image():
img = np.zeros((25,25))
draw_circle(img,(10,15),5, .5)
return add_noise(img,.01)
def two_cell_image():
img = np.zeros((50,50))
draw_circle(img,(10,35),5, .8)
draw_circle(img,(30,15),5, .6)
return add_noise(img,.01)
def fly_image():
return read_example_image('ExampleFlyImages','01_POS002_D.TIF')
def draw_circle(img,center,radius,value):
x,y=np.mgrid[0:img.shape[0],0:img.shape[1]]
distance = np.sqrt((x-center[0])*(x-center[0])+(y-center[1])*(y-center[1]))
img[distance<=radius]=value
class TestWeightedVariance(unittest.TestCase):
def test_01_masked_wv(self):
output = T.weighted_variance(np.zeros((3,3)),
np.zeros((3,3),bool), 1)
self.assertEqual(output, 0)
def test_02_zero_wv(self):
output = T.weighted_variance(np.zeros((3,3)),
np.ones((3,3),bool),
np.ones((3,3),bool))
self.assertEqual(output, 0)
def test_03_fg_0_bg_0(self):
"""Test all foreground pixels same, all background same, wv = 0"""
img = np.zeros((4,4))
img[:,2:4]=1
binary_image = img > .5
output = T.weighted_variance(img, np.ones(img.shape,bool), binary_image)
self.assertEqual(output,0)
def test_04_values(self):
"""Test with two foreground and two background values"""
#
# The log of this array is [-4,-3],[-2,-1] and
# the variance should be (.25 *2 + .25 *2)/4 = .25
img = np.array([[1.0/16.,1.0/8.0],[1.0/4.0,1.0/2.0]])
binary_image = np.array([[False, False], [True, True]])
output = T.weighted_variance(img, np.ones((2,2),bool), binary_image)
self.assertAlmostEqual(output,.25)
def test_05_mask(self):
"""Test, masking out one of the background values"""
#
# The log of this array is [-4,-3],[-2,-1] and
# the variance should be (.25*2 + .25 *2)/4 = .25
img = np.array([[1.0/16.,1.0/16.0,1.0/8.0],[1.0/4.0,1.0/4.0,1.0/2.0]])
mask = np.array([[False,True,True],[False,True,True]])
binary_image = np.array([[False, False, False], [True, True, True]])
output = T.weighted_variance(img, mask, binary_image)
self.assertAlmostEquals(output,.25)
class TestSumOfEntropies(unittest.TestCase):
def test_01_all_masked(self):
output = T.sum_of_entropies(np.zeros((3,3)),
np.zeros((3,3),bool), 1)
self.assertEqual(output,0)
def test_020_all_zero(self):
"""Can't take the log of zero, so all zero matrix = 0"""
output = T.sum_of_entropies(np.zeros((4,2)),
np.ones((4,2),bool),
np.ones((4,2), bool))
self.assertAlmostEqual(output,0)
def test_03_fg_bg_equal(self):
img = np.ones((128,128))
img[0:64,:] *= .15
img[64:128,:] *= .85
img[0, 0] = img[-1, 0] = 0
img[0, -1] = img[-1, -1] = 1
binary_mask = np.zeros(img.shape, bool)
binary_mask[64:, :] = True
#
# You need one foreground and one background pixel to defeat a
# divide-by-zero (that's appropriately handled)
#
one_of_each = np.zeros(img.shape, bool)
one_of_each[0,0] = one_of_each[-1, -1] = True
output = T.sum_of_entropies(img, np.ones((128,128),bool), binary_mask)
ob = T.sum_of_entropies(img, one_of_each | ~binary_mask, binary_mask)
of = T.sum_of_entropies(img, one_of_each | binary_mask, binary_mask)
self.assertAlmostEqual(output, ob + of)
def test_04_fg_bg_different(self):
img = np.ones((128,128))
img[0:64,0:64] *= .15
img[0:64,64:128] *= .3
img[64:128,0:64] *= .7
img[64:128,64:128] *= .85
binary_mask = np.zeros(img.shape, bool)
binary_mask[64:, :] = True
one_of_each = np.zeros(img.shape, bool)
one_of_each[0,0] = one_of_each[-1, -1] = True
output = T.sum_of_entropies(img, np.ones((128,128),bool), binary_mask)
ob = T.sum_of_entropies(img, one_of_each | ~binary_mask, binary_mask)
of = T.sum_of_entropies(img, one_of_each | binary_mask, binary_mask)
self.assertAlmostEqual(output, ob + of)
| gpl-2.0 |
catapult-project/catapult-csm | third_party/gsutil/third_party/httplib2/python2/httplib2/__init__.py | 29 | 69586 | from __future__ import generators
"""
httplib2
A caching http interface that supports ETags and gzip
to conserve bandwidth.
Requires Python 2.3 or later
Changelog:
2007-08-18, Rick: Modified so it's able to use a socks proxy if needed.
"""
__author__ = "Joe Gregorio ([email protected])"
__copyright__ = "Copyright 2006, Joe Gregorio"
__contributors__ = ["Thomas Broyer ([email protected])",
"James Antill",
"Xavier Verges Farrero",
"Jonathan Feinberg",
"Blair Zajac",
"Sam Ruby",
"Louis Nyffenegger"]
__license__ = "MIT"
__version__ = "0.7.7"
import re
import sys
import email
import email.Utils
import email.Message
import email.FeedParser
import StringIO
import gzip
import zlib
import httplib
import urlparse
import urllib
import base64
import os
import copy
import calendar
import time
import random
import errno
try:
from hashlib import sha1 as _sha, md5 as _md5
except ImportError:
# prior to Python 2.5, these were separate modules
import sha
import md5
_sha = sha.new
_md5 = md5.new
import hmac
from gettext import gettext as _
import socket
try:
from httplib2 import socks
except ImportError:
try:
import socks
except (ImportError, AttributeError):
socks = None
# Build the appropriate socket wrapper for ssl
try:
import ssl # python 2.6
ssl_SSLError = ssl.SSLError
def _ssl_wrap_socket(sock, key_file, cert_file,
disable_validation, ca_certs):
if disable_validation:
cert_reqs = ssl.CERT_NONE
else:
cert_reqs = ssl.CERT_REQUIRED
# We should be specifying SSL version 3 or TLS v1, but the ssl module
# doesn't expose the necessary knobs. So we need to go with the default
# of SSLv23.
return ssl.wrap_socket(sock, keyfile=key_file, certfile=cert_file,
cert_reqs=cert_reqs, ca_certs=ca_certs)
except (AttributeError, ImportError):
ssl_SSLError = None
def _ssl_wrap_socket(sock, key_file, cert_file,
disable_validation, ca_certs):
if not disable_validation:
raise CertificateValidationUnsupported(
"SSL certificate validation is not supported without "
"the ssl module installed. To avoid this error, install "
"the ssl module, or explicity disable validation.")
ssl_sock = socket.ssl(sock, key_file, cert_file)
return httplib.FakeSocket(sock, ssl_sock)
if sys.version_info >= (2,3):
from iri2uri import iri2uri
else:
def iri2uri(uri):
return uri
def has_timeout(timeout): # python 2.6
if hasattr(socket, '_GLOBAL_DEFAULT_TIMEOUT'):
return (timeout is not None and timeout is not socket._GLOBAL_DEFAULT_TIMEOUT)
return (timeout is not None)
__all__ = [
'Http', 'Response', 'ProxyInfo', 'HttpLib2Error', 'RedirectMissingLocation',
'RedirectLimit', 'FailedToDecompressContent',
'UnimplementedDigestAuthOptionError',
'UnimplementedHmacDigestAuthOptionError',
'debuglevel', 'ProxiesUnavailableError']
# The httplib debug level, set to a non-zero value to get debug output
debuglevel = 0
# A request will be tried 'RETRIES' times if it fails at the socket/connection level.
RETRIES = 2
# Python 2.3 support
if sys.version_info < (2,4):
def sorted(seq):
seq.sort()
return seq
# Python 2.3 support
def HTTPResponse__getheaders(self):
"""Return list of (header, value) tuples."""
if self.msg is None:
raise httplib.ResponseNotReady()
return self.msg.items()
if not hasattr(httplib.HTTPResponse, 'getheaders'):
httplib.HTTPResponse.getheaders = HTTPResponse__getheaders
# All exceptions raised here derive from HttpLib2Error
class HttpLib2Error(Exception): pass
# Some exceptions can be caught and optionally
# be turned back into responses.
class HttpLib2ErrorWithResponse(HttpLib2Error):
def __init__(self, desc, response, content):
self.response = response
self.content = content
HttpLib2Error.__init__(self, desc)
class RedirectMissingLocation(HttpLib2ErrorWithResponse): pass
class RedirectLimit(HttpLib2ErrorWithResponse): pass
class FailedToDecompressContent(HttpLib2ErrorWithResponse): pass
class UnimplementedDigestAuthOptionError(HttpLib2ErrorWithResponse): pass
class UnimplementedHmacDigestAuthOptionError(HttpLib2ErrorWithResponse): pass
class MalformedHeader(HttpLib2Error): pass
class RelativeURIError(HttpLib2Error): pass
class ServerNotFoundError(HttpLib2Error): pass
class ProxiesUnavailableError(HttpLib2Error): pass
class CertificateValidationUnsupported(HttpLib2Error): pass
class SSLHandshakeError(HttpLib2Error): pass
class NotSupportedOnThisPlatform(HttpLib2Error): pass
class CertificateHostnameMismatch(SSLHandshakeError):
def __init__(self, desc, host, cert):
HttpLib2Error.__init__(self, desc)
self.host = host
self.cert = cert
# Open Items:
# -----------
# Proxy support
# Are we removing the cached content too soon on PUT (only delete on 200 Maybe?)
# Pluggable cache storage (supports storing the cache in
# flat files by default. We need a plug-in architecture
# that can support Berkeley DB and Squid)
# == Known Issues ==
# Does not handle a resource that uses conneg and Last-Modified but no ETag as a cache validator.
# Does not handle Cache-Control: max-stale
# Does not use Age: headers when calculating cache freshness.
# The number of redirections to follow before giving up.
# Note that only GET redirects are automatically followed.
# Will also honor 301 requests by saving that info and never
# requesting that URI again.
DEFAULT_MAX_REDIRECTS = 5
try:
# Users can optionally provide a module that tells us where the CA_CERTS
# are located.
import ca_certs_locater
CA_CERTS = ca_certs_locater.get()
except ImportError:
# Default CA certificates file bundled with httplib2.
CA_CERTS = os.path.join(
os.path.dirname(os.path.abspath(__file__ )), "cacerts.txt")
# Which headers are hop-by-hop headers by default
HOP_BY_HOP = ['connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'te', 'trailers', 'transfer-encoding', 'upgrade']
def _get_end2end_headers(response):
hopbyhop = list(HOP_BY_HOP)
hopbyhop.extend([x.strip() for x in response.get('connection', '').split(',')])
return [header for header in response.keys() if header not in hopbyhop]
URI = re.compile(r"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?")
def parse_uri(uri):
"""Parses a URI using the regex given in Appendix B of RFC 3986.
(scheme, authority, path, query, fragment) = parse_uri(uri)
"""
groups = URI.match(uri).groups()
return (groups[1], groups[3], groups[4], groups[6], groups[8])
def urlnorm(uri):
(scheme, authority, path, query, fragment) = parse_uri(uri)
if not scheme or not authority:
raise RelativeURIError("Only absolute URIs are allowed. uri = %s" % uri)
authority = authority.lower()
scheme = scheme.lower()
if not path:
path = "/"
# Could do syntax based normalization of the URI before
# computing the digest. See Section 6.2.2 of Std 66.
request_uri = query and "?".join([path, query]) or path
scheme = scheme.lower()
defrag_uri = scheme + "://" + authority + request_uri
return scheme, authority, request_uri, defrag_uri
# Cache filename construction (original borrowed from Venus http://intertwingly.net/code/venus/)
re_url_scheme = re.compile(r'^\w+://')
re_slash = re.compile(r'[?/:|]+')
def safename(filename):
"""Return a filename suitable for the cache.
Strips dangerous and common characters to create a filename we
can use to store the cache in.
"""
try:
if re_url_scheme.match(filename):
if isinstance(filename,str):
filename = filename.decode('utf-8')
filename = filename.encode('idna')
else:
filename = filename.encode('idna')
except UnicodeError:
pass
if isinstance(filename,unicode):
filename=filename.encode('utf-8')
filemd5 = _md5(filename).hexdigest()
filename = re_url_scheme.sub("", filename)
filename = re_slash.sub(",", filename)
# limit length of filename
if len(filename)>200:
filename=filename[:200]
return ",".join((filename, filemd5))
NORMALIZE_SPACE = re.compile(r'(?:\r\n)?[ \t]+')
def _normalize_headers(headers):
return dict([ (key.lower(), NORMALIZE_SPACE.sub(value, ' ').strip()) for (key, value) in headers.iteritems()])
def _parse_cache_control(headers):
retval = {}
if headers.has_key('cache-control'):
parts = headers['cache-control'].split(',')
parts_with_args = [tuple([x.strip().lower() for x in part.split("=", 1)]) for part in parts if -1 != part.find("=")]
parts_wo_args = [(name.strip().lower(), 1) for name in parts if -1 == name.find("=")]
retval = dict(parts_with_args + parts_wo_args)
return retval
# Whether to use a strict mode to parse WWW-Authenticate headers
# Might lead to bad results in case of ill-formed header value,
# so disabled by default, falling back to relaxed parsing.
# Set to true to turn on, usefull for testing servers.
USE_WWW_AUTH_STRICT_PARSING = 0
# In regex below:
# [^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+ matches a "token" as defined by HTTP
# "(?:[^\0-\x08\x0A-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?" matches a "quoted-string" as defined by HTTP, when LWS have already been replaced by a single space
# Actually, as an auth-param value can be either a token or a quoted-string, they are combined in a single pattern which matches both:
# \"?((?<=\")(?:[^\0-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?(?=\")|(?<!\")[^\0-\x08\x0A-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+(?!\"))\"?
WWW_AUTH_STRICT = re.compile(r"^(?:\s*(?:,\s*)?([^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+)\s*=\s*\"?((?<=\")(?:[^\0-\x08\x0A-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?(?=\")|(?<!\")[^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+(?!\"))\"?)(.*)$")
WWW_AUTH_RELAXED = re.compile(r"^(?:\s*(?:,\s*)?([^ \t\r\n=]+)\s*=\s*\"?((?<=\")(?:[^\\\"]|\\.)*?(?=\")|(?<!\")[^ \t\r\n,]+(?!\"))\"?)(.*)$")
UNQUOTE_PAIRS = re.compile(r'\\(.)')
def _parse_www_authenticate(headers, headername='www-authenticate'):
"""Returns a dictionary of dictionaries, one dict
per auth_scheme."""
retval = {}
if headers.has_key(headername):
try:
authenticate = headers[headername].strip()
www_auth = USE_WWW_AUTH_STRICT_PARSING and WWW_AUTH_STRICT or WWW_AUTH_RELAXED
while authenticate:
# Break off the scheme at the beginning of the line
if headername == 'authentication-info':
(auth_scheme, the_rest) = ('digest', authenticate)
else:
(auth_scheme, the_rest) = authenticate.split(" ", 1)
# Now loop over all the key value pairs that come after the scheme,
# being careful not to roll into the next scheme
match = www_auth.search(the_rest)
auth_params = {}
while match:
if match and len(match.groups()) == 3:
(key, value, the_rest) = match.groups()
auth_params[key.lower()] = UNQUOTE_PAIRS.sub(r'\1', value) # '\\'.join([x.replace('\\', '') for x in value.split('\\\\')])
match = www_auth.search(the_rest)
retval[auth_scheme.lower()] = auth_params
authenticate = the_rest.strip()
except ValueError:
raise MalformedHeader("WWW-Authenticate")
return retval
def _entry_disposition(response_headers, request_headers):
"""Determine freshness from the Date, Expires and Cache-Control headers.
We don't handle the following:
1. Cache-Control: max-stale
2. Age: headers are not used in the calculations.
Not that this algorithm is simpler than you might think
because we are operating as a private (non-shared) cache.
This lets us ignore 's-maxage'. We can also ignore
'proxy-invalidate' since we aren't a proxy.
We will never return a stale document as
fresh as a design decision, and thus the non-implementation
of 'max-stale'. This also lets us safely ignore 'must-revalidate'
since we operate as if every server has sent 'must-revalidate'.
Since we are private we get to ignore both 'public' and
'private' parameters. We also ignore 'no-transform' since
we don't do any transformations.
The 'no-store' parameter is handled at a higher level.
So the only Cache-Control parameters we look at are:
no-cache
only-if-cached
max-age
min-fresh
"""
retval = "STALE"
cc = _parse_cache_control(request_headers)
cc_response = _parse_cache_control(response_headers)
if request_headers.has_key('pragma') and request_headers['pragma'].lower().find('no-cache') != -1:
retval = "TRANSPARENT"
if 'cache-control' not in request_headers:
request_headers['cache-control'] = 'no-cache'
elif cc.has_key('no-cache'):
retval = "TRANSPARENT"
elif cc_response.has_key('no-cache'):
retval = "STALE"
elif cc.has_key('only-if-cached'):
retval = "FRESH"
elif response_headers.has_key('date'):
date = calendar.timegm(email.Utils.parsedate_tz(response_headers['date']))
now = time.time()
current_age = max(0, now - date)
if cc_response.has_key('max-age'):
try:
freshness_lifetime = int(cc_response['max-age'])
except ValueError:
freshness_lifetime = 0
elif response_headers.has_key('expires'):
expires = email.Utils.parsedate_tz(response_headers['expires'])
if None == expires:
freshness_lifetime = 0
else:
freshness_lifetime = max(0, calendar.timegm(expires) - date)
else:
freshness_lifetime = 0
if cc.has_key('max-age'):
try:
freshness_lifetime = int(cc['max-age'])
except ValueError:
freshness_lifetime = 0
if cc.has_key('min-fresh'):
try:
min_fresh = int(cc['min-fresh'])
except ValueError:
min_fresh = 0
current_age += min_fresh
if freshness_lifetime > current_age:
retval = "FRESH"
return retval
def _decompressContent(response, new_content):
content = new_content
try:
encoding = response.get('content-encoding', None)
if encoding in ['gzip', 'deflate']:
if encoding == 'gzip':
content = gzip.GzipFile(fileobj=StringIO.StringIO(new_content)).read()
if encoding == 'deflate':
content = zlib.decompress(content)
response['content-length'] = str(len(content))
# Record the historical presence of the encoding in a way the won't interfere.
response['-content-encoding'] = response['content-encoding']
del response['content-encoding']
except IOError:
content = ""
raise FailedToDecompressContent(_("Content purported to be compressed with %s but failed to decompress.") % response.get('content-encoding'), response, content)
return content
def _updateCache(request_headers, response_headers, content, cache, cachekey):
if cachekey:
cc = _parse_cache_control(request_headers)
cc_response = _parse_cache_control(response_headers)
if cc.has_key('no-store') or cc_response.has_key('no-store'):
cache.delete(cachekey)
else:
info = email.Message.Message()
for key, value in response_headers.iteritems():
if key not in ['status','content-encoding','transfer-encoding']:
info[key] = value
# Add annotations to the cache to indicate what headers
# are variant for this request.
vary = response_headers.get('vary', None)
if vary:
vary_headers = vary.lower().replace(' ', '').split(',')
for header in vary_headers:
key = '-varied-%s' % header
try:
info[key] = request_headers[header]
except KeyError:
pass
status = response_headers.status
if status == 304:
status = 200
status_header = 'status: %d\r\n' % status
header_str = info.as_string()
header_str = re.sub("\r(?!\n)|(?<!\r)\n", "\r\n", header_str)
text = "".join([status_header, header_str, content])
cache.set(cachekey, text)
def _cnonce():
dig = _md5("%s:%s" % (time.ctime(), ["0123456789"[random.randrange(0, 9)] for i in range(20)])).hexdigest()
return dig[:16]
def _wsse_username_token(cnonce, iso_now, password):
return base64.b64encode(_sha("%s%s%s" % (cnonce, iso_now, password)).digest()).strip()
# For credentials we need two things, first
# a pool of credential to try (not necesarily tied to BAsic, Digest, etc.)
# Then we also need a list of URIs that have already demanded authentication
# That list is tricky since sub-URIs can take the same auth, or the
# auth scheme may change as you descend the tree.
# So we also need each Auth instance to be able to tell us
# how close to the 'top' it is.
class Authentication(object):
def __init__(self, credentials, host, request_uri, headers, response, content, http):
(scheme, authority, path, query, fragment) = parse_uri(request_uri)
self.path = path
self.host = host
self.credentials = credentials
self.http = http
def depth(self, request_uri):
(scheme, authority, path, query, fragment) = parse_uri(request_uri)
return request_uri[len(self.path):].count("/")
def inscope(self, host, request_uri):
# XXX Should we normalize the request_uri?
(scheme, authority, path, query, fragment) = parse_uri(request_uri)
return (host == self.host) and path.startswith(self.path)
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header. Over-ride this in sub-classes."""
pass
def response(self, response, content):
"""Gives us a chance to update with new nonces
or such returned from the last authorized response.
Over-rise this in sub-classes if necessary.
Return TRUE is the request is to be retried, for
example Digest may return stale=true.
"""
return False
class BasicAuthentication(Authentication):
def __init__(self, credentials, host, request_uri, headers, response, content, http):
Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http)
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header."""
headers['authorization'] = 'Basic ' + base64.b64encode("%s:%s" % self.credentials).strip()
class DigestAuthentication(Authentication):
"""Only do qop='auth' and MD5, since that
is all Apache currently implements"""
def __init__(self, credentials, host, request_uri, headers, response, content, http):
Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http)
challenge = _parse_www_authenticate(response, 'www-authenticate')
self.challenge = challenge['digest']
qop = self.challenge.get('qop', 'auth')
self.challenge['qop'] = ('auth' in [x.strip() for x in qop.split()]) and 'auth' or None
if self.challenge['qop'] is None:
raise UnimplementedDigestAuthOptionError( _("Unsupported value for qop: %s." % qop))
self.challenge['algorithm'] = self.challenge.get('algorithm', 'MD5').upper()
if self.challenge['algorithm'] != 'MD5':
raise UnimplementedDigestAuthOptionError( _("Unsupported value for algorithm: %s." % self.challenge['algorithm']))
self.A1 = "".join([self.credentials[0], ":", self.challenge['realm'], ":", self.credentials[1]])
self.challenge['nc'] = 1
def request(self, method, request_uri, headers, content, cnonce = None):
"""Modify the request headers"""
H = lambda x: _md5(x).hexdigest()
KD = lambda s, d: H("%s:%s" % (s, d))
A2 = "".join([method, ":", request_uri])
self.challenge['cnonce'] = cnonce or _cnonce()
request_digest = '"%s"' % KD(H(self.A1), "%s:%s:%s:%s:%s" % (
self.challenge['nonce'],
'%08x' % self.challenge['nc'],
self.challenge['cnonce'],
self.challenge['qop'], H(A2)))
headers['authorization'] = 'Digest username="%s", realm="%s", nonce="%s", uri="%s", algorithm=%s, response=%s, qop=%s, nc=%08x, cnonce="%s"' % (
self.credentials[0],
self.challenge['realm'],
self.challenge['nonce'],
request_uri,
self.challenge['algorithm'],
request_digest,
self.challenge['qop'],
self.challenge['nc'],
self.challenge['cnonce'])
if self.challenge.get('opaque'):
headers['authorization'] += ', opaque="%s"' % self.challenge['opaque']
self.challenge['nc'] += 1
def response(self, response, content):
if not response.has_key('authentication-info'):
challenge = _parse_www_authenticate(response, 'www-authenticate').get('digest', {})
if 'true' == challenge.get('stale'):
self.challenge['nonce'] = challenge['nonce']
self.challenge['nc'] = 1
return True
else:
updated_challenge = _parse_www_authenticate(response, 'authentication-info').get('digest', {})
if updated_challenge.has_key('nextnonce'):
self.challenge['nonce'] = updated_challenge['nextnonce']
self.challenge['nc'] = 1
return False
class HmacDigestAuthentication(Authentication):
"""Adapted from Robert Sayre's code and DigestAuthentication above."""
__author__ = "Thomas Broyer ([email protected])"
def __init__(self, credentials, host, request_uri, headers, response, content, http):
Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http)
challenge = _parse_www_authenticate(response, 'www-authenticate')
self.challenge = challenge['hmacdigest']
# TODO: self.challenge['domain']
self.challenge['reason'] = self.challenge.get('reason', 'unauthorized')
if self.challenge['reason'] not in ['unauthorized', 'integrity']:
self.challenge['reason'] = 'unauthorized'
self.challenge['salt'] = self.challenge.get('salt', '')
if not self.challenge.get('snonce'):
raise UnimplementedHmacDigestAuthOptionError( _("The challenge doesn't contain a server nonce, or this one is empty."))
self.challenge['algorithm'] = self.challenge.get('algorithm', 'HMAC-SHA-1')
if self.challenge['algorithm'] not in ['HMAC-SHA-1', 'HMAC-MD5']:
raise UnimplementedHmacDigestAuthOptionError( _("Unsupported value for algorithm: %s." % self.challenge['algorithm']))
self.challenge['pw-algorithm'] = self.challenge.get('pw-algorithm', 'SHA-1')
if self.challenge['pw-algorithm'] not in ['SHA-1', 'MD5']:
raise UnimplementedHmacDigestAuthOptionError( _("Unsupported value for pw-algorithm: %s." % self.challenge['pw-algorithm']))
if self.challenge['algorithm'] == 'HMAC-MD5':
self.hashmod = _md5
else:
self.hashmod = _sha
if self.challenge['pw-algorithm'] == 'MD5':
self.pwhashmod = _md5
else:
self.pwhashmod = _sha
self.key = "".join([self.credentials[0], ":",
self.pwhashmod.new("".join([self.credentials[1], self.challenge['salt']])).hexdigest().lower(),
":", self.challenge['realm']])
self.key = self.pwhashmod.new(self.key).hexdigest().lower()
def request(self, method, request_uri, headers, content):
"""Modify the request headers"""
keys = _get_end2end_headers(headers)
keylist = "".join(["%s " % k for k in keys])
headers_val = "".join([headers[k] for k in keys])
created = time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime())
cnonce = _cnonce()
request_digest = "%s:%s:%s:%s:%s" % (method, request_uri, cnonce, self.challenge['snonce'], headers_val)
request_digest = hmac.new(self.key, request_digest, self.hashmod).hexdigest().lower()
headers['authorization'] = 'HMACDigest username="%s", realm="%s", snonce="%s", cnonce="%s", uri="%s", created="%s", response="%s", headers="%s"' % (
self.credentials[0],
self.challenge['realm'],
self.challenge['snonce'],
cnonce,
request_uri,
created,
request_digest,
keylist)
def response(self, response, content):
challenge = _parse_www_authenticate(response, 'www-authenticate').get('hmacdigest', {})
if challenge.get('reason') in ['integrity', 'stale']:
return True
return False
class WsseAuthentication(Authentication):
"""This is thinly tested and should not be relied upon.
At this time there isn't any third party server to test against.
Blogger and TypePad implemented this algorithm at one point
but Blogger has since switched to Basic over HTTPS and
TypePad has implemented it wrong, by never issuing a 401
challenge but instead requiring your client to telepathically know that
their endpoint is expecting WSSE profile="UsernameToken"."""
def __init__(self, credentials, host, request_uri, headers, response, content, http):
Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http)
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header."""
headers['authorization'] = 'WSSE profile="UsernameToken"'
iso_now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
cnonce = _cnonce()
password_digest = _wsse_username_token(cnonce, iso_now, self.credentials[1])
headers['X-WSSE'] = 'UsernameToken Username="%s", PasswordDigest="%s", Nonce="%s", Created="%s"' % (
self.credentials[0],
password_digest,
cnonce,
iso_now)
class GoogleLoginAuthentication(Authentication):
def __init__(self, credentials, host, request_uri, headers, response, content, http):
from urllib import urlencode
Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http)
challenge = _parse_www_authenticate(response, 'www-authenticate')
service = challenge['googlelogin'].get('service', 'xapi')
# Bloggger actually returns the service in the challenge
# For the rest we guess based on the URI
if service == 'xapi' and request_uri.find("calendar") > 0:
service = "cl"
# No point in guessing Base or Spreadsheet
#elif request_uri.find("spreadsheets") > 0:
# service = "wise"
auth = dict(Email=credentials[0], Passwd=credentials[1], service=service, source=headers['user-agent'])
resp, content = self.http.request("https://www.google.com/accounts/ClientLogin", method="POST", body=urlencode(auth), headers={'Content-Type': 'application/x-www-form-urlencoded'})
lines = content.split('\n')
d = dict([tuple(line.split("=", 1)) for line in lines if line])
if resp.status == 403:
self.Auth = ""
else:
self.Auth = d['Auth']
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header."""
headers['authorization'] = 'GoogleLogin Auth=' + self.Auth
AUTH_SCHEME_CLASSES = {
"basic": BasicAuthentication,
"wsse": WsseAuthentication,
"digest": DigestAuthentication,
"hmacdigest": HmacDigestAuthentication,
"googlelogin": GoogleLoginAuthentication
}
AUTH_SCHEME_ORDER = ["hmacdigest", "googlelogin", "digest", "wsse", "basic"]
class FileCache(object):
"""Uses a local directory as a store for cached files.
Not really safe to use if multiple threads or processes are going to
be running on the same cache.
"""
def __init__(self, cache, safe=safename): # use safe=lambda x: md5.new(x).hexdigest() for the old behavior
self.cache = cache
self.safe = safe
if not os.path.exists(cache):
os.makedirs(self.cache)
def get(self, key):
retval = None
cacheFullPath = os.path.join(self.cache, self.safe(key))
try:
f = file(cacheFullPath, "rb")
retval = f.read()
f.close()
except IOError:
pass
return retval
def set(self, key, value):
cacheFullPath = os.path.join(self.cache, self.safe(key))
f = file(cacheFullPath, "wb")
f.write(value)
f.close()
def delete(self, key):
cacheFullPath = os.path.join(self.cache, self.safe(key))
if os.path.exists(cacheFullPath):
os.remove(cacheFullPath)
class Credentials(object):
def __init__(self):
self.credentials = []
def add(self, name, password, domain=""):
self.credentials.append((domain.lower(), name, password))
def clear(self):
self.credentials = []
def iter(self, domain):
for (cdomain, name, password) in self.credentials:
if cdomain == "" or domain == cdomain:
yield (name, password)
class KeyCerts(Credentials):
"""Identical to Credentials except that
name/password are mapped to key/cert."""
pass
class AllHosts(object):
pass
class ProxyInfo(object):
"""Collect information required to use a proxy."""
bypass_hosts = ()
def __init__(self, proxy_type, proxy_host, proxy_port,
proxy_rdns=None, proxy_user=None, proxy_pass=None):
"""The parameter proxy_type must be set to one of socks.PROXY_TYPE_XXX
constants. For example:
p = ProxyInfo(proxy_type=socks.PROXY_TYPE_HTTP,
proxy_host='localhost', proxy_port=8000)
"""
self.proxy_type = proxy_type
self.proxy_host = proxy_host
self.proxy_port = proxy_port
self.proxy_rdns = proxy_rdns
self.proxy_user = proxy_user
self.proxy_pass = proxy_pass
def astuple(self):
return (self.proxy_type, self.proxy_host, self.proxy_port,
self.proxy_rdns, self.proxy_user, self.proxy_pass)
def isgood(self):
return (self.proxy_host != None) and (self.proxy_port != None)
def applies_to(self, hostname):
return not self.bypass_host(hostname)
def bypass_host(self, hostname):
"""Has this host been excluded from the proxy config"""
if self.bypass_hosts is AllHosts:
return True
bypass = False
for domain in self.bypass_hosts:
if hostname.endswith(domain):
bypass = True
return bypass
def proxy_info_from_environment(method='http'):
"""
Read proxy info from the environment variables.
"""
if method not in ['http', 'https']:
return
env_var = method + '_proxy'
url = os.environ.get(env_var, os.environ.get(env_var.upper()))
if not url:
return
pi = proxy_info_from_url(url, method)
no_proxy = os.environ.get('no_proxy', os.environ.get('NO_PROXY', ''))
bypass_hosts = []
if no_proxy:
bypass_hosts = no_proxy.split(',')
# special case, no_proxy=* means all hosts bypassed
if no_proxy == '*':
bypass_hosts = AllHosts
pi.bypass_hosts = bypass_hosts
return pi
def proxy_info_from_url(url, method='http'):
"""
Construct a ProxyInfo from a URL (such as http_proxy env var)
"""
url = urlparse.urlparse(url)
username = None
password = None
port = None
if '@' in url[1]:
ident, host_port = url[1].split('@', 1)
if ':' in ident:
username, password = ident.split(':', 1)
else:
password = ident
else:
host_port = url[1]
if ':' in host_port:
host, port = host_port.split(':', 1)
else:
host = host_port
if port:
port = int(port)
else:
port = dict(https=443, http=80)[method]
proxy_type = 3 # socks.PROXY_TYPE_HTTP
return ProxyInfo(
proxy_type = proxy_type,
proxy_host = host,
proxy_port = port,
proxy_user = username or None,
proxy_pass = password or None,
)
class HTTPConnectionWithTimeout(httplib.HTTPConnection):
"""
HTTPConnection subclass that supports timeouts
All timeouts are in seconds. If None is passed for timeout then
Python's default timeout for sockets will be used. See for example
the docs of socket.setdefaulttimeout():
http://docs.python.org/library/socket.html#socket.setdefaulttimeout
"""
def __init__(self, host, port=None, strict=None, timeout=None, proxy_info=None):
httplib.HTTPConnection.__init__(self, host, port, strict)
self.timeout = timeout
self.proxy_info = proxy_info
def connect(self):
"""Connect to the host and port specified in __init__."""
# Mostly verbatim from httplib.py.
if self.proxy_info and socks is None:
raise ProxiesUnavailableError(
'Proxy support missing but proxy use was requested!')
msg = "getaddrinfo returns an empty list"
if self.proxy_info and self.proxy_info.isgood():
use_proxy = True
proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass = self.proxy_info.astuple()
else:
use_proxy = False
if use_proxy and proxy_rdns:
host = proxy_host
port = proxy_port
else:
host = self.host
port = self.port
for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
if use_proxy:
self.sock = socks.socksocket(af, socktype, proto)
self.sock.setproxy(proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass)
else:
self.sock = socket.socket(af, socktype, proto)
self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
# Different from httplib: support timeouts.
if has_timeout(self.timeout):
self.sock.settimeout(self.timeout)
# End of difference from httplib.
if self.debuglevel > 0:
print "connect: (%s, %s) ************" % (self.host, self.port)
if use_proxy:
print "proxy: %s ************" % str((proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass))
self.sock.connect((self.host, self.port) + sa[2:])
except socket.error, msg:
if self.debuglevel > 0:
print "connect fail: (%s, %s)" % (self.host, self.port)
if use_proxy:
print "proxy: %s" % str((proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass))
if self.sock:
self.sock.close()
self.sock = None
continue
break
if not self.sock:
raise socket.error, msg
class HTTPSConnectionWithTimeout(httplib.HTTPSConnection):
"""
This class allows communication via SSL.
All timeouts are in seconds. If None is passed for timeout then
Python's default timeout for sockets will be used. See for example
the docs of socket.setdefaulttimeout():
http://docs.python.org/library/socket.html#socket.setdefaulttimeout
"""
def __init__(self, host, port=None, key_file=None, cert_file=None,
strict=None, timeout=None, proxy_info=None,
ca_certs=None, disable_ssl_certificate_validation=False):
httplib.HTTPSConnection.__init__(self, host, port=port,
key_file=key_file,
cert_file=cert_file, strict=strict)
self.timeout = timeout
self.proxy_info = proxy_info
if ca_certs is None:
ca_certs = CA_CERTS
self.ca_certs = ca_certs
self.disable_ssl_certificate_validation = \
disable_ssl_certificate_validation
# The following two methods were adapted from https_wrapper.py, released
# with the Google Appengine SDK at
# http://googleappengine.googlecode.com/svn-history/r136/trunk/python/google/appengine/tools/https_wrapper.py
# under the following license:
#
# Copyright 2007 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.
#
def _GetValidHostsForCert(self, cert):
"""Returns a list of valid host globs for an SSL certificate.
Args:
cert: A dictionary representing an SSL certificate.
Returns:
list: A list of valid host globs.
"""
if 'subjectAltName' in cert:
return [x[1] for x in cert['subjectAltName']
if x[0].lower() == 'dns']
else:
return [x[0][1] for x in cert['subject']
if x[0][0].lower() == 'commonname']
def _ValidateCertificateHostname(self, cert, hostname):
"""Validates that a given hostname is valid for an SSL certificate.
Args:
cert: A dictionary representing an SSL certificate.
hostname: The hostname to test.
Returns:
bool: Whether or not the hostname is valid for this certificate.
"""
hosts = self._GetValidHostsForCert(cert)
for host in hosts:
host_re = host.replace('.', '\.').replace('*', '[^.]*')
if re.search('^%s$' % (host_re,), hostname, re.I):
return True
return False
def connect(self):
"Connect to a host on a given (SSL) port."
msg = "getaddrinfo returns an empty list"
if self.proxy_info and self.proxy_info.isgood():
use_proxy = True
proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass = self.proxy_info.astuple()
else:
use_proxy = False
if use_proxy and proxy_rdns:
host = proxy_host
port = proxy_port
else:
host = self.host
port = self.port
address_info = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)
for family, socktype, proto, canonname, sockaddr in address_info:
try:
if use_proxy:
sock = socks.socksocket(family, socktype, proto)
sock.setproxy(proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass)
else:
sock = socket.socket(family, socktype, proto)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
if has_timeout(self.timeout):
sock.settimeout(self.timeout)
sock.connect((self.host, self.port))
self.sock =_ssl_wrap_socket(
sock, self.key_file, self.cert_file,
self.disable_ssl_certificate_validation, self.ca_certs)
if self.debuglevel > 0:
print "connect: (%s, %s)" % (self.host, self.port)
if use_proxy:
print "proxy: %s" % str((proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass))
if not self.disable_ssl_certificate_validation:
cert = self.sock.getpeercert()
hostname = self.host.split(':', 0)[0]
if not self._ValidateCertificateHostname(cert, hostname):
raise CertificateHostnameMismatch(
'Server presented certificate that does not match '
'host %s: %s' % (hostname, cert), hostname, cert)
except ssl_SSLError, e:
if sock:
sock.close()
if self.sock:
self.sock.close()
self.sock = None
# Unfortunately the ssl module doesn't seem to provide any way
# to get at more detailed error information, in particular
# whether the error is due to certificate validation or
# something else (such as SSL protocol mismatch).
if e.errno == ssl.SSL_ERROR_SSL:
raise SSLHandshakeError(e)
else:
raise
except (socket.timeout, socket.gaierror):
raise
except socket.error, msg:
if self.debuglevel > 0:
print "connect fail: (%s, %s)" % (self.host, self.port)
if use_proxy:
print "proxy: %s" % str((proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass))
if self.sock:
self.sock.close()
self.sock = None
continue
break
if not self.sock:
raise socket.error, msg
SCHEME_TO_CONNECTION = {
'http': HTTPConnectionWithTimeout,
'https': HTTPSConnectionWithTimeout
}
# Use a different connection object for Google App Engine
try:
try:
from google.appengine.api import apiproxy_stub_map
if apiproxy_stub_map.apiproxy.GetStub('urlfetch') is None:
raise ImportError # Bail out; we're not actually running on App Engine.
from google.appengine.api.urlfetch import fetch
from google.appengine.api.urlfetch import InvalidURLError
except ImportError:
from google3.apphosting.api import apiproxy_stub_map
if apiproxy_stub_map.apiproxy.GetStub('urlfetch') is None:
raise ImportError # Bail out; we're not actually running on App Engine.
from google3.apphosting.api.urlfetch import fetch
from google3.apphosting.api.urlfetch import InvalidURLError
def _new_fixed_fetch(validate_certificate):
def fixed_fetch(url, payload=None, method="GET", headers={},
allow_truncated=False, follow_redirects=True,
deadline=5):
return fetch(url, payload=payload, method=method, headers=header,
allow_truncated=allow_truncated,
follow_redirects=follow_redirects, deadline=deadline,
validate_certificate=validate_certificate)
return fixed_fetch
class AppEngineHttpConnection(httplib.HTTPConnection):
"""Use httplib on App Engine, but compensate for its weirdness.
The parameters key_file, cert_file, proxy_info, ca_certs, and
disable_ssl_certificate_validation are all dropped on the ground.
"""
def __init__(self, host, port=None, key_file=None, cert_file=None,
strict=None, timeout=None, proxy_info=None, ca_certs=None,
disable_ssl_certificate_validation=False):
httplib.HTTPConnection.__init__(self, host, port=port,
strict=strict, timeout=timeout)
class AppEngineHttpsConnection(httplib.HTTPSConnection):
"""Same as AppEngineHttpConnection, but for HTTPS URIs."""
def __init__(self, host, port=None, key_file=None, cert_file=None,
strict=None, timeout=None, proxy_info=None, ca_certs=None,
disable_ssl_certificate_validation=False):
httplib.HTTPSConnection.__init__(self, host, port=port,
key_file=key_file,
cert_file=cert_file, strict=strict,
timeout=timeout)
self._fetch = _new_fixed_fetch(
not disable_ssl_certificate_validation)
# Update the connection classes to use the Googel App Engine specific ones.
SCHEME_TO_CONNECTION = {
'http': AppEngineHttpConnection,
'https': AppEngineHttpsConnection
}
except ImportError:
pass
class Http(object):
"""An HTTP client that handles:
- all methods
- caching
- ETags
- compression,
- HTTPS
- Basic
- Digest
- WSSE
and more.
"""
def __init__(self, cache=None, timeout=None,
proxy_info=proxy_info_from_environment,
ca_certs=None, disable_ssl_certificate_validation=False):
"""If 'cache' is a string then it is used as a directory name for
a disk cache. Otherwise it must be an object that supports the
same interface as FileCache.
All timeouts are in seconds. If None is passed for timeout
then Python's default timeout for sockets will be used. See
for example the docs of socket.setdefaulttimeout():
http://docs.python.org/library/socket.html#socket.setdefaulttimeout
`proxy_info` may be:
- a callable that takes the http scheme ('http' or 'https') and
returns a ProxyInfo instance per request. By default, uses
proxy_nfo_from_environment.
- a ProxyInfo instance (static proxy config).
- None (proxy disabled).
ca_certs is the path of a file containing root CA certificates for SSL
server certificate validation. By default, a CA cert file bundled with
httplib2 is used.
If disable_ssl_certificate_validation is true, SSL cert validation will
not be performed.
"""
self.proxy_info = proxy_info
self.ca_certs = ca_certs
self.disable_ssl_certificate_validation = \
disable_ssl_certificate_validation
# Map domain name to an httplib connection
self.connections = {}
# The location of the cache, for now a directory
# where cached responses are held.
if cache and isinstance(cache, basestring):
self.cache = FileCache(cache)
else:
self.cache = cache
# Name/password
self.credentials = Credentials()
# Key/cert
self.certificates = KeyCerts()
# authorization objects
self.authorizations = []
# If set to False then no redirects are followed, even safe ones.
self.follow_redirects = True
# Which HTTP methods do we apply optimistic concurrency to, i.e.
# which methods get an "if-match:" etag header added to them.
self.optimistic_concurrency_methods = ["PUT", "PATCH"]
# If 'follow_redirects' is True, and this is set to True then
# all redirecs are followed, including unsafe ones.
self.follow_all_redirects = False
self.ignore_etag = False
self.force_exception_to_status_code = False
self.timeout = timeout
# Keep Authorization: headers on a redirect.
self.forward_authorization_headers = False
def __getstate__(self):
state_dict = copy.copy(self.__dict__)
# In case request is augmented by some foreign object such as
# credentials which handle auth
if 'request' in state_dict:
del state_dict['request']
if 'connections' in state_dict:
del state_dict['connections']
return state_dict
def __setstate__(self, state):
self.__dict__.update(state)
self.connections = {}
def _auth_from_challenge(self, host, request_uri, headers, response, content):
"""A generator that creates Authorization objects
that can be applied to requests.
"""
challenges = _parse_www_authenticate(response, 'www-authenticate')
for cred in self.credentials.iter(host):
for scheme in AUTH_SCHEME_ORDER:
if challenges.has_key(scheme):
yield AUTH_SCHEME_CLASSES[scheme](cred, host, request_uri, headers, response, content, self)
def add_credentials(self, name, password, domain=""):
"""Add a name and password that will be used
any time a request requires authentication."""
self.credentials.add(name, password, domain)
def add_certificate(self, key, cert, domain):
"""Add a key and cert that will be used
any time a request requires authentication."""
self.certificates.add(key, cert, domain)
def clear_credentials(self):
"""Remove all the names and passwords
that are used for authentication"""
self.credentials.clear()
self.authorizations = []
def _conn_request(self, conn, request_uri, method, body, headers):
for i in range(RETRIES):
try:
if hasattr(conn, 'sock') and conn.sock is None:
conn.connect()
conn.request(method, request_uri, body, headers)
except socket.timeout:
raise
except socket.gaierror:
conn.close()
raise ServerNotFoundError("Unable to find the server at %s" % conn.host)
except ssl_SSLError:
conn.close()
raise
except socket.error, e:
err = 0
if hasattr(e, 'args'):
err = getattr(e, 'args')[0]
else:
err = e.errno
if err == errno.ECONNREFUSED: # Connection refused
raise
except httplib.HTTPException:
# Just because the server closed the connection doesn't apparently mean
# that the server didn't send a response.
if hasattr(conn, 'sock') and conn.sock is None:
if i < RETRIES-1:
conn.close()
conn.connect()
continue
else:
conn.close()
raise
if i < RETRIES-1:
conn.close()
conn.connect()
continue
try:
response = conn.getresponse()
except (socket.error, httplib.HTTPException):
if i < RETRIES-1:
conn.close()
conn.connect()
continue
else:
conn.close()
raise
else:
content = ""
if method == "HEAD":
conn.close()
else:
content = response.read()
response = Response(response)
if method != "HEAD":
content = _decompressContent(response, content)
break
return (response, content)
def _request(self, conn, host, absolute_uri, request_uri, method, body, headers, redirections, cachekey):
"""Do the actual request using the connection object
and also follow one level of redirects if necessary"""
auths = [(auth.depth(request_uri), auth) for auth in self.authorizations if auth.inscope(host, request_uri)]
auth = auths and sorted(auths)[0][1] or None
if auth:
auth.request(method, request_uri, headers, body)
(response, content) = self._conn_request(conn, request_uri, method, body, headers)
if auth:
if auth.response(response, body):
auth.request(method, request_uri, headers, body)
(response, content) = self._conn_request(conn, request_uri, method, body, headers )
response._stale_digest = 1
if response.status == 401:
for authorization in self._auth_from_challenge(host, request_uri, headers, response, content):
authorization.request(method, request_uri, headers, body)
(response, content) = self._conn_request(conn, request_uri, method, body, headers, )
if response.status != 401:
self.authorizations.append(authorization)
authorization.response(response, body)
break
if (self.follow_all_redirects or (method in ["GET", "HEAD"]) or response.status == 303):
if self.follow_redirects and response.status in [300, 301, 302, 303, 307]:
# Pick out the location header and basically start from the beginning
# remembering first to strip the ETag header and decrement our 'depth'
if redirections:
if not response.has_key('location') and response.status != 300:
raise RedirectMissingLocation( _("Redirected but the response is missing a Location: header."), response, content)
# Fix-up relative redirects (which violate an RFC 2616 MUST)
if response.has_key('location'):
location = response['location']
(scheme, authority, path, query, fragment) = parse_uri(location)
if authority == None:
response['location'] = urlparse.urljoin(absolute_uri, location)
if response.status == 301 and method in ["GET", "HEAD"]:
response['-x-permanent-redirect-url'] = response['location']
if not response.has_key('content-location'):
response['content-location'] = absolute_uri
_updateCache(headers, response, content, self.cache, cachekey)
if headers.has_key('if-none-match'):
del headers['if-none-match']
if headers.has_key('if-modified-since'):
del headers['if-modified-since']
if 'authorization' in headers and not self.forward_authorization_headers:
del headers['authorization']
if response.has_key('location'):
location = response['location']
old_response = copy.deepcopy(response)
if not old_response.has_key('content-location'):
old_response['content-location'] = absolute_uri
redirect_method = method
if response.status in [302, 303]:
redirect_method = "GET"
body = None
(response, content) = self.request(location, redirect_method, body=body, headers = headers, redirections = redirections - 1)
response.previous = old_response
else:
raise RedirectLimit("Redirected more times than rediection_limit allows.", response, content)
elif response.status in [200, 203] and method in ["GET", "HEAD"]:
# Don't cache 206's since we aren't going to handle byte range requests
if not response.has_key('content-location'):
response['content-location'] = absolute_uri
_updateCache(headers, response, content, self.cache, cachekey)
return (response, content)
def _normalize_headers(self, headers):
return _normalize_headers(headers)
# Need to catch and rebrand some exceptions
# Then need to optionally turn all exceptions into status codes
# including all socket.* and httplib.* exceptions.
def request(self, uri, method="GET", body=None, headers=None, redirections=DEFAULT_MAX_REDIRECTS, connection_type=None):
""" Performs a single HTTP request.
The 'uri' is the URI of the HTTP resource and can begin with either
'http' or 'https'. The value of 'uri' must be an absolute URI.
The 'method' is the HTTP method to perform, such as GET, POST, DELETE,
etc. There is no restriction on the methods allowed.
The 'body' is the entity body to be sent with the request. It is a
string object.
Any extra headers that are to be sent with the request should be
provided in the 'headers' dictionary.
The maximum number of redirect to follow before raising an
exception is 'redirections. The default is 5.
The return value is a tuple of (response, content), the first
being and instance of the 'Response' class, the second being
a string that contains the response entity body.
"""
try:
if headers is None:
headers = {}
else:
headers = self._normalize_headers(headers)
if not headers.has_key('user-agent'):
headers['user-agent'] = "Python-httplib2/%s (gzip)" % __version__
uri = iri2uri(uri)
(scheme, authority, request_uri, defrag_uri) = urlnorm(uri)
domain_port = authority.split(":")[0:2]
if len(domain_port) == 2 and domain_port[1] == '443' and scheme == 'http':
scheme = 'https'
authority = domain_port[0]
proxy_info = self._get_proxy_info(scheme, authority)
conn_key = scheme+":"+authority
if conn_key in self.connections:
conn = self.connections[conn_key]
else:
if not connection_type:
connection_type = SCHEME_TO_CONNECTION[scheme]
certs = list(self.certificates.iter(authority))
if scheme == 'https':
if certs:
conn = self.connections[conn_key] = connection_type(
authority, key_file=certs[0][0],
cert_file=certs[0][1], timeout=self.timeout,
proxy_info=proxy_info,
ca_certs=self.ca_certs,
disable_ssl_certificate_validation=
self.disable_ssl_certificate_validation)
else:
conn = self.connections[conn_key] = connection_type(
authority, timeout=self.timeout,
proxy_info=proxy_info,
ca_certs=self.ca_certs,
disable_ssl_certificate_validation=
self.disable_ssl_certificate_validation)
else:
conn = self.connections[conn_key] = connection_type(
authority, timeout=self.timeout,
proxy_info=proxy_info)
conn.set_debuglevel(debuglevel)
if 'range' not in headers and 'accept-encoding' not in headers:
headers['accept-encoding'] = 'gzip, deflate'
info = email.Message.Message()
cached_value = None
if self.cache:
cachekey = defrag_uri
cached_value = self.cache.get(cachekey)
if cached_value:
# info = email.message_from_string(cached_value)
#
# Need to replace the line above with the kludge below
# to fix the non-existent bug not fixed in this
# bug report: http://mail.python.org/pipermail/python-bugs-list/2005-September/030289.html
try:
info, content = cached_value.split('\r\n\r\n', 1)
feedparser = email.FeedParser.FeedParser()
feedparser.feed(info)
info = feedparser.close()
feedparser._parse = None
except (IndexError, ValueError):
self.cache.delete(cachekey)
cachekey = None
cached_value = None
else:
cachekey = None
if method in self.optimistic_concurrency_methods and self.cache and info.has_key('etag') and not self.ignore_etag and 'if-match' not in headers:
# http://www.w3.org/1999/04/Editing/
headers['if-match'] = info['etag']
if method not in ["GET", "HEAD"] and self.cache and cachekey:
# RFC 2616 Section 13.10
self.cache.delete(cachekey)
# Check the vary header in the cache to see if this request
# matches what varies in the cache.
if method in ['GET', 'HEAD'] and 'vary' in info:
vary = info['vary']
vary_headers = vary.lower().replace(' ', '').split(',')
for header in vary_headers:
key = '-varied-%s' % header
value = info[key]
if headers.get(header, None) != value:
cached_value = None
break
if cached_value and method in ["GET", "HEAD"] and self.cache and 'range' not in headers:
if info.has_key('-x-permanent-redirect-url'):
# Should cached permanent redirects be counted in our redirection count? For now, yes.
if redirections <= 0:
raise RedirectLimit("Redirected more times than rediection_limit allows.", {}, "")
(response, new_content) = self.request(info['-x-permanent-redirect-url'], "GET", headers = headers, redirections = redirections - 1)
response.previous = Response(info)
response.previous.fromcache = True
else:
# Determine our course of action:
# Is the cached entry fresh or stale?
# Has the client requested a non-cached response?
#
# There seems to be three possible answers:
# 1. [FRESH] Return the cache entry w/o doing a GET
# 2. [STALE] Do the GET (but add in cache validators if available)
# 3. [TRANSPARENT] Do a GET w/o any cache validators (Cache-Control: no-cache) on the request
entry_disposition = _entry_disposition(info, headers)
if entry_disposition == "FRESH":
if not cached_value:
info['status'] = '504'
content = ""
response = Response(info)
if cached_value:
response.fromcache = True
return (response, content)
if entry_disposition == "STALE":
if info.has_key('etag') and not self.ignore_etag and not 'if-none-match' in headers:
headers['if-none-match'] = info['etag']
if info.has_key('last-modified') and not 'last-modified' in headers:
headers['if-modified-since'] = info['last-modified']
elif entry_disposition == "TRANSPARENT":
pass
(response, new_content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
if response.status == 304 and method == "GET":
# Rewrite the cache entry with the new end-to-end headers
# Take all headers that are in response
# and overwrite their values in info.
# unless they are hop-by-hop, or are listed in the connection header.
for key in _get_end2end_headers(response):
info[key] = response[key]
merged_response = Response(info)
if hasattr(response, "_stale_digest"):
merged_response._stale_digest = response._stale_digest
_updateCache(headers, merged_response, content, self.cache, cachekey)
response = merged_response
response.status = 200
response.fromcache = True
elif response.status == 200:
content = new_content
else:
self.cache.delete(cachekey)
content = new_content
else:
cc = _parse_cache_control(headers)
if cc.has_key('only-if-cached'):
info['status'] = '504'
response = Response(info)
content = ""
else:
(response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
except Exception, e:
if self.force_exception_to_status_code:
if isinstance(e, HttpLib2ErrorWithResponse):
response = e.response
content = e.content
response.status = 500
response.reason = str(e)
elif isinstance(e, socket.timeout):
content = "Request Timeout"
response = Response({
"content-type": "text/plain",
"status": "408",
"content-length": len(content)
})
response.reason = "Request Timeout"
else:
content = str(e)
response = Response({
"content-type": "text/plain",
"status": "400",
"content-length": len(content)
})
response.reason = "Bad Request"
else:
raise
return (response, content)
def _get_proxy_info(self, scheme, authority):
"""Return a ProxyInfo instance (or None) based on the scheme
and authority.
"""
hostname, port = urllib.splitport(authority)
proxy_info = self.proxy_info
if callable(proxy_info):
proxy_info = proxy_info(scheme)
if (hasattr(proxy_info, 'applies_to')
and not proxy_info.applies_to(hostname)):
proxy_info = None
return proxy_info
class Response(dict):
"""An object more like email.Message than httplib.HTTPResponse."""
"""Is this response from our local cache"""
fromcache = False
"""HTTP protocol version used by server. 10 for HTTP/1.0, 11 for HTTP/1.1. """
version = 11
"Status code returned by server. "
status = 200
"""Reason phrase returned by server."""
reason = "Ok"
previous = None
def __init__(self, info):
# info is either an email.Message or
# an httplib.HTTPResponse object.
if isinstance(info, httplib.HTTPResponse):
for key, value in info.getheaders():
self[key.lower()] = value
self.status = info.status
self['status'] = str(self.status)
self.reason = info.reason
self.version = info.version
elif isinstance(info, email.Message.Message):
for key, value in info.items():
self[key.lower()] = value
self.status = int(self['status'])
else:
for key, value in info.iteritems():
self[key.lower()] = value
self.status = int(self.get('status', self.status))
self.reason = self.get('reason', self.reason)
def __getattr__(self, name):
if name == 'dict':
return self
else:
raise AttributeError, name
| bsd-3-clause |
surgebiswas/poker | PokerBots_2017/Johnny/scipy/weave/ext_tools.py | 92 | 17820 | from __future__ import absolute_import, print_function
import os
import sys
import re
from . import catalog
from . import build_tools
from . import converters
from . import base_spec
class ext_function_from_specs(object):
def __init__(self,name,code_block,arg_specs):
self.name = name
self.arg_specs = base_spec.arg_spec_list(arg_specs)
self.code_block = code_block
self.compiler = ''
self.customize = base_info.custom_info()
def header_code(self):
pass
def function_declaration_code(self):
code = 'static PyObject* %s(PyObject*self, PyObject* args,' \
' PyObject* kywds)\n{\n'
return code % self.name
def template_declaration_code(self):
code = 'template<class T>\n' \
'static PyObject* %s(PyObject*self, PyObject* args,' \
' PyObject* kywds)\n{\n'
return code % self.name
#def cpp_function_declaration_code(self):
# pass
#def cpp_function_call_code(self):
#s pass
def parse_tuple_code(self):
""" Create code block for PyArg_ParseTuple. Variable declarations
for all PyObjects are done also.
This code got a lot uglier when I added local_dict...
"""
declare_return = 'py::object return_val;\n' \
'int exception_occurred = 0;\n' \
'PyObject *py_local_dict = NULL;\n'
arg_string_list = self.arg_specs.variable_as_strings() + ['"local_dict"']
arg_strings = ','.join(arg_string_list)
if arg_strings:
arg_strings += ','
declare_kwlist = 'static const char *kwlist[] = {%s NULL};\n' % \
arg_strings
py_objects = ', '.join(self.arg_specs.py_pointers())
init_flags = ', '.join(self.arg_specs.init_flags())
init_flags_init = '= '.join(self.arg_specs.init_flags())
py_vars = ' = '.join(self.arg_specs.py_variables())
if py_objects:
declare_py_objects = 'PyObject ' + py_objects + ';\n'
declare_py_objects += 'int ' + init_flags + ';\n'
init_values = py_vars + ' = NULL;\n'
init_values += init_flags_init + ' = 0;\n\n'
else:
declare_py_objects = ''
init_values = ''
#Each variable is in charge of its own cleanup now.
#cnt = len(arg_list)
#declare_cleanup = "blitz::TinyVector<PyObject*,%d> clean_up(0);\n" % cnt
ref_string = ', '.join(self.arg_specs.py_references())
if ref_string:
ref_string += ', &py_local_dict'
else:
ref_string = '&py_local_dict'
format = "O" * len(self.arg_specs) + "|O" + ':' + self.name
parse_tuple = 'if(!PyArg_ParseTupleAndKeywords(args,' \
'kywds,"%s",const_cast<char**>(kwlist),%s))\n' % \
(format,ref_string)
parse_tuple += ' return NULL;\n'
return declare_return + declare_kwlist + declare_py_objects \
+ init_values + parse_tuple
def arg_declaration_code(self):
arg_strings = []
for arg in self.arg_specs:
arg_strings.append(arg.declaration_code())
arg_strings.append(arg.init_flag() + " = 1;\n")
code = "".join(arg_strings)
return code
def arg_cleanup_code(self):
arg_strings = []
have_cleanup = filter(lambda x:x.cleanup_code(),self.arg_specs)
for arg in have_cleanup:
code = "if(%s)\n" % arg.init_flag()
code += "{\n"
code += indent(arg.cleanup_code(),4)
code += "}\n"
arg_strings.append(code)
code = "".join(arg_strings)
return code
def arg_local_dict_code(self):
arg_strings = []
for arg in self.arg_specs:
arg_strings.append(arg.local_dict_code())
code = "".join(arg_strings)
return code
def function_code(self):
decl_code = indent(self.arg_declaration_code(),4)
cleanup_code = indent(self.arg_cleanup_code(),4)
function_code = indent(self.code_block,4)
local_dict_code = indent(self.arg_local_dict_code(),4)
dict_code = "if(py_local_dict) \n" \
"{ \n" \
" py::dict local_dict = py::dict(py_local_dict); \n" + \
local_dict_code + \
"} \n"
try_code = "try \n" \
"{ \n" + \
decl_code + \
" /*<function call here>*/ \n" + \
function_code + \
indent(dict_code,4) + \
"\n} \n"
catch_code = "catch(...) \n" \
"{ \n" + \
" return_val = py::object(); \n" \
" exception_occurred = 1; \n" \
"} \n"
return_code = " /*cleanup code*/ \n" + \
cleanup_code + \
' if(!(PyObject*)return_val && !exception_occurred)\n' \
' {\n \n' \
' return_val = Py_None; \n' \
' }\n \n' \
' return return_val.disown(); \n' \
'} \n'
all_code = self.function_declaration_code() + \
indent(self.parse_tuple_code(),4) + \
indent(try_code,4) + \
indent(catch_code,4) + \
return_code
return all_code
def python_function_definition_code(self):
args = (self.name, self.name)
function_decls = '{"%s",(PyCFunction)%s , METH_VARARGS|' \
'METH_KEYWORDS},\n' % args
return function_decls
def set_compiler(self,compiler):
self.compiler = compiler
for arg in self.arg_specs:
arg.set_compiler(compiler)
class ext_function(ext_function_from_specs):
def __init__(self,name,code_block, args, local_dict=None, global_dict=None,
auto_downcast=1, type_converters=None):
call_frame = sys._getframe().f_back
if local_dict is None:
local_dict = call_frame.f_locals
if global_dict is None:
global_dict = call_frame.f_globals
if type_converters is None:
type_converters = converters.default
arg_specs = assign_variable_types(args,local_dict, global_dict,
auto_downcast, type_converters)
ext_function_from_specs.__init__(self,name,code_block,arg_specs)
from . import base_info
class ext_module(object):
def __init__(self,name,compiler=''):
standard_info = converters.standard_info
self.name = name
self.functions = []
self.compiler = compiler
self.customize = base_info.custom_info()
self._build_information = base_info.info_list(standard_info)
def add_function(self,func):
self.functions.append(func)
def module_code(self):
code = '\n'.join([
"""\
#ifdef __CPLUSPLUS__
extern "C" {
#endif
""",
self.warning_code(),
self.header_code(),
self.support_code(),
self.function_code(),
self.python_function_definition_code(),
self.module_init_code(),
"""\
#ifdef __CPLUSCPLUS__
}
#endif
"""
])
return code
def arg_specs(self):
all_arg_specs = base_spec.arg_spec_list()
for func in self.functions:
all_arg_specs += func.arg_specs
return all_arg_specs
def build_information(self):
info = self._build_information + [self.customize] + \
self.arg_specs().build_information()
for func in self.functions:
info.append(func.customize)
#redundant, but easiest place to make sure compiler is set
for i in info:
i.set_compiler(self.compiler)
return info
def get_headers(self):
all_headers = self.build_information().headers()
# blitz/array.h always needs to go before most other headers, so we
# hack that here, but we need to ensure that Python.h is the very
# first header included. As indicated in
# http://docs.python.org/api/includes.html
# "Warning: Since Python may define some pre-processor definitions which
# affect the standard headers on some systems, you must include Python.h
# before any standard headers are included. "
# Since blitz/array.h pulls in system headers, we must massage this
# list a bit so that the order is Python.h, blitz/array.h, ...
if '"blitz/array.h"' in all_headers:
all_headers.remove('"blitz/array.h"')
# Insert blitz AFTER Python.h, which must remain the first header
all_headers.insert(1,'"blitz/array.h"')
return all_headers
def warning_code(self):
all_warnings = self.build_information().warnings()
w = map(lambda x: "#pragma warning(%s)\n" % x,all_warnings)
return '#ifndef __GNUC__\n' + ''.join(w) + '\n#endif'
def header_code(self):
h = self.get_headers()
h = map(lambda x: '#include ' + x + '\n',h)
return ''.join(h) + '\n'
def support_code(self):
code = self.build_information().support_code()
return ''.join(code) + '\n'
def function_code(self):
all_function_code = ""
for func in self.functions:
all_function_code += func.function_code()
return ''.join(all_function_code) + '\n'
def python_function_definition_code(self):
all_definition_code = ""
for func in self.functions:
all_definition_code += func.python_function_definition_code()
all_definition_code = indent(''.join(all_definition_code),4)
code = 'static PyMethodDef compiled_methods[] = \n' \
'{\n' \
'%s' \
' {NULL, NULL} /* Sentinel */\n' \
'};\n'
return code % (all_definition_code)
def module_init_code(self):
init_code_list = self.build_information().module_init_code()
init_code = indent(''.join(init_code_list),4)
code = 'PyMODINIT_FUNC init%s(void)\n' \
'{\n' \
'%s' \
' (void) Py_InitModule("%s", compiled_methods);\n' \
'}\n' % (self.name,init_code,self.name)
return code
def generate_file(self,file_name="",location='.'):
code = self.module_code()
if not file_name:
file_name = self.name + '.cpp'
name = generate_file_name(file_name,location)
#return name
return generate_module(code,name)
def set_compiler(self,compiler):
# This is not used anymore -- I think we should ditch it.
#for i in self.arg_specs()
# i.set_compiler(compiler)
for i in self.build_information():
i.set_compiler(compiler)
for i in self.functions:
i.set_compiler(compiler)
self.compiler = compiler
def build_kw_and_file(self,location,kw):
arg_specs = self.arg_specs()
info = self.build_information()
_source_files = info.sources()
# remove duplicates
source_files = {}
for i in _source_files:
source_files[i] = None
source_files = source_files.keys()
# add internally specified macros, includes, etc. to the key words
# values of the same names so that distutils will use them.
kw['define_macros'] = kw.get('define_macros',[]) + \
info.define_macros()
kw['include_dirs'] = kw.get('include_dirs',[]) + info.include_dirs()
kw['libraries'] = kw.get('libraries',[]) + info.libraries()
kw['library_dirs'] = kw.get('library_dirs',[]) + info.library_dirs()
kw['extra_compile_args'] = kw.get('extra_compile_args',[]) + \
info.extra_compile_args()
kw['extra_link_args'] = kw.get('extra_link_args',[]) + \
info.extra_link_args()
kw['sources'] = kw.get('sources',[]) + source_files
file = self.generate_file(location=location)
return kw,file
def setup_extension(self,location='.',**kw):
kw,file = self.build_kw_and_file(location,kw)
return build_tools.create_extension(file, **kw)
def compile(self,location='.',compiler=None, verbose=0, **kw):
if compiler is not None:
self.compiler = compiler
# !! removed -- we don't have any compiler dependent code
# currently in spec or info classes
# hmm. Is there a cleaner way to do this? Seems like
# choosing the compiler spagettis around a little.
#compiler = build_tools.choose_compiler(self.compiler)
#self.set_compiler(compiler)
kw,file = self.build_kw_and_file(location,kw)
# This is needed so that files build correctly even when different
# versions of Python are running around.
# Imported at beginning of file now to help with test paths.
# import catalog
#temp = catalog.default_temp_dir()
# for speed, build in the machines temp directory
temp = catalog.intermediate_dir()
success = build_tools.build_extension(file, temp_dir=temp,
compiler_name=compiler,
verbose=verbose, **kw)
if not success:
raise SystemError('Compilation failed')
def generate_file_name(module_name,module_location):
module_file = os.path.join(module_location,module_name)
return os.path.abspath(module_file)
def generate_module(module_string, module_file):
""" generate the source code file. Only overwrite
the existing file if the actual source has changed.
"""
file_changed = 1
if os.path.exists(module_file):
f = open(module_file,'r')
old_string = f.read()
f.close()
if old_string == module_string:
file_changed = 0
if file_changed:
f = open(module_file,'w')
f.write(module_string)
f.close()
return module_file
def assign_variable_types(variables,local_dict={}, global_dict={},
auto_downcast=1,
type_converters=converters.default):
incoming_vars = {}
incoming_vars.update(global_dict)
incoming_vars.update(local_dict)
variable_specs = []
errors = {}
for var in variables:
try:
example_type = incoming_vars[var]
# look through possible type specs to find which one
# should be used to for example_type
spec = None
for factory in type_converters:
if factory.type_match(example_type):
spec = factory.type_spec(var,example_type)
break
if not spec:
# should really define our own type.
raise IndexError
else:
variable_specs.append(spec)
except KeyError:
errors[var] = ("The type and dimensionality specifications" +
"for variable '" + var + "' are missing.")
except IndexError:
errors[var] = ("Unable to convert variable '" + var +
"' to a C++ type.")
if errors:
raise TypeError(format_error_msg(errors))
if auto_downcast:
variable_specs = downcast(variable_specs)
return variable_specs
def downcast(var_specs):
""" Cast python scalars down to most common type of
arrays used.
Right now, focus on complex and float types. Ignore int types.
Require all arrays to have same type before forcing downcasts.
Note: var_specs are currently altered in place (horrors...!)
"""
numeric_types = []
#grab all the numeric types associated with a variables.
for var in var_specs:
if hasattr(var,'numeric_type'):
numeric_types.append(var.numeric_type)
# if arrays are present, but none of them are double precision,
# make all numeric types float or complex(float)
if (('f' in numeric_types or 'F' in numeric_types) and not (
'd' in numeric_types or 'D' in numeric_types)):
for var in var_specs:
if hasattr(var,'numeric_type'):
if issubclass(var.numeric_type, complex):
var.numeric_type = 'F'
elif issubclass(var.numeric_type, float):
var.numeric_type = 'f'
return var_specs
def indent(st,spaces):
indention = ' '*spaces
indented = indention + st.replace('\n','\n'+indention)
# trim off any trailing spaces
indented = re.sub(r' +$',r'',indented)
return indented
def format_error_msg(errors):
#minimum effort right now...
import pprint
import cStringIO
msg = cStringIO.StringIO()
pprint.pprint(errors,msg)
return msg.getvalue()
| mit |
nitin-cherian/Webapps | SimpleIsBetterThanComplex.com/myproject/.env/lib/python3.5/site-packages/django/contrib/messages/api.py | 48 | 3147 | from django.contrib.messages import constants
from django.contrib.messages.storage import default_storage
__all__ = (
'add_message', 'get_messages',
'get_level', 'set_level',
'debug', 'info', 'success', 'warning', 'error',
'MessageFailure',
)
class MessageFailure(Exception):
pass
def add_message(request, level, message, extra_tags='', fail_silently=False):
"""
Attempts to add a message to the request using the 'messages' app.
"""
try:
messages = request._messages
except AttributeError:
if not hasattr(request, 'META'):
raise TypeError(
"add_message() argument must be an HttpRequest object, not "
"'%s'." % request.__class__.__name__
)
if not fail_silently:
raise MessageFailure(
'You cannot add messages without installing '
'django.contrib.messages.middleware.MessageMiddleware'
)
else:
return messages.add(level, message, extra_tags)
def get_messages(request):
"""
Returns the message storage on the request if it exists, otherwise returns
an empty list.
"""
return getattr(request, '_messages', [])
def get_level(request):
"""
Returns the minimum level of messages to be recorded.
The default level is the ``MESSAGE_LEVEL`` setting. If this is not found,
the ``INFO`` level is used.
"""
storage = getattr(request, '_messages', default_storage(request))
return storage.level
def set_level(request, level):
"""
Sets the minimum level of messages to be recorded, returning ``True`` if
the level was recorded successfully.
If set to ``None``, the default level will be used (see the ``get_level``
method).
"""
if not hasattr(request, '_messages'):
return False
request._messages.level = level
return True
def debug(request, message, extra_tags='', fail_silently=False):
"""
Adds a message with the ``DEBUG`` level.
"""
add_message(request, constants.DEBUG, message, extra_tags=extra_tags,
fail_silently=fail_silently)
def info(request, message, extra_tags='', fail_silently=False):
"""
Adds a message with the ``INFO`` level.
"""
add_message(request, constants.INFO, message, extra_tags=extra_tags,
fail_silently=fail_silently)
def success(request, message, extra_tags='', fail_silently=False):
"""
Adds a message with the ``SUCCESS`` level.
"""
add_message(request, constants.SUCCESS, message, extra_tags=extra_tags,
fail_silently=fail_silently)
def warning(request, message, extra_tags='', fail_silently=False):
"""
Adds a message with the ``WARNING`` level.
"""
add_message(request, constants.WARNING, message, extra_tags=extra_tags,
fail_silently=fail_silently)
def error(request, message, extra_tags='', fail_silently=False):
"""
Adds a message with the ``ERROR`` level.
"""
add_message(request, constants.ERROR, message, extra_tags=extra_tags,
fail_silently=fail_silently)
| mit |
averagehat/scikit-bio | skbio/io/format/fasta.py | 3 | 38087 | """
FASTA/QUAL format (:mod:`skbio.io.format.fasta`)
================================================
.. currentmodule:: skbio.io.format.fasta
The FASTA file format (``fasta``) stores biological (i.e., nucleotide or
protein) sequences in a simple plain text format that is both human-readable
and easy to parse. The file format was first introduced and used in the FASTA
software package [1]_. Additional descriptions of the file format can be found
in [2]_ and [3]_.
An example of a FASTA-formatted file containing two DNA sequences::
>seq1 db-accession-149855
CGATGTCGATCGATCGATCGATCAG
>seq2 db-accession-34989
CATCGATCGATCGATGCATGCATGCATG
The QUAL file format is an additional format related to FASTA. A FASTA file is
sometimes accompanied by a QUAL file, particuarly when the FASTA file contains
sequences generated on a high-throughput sequencing instrument. QUAL files
store a Phred quality score (nonnegative integer) for each base in a sequence
stored in FASTA format (see [4]_ for more details). scikit-bio supports reading
and writing FASTA (and optionally QUAL) file formats.
Format Support
--------------
**Has Sniffer: Yes**
+------+------+---------------------------------------------------------------+
|Reader|Writer| Object Class |
+======+======+===============================================================+
|Yes |Yes |generator of :mod:`skbio.sequence.Sequence` objects |
+------+------+---------------------------------------------------------------+
|Yes |Yes |:mod:`skbio.alignment.SequenceCollection` |
+------+------+---------------------------------------------------------------+
|Yes |Yes |:mod:`skbio.alignment.Alignment` |
+------+------+---------------------------------------------------------------+
|Yes |Yes |:mod:`skbio.sequence.Sequence` |
+------+------+---------------------------------------------------------------+
|Yes |Yes |:mod:`skbio.sequence.DNA` |
+------+------+---------------------------------------------------------------+
|Yes |Yes |:mod:`skbio.sequence.RNA` |
+------+------+---------------------------------------------------------------+
|Yes |Yes |:mod:`skbio.sequence.Protein` |
+------+------+---------------------------------------------------------------+
.. note:: All readers and writers support an optional QUAL file via the
``qual`` parameter. If one is provided, quality scores will be read/written
in addition to FASTA sequence data.
Format Specification
--------------------
The following sections define the FASTA and QUAL file formats in detail.
FASTA Format
^^^^^^^^^^^^
A FASTA file contains one or more biological sequences. The sequences are
stored sequentially, with a *record* for each sequence (also referred to as a
*FASTA record*). Each *record* consists of a single-line *header* (sometimes
referred to as a *defline*, *label*, *description*, or *comment*) followed by
the sequence data, optionally split over multiple lines.
.. note:: Blank or whitespace-only lines are only allowed at the beginning of
the file, between FASTA records, or at the end of the file. A blank or
whitespace-only line after the header line, within the sequence (for FASTA
files), or within quality scores (for QUAL files) will raise an error.
scikit-bio will ignore leading and trailing whitespace characters on each
line while reading.
.. note:: scikit-bio does not currently support legacy FASTA format (i.e.,
headers/comments denoted with a semicolon). The format supported by
scikit-bio (described below in detail) most closely resembles the
description given in NCBI's BLAST documentation [3]_. See [2]_ for more
details on legacy FASTA format. If you would like legacy FASTA format
support added to scikit-bio, please consider submitting a feature request on
the
`scikit-bio issue tracker <https://github.com/biocore/scikit-bio/issues>`_
(pull requests are also welcome!).
Sequence Header
~~~~~~~~~~~~~~~
Each sequence header consists of a single line beginning with a greater-than
(``>``) symbol. Immediately following this is a sequence identifier (ID) and
description separated by one or more whitespace characters. The sequence ID and
description are stored in the sequence `metadata` attribute, under the `'id'`
and `'description'` keys, repectively. Both are optional. Each will be
represented as the empty string (``''``) in `metadata` if it is not present
in the header.
A sequence ID consists of a single *word*: all characters after the greater-
than symbol and before the first whitespace character (if any) are taken as the
sequence ID. Unique sequence IDs are not strictly enforced by the FASTA format
itself. A single standardized ID format is similarly not enforced by the FASTA
format, though it is often common to use a unique library accession number for
a sequence ID (e.g., NCBI's FASTA defline format [5]_).
.. note:: scikit-bio will enforce sequence ID uniqueness depending on the type
of object that the FASTA file is read into. For example, reading a FASTA
file as a generator of ``Sequence`` objects will not enforce
unique IDs since it simply yields each sequence it finds in the FASTA file.
However, if the FASTA file is read into a ``SequenceCollection`` object, ID
uniqueness will be enforced because that is a requirement of a
``SequenceCollection``.
If a description is present, it is taken as the remaining characters that
follow the sequence ID and initial whitespace(s). The description is considered
additional information about the sequence (e.g., comments about the source of
the sequence or the molecule that it encodes).
For example, consider the following header::
>seq1 db-accession-149855
``seq1`` is the sequence ID and ``db-accession-149855`` is the sequence
description.
.. note:: scikit-bio's readers will remove all leading and trailing whitespace
from the description. If a header line begins with whitespace following the
``>``, the ID is assumed to be missing and the remainder of the line is
taken as the description.
Sequence Data
~~~~~~~~~~~~~
Biological sequence data follows the header, and can be split over multiple
lines. The sequence data (i.e., nucleotides or amino acids) are stored using
the standard IUPAC lexicon (single-letter codes).
.. note:: scikit-bio supports both upper and lower case characters.
This functionality depends on the type of object the data is
being read into. For ``Sequence``
objects, sciki-bio doesn't care about the case. However, for other object
types, such as :class:`skbio.sequence.DNA`, :class:`skbio.sequence.RNA`,
and :class:`skbio.sequence.Protein`, the `lowercase` parameter
must be used to control case functionality. Refer to the documentation for
the constructors for details.
.. note:: Both ``-`` and ``.`` are supported as gap characters. See
:mod:`skbio.sequence` for more details on how scikit-bio interprets
sequence data in its in-memory objects.
Validation is performed for all scikit-bio objects which support it. This
consists of all objects which enforce usage of IUPAC characters. If any
invalid IUPAC characters are found in the sequence while reading from the
FASTA file, an exception is raised.
QUAL Format
^^^^^^^^^^^
A QUAL file contains quality scores for one or more biological sequences stored
in a corresponding FASTA file. QUAL format is very similar to FASTA format: it
stores records sequentially, with each record beginning with a header line
containing a sequence ID and description. The same rules apply to QUAL headers
as FASTA headers (see the above sections for details). scikit-bio processes
FASTA and QUAL headers in exactly the same way.
Quality scores are automatically stored in the object's `positional_metadata`
attribute, under the `'quality'` column.
Instead of storing biological sequence data in each record, a QUAL file stores
a Phred quality score for each base in the corresponding sequence. Quality
scores are represented as nonnegative integers separated by whitespace
(typically a single space or newline), and can span multiple lines.
.. note:: When reading FASTA and QUAL files, scikit-bio requires records to be
in the same order in both files (i.e., each FASTA and QUAL record must have
the same ID and description after being parsed). In addition to having the
same order, the number of FASTA records must match the number of QUAL
records (i.e., missing or additonal records are not allowed). scikit-bio
also requires that the number of quality scores match the number of bases in
the corresponding sequence.
When writing FASTA and QUAL files, scikit-bio will maintain the same
ordering of records in both files (i.e., using the same ID and description
in both records) to support future reading.
Format Parameters
-----------------
The following parameters are available to change how FASTA/QUAL files are read
or written in scikit-bio.
QUAL File Parameter (Readers and Writers)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The ``qual`` parameter is available to all FASTA format readers and writers. It
can be any file-like type supported by scikit-bio's I/O registry (e.g., file
handle, file path, etc.). If ``qual`` is provided when reading, quality scores
will be included in each in-memory ``Sequence`` object, in addition
to sequence data stored in the FASTA file. When writing, quality scores will be
written in QUAL format in addition to the sequence data being written in FASTA
format.
Reader-specific Parameters
^^^^^^^^^^^^^^^^^^^^^^^^^^
The available reader parameters differ depending on which reader is used.
Generator, SequenceCollection, and Alignment Reader Parameters
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The ``constructor`` parameter can be used with the ``Sequence``
generator, ``SequenceCollection``, and ``Alignment`` FASTA readers.
``constructor`` specifies the in-memory type of each sequence that is parsed,
and defaults to ``Sequence``. ``constructor`` should be a subclass of
``Sequence``. For example, if you know that the FASTA file you're
reading contains protein sequences, you would pass
``constructor=Protein`` to the reader call.
.. note:: The FASTA sniffer will not attempt to guess the ``constructor``
parameter, so it will always default to ``Sequence`` if another
type is not provided to the reader.
Sequence Reader Parameters
~~~~~~~~~~~~~~~~~~~~~~~~~~
The ``seq_num`` parameter can be used with the ``Sequence``,
``DNA``, ``RNA``, and ``Protein`` FASTA readers. ``seq_num`` specifies which
sequence to read from the FASTA file (and optional QUAL file), and defaults to
1 (i.e., such that the first sequence is read). For example, to read the 50th
sequence from a FASTA file, you would pass ``seq_num=50`` to the reader call.
Writer-specific Parameters
^^^^^^^^^^^^^^^^^^^^^^^^^^
The following parameters are available to all FASTA format writers:
- ``id_whitespace_replacement``: string to replace **each** whitespace
character in a sequence ID. This parameter is useful for cases where an
in-memory sequence ID contains whitespace, which would result in an on-disk
representation that would not be read back into memory as the same ID (since
IDs in FASTA format cannot contain whitespace). Defaults to ``_``. If
``None``, no whitespace replacement is performed and IDs are written as they
are stored in memory (this has the potential to create an invalid
FASTA-formatted file; see note below). This parameter also applies to a QUAL
file if one is provided.
- ``description_newline_replacement``: string to replace **each** newline
character in a sequence description. Since a FASTA header must be a single
line, newlines are not allowed in sequence descriptions and must be replaced
in order to write a valid FASTA file. Defaults to a single space. If
``None``, no newline replacement is performed and descriptions are written as
they are stored in memory (this has the potential to create an invalid
FASTA-formatted file; see note below). This parameter also applies to a QUAL
file if one is provided.
- ``max_width``: integer specifying the maximum line width (i.e., number of
characters) for sequence data and/or quality scores. If a sequence or its
quality scores are longer than ``max_width``, it will be split across
multiple lines, each with a maximum width of ``max_width``. Note that there
are some caveats when splitting quality scores. A single quality score will
*never* be split across multiple lines, otherwise it would become two
different quality scores when read again. Thus, splitting only occurs
*between* quality scores. This makes it possible to have a single long
quality score written on its own line that exceeds ``max_width``. For
example, the quality score ``12345`` would not be split across multiple lines
even if ``max_width=3``. Thus, a 5-character line would be written. Default
behavior is to not split sequence data or quality scores across multiple
lines.
- ``lowercase``: String or boolean array. If a string, it is treated as a key
into the positional metadata of the object. If a boolean array, it
indicates characters to write in lowercase. Characters in the sequence
corresponding to `True` values will be written in lowercase. The boolean
array must be the same length as the sequence.
.. note:: The FASTA format writers will have noticeably better runtime
performance if ``id_whitespace_replacement`` and/or
``description_newline_replacement`` are set to ``None`` so that whitespace
replacement is not performed during writing. However, this can potentially
create invalid FASTA files, especially if there are newline characters in
the IDs or descriptions. For IDs with whitespace, this can also affect how
the IDs are read into memory in a subsequent read operation. For example, if
an in-memory sequence ID is ``'seq 1'`` and
``id_whitespace_replacement=None``, reading the FASTA file back into memory
would result in an ID of ``'seq'``, and ``'1'`` would be part of the
sequence description.
Examples
--------
Reading and Writing FASTA Files
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Suppose we have the following FASTA file with five equal-length sequences
(example modified from [6]_)::
>seq1 Turkey
AAGCTNGGGCATTTCAGGGTGAGCCCGGGCAATACAGGGTAT
>seq2 Salmo gair
AAGCCTTGGCAGTGCAGGGTGAGCCGTGG
CCGGGCACGGTAT
>seq3 H. Sapiens
ACCGGTTGGCCGTTCAGGGTACAGGTTGGCCGTTCAGGGTAA
>seq4 Chimp
AAACCCTTGCCG
TTACGCTTAAAC
CGAGGCCGGGAC
ACTCAT
>seq5 Gorilla
AAACCCTTGCCGGTACGCTTAAACCATTGCCGGTACGCTTAA
.. note:: Original copyright notice for the above example file:
*(c) Copyright 1986-2008 by The University of Washington. Written by Joseph
Felsenstein. Permission is granted to copy this document provided that no
fee is charged for it and that this copyright notice is not removed.*
Note that the sequences are not required to be of equal length in order for the
file to be a valid FASTA file (this depends on the object that you're reading
the file into). Also note that some of the sequences occur on a single line,
while others are split across multiple lines.
Let's define this file in-memory as a ``StringIO``, though this could be a real
file path, file handle, or anything that's supported by scikit-bio's I/O
registry in practice:
>>> fl = [u">seq1 Turkey\\n",
... u"AAGCTNGGGCATTTCAGGGTGAGCCCGGGCAATACAGGGTAT\\n",
... u">seq2 Salmo gair\\n",
... u"AAGCCTTGGCAGTGCAGGGTGAGCCGTGG\\n",
... u"CCGGGCACGGTAT\\n",
... u">seq3 H. Sapiens\\n",
... u"ACCGGTTGGCCGTTCAGGGTACAGGTTGGCCGTTCAGGGTAA\\n",
... u">seq4 Chimp\\n",
... u"AAACCCTTGCCG\\n",
... u"TTACGCTTAAAC\\n",
... u"CGAGGCCGGGAC\\n",
... u"ACTCAT\\n",
... u">seq5 Gorilla\\n",
... u"AAACCCTTGCCGGTACGCTTAAACCATTGCCGGTACGCTTAA\\n"]
Let's read the FASTA file into a ``SequenceCollection``:
>>> from skbio import SequenceCollection
>>> sc = SequenceCollection.read(fl)
>>> sc.sequence_lengths()
[42, 42, 42, 42, 42]
>>> sc.ids()
[u'seq1', u'seq2', u'seq3', u'seq4', u'seq5']
We see that all 5 sequences have 42 characters, and that each of the sequence
IDs were successfully read into memory.
Since these sequences are of equal length (presumably because they've been
aligned), let's load the FASTA file into an ``Alignment`` object, which is a
more appropriate data structure:
>>> from skbio import Alignment
>>> aln = Alignment.read(fl)
>>> aln.sequence_length()
42
Note that we were able to read the FASTA file into two different data
structures (``SequenceCollection`` and ``Alignment``) using the exact same
``read`` method call (and underlying reading/parsing logic). Also note that we
didn't specify a file format in the ``read`` call. The FASTA sniffer detected
the correct file format for us!
Let's inspect the type of sequences stored in the ``Alignment``:
>>> aln[0]
Sequence
------------------------------------------------
Metadata:
u'description': u'Turkey'
u'id': u'seq1'
Stats:
length: 42
------------------------------------------------
0 AAGCTNGGGC ATTTCAGGGT GAGCCCGGGC AATACAGGGT AT
By default, sequences are loaded as ``Sequence`` objects. We can
change the type of sequence via the ``constructor`` parameter:
>>> from skbio import DNA
>>> aln = Alignment.read(fl, constructor=DNA)
>>> aln[0] # doctest: +NORMALIZE_WHITESPACE
DNA
------------------------------------------------
Metadata:
u'description': u'Turkey'
u'id': u'seq1'
Stats:
length: 42
has gaps: False
has degenerates: True
has non-degenerates: True
GC-content: 54.76%
------------------------------------------------
0 AAGCTNGGGC ATTTCAGGGT GAGCCCGGGC AATACAGGGT AT
We now have an ``Alignment`` of ``DNA`` objects instead of
``Sequence`` objects.
To write the alignment in FASTA format:
>>> from io import StringIO
>>> with StringIO() as fh:
... print(aln.write(fh).getvalue())
>seq1 Turkey
AAGCTNGGGCATTTCAGGGTGAGCCCGGGCAATACAGGGTAT
>seq2 Salmo gair
AAGCCTTGGCAGTGCAGGGTGAGCCGTGGCCGGGCACGGTAT
>seq3 H. Sapiens
ACCGGTTGGCCGTTCAGGGTACAGGTTGGCCGTTCAGGGTAA
>seq4 Chimp
AAACCCTTGCCGTTACGCTTAAACCGAGGCCGGGACACTCAT
>seq5 Gorilla
AAACCCTTGCCGGTACGCTTAAACCATTGCCGGTACGCTTAA
<BLANKLINE>
Both ``SequenceCollection`` and ``Alignment`` load all of the sequences from
the FASTA file into memory at once. If the FASTA file is large (which is often
the case), this may be infeasible if you don't have enough memory. To work
around this issue, you can stream the sequences using scikit-bio's
generator-based FASTA reader and writer. The generator-based reader yields
``Sequence`` objects (or subclasses if ``constructor`` is supplied)
one at a time, instead of loading all sequences into memory. For example, let's
use the generator-based reader to process a single sequence at a time in a
``for`` loop:
>>> import skbio.io
>>> for seq in skbio.io.read(fl, format='fasta'):
... seq
... print('')
Sequence
------------------------------------------------
Metadata:
u'description': u'Turkey'
u'id': u'seq1'
Stats:
length: 42
------------------------------------------------
0 AAGCTNGGGC ATTTCAGGGT GAGCCCGGGC AATACAGGGT AT
<BLANKLINE>
Sequence
------------------------------------------------
Metadata:
u'description': u'Salmo gair'
u'id': u'seq2'
Stats:
length: 42
------------------------------------------------
0 AAGCCTTGGC AGTGCAGGGT GAGCCGTGGC CGGGCACGGT AT
<BLANKLINE>
Sequence
------------------------------------------------
Metadata:
u'description': u'H. Sapiens'
u'id': u'seq3'
Stats:
length: 42
------------------------------------------------
0 ACCGGTTGGC CGTTCAGGGT ACAGGTTGGC CGTTCAGGGT AA
<BLANKLINE>
Sequence
------------------------------------------------
Metadata:
u'description': u'Chimp'
u'id': u'seq4'
Stats:
length: 42
------------------------------------------------
0 AAACCCTTGC CGTTACGCTT AAACCGAGGC CGGGACACTC AT
<BLANKLINE>
Sequence
------------------------------------------------
Metadata:
u'description': u'Gorilla'
u'id': u'seq5'
Stats:
length: 42
------------------------------------------------
0 AAACCCTTGC CGGTACGCTT AAACCATTGC CGGTACGCTT AA
<BLANKLINE>
A single sequence can also be read into a ``Sequence`` (or subclass):
>>> from skbio import Sequence
>>> seq = Sequence.read(fl)
>>> seq
Sequence
------------------------------------------------
Metadata:
u'description': u'Turkey'
u'id': u'seq1'
Stats:
length: 42
------------------------------------------------
0 AAGCTNGGGC ATTTCAGGGT GAGCCCGGGC AATACAGGGT AT
By default, the first sequence in the FASTA file is read. This can be
controlled with ``seq_num``. For example, to read the fifth sequence:
>>> seq = Sequence.read(fl, seq_num=5)
>>> seq
Sequence
------------------------------------------------
Metadata:
u'description': u'Gorilla'
u'id': u'seq5'
Stats:
length: 42
------------------------------------------------
0 AAACCCTTGC CGGTACGCTT AAACCATTGC CGGTACGCTT AA
We can use the same API to read the fifth sequence into a ``DNA``:
>>> dna_seq = DNA.read(fl, seq_num=5)
>>> dna_seq
DNA
------------------------------------------------
Metadata:
u'description': u'Gorilla'
u'id': u'seq5'
Stats:
length: 42
has gaps: False
has degenerates: False
has non-degenerates: True
GC-content: 50.00%
------------------------------------------------
0 AAACCCTTGC CGGTACGCTT AAACCATTGC CGGTACGCTT AA
Individual sequence objects can also be written in FASTA format:
>>> with StringIO() as fh:
... print(dna_seq.write(fh).getvalue())
>seq5 Gorilla
AAACCCTTGCCGGTACGCTTAAACCATTGCCGGTACGCTTAA
<BLANKLINE>
Reading and Writing FASTA/QUAL Files
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
In addition to reading and writing standalone FASTA files, scikit-bio also
supports reading and writing FASTA and QUAL files together. Suppose we have the
following FASTA file::
>seq1 db-accession-149855
CGATGTC
>seq2 db-accession-34989
CATCG
Also suppose we have the following QUAL file::
>seq1 db-accession-149855
40 39 39 4
50 1 100
>seq2 db-accession-34989
3 3 10 42 80
>>> fasta_fl = [
... u">seq1 db-accession-149855\\n",
... u"CGATGTC\\n",
... u">seq2 db-accession-34989\\n",
... u"CATCG\\n"]
>>> qual_fl = [
... u">seq1 db-accession-149855\\n",
... u"40 39 39 4\\n",
... u"50 1 100\\n",
... u">seq2 db-accession-34989\\n",
... u"3 3 10 42 80\\n"]
To read in a single ``Sequence`` at a time, we can use the
generator-based reader as we did above, providing both FASTA and QUAL files:
>>> for seq in skbio.io.read(fasta_fl, qual=qual_fl, format='fasta'):
... seq
... print('')
Sequence
------------------------------------------
Metadata:
u'description': u'db-accession-149855'
u'id': u'seq1'
Positional metadata:
u'quality': <dtype: uint8>
Stats:
length: 7
------------------------------------------
0 CGATGTC
<BLANKLINE>
Sequence
-----------------------------------------
Metadata:
u'description': u'db-accession-34989'
u'id': u'seq2'
Positional metadata:
u'quality': <dtype: uint8>
Stats:
length: 5
-----------------------------------------
0 CATCG
<BLANKLINE>
Note that the sequence objects have quality scores stored as positional
metadata since we provided a QUAL file. The other FASTA readers operate in a
similar manner.
Now let's load the sequences and their quality scores into a
``SequenceCollection``:
>>> sc = SequenceCollection.read(fasta_fl, qual=qual_fl)
>>> sc
<SequenceCollection: n=2; mean +/- std length=6.00 +/- 1.00>
To write the sequence data and quality scores in the ``SequenceCollection`` to
FASTA and QUAL files, respectively, we run:
>>> new_fasta_fh = StringIO()
>>> new_qual_fh = StringIO()
>>> _ = sc.write(new_fasta_fh, qual=new_qual_fh)
>>> print(new_fasta_fh.getvalue())
>seq1 db-accession-149855
CGATGTC
>seq2 db-accession-34989
CATCG
<BLANKLINE>
>>> print(new_qual_fh.getvalue())
>seq1 db-accession-149855
40 39 39 4 50 1 100
>seq2 db-accession-34989
3 3 10 42 80
<BLANKLINE>
>>> new_fasta_fh.close()
>>> new_qual_fh.close()
References
----------
.. [1] Lipman, DJ; Pearson, WR (1985). "Rapid and sensitive protein similarity
searches". Science 227 (4693): 1435-41.
.. [2] http://en.wikipedia.org/wiki/FASTA_format
.. [3] http://blast.ncbi.nlm.nih.gov/blastcgihelp.shtml
.. [4] https://www.broadinstitute.org/crd/wiki/index.php/Qual
.. [5] Madden T. The BLAST Sequence Analysis Tool. 2002 Oct 9
[Updated 2003 Aug 13]. In: McEntyre J, Ostell J, editors. The NCBI Handbook
[Internet]. Bethesda (MD): National Center for Biotechnology Information
(US); 2002-. Chapter 16. Available from:
http://www.ncbi.nlm.nih.gov/books/NBK21097/
.. [6] http://evolution.genetics.washington.edu/phylip/doc/sequence.html
"""
# ----------------------------------------------------------------------------
# Copyright (c) 2013--, scikit-bio development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ----------------------------------------------------------------------------
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from future.builtins import range, zip
from six.moves import zip_longest
import textwrap
import numpy as np
from skbio.io import create_format, FASTAFormatError, QUALFormatError
from skbio.io.registry import FileSentinel
from skbio.io.format._base import (_get_nth_sequence,
_parse_fasta_like_header,
_format_fasta_like_records, _line_generator,
_too_many_blanks)
from skbio.util._misc import chunk_str
from skbio.alignment import SequenceCollection, Alignment
from skbio.sequence import Sequence, DNA, RNA, Protein
fasta = create_format('fasta')
@fasta.sniffer()
def _fasta_sniffer(fh):
# Strategy:
# Ignore up to 5 blank/whitespace-only lines at the beginning of the
# file. Read up to 10 records. If at least one record is read (i.e.
# the file isn't empty) and no errors are thrown during reading, assume
# the file is in FASTA format. If a record appears to be QUAL, do *not*
# identify the file as FASTA since we don't want to sniff QUAL files as
# FASTA (technically they can be read as FASTA since the sequences may
# not be validated but it probably isn't what the user wanted). Also, if
# we add QUAL as its own file format in the future, we wouldn't want the
# FASTA and QUAL sniffers to both positively identify a QUAL file.
if _too_many_blanks(fh, 5):
return False, {}
num_records = 10
empty = True
try:
parser = _parse_fasta_raw(fh, _sniffer_data_parser, FASTAFormatError)
for _ in zip(range(num_records), parser):
empty = False
except FASTAFormatError:
return False, {}
if empty:
return False, {}
else:
return True, {}
def _sniffer_data_parser(chunks):
data = _parse_sequence_data(chunks)
try:
_parse_quality_scores(chunks)
except QUALFormatError:
return data
else:
# used for flow control within sniffer, user should never see this
# message
raise FASTAFormatError('Data appear to be quality scores.')
@fasta.reader(None)
def _fasta_to_generator(fh, qual=FileSentinel, constructor=Sequence, **kwargs):
if qual is None:
for seq, id_, desc in _parse_fasta_raw(fh, _parse_sequence_data,
FASTAFormatError):
yield constructor(seq, metadata={'id': id_, 'description': desc},
**kwargs)
else:
fasta_gen = _parse_fasta_raw(fh, _parse_sequence_data,
FASTAFormatError)
qual_gen = _parse_fasta_raw(qual, _parse_quality_scores,
QUALFormatError)
for fasta_rec, qual_rec in zip_longest(fasta_gen, qual_gen,
fillvalue=None):
if fasta_rec is None:
raise FASTAFormatError(
"QUAL file has more records than FASTA file.")
if qual_rec is None:
raise FASTAFormatError(
"FASTA file has more records than QUAL file.")
fasta_seq, fasta_id, fasta_desc = fasta_rec
qual_scores, qual_id, qual_desc = qual_rec
if fasta_id != qual_id:
raise FASTAFormatError(
"IDs do not match between FASTA and QUAL records: %r != %r"
% (str(fasta_id), str(qual_id)))
if fasta_desc != qual_desc:
raise FASTAFormatError(
"Descriptions do not match between FASTA and QUAL "
"records: %r != %r" % (str(fasta_desc), str(qual_desc)))
# sequence and quality scores lengths are checked in constructor
yield constructor(
fasta_seq,
metadata={'id': fasta_id, 'description': fasta_desc},
positional_metadata={'quality': qual_scores}, **kwargs)
@fasta.reader(Sequence)
def _fasta_to_biological_sequence(fh, qual=FileSentinel, seq_num=1):
return _get_nth_sequence(
_fasta_to_generator(fh, qual=qual, constructor=Sequence),
seq_num)
@fasta.reader(DNA)
def _fasta_to_dna_sequence(fh, qual=FileSentinel, seq_num=1, **kwargs):
return _get_nth_sequence(
_fasta_to_generator(fh, qual=qual,
constructor=DNA, **kwargs),
seq_num)
@fasta.reader(RNA)
def _fasta_to_rna_sequence(fh, qual=FileSentinel, seq_num=1, **kwargs):
return _get_nth_sequence(
_fasta_to_generator(fh, qual=qual,
constructor=RNA, **kwargs),
seq_num)
@fasta.reader(Protein)
def _fasta_to_protein_sequence(fh, qual=FileSentinel, seq_num=1, **kwargs):
return _get_nth_sequence(
_fasta_to_generator(fh, qual=qual,
constructor=Protein, **kwargs),
seq_num)
@fasta.reader(SequenceCollection)
def _fasta_to_sequence_collection(fh, qual=FileSentinel,
constructor=Sequence, **kwargs):
return SequenceCollection(
list(_fasta_to_generator(fh, qual=qual, constructor=constructor,
**kwargs)))
@fasta.reader(Alignment)
def _fasta_to_alignment(fh, qual=FileSentinel, constructor=Sequence, **kwargs):
return Alignment(
list(_fasta_to_generator(fh, qual=qual, constructor=constructor,
**kwargs)))
@fasta.writer(None)
def _generator_to_fasta(obj, fh, qual=FileSentinel,
id_whitespace_replacement='_',
description_newline_replacement=' ', max_width=None,
lowercase=None):
if max_width is not None:
if max_width < 1:
raise ValueError(
"Maximum line width must be greater than zero (max_width=%d)."
% max_width)
if qual is not None:
# define text wrapper for splitting quality scores here for
# efficiency. textwrap docs recommend reusing a TextWrapper
# instance when it is used many times. configure text wrapper to
# never break "words" (i.e., integer quality scores) across lines
qual_wrapper = textwrap.TextWrapper(
width=max_width, break_long_words=False,
break_on_hyphens=False)
formatted_records = _format_fasta_like_records(
obj, id_whitespace_replacement, description_newline_replacement,
qual is not None, lowercase)
for header, seq_str, qual_scores in formatted_records:
if max_width is not None:
seq_str = chunk_str(seq_str, max_width, '\n')
fh.write('>%s\n%s\n' % (header, seq_str))
if qual is not None:
qual_str = ' '.join(np.asarray(qual_scores, dtype=np.str))
if max_width is not None:
qual_str = qual_wrapper.fill(qual_str)
qual.write('>%s\n%s\n' % (header, qual_str))
@fasta.writer(Sequence)
def _biological_sequence_to_fasta(obj, fh, qual=FileSentinel,
id_whitespace_replacement='_',
description_newline_replacement=' ',
max_width=None):
_sequences_to_fasta([obj], fh, qual, id_whitespace_replacement,
description_newline_replacement, max_width)
@fasta.writer(DNA)
def _dna_sequence_to_fasta(obj, fh, qual=FileSentinel,
id_whitespace_replacement='_',
description_newline_replacement=' ',
max_width=None, lowercase=None):
_sequences_to_fasta([obj], fh, qual, id_whitespace_replacement,
description_newline_replacement, max_width, lowercase)
@fasta.writer(RNA)
def _rna_sequence_to_fasta(obj, fh, qual=FileSentinel,
id_whitespace_replacement='_',
description_newline_replacement=' ',
max_width=None, lowercase=None):
_sequences_to_fasta([obj], fh, qual, id_whitespace_replacement,
description_newline_replacement, max_width, lowercase)
@fasta.writer(Protein)
def _protein_sequence_to_fasta(obj, fh, qual=FileSentinel,
id_whitespace_replacement='_',
description_newline_replacement=' ',
max_width=None, lowercase=None):
_sequences_to_fasta([obj], fh, qual, id_whitespace_replacement,
description_newline_replacement, max_width, lowercase)
@fasta.writer(SequenceCollection)
def _sequence_collection_to_fasta(obj, fh, qual=FileSentinel,
id_whitespace_replacement='_',
description_newline_replacement=' ',
max_width=None, lowercase=None):
_sequences_to_fasta(obj, fh, qual, id_whitespace_replacement,
description_newline_replacement, max_width, lowercase)
@fasta.writer(Alignment)
def _alignment_to_fasta(obj, fh, qual=FileSentinel,
id_whitespace_replacement='_',
description_newline_replacement=' ', max_width=None,
lowercase=None):
_sequences_to_fasta(obj, fh, qual, id_whitespace_replacement,
description_newline_replacement, max_width, lowercase)
def _parse_fasta_raw(fh, data_parser, error_type):
"""Raw parser for FASTA or QUAL files.
Returns raw values (seq/qual, id, description). It is the responsibility of
the caller to construct the correct in-memory object to hold the data.
"""
# Skip any blank or whitespace-only lines at beginning of file
seq_header = next(_line_generator(fh, skip_blanks=True))
# header check inlined here and below for performance
if seq_header.startswith('>'):
id_, desc = _parse_fasta_like_header(seq_header)
else:
raise error_type(
"Found non-header line when attempting to read the 1st record:"
"\n%s" % seq_header)
data_chunks = []
prev = seq_header
for line in _line_generator(fh, skip_blanks=False):
if line.startswith('>'):
# new header, so yield current record and reset state
yield data_parser(data_chunks), id_, desc
data_chunks = []
id_, desc = _parse_fasta_like_header(line)
else:
if line:
# ensure no blank lines within a single record
if not prev:
raise error_type(
"Found blank or whitespace-only line within record.")
data_chunks.append(line)
prev = line
# yield last record in file
yield data_parser(data_chunks), id_, desc
def _parse_sequence_data(chunks):
if not chunks:
raise FASTAFormatError("Found header without sequence data.")
return ''.join(chunks)
def _parse_quality_scores(chunks):
if not chunks:
raise QUALFormatError("Found header without quality scores.")
qual_str = ' '.join(chunks)
try:
quality = np.asarray(qual_str.split(), dtype=int)
except ValueError:
raise QUALFormatError(
"Could not convert quality scores to integers:\n%s"
% str(qual_str))
if (quality < 0).any():
raise QUALFormatError(
"Encountered negative quality score(s). Quality scores must be "
"greater than or equal to zero.")
if (quality > 255).any():
raise QUALFormatError(
"Encountered quality score(s) greater than 255. scikit-bio only "
"supports quality scores in the range 0-255 (inclusive) when "
"reading QUAL files.")
return quality.astype(np.uint8, casting='unsafe', copy=False)
def _sequences_to_fasta(obj, fh, qual, id_whitespace_replacement,
description_newline_replacement, max_width,
lowercase=None):
def seq_gen():
for seq in obj:
yield seq
_generator_to_fasta(
seq_gen(), fh, qual=qual,
id_whitespace_replacement=id_whitespace_replacement,
description_newline_replacement=description_newline_replacement,
max_width=max_width, lowercase=lowercase)
| bsd-3-clause |
gitlabhq/pygments.rb | vendor/pygments-main/pygments/filter.py | 365 | 2071 | # -*- coding: utf-8 -*-
"""
pygments.filter
~~~~~~~~~~~~~~~
Module that implements the default filter.
:copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
def apply_filters(stream, filters, lexer=None):
"""
Use this method to apply an iterable of filters to
a stream. If lexer is given it's forwarded to the
filter, otherwise the filter receives `None`.
"""
def _apply(filter_, stream):
for token in filter_.filter(lexer, stream):
yield token
for filter_ in filters:
stream = _apply(filter_, stream)
return stream
def simplefilter(f):
"""
Decorator that converts a function into a filter::
@simplefilter
def lowercase(lexer, stream, options):
for ttype, value in stream:
yield ttype, value.lower()
"""
return type(f.__name__, (FunctionFilter,), {
'function': f,
'__module__': getattr(f, '__module__'),
'__doc__': f.__doc__
})
class Filter(object):
"""
Default filter. Subclass this class or use the `simplefilter`
decorator to create own filters.
"""
def __init__(self, **options):
self.options = options
def filter(self, lexer, stream):
raise NotImplementedError()
class FunctionFilter(Filter):
"""
Abstract class used by `simplefilter` to create simple
function filters on the fly. The `simplefilter` decorator
automatically creates subclasses of this class for
functions passed to it.
"""
function = None
def __init__(self, **options):
if not hasattr(self, 'function'):
raise TypeError('%r used without bound function' %
self.__class__.__name__)
Filter.__init__(self, **options)
def filter(self, lexer, stream):
# pylint: disable-msg=E1102
for ttype, value in self.function(lexer, stream, self.options):
yield ttype, value
| mit |
SPACEDAC7/TrabajoFinalGrado | StaticAnalyzer/tools/enjarify/enjarify/dalvikformats.py | 30 | 4154 | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from . import util
# Code for parsing the various Dalvik opcode formats
INSTRUCTION_FORMAT = util.keysToRanges({
0x00: '10x',
0x01: '12x',
0x02: '22x',
0x03: '32x',
0x04: '12x',
0x05: '22x',
0x06: '32x',
0x07: '12x',
0x08: '22x',
0x09: '32x',
0x0a: '11x',
0x0b: '11x',
0x0c: '11x',
0x0d: '11x',
0x0e: '10x',
0x0f: '11x',
0x10: '11x',
0x11: '11x',
0x12: '11n',
0x13: '21s',
0x14: '31i',
0x15: '21h',
0x16: '21s',
0x17: '31i',
0x18: '51l',
0x19: '21h',
0x1a: '21c',
0x1b: '31c',
0x1c: '21c',
0x1d: '11x',
0x1e: '11x',
0x1f: '21c',
0x20: '22c',
0x21: '12x',
0x22: '21c',
0x23: '22c',
0x24: '35c',
0x25: '3rc',
0x26: '31t',
0x27: '11x',
0x28: '10t',
0x29: '20t',
0x2a: '30t',
0x2b: '31t',
0x2c: '31t',
0x2d: '23x',
0x32: '22t',
0x38: '21t',
0x3e: '10x',
0x44: '23x',
0x52: '22c',
0x60: '21c',
0x6e: '35c',
0x73: '10x',
0x74: '3rc',
0x79: '10x',
0x7b: '12x',
0x90: '23x',
0xb0: '12x',
0xd0: '22s',
0xd8: '22b',
0xe3: '10x',
}, 256)
# parsing funcs
def p00op(w): return []
def pBAop(w): return [(w >> 8) & 0xF, w >> 12]
def pAAop(w): return [w >> 8]
def p00opAAAA(w, w2): return [w2]
def pAAopBBBB(w, w2): return [w >> 8, w2]
def pAAopCCBB(w, w2): return [w >> 8, w2 & 0xFF, w2 >> 8]
def pBAopCCCC(w, w2): return [(w >> 8) & 0xF, w >> 12, w2]
def p00opAAAAAAAA(w, w2, w3): return [w2 ^ (w3 << 16)]
def p00opAAAABBBB(w, w2, w3): return [w2, w3]
def pAAopBBBBBBBB(w, w2, w3): return [w >> 8, w2 ^ (w3 << 16)]
def pAGopBBBBFEDC(w, w2, w3):
a = w >> 12
c, d, e, f = (w3) & 0xF, (w3 >> 4) & 0xF, (w3 >> 8) & 0xF, (w3 >> 12) & 0xF
g = (w >> 8) & 0xF
return [w2, [c, d, e, f, g][:a]]
def pAAopBBBBCCCC(w, w2, w3):
a = w >> 8
return [w2, range(w3, w3+a)]
def pAAopBBBBBBBBBBBBBBBB(w, w2, w3, w4, w5):
b = w2 ^ (w3 << 16) ^ (w4 << 32) ^ (w5 << 48)
return [w >> 8, b]
_FUNC = {
'10x': p00op,
'12x': pBAop,
'11n': pBAop,
'11x': pAAop,
'10t': pAAop,
'20t': p00opAAAA,
'22x': pAAopBBBB,
'21t': pAAopBBBB,
'21s': pAAopBBBB,
'21h': pAAopBBBB,
'21c': pAAopBBBB,
'23x': pAAopCCBB,
'22b': pAAopCCBB,
'22t': pBAopCCCC,
'22s': pBAopCCCC,
'22c': pBAopCCCC,
'30t': p00opAAAAAAAA,
'32x': p00opAAAABBBB,
'31i': pAAopBBBBBBBB,
'31t': pAAopBBBBBBBB,
'31c': pAAopBBBBBBBB,
'35c': pAGopBBBBFEDC,
'3rc': pAAopBBBBCCCC,
'51l': pAAopBBBBBBBBBBBBBBBB,
}
def sign(x, bits):
if x >= (1 << (bits-1)):
x -= 1 << bits
return x
def decode(shorts, pos, opcode):
fmt = INSTRUCTION_FORMAT[opcode]
size = int(fmt[0])
results = _FUNC[fmt](*shorts[pos:pos+size])
# Check if we need to sign extend
if fmt[2] == 'n':
results[-1] = sign(results[-1], 4)
elif fmt[2] == 'b' or (fmt[2] == 't' and size == 1):
results[-1] = sign(results[-1], 8)
elif fmt[2] == 's' or (fmt[2] == 't' and size == 2):
results[-1] = sign(results[-1], 16)
elif fmt[2] == 't' and size == 3:
results[-1] = sign(results[-1], 32)
# Hats depend on actual size expected, so we rely on opcode as a hack
if fmt[2] == 'h':
assert(opcode == 0x15 or opcode == 0x19)
results[-1] = results[-1] << (16 if opcode == 0x15 else 48)
# Convert code offsets to actual code position
if fmt[2] == 't':
results[-1] += pos
return pos + size, results
| gpl-3.0 |
Himon-SYNCRAFT/taskplus | tests/core/actions/test_get_task_status_details.py | 1 | 3408 | from unittest import mock
from taskplus.core.actions import (GetTaskStatusDetailsAction,
GetTaskStatusDetailsRequest)
from taskplus.core.domain import TaskStatus
from taskplus.core.shared.response import ResponseFailure
def test_get_status_details_action():
status = mock.Mock()
status = TaskStatus(name='new', id=1)
statuses_repo = mock.Mock()
statuses_repo.one.return_value = status
request = GetTaskStatusDetailsRequest(status.id)
action = GetTaskStatusDetailsAction(statuses_repo)
response = action.execute(request)
assert bool(response) is True
statuses_repo.one.assert_called_once_with(status.id)
assert response.value == status
def test_get_status_details_action_with_hooks():
status = mock.Mock()
status = TaskStatus(name='new', id=1)
statuses_repo = mock.Mock()
statuses_repo.one.return_value = status
request = GetTaskStatusDetailsRequest(status.id)
action = GetTaskStatusDetailsAction(statuses_repo)
before = mock.MagicMock()
after = mock.MagicMock()
action.add_before_execution_hook(before)
action.add_after_execution_hook(after)
response = action.execute(request)
assert before.called
assert after.called
assert bool(response) is True
statuses_repo.one.assert_called_once_with(status.id)
assert response.value == status
def test_get_status_details_action_handles_bad_request():
status = mock.Mock()
status = TaskStatus(name='new', id=1)
statuses_repo = mock.Mock()
statuses_repo.one.return_value = status
request = GetTaskStatusDetailsRequest(status_id=None)
action = GetTaskStatusDetailsAction(statuses_repo)
response = action.execute(request)
assert bool(response) is False
assert not statuses_repo.one.called
assert response.value == {
'type': ResponseFailure.PARAMETER_ERROR,
'message': 'status_id: is required'
}
def test_get_status_details_action_handles_generic_error():
error_message = 'Error!!!'
statuses_repo = mock.Mock()
statuses_repo.one.side_effect = Exception(error_message)
request = GetTaskStatusDetailsRequest(status_id=1)
action = GetTaskStatusDetailsAction(statuses_repo)
response = action.execute(request)
assert bool(response) is False
statuses_repo.one.assert_called_once_with(1)
assert response.value == {
'type': ResponseFailure.SYSTEM_ERROR,
'message': 'Exception: {}'.format(error_message)
}
def test_get_status_details_request():
status_id = 1
request = GetTaskStatusDetailsRequest(status_id)
assert request.is_valid()
assert request.status_id == status_id
def test_get_status_details_request_without_id():
status_id = None
request = GetTaskStatusDetailsRequest(status_id)
assert not request.is_valid()
assert request.status_id == status_id
assert len(request.errors) == 1
error = request.errors[0]
assert error.parameter == 'status_id'
assert error.message == 'is required'
def test_get_status_details_bad_request():
status_id = 'asd'
request = GetTaskStatusDetailsRequest(status_id)
assert not request.is_valid()
assert request.status_id == status_id
assert len(request.errors) == 1
error = request.errors[0]
assert error.parameter == 'status_id'
assert error.message == 'expected int, got str(asd)'
| bsd-3-clause |
TOCyna/tabelinha | flask/lib/python2.7/site-packages/werkzeug/test.py | 32 | 34230 | # -*- coding: utf-8 -*-
"""
werkzeug.test
~~~~~~~~~~~~~
This module implements a client to WSGI applications for testing.
:copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import sys
import mimetypes
from time import time
from random import random
from itertools import chain
from tempfile import TemporaryFile
from io import BytesIO
try:
from urllib2 import Request as U2Request
except ImportError:
from urllib.request import Request as U2Request
try:
from http.cookiejar import CookieJar
except ImportError: # Py2
from cookielib import CookieJar
from werkzeug._compat import iterlists, iteritems, itervalues, to_bytes, \
string_types, text_type, reraise, wsgi_encoding_dance, \
make_literal_wrapper
from werkzeug._internal import _empty_stream, _get_environ
from werkzeug.wrappers import BaseRequest
from werkzeug.urls import url_encode, url_fix, iri_to_uri, url_unquote, \
url_unparse, url_parse
from werkzeug.wsgi import get_host, get_current_url, ClosingIterator
from werkzeug.utils import dump_cookie
from werkzeug.datastructures import FileMultiDict, MultiDict, \
CombinedMultiDict, Headers, FileStorage
def stream_encode_multipart(values, use_tempfile=True, threshold=1024 * 500,
boundary=None, charset='utf-8'):
"""Encode a dict of values (either strings or file descriptors or
:class:`FileStorage` objects.) into a multipart encoded string stored
in a file descriptor.
"""
if boundary is None:
boundary = '---------------WerkzeugFormPart_%s%s' % (time(), random())
_closure = [BytesIO(), 0, False]
if use_tempfile:
def write_binary(string):
stream, total_length, on_disk = _closure
if on_disk:
stream.write(string)
else:
length = len(string)
if length + _closure[1] <= threshold:
stream.write(string)
else:
new_stream = TemporaryFile('wb+')
new_stream.write(stream.getvalue())
new_stream.write(string)
_closure[0] = new_stream
_closure[2] = True
_closure[1] = total_length + length
else:
write_binary = _closure[0].write
def write(string):
write_binary(string.encode(charset))
if not isinstance(values, MultiDict):
values = MultiDict(values)
for key, values in iterlists(values):
for value in values:
write('--%s\r\nContent-Disposition: form-data; name="%s"' %
(boundary, key))
reader = getattr(value, 'read', None)
if reader is not None:
filename = getattr(value, 'filename',
getattr(value, 'name', None))
content_type = getattr(value, 'content_type', None)
if content_type is None:
content_type = filename and \
mimetypes.guess_type(filename)[0] or \
'application/octet-stream'
if filename is not None:
write('; filename="%s"\r\n' % filename)
else:
write('\r\n')
write('Content-Type: %s\r\n\r\n' % content_type)
while 1:
chunk = reader(16384)
if not chunk:
break
write_binary(chunk)
else:
if not isinstance(value, string_types):
value = str(value)
else:
value = to_bytes(value, charset)
write('\r\n\r\n')
write_binary(value)
write('\r\n')
write('--%s--\r\n' % boundary)
length = int(_closure[0].tell())
_closure[0].seek(0)
return _closure[0], length, boundary
def encode_multipart(values, boundary=None, charset='utf-8'):
"""Like `stream_encode_multipart` but returns a tuple in the form
(``boundary``, ``data``) where data is a bytestring.
"""
stream, length, boundary = stream_encode_multipart(
values, use_tempfile=False, boundary=boundary, charset=charset)
return boundary, stream.read()
def File(fd, filename=None, mimetype=None):
"""Backwards compat."""
from warnings import warn
warn(DeprecationWarning('werkzeug.test.File is deprecated, use the '
'EnvironBuilder or FileStorage instead'))
return FileStorage(fd, filename=filename, content_type=mimetype)
class _TestCookieHeaders(object):
"""A headers adapter for cookielib
"""
def __init__(self, headers):
self.headers = headers
def getheaders(self, name):
headers = []
name = name.lower()
for k, v in self.headers:
if k.lower() == name:
headers.append(v)
return headers
def get_all(self, name, default=None):
rv = []
for k, v in self.headers:
if k.lower() == name.lower():
rv.append(v)
return rv or default or []
class _TestCookieResponse(object):
"""Something that looks like a httplib.HTTPResponse, but is actually just an
adapter for our test responses to make them available for cookielib.
"""
def __init__(self, headers):
self.headers = _TestCookieHeaders(headers)
def info(self):
return self.headers
class _TestCookieJar(CookieJar):
"""A cookielib.CookieJar modified to inject and read cookie headers from
and to wsgi environments, and wsgi application responses.
"""
def inject_wsgi(self, environ):
"""Inject the cookies as client headers into the server's wsgi
environment.
"""
cvals = []
for cookie in self:
cvals.append('%s=%s' % (cookie.name, cookie.value))
if cvals:
environ['HTTP_COOKIE'] = '; '.join(cvals)
def extract_wsgi(self, environ, headers):
"""Extract the server's set-cookie headers as cookies into the
cookie jar.
"""
self.extract_cookies(
_TestCookieResponse(headers),
U2Request(get_current_url(environ)),
)
def _iter_data(data):
"""Iterates over a dict or multidict yielding all keys and values.
This is used to iterate over the data passed to the
:class:`EnvironBuilder`.
"""
if isinstance(data, MultiDict):
for key, values in iterlists(data):
for value in values:
yield key, value
else:
for key, values in iteritems(data):
if isinstance(values, list):
for value in values:
yield key, value
else:
yield key, values
class EnvironBuilder(object):
"""This class can be used to conveniently create a WSGI environment
for testing purposes. It can be used to quickly create WSGI environments
or request objects from arbitrary data.
The signature of this class is also used in some other places as of
Werkzeug 0.5 (:func:`create_environ`, :meth:`BaseResponse.from_values`,
:meth:`Client.open`). Because of this most of the functionality is
available through the constructor alone.
Files and regular form data can be manipulated independently of each
other with the :attr:`form` and :attr:`files` attributes, but are
passed with the same argument to the constructor: `data`.
`data` can be any of these values:
- a `str`: If it's a string it is converted into a :attr:`input_stream`,
the :attr:`content_length` is set and you have to provide a
:attr:`content_type`.
- a `dict`: If it's a dict the keys have to be strings and the values
any of the following objects:
- a :class:`file`-like object. These are converted into
:class:`FileStorage` objects automatically.
- a tuple. The :meth:`~FileMultiDict.add_file` method is called
with the tuple items as positional arguments.
.. versionadded:: 0.6
`path` and `base_url` can now be unicode strings that are encoded using
the :func:`iri_to_uri` function.
:param path: the path of the request. In the WSGI environment this will
end up as `PATH_INFO`. If the `query_string` is not defined
and there is a question mark in the `path` everything after
it is used as query string.
:param base_url: the base URL is a URL that is used to extract the WSGI
URL scheme, host (server name + server port) and the
script root (`SCRIPT_NAME`).
:param query_string: an optional string or dict with URL parameters.
:param method: the HTTP method to use, defaults to `GET`.
:param input_stream: an optional input stream. Do not specify this and
`data`. As soon as an input stream is set you can't
modify :attr:`args` and :attr:`files` unless you
set the :attr:`input_stream` to `None` again.
:param content_type: The content type for the request. As of 0.5 you
don't have to provide this when specifying files
and form data via `data`.
:param content_length: The content length for the request. You don't
have to specify this when providing data via
`data`.
:param errors_stream: an optional error stream that is used for
`wsgi.errors`. Defaults to :data:`stderr`.
:param multithread: controls `wsgi.multithread`. Defaults to `False`.
:param multiprocess: controls `wsgi.multiprocess`. Defaults to `False`.
:param run_once: controls `wsgi.run_once`. Defaults to `False`.
:param headers: an optional list or :class:`Headers` object of headers.
:param data: a string or dict of form data. See explanation above.
:param environ_base: an optional dict of environment defaults.
:param environ_overrides: an optional dict of environment overrides.
:param charset: the charset used to encode unicode data.
"""
#: the server protocol to use. defaults to HTTP/1.1
server_protocol = 'HTTP/1.1'
#: the wsgi version to use. defaults to (1, 0)
wsgi_version = (1, 0)
#: the default request class for :meth:`get_request`
request_class = BaseRequest
def __init__(self, path='/', base_url=None, query_string=None,
method='GET', input_stream=None, content_type=None,
content_length=None, errors_stream=None, multithread=False,
multiprocess=False, run_once=False, headers=None, data=None,
environ_base=None, environ_overrides=None, charset='utf-8'):
path_s = make_literal_wrapper(path)
if query_string is None and path_s('?') in path:
path, query_string = path.split(path_s('?'), 1)
self.charset = charset
self.path = iri_to_uri(path)
if base_url is not None:
base_url = url_fix(iri_to_uri(base_url, charset), charset)
self.base_url = base_url
if isinstance(query_string, (bytes, text_type)):
self.query_string = query_string
else:
if query_string is None:
query_string = MultiDict()
elif not isinstance(query_string, MultiDict):
query_string = MultiDict(query_string)
self.args = query_string
self.method = method
if headers is None:
headers = Headers()
elif not isinstance(headers, Headers):
headers = Headers(headers)
self.headers = headers
if content_type is not None:
self.content_type = content_type
if errors_stream is None:
errors_stream = sys.stderr
self.errors_stream = errors_stream
self.multithread = multithread
self.multiprocess = multiprocess
self.run_once = run_once
self.environ_base = environ_base
self.environ_overrides = environ_overrides
self.input_stream = input_stream
self.content_length = content_length
self.closed = False
if data:
if input_stream is not None:
raise TypeError('can\'t provide input stream and data')
if isinstance(data, text_type):
data = data.encode(self.charset)
if isinstance(data, bytes):
self.input_stream = BytesIO(data)
if self.content_length is None:
self.content_length = len(data)
else:
for key, value in _iter_data(data):
if isinstance(value, (tuple, dict)) or \
hasattr(value, 'read'):
self._add_file_from_data(key, value)
else:
self.form.setlistdefault(key).append(value)
def _add_file_from_data(self, key, value):
"""Called in the EnvironBuilder to add files from the data dict."""
if isinstance(value, tuple):
self.files.add_file(key, *value)
elif isinstance(value, dict):
from warnings import warn
warn(DeprecationWarning('it\'s no longer possible to pass dicts '
'as `data`. Use tuples or FileStorage '
'objects instead'), stacklevel=2)
value = dict(value)
mimetype = value.pop('mimetype', None)
if mimetype is not None:
value['content_type'] = mimetype
self.files.add_file(key, **value)
else:
self.files.add_file(key, value)
def _get_base_url(self):
return url_unparse((self.url_scheme, self.host,
self.script_root, '', '')).rstrip('/') + '/'
def _set_base_url(self, value):
if value is None:
scheme = 'http'
netloc = 'localhost'
script_root = ''
else:
scheme, netloc, script_root, qs, anchor = url_parse(value)
if qs or anchor:
raise ValueError('base url must not contain a query string '
'or fragment')
self.script_root = script_root.rstrip('/')
self.host = netloc
self.url_scheme = scheme
base_url = property(_get_base_url, _set_base_url, doc='''
The base URL is a URL that is used to extract the WSGI
URL scheme, host (server name + server port) and the
script root (`SCRIPT_NAME`).''')
del _get_base_url, _set_base_url
def _get_content_type(self):
ct = self.headers.get('Content-Type')
if ct is None and not self._input_stream:
if self._files:
return 'multipart/form-data'
elif self._form:
return 'application/x-www-form-urlencoded'
return None
return ct
def _set_content_type(self, value):
if value is None:
self.headers.pop('Content-Type', None)
else:
self.headers['Content-Type'] = value
content_type = property(_get_content_type, _set_content_type, doc='''
The content type for the request. Reflected from and to the
:attr:`headers`. Do not set if you set :attr:`files` or
:attr:`form` for auto detection.''')
del _get_content_type, _set_content_type
def _get_content_length(self):
return self.headers.get('Content-Length', type=int)
def _set_content_length(self, value):
if value is None:
self.headers.pop('Content-Length', None)
else:
self.headers['Content-Length'] = str(value)
content_length = property(_get_content_length, _set_content_length, doc='''
The content length as integer. Reflected from and to the
:attr:`headers`. Do not set if you set :attr:`files` or
:attr:`form` for auto detection.''')
del _get_content_length, _set_content_length
def form_property(name, storage, doc):
key = '_' + name
def getter(self):
if self._input_stream is not None:
raise AttributeError('an input stream is defined')
rv = getattr(self, key)
if rv is None:
rv = storage()
setattr(self, key, rv)
return rv
def setter(self, value):
self._input_stream = None
setattr(self, key, value)
return property(getter, setter, doc)
form = form_property('form', MultiDict, doc='''
A :class:`MultiDict` of form values.''')
files = form_property('files', FileMultiDict, doc='''
A :class:`FileMultiDict` of uploaded files. You can use the
:meth:`~FileMultiDict.add_file` method to add new files to the
dict.''')
del form_property
def _get_input_stream(self):
return self._input_stream
def _set_input_stream(self, value):
self._input_stream = value
self._form = self._files = None
input_stream = property(_get_input_stream, _set_input_stream, doc='''
An optional input stream. If you set this it will clear
:attr:`form` and :attr:`files`.''')
del _get_input_stream, _set_input_stream
def _get_query_string(self):
if self._query_string is None:
if self._args is not None:
return url_encode(self._args, charset=self.charset)
return ''
return self._query_string
def _set_query_string(self, value):
self._query_string = value
self._args = None
query_string = property(_get_query_string, _set_query_string, doc='''
The query string. If you set this to a string :attr:`args` will
no longer be available.''')
del _get_query_string, _set_query_string
def _get_args(self):
if self._query_string is not None:
raise AttributeError('a query string is defined')
if self._args is None:
self._args = MultiDict()
return self._args
def _set_args(self, value):
self._query_string = None
self._args = value
args = property(_get_args, _set_args, doc='''
The URL arguments as :class:`MultiDict`.''')
del _get_args, _set_args
@property
def server_name(self):
"""The server name (read-only, use :attr:`host` to set)"""
return self.host.split(':', 1)[0]
@property
def server_port(self):
"""The server port as integer (read-only, use :attr:`host` to set)"""
pieces = self.host.split(':', 1)
if len(pieces) == 2 and pieces[1].isdigit():
return int(pieces[1])
elif self.url_scheme == 'https':
return 443
return 80
def __del__(self):
try:
self.close()
except Exception:
pass
def close(self):
"""Closes all files. If you put real :class:`file` objects into the
:attr:`files` dict you can call this method to automatically close
them all in one go.
"""
if self.closed:
return
try:
files = itervalues(self.files)
except AttributeError:
files = ()
for f in files:
try:
f.close()
except Exception:
pass
self.closed = True
def get_environ(self):
"""Return the built environ."""
input_stream = self.input_stream
content_length = self.content_length
content_type = self.content_type
if input_stream is not None:
start_pos = input_stream.tell()
input_stream.seek(0, 2)
end_pos = input_stream.tell()
input_stream.seek(start_pos)
content_length = end_pos - start_pos
elif content_type == 'multipart/form-data':
values = CombinedMultiDict([self.form, self.files])
input_stream, content_length, boundary = \
stream_encode_multipart(values, charset=self.charset)
content_type += '; boundary="%s"' % boundary
elif content_type == 'application/x-www-form-urlencoded':
#py2v3 review
values = url_encode(self.form, charset=self.charset)
values = values.encode('ascii')
content_length = len(values)
input_stream = BytesIO(values)
else:
input_stream = _empty_stream
result = {}
if self.environ_base:
result.update(self.environ_base)
def _path_encode(x):
return wsgi_encoding_dance(url_unquote(x, self.charset), self.charset)
qs = wsgi_encoding_dance(self.query_string)
result.update({
'REQUEST_METHOD': self.method,
'SCRIPT_NAME': _path_encode(self.script_root),
'PATH_INFO': _path_encode(self.path),
'QUERY_STRING': qs,
'SERVER_NAME': self.server_name,
'SERVER_PORT': str(self.server_port),
'HTTP_HOST': self.host,
'SERVER_PROTOCOL': self.server_protocol,
'CONTENT_TYPE': content_type or '',
'CONTENT_LENGTH': str(content_length or '0'),
'wsgi.version': self.wsgi_version,
'wsgi.url_scheme': self.url_scheme,
'wsgi.input': input_stream,
'wsgi.errors': self.errors_stream,
'wsgi.multithread': self.multithread,
'wsgi.multiprocess': self.multiprocess,
'wsgi.run_once': self.run_once
})
for key, value in self.headers.to_wsgi_list():
result['HTTP_%s' % key.upper().replace('-', '_')] = value
if self.environ_overrides:
result.update(self.environ_overrides)
return result
def get_request(self, cls=None):
"""Returns a request with the data. If the request class is not
specified :attr:`request_class` is used.
:param cls: The request wrapper to use.
"""
if cls is None:
cls = self.request_class
return cls(self.get_environ())
class ClientRedirectError(Exception):
"""
If a redirect loop is detected when using follow_redirects=True with
the :cls:`Client`, then this exception is raised.
"""
class Client(object):
"""This class allows to send requests to a wrapped application.
The response wrapper can be a class or factory function that takes
three arguments: app_iter, status and headers. The default response
wrapper just returns a tuple.
Example::
class ClientResponse(BaseResponse):
...
client = Client(MyApplication(), response_wrapper=ClientResponse)
The use_cookies parameter indicates whether cookies should be stored and
sent for subsequent requests. This is True by default, but passing False
will disable this behaviour.
If you want to request some subdomain of your application you may set
`allow_subdomain_redirects` to `True` as if not no external redirects
are allowed.
.. versionadded:: 0.5
`use_cookies` is new in this version. Older versions did not provide
builtin cookie support.
"""
def __init__(self, application, response_wrapper=None, use_cookies=True,
allow_subdomain_redirects=False):
self.application = application
self.response_wrapper = response_wrapper
if use_cookies:
self.cookie_jar = _TestCookieJar()
else:
self.cookie_jar = None
self.allow_subdomain_redirects = allow_subdomain_redirects
def set_cookie(self, server_name, key, value='', max_age=None,
expires=None, path='/', domain=None, secure=None,
httponly=False, charset='utf-8'):
"""Sets a cookie in the client's cookie jar. The server name
is required and has to match the one that is also passed to
the open call.
"""
assert self.cookie_jar is not None, 'cookies disabled'
header = dump_cookie(key, value, max_age, expires, path, domain,
secure, httponly, charset)
environ = create_environ(path, base_url='http://' + server_name)
headers = [('Set-Cookie', header)]
self.cookie_jar.extract_wsgi(environ, headers)
def delete_cookie(self, server_name, key, path='/', domain=None):
"""Deletes a cookie in the test client."""
self.set_cookie(server_name, key, expires=0, max_age=0,
path=path, domain=domain)
def run_wsgi_app(self, environ, buffered=False):
"""Runs the wrapped WSGI app with the given environment."""
if self.cookie_jar is not None:
self.cookie_jar.inject_wsgi(environ)
rv = run_wsgi_app(self.application, environ, buffered=buffered)
if self.cookie_jar is not None:
self.cookie_jar.extract_wsgi(environ, rv[2])
return rv
def resolve_redirect(self, response, new_location, environ, buffered=False):
"""Resolves a single redirect and triggers the request again
directly on this redirect client.
"""
scheme, netloc, script_root, qs, anchor = url_parse(new_location)
base_url = url_unparse((scheme, netloc, '', '', '')).rstrip('/') + '/'
cur_server_name = netloc.split(':', 1)[0].split('.')
real_server_name = get_host(environ).rsplit(':', 1)[0].split('.')
if self.allow_subdomain_redirects:
allowed = cur_server_name[-len(real_server_name):] == real_server_name
else:
allowed = cur_server_name == real_server_name
if not allowed:
raise RuntimeError('%r does not support redirect to '
'external targets' % self.__class__)
status_code = int(response[1].split(None, 1)[0])
if status_code == 307:
method = environ['REQUEST_METHOD']
else:
method = 'GET'
# For redirect handling we temporarily disable the response
# wrapper. This is not threadsafe but not a real concern
# since the test client must not be shared anyways.
old_response_wrapper = self.response_wrapper
self.response_wrapper = None
try:
return self.open(path=script_root, base_url=base_url,
query_string=qs, as_tuple=True,
buffered=buffered, method=method)
finally:
self.response_wrapper = old_response_wrapper
def open(self, *args, **kwargs):
"""Takes the same arguments as the :class:`EnvironBuilder` class with
some additions: You can provide a :class:`EnvironBuilder` or a WSGI
environment as only argument instead of the :class:`EnvironBuilder`
arguments and two optional keyword arguments (`as_tuple`, `buffered`)
that change the type of the return value or the way the application is
executed.
.. versionchanged:: 0.5
If a dict is provided as file in the dict for the `data` parameter
the content type has to be called `content_type` now instead of
`mimetype`. This change was made for consistency with
:class:`werkzeug.FileWrapper`.
The `follow_redirects` parameter was added to :func:`open`.
Additional parameters:
:param as_tuple: Returns a tuple in the form ``(environ, result)``
:param buffered: Set this to True to buffer the application run.
This will automatically close the application for
you as well.
:param follow_redirects: Set this to True if the `Client` should
follow HTTP redirects.
"""
as_tuple = kwargs.pop('as_tuple', False)
buffered = kwargs.pop('buffered', False)
follow_redirects = kwargs.pop('follow_redirects', False)
environ = None
if not kwargs and len(args) == 1:
if isinstance(args[0], EnvironBuilder):
environ = args[0].get_environ()
elif isinstance(args[0], dict):
environ = args[0]
if environ is None:
builder = EnvironBuilder(*args, **kwargs)
try:
environ = builder.get_environ()
finally:
builder.close()
response = self.run_wsgi_app(environ, buffered=buffered)
# handle redirects
redirect_chain = []
while 1:
status_code = int(response[1].split(None, 1)[0])
if status_code not in (301, 302, 303, 305, 307) \
or not follow_redirects:
break
new_location = response[2]['location']
method = 'GET'
if status_code == 307:
method = environ['REQUEST_METHOD']
new_redirect_entry = (new_location, status_code)
if new_redirect_entry in redirect_chain:
raise ClientRedirectError('loop detected')
redirect_chain.append(new_redirect_entry)
environ, response = self.resolve_redirect(response, new_location,
environ,
buffered=buffered)
if self.response_wrapper is not None:
response = self.response_wrapper(*response)
if as_tuple:
return environ, response
return response
def get(self, *args, **kw):
"""Like open but method is enforced to GET."""
kw['method'] = 'GET'
return self.open(*args, **kw)
def patch(self, *args, **kw):
"""Like open but method is enforced to PATCH."""
kw['method'] = 'PATCH'
return self.open(*args, **kw)
def post(self, *args, **kw):
"""Like open but method is enforced to POST."""
kw['method'] = 'POST'
return self.open(*args, **kw)
def head(self, *args, **kw):
"""Like open but method is enforced to HEAD."""
kw['method'] = 'HEAD'
return self.open(*args, **kw)
def put(self, *args, **kw):
"""Like open but method is enforced to PUT."""
kw['method'] = 'PUT'
return self.open(*args, **kw)
def delete(self, *args, **kw):
"""Like open but method is enforced to DELETE."""
kw['method'] = 'DELETE'
return self.open(*args, **kw)
def options(self, *args, **kw):
"""Like open but method is enforced to OPTIONS."""
kw['method'] = 'OPTIONS'
return self.open(*args, **kw)
def trace(self, *args, **kw):
"""Like open but method is enforced to TRACE."""
kw['method'] = 'TRACE'
return self.open(*args, **kw)
def __repr__(self):
return '<%s %r>' % (
self.__class__.__name__,
self.application
)
def create_environ(*args, **kwargs):
"""Create a new WSGI environ dict based on the values passed. The first
parameter should be the path of the request which defaults to '/'. The
second one can either be an absolute path (in that case the host is
localhost:80) or a full path to the request with scheme, netloc port and
the path to the script.
This accepts the same arguments as the :class:`EnvironBuilder`
constructor.
.. versionchanged:: 0.5
This function is now a thin wrapper over :class:`EnvironBuilder` which
was added in 0.5. The `headers`, `environ_base`, `environ_overrides`
and `charset` parameters were added.
"""
builder = EnvironBuilder(*args, **kwargs)
try:
return builder.get_environ()
finally:
builder.close()
def run_wsgi_app(app, environ, buffered=False):
"""Return a tuple in the form (app_iter, status, headers) of the
application output. This works best if you pass it an application that
returns an iterator all the time.
Sometimes applications may use the `write()` callable returned
by the `start_response` function. This tries to resolve such edge
cases automatically. But if you don't get the expected output you
should set `buffered` to `True` which enforces buffering.
If passed an invalid WSGI application the behavior of this function is
undefined. Never pass non-conforming WSGI applications to this function.
:param app: the application to execute.
:param buffered: set to `True` to enforce buffering.
:return: tuple in the form ``(app_iter, status, headers)``
"""
environ = _get_environ(environ)
response = []
buffer = []
def start_response(status, headers, exc_info=None):
if exc_info is not None:
reraise(*exc_info)
response[:] = [status, headers]
return buffer.append
app_iter = app(environ, start_response)
# when buffering we emit the close call early and convert the
# application iterator into a regular list
if buffered:
close_func = getattr(app_iter, 'close', None)
try:
app_iter = list(app_iter)
finally:
if close_func is not None:
close_func()
# otherwise we iterate the application iter until we have
# a response, chain the already received data with the already
# collected data and wrap it in a new `ClosingIterator` if
# we have a close callable.
else:
while not response:
buffer.append(next(app_iter))
if buffer:
close_func = getattr(app_iter, 'close', None)
app_iter = chain(buffer, app_iter)
if close_func is not None:
app_iter = ClosingIterator(app_iter, close_func)
return app_iter, response[0], Headers(response[1])
| gpl-2.0 |
ppmt/Crust | flask/lib/python2.7/site-packages/setuptools/depends.py | 462 | 6370 | import sys
import imp
import marshal
from imp import PKG_DIRECTORY, PY_COMPILED, PY_SOURCE, PY_FROZEN
from distutils.version import StrictVersion
from setuptools import compat
__all__ = [
'Require', 'find_module', 'get_module_constant', 'extract_constant'
]
class Require:
"""A prerequisite to building or installing a distribution"""
def __init__(self, name, requested_version, module, homepage='',
attribute=None, format=None):
if format is None and requested_version is not None:
format = StrictVersion
if format is not None:
requested_version = format(requested_version)
if attribute is None:
attribute = '__version__'
self.__dict__.update(locals())
del self.self
def full_name(self):
"""Return full package/distribution name, w/version"""
if self.requested_version is not None:
return '%s-%s' % (self.name,self.requested_version)
return self.name
def version_ok(self, version):
"""Is 'version' sufficiently up-to-date?"""
return self.attribute is None or self.format is None or \
str(version) != "unknown" and version >= self.requested_version
def get_version(self, paths=None, default="unknown"):
"""Get version number of installed module, 'None', or 'default'
Search 'paths' for module. If not found, return 'None'. If found,
return the extracted version attribute, or 'default' if no version
attribute was specified, or the value cannot be determined without
importing the module. The version is formatted according to the
requirement's version format (if any), unless it is 'None' or the
supplied 'default'.
"""
if self.attribute is None:
try:
f,p,i = find_module(self.module,paths)
if f: f.close()
return default
except ImportError:
return None
v = get_module_constant(self.module, self.attribute, default, paths)
if v is not None and v is not default and self.format is not None:
return self.format(v)
return v
def is_present(self, paths=None):
"""Return true if dependency is present on 'paths'"""
return self.get_version(paths) is not None
def is_current(self, paths=None):
"""Return true if dependency is present and up-to-date on 'paths'"""
version = self.get_version(paths)
if version is None:
return False
return self.version_ok(version)
def _iter_code(code):
"""Yield '(op,arg)' pair for each operation in code object 'code'"""
from array import array
from dis import HAVE_ARGUMENT, EXTENDED_ARG
bytes = array('b',code.co_code)
eof = len(code.co_code)
ptr = 0
extended_arg = 0
while ptr<eof:
op = bytes[ptr]
if op>=HAVE_ARGUMENT:
arg = bytes[ptr+1] + bytes[ptr+2]*256 + extended_arg
ptr += 3
if op==EXTENDED_ARG:
extended_arg = arg * compat.long_type(65536)
continue
else:
arg = None
ptr += 1
yield op,arg
def find_module(module, paths=None):
"""Just like 'imp.find_module()', but with package support"""
parts = module.split('.')
while parts:
part = parts.pop(0)
f, path, (suffix,mode,kind) = info = imp.find_module(part, paths)
if kind==PKG_DIRECTORY:
parts = parts or ['__init__']
paths = [path]
elif parts:
raise ImportError("Can't find %r in %s" % (parts,module))
return info
def get_module_constant(module, symbol, default=-1, paths=None):
"""Find 'module' by searching 'paths', and extract 'symbol'
Return 'None' if 'module' does not exist on 'paths', or it does not define
'symbol'. If the module defines 'symbol' as a constant, return the
constant. Otherwise, return 'default'."""
try:
f, path, (suffix, mode, kind) = find_module(module, paths)
except ImportError:
# Module doesn't exist
return None
try:
if kind==PY_COMPILED:
f.read(8) # skip magic & date
code = marshal.load(f)
elif kind==PY_FROZEN:
code = imp.get_frozen_object(module)
elif kind==PY_SOURCE:
code = compile(f.read(), path, 'exec')
else:
# Not something we can parse; we'll have to import it. :(
if module not in sys.modules:
imp.load_module(module, f, path, (suffix, mode, kind))
return getattr(sys.modules[module], symbol, None)
finally:
if f:
f.close()
return extract_constant(code, symbol, default)
def extract_constant(code, symbol, default=-1):
"""Extract the constant value of 'symbol' from 'code'
If the name 'symbol' is bound to a constant value by the Python code
object 'code', return that value. If 'symbol' is bound to an expression,
return 'default'. Otherwise, return 'None'.
Return value is based on the first assignment to 'symbol'. 'symbol' must
be a global, or at least a non-"fast" local in the code block. That is,
only 'STORE_NAME' and 'STORE_GLOBAL' opcodes are checked, and 'symbol'
must be present in 'code.co_names'.
"""
if symbol not in code.co_names:
# name's not there, can't possibly be an assigment
return None
name_idx = list(code.co_names).index(symbol)
STORE_NAME = 90
STORE_GLOBAL = 97
LOAD_CONST = 100
const = default
for op, arg in _iter_code(code):
if op==LOAD_CONST:
const = code.co_consts[arg]
elif arg==name_idx and (op==STORE_NAME or op==STORE_GLOBAL):
return const
else:
const = default
def _update_globals():
"""
Patch the globals to remove the objects not available on some platforms.
XXX it'd be better to test assertions about bytecode instead.
"""
if not sys.platform.startswith('java') and sys.platform != 'cli':
return
incompatible = 'extract_constant', 'get_module_constant'
for name in incompatible:
del globals()[name]
__all__.remove(name)
_update_globals()
| gpl-2.0 |
kennydude/django-rest-framework | tests/test_htmlrenderer.py | 79 | 4406 | from __future__ import unicode_literals
import django.template.loader
from django.conf.urls import url
from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.template import Template, TemplateDoesNotExist
from django.test import TestCase
from django.utils import six
from rest_framework import status
from rest_framework.decorators import api_view, renderer_classes
from rest_framework.renderers import TemplateHTMLRenderer
from rest_framework.response import Response
@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer,))
def example(request):
"""
A view that can returns an HTML representation.
"""
data = {'object': 'foobar'}
return Response(data, template_name='example.html')
@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer,))
def permission_denied(request):
raise PermissionDenied()
@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer,))
def not_found(request):
raise Http404()
urlpatterns = [
url(r'^$', example),
url(r'^permission_denied$', permission_denied),
url(r'^not_found$', not_found),
]
class TemplateHTMLRendererTests(TestCase):
urls = 'tests.test_htmlrenderer'
def setUp(self):
"""
Monkeypatch get_template
"""
self.get_template = django.template.loader.get_template
def get_template(template_name, dirs=None):
if template_name == 'example.html':
return Template("example: {{ object }}")
raise TemplateDoesNotExist(template_name)
def select_template(template_name_list, dirs=None, using=None):
if template_name_list == ['example.html']:
return Template("example: {{ object }}")
raise TemplateDoesNotExist(template_name_list[0])
django.template.loader.get_template = get_template
django.template.loader.select_template = select_template
def tearDown(self):
"""
Revert monkeypatching
"""
django.template.loader.get_template = self.get_template
def test_simple_html_view(self):
response = self.client.get('/')
self.assertContains(response, "example: foobar")
self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8')
def test_not_found_html_view(self):
response = self.client.get('/not_found')
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
self.assertEqual(response.content, six.b("404 Not Found"))
self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8')
def test_permission_denied_html_view(self):
response = self.client.get('/permission_denied')
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertEqual(response.content, six.b("403 Forbidden"))
self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8')
class TemplateHTMLRendererExceptionTests(TestCase):
urls = 'tests.test_htmlrenderer'
def setUp(self):
"""
Monkeypatch get_template
"""
self.get_template = django.template.loader.get_template
def get_template(template_name):
if template_name == '404.html':
return Template("404: {{ detail }}")
if template_name == '403.html':
return Template("403: {{ detail }}")
raise TemplateDoesNotExist(template_name)
django.template.loader.get_template = get_template
def tearDown(self):
"""
Revert monkeypatching
"""
django.template.loader.get_template = self.get_template
def test_not_found_html_view_with_template(self):
response = self.client.get('/not_found')
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
self.assertTrue(response.content in (
six.b("404: Not found"), six.b("404 Not Found")))
self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8')
def test_permission_denied_html_view_with_template(self):
response = self.client.get('/permission_denied')
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertTrue(response.content in (
six.b("403: Permission denied"), six.b("403 Forbidden")))
self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8')
| bsd-2-clause |
codeforamerica/comport | migrations/versions/0d78d545906f_.py | 1 | 1135 | """Add 'is_public' flags for datasets
Revision ID: 0d78d545906f
Revises: 6d30846080b2
Create Date: 2016-06-27 15:30:14.415519
"""
# revision identifiers, used by Alembic.
revision = '0d78d545906f'
down_revision = '6d30846080b2'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('departments', sa.Column('is_public_assaults_on_officers', sa.Boolean(), server_default=sa.true(), nullable=False))
op.add_column('departments', sa.Column('is_public_citizen_complaints', sa.Boolean(), server_default=sa.true(), nullable=False))
op.add_column('departments', sa.Column('is_public_officer_involved_shootings', sa.Boolean(), server_default=sa.true(), nullable=False))
op.add_column('departments', sa.Column('is_public_use_of_force_incidents', sa.Boolean(), server_default=sa.true(), nullable=False))
def downgrade():
op.drop_column('departments', 'is_public_use_of_force_incidents')
op.drop_column('departments', 'is_public_officer_involved_shootings')
op.drop_column('departments', 'is_public_citizen_complaints')
op.drop_column('departments', 'is_public_assaults_on_officers')
| bsd-3-clause |
alihalabyah/flexx | exp/wgui.py | 22 | 5614 | # -*- coding: utf-8 -*-
# Copyright (c) 2014, Almar Klein
"""
Little experiment for the purpose for creating a GUI toolkit based on
web technologies like HTML/CSS/JS.
Applications build with such a GUI can be easily deployed on all
platforms and also run in a web browser...
Usefull links:
* http://www.aclevername.com/articles/python-webgui/
"""
import time
#from zoof.qt import QtCore, QtGui, QtWebKit
from PyQt4 import QtCore, QtGui, QtWebKit
HTML = """<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<head>
<title></title>
<link href="demo.css" rel="stylesheet" type="text/css"></link>
<!-- <script src="jquery-1.11.1.min.js"></script> -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
// <![CDATA[
function send(msg) {
// we communicate to Python by modifying the title
document.title = "null";
document.title = msg;
}
function got_a_click(e) {
send('got-a-click:' + e.target.id);
}
function got_a_move(e) {
if (e.clientX & e.clientY) {
//send('got-a-move:' + e.target.id);
send('got-a-move:' + e.target.id + '-' + e.clientX + ',' + e.clientY);
}
}
$(document).ready(function() {
$('#messages').click(got_a_click);
//send($.toJSON('document.ready'));
send('document.ready');
})
// ]]>
</script>
</head>
<body>
<h1>Python + Web GUI Demo</h1>
<h2>Uptime</h2>
<p class="uptime">
Python uptime:
<span id="uptime-value">?</span> seconds.
</p>
<h2>Messages</h2>
<p id="messages">
Click here (yes, anywhere here)...<br/>
</p>
</body>
</html>
"""
class Page(QtWebKit.QWebPage):
""" Subclass Pagse to catch JS errors and prompts.
"""
def javaScriptConsoleMessage(self, msg, linenr, sourceID):
print('ERROR: on line %i in %r: %s' % (linenr, sourceID, msg))
def javaScriptAlert(self, frame, msg):
print('ALERT:', msg)
def javaScriptConfirm(self, frame, msg):
while True:
a = input('Need confirm from JS: msg [Y/n] ')
if not a or a.lower() == 'y':
return True
elif a.lower() == 'n':
return False
def javaScriptPrompt(self, frame, *args):
pass # todo
class Main(QtWebKit.QWebView):
""" Our main application window.
"""
def __init__(self):
super().__init__(None)
self.setPage(Page(self))
self.page().mainFrame().setHtml(HTML)
self.titleChanged.connect(self.on_title_changed)
self._timer = QtCore.QTimer()
self._timer.setSingleShot(False)
self._timer.timeout.connect(self.on_timer)
self._timer.start(207)
self._t0 = time.time()
def on_error(self, msg):
print('ERROR:', msg)
def on_timer(self):
t = time.time() - self._t0
msg = 'document.getElementById("uptime-value").innerHTML = %1.01f' % t
self.web_send(msg)
def web_send(self, msg):
f = self.page().mainFrame()
f.evaluateJavaScript(msg)
def on_title_changed(self, title):
if title == 'null':
return
print('MSG:', title)
if title.startswith("got-a-move:test-widget"):
xy = title.split('-')[-1]
x, y = [int(i)-20 for i in xy.split(',')]
msg = 'document.getElementById("test-widget").style.left = "%ipx";' % x
msg += 'document.getElementById("test-widget").style.top = "%ipx";' % y
self.web_send(msg)
print(title)
if title == "got-a-click:messages":
#self.web_send("confirm('Please confitm');")
#self.web_send("alert('wooot');")
self.web_send("""
$(document.body).append("<div id='test-widget' class='draggable'>This is a paragraph</div>");
$("#test-widget").css({ "width": "100px",
"height": "35px",
"position":"absolute",
"top":"100px",
"left":"100px",
"background": "red",
"overflow":"hidden",
"user-select": "none",
"handle": "",
"cursor": "move",
});
// Implement some dragging (sort of)
$("#test-widget")._down = false;
$("#test-widget").mousedown(function(e){this._down=true});
$("#test-widget").mouseup(function(e){this._down=false});
$("#test-widget").mouseleave(function(e){this._down=false});
$("#test-widget").mousemove(function(e){if (this._down) {got_a_move(e);}});
""")
if __name__ == '__main__':
app = QtGui.QApplication([])
m = Main()
m.show()
app.exec_()
| bsd-2-clause |
thomaskeck/root | interpreter/llvm/src/examples/Kaleidoscope/MCJIT/cached/genk-timing.py | 214 | 10499 | #!/usr/bin/env python
import sys
import random
class TimingScriptGenerator:
"""Used to generate a bash script which will invoke the toy and time it"""
def __init__(self, scriptname, outputname):
self.timeFile = outputname
self.shfile = open(scriptname, 'w')
self.shfile.write("echo \"\" > %s\n" % self.timeFile)
def writeTimingCall(self, filename, numFuncs, funcsCalled, totalCalls):
"""Echo some comments and invoke both versions of toy"""
rootname = filename
if '.' in filename:
rootname = filename[:filename.rfind('.')]
self.shfile.write("echo \"%s: Calls %d of %d functions, %d total\" >> %s\n" % (filename, funcsCalled, numFuncs, totalCalls, self.timeFile))
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
self.shfile.write("echo \"With MCJIT\" >> %s\n" % self.timeFile)
self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"")
self.shfile.write(" -o %s -a " % self.timeFile)
self.shfile.write("./toy-mcjit < %s > %s-mcjit.out 2> %s-mcjit.err\n" % (filename, rootname, rootname))
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
self.shfile.write("echo \"With JIT\" >> %s\n" % self.timeFile)
self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"")
self.shfile.write(" -o %s -a " % self.timeFile)
self.shfile.write("./toy-jit < %s > %s-jit.out 2> %s-jit.err\n" % (filename, rootname, rootname))
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
class KScriptGenerator:
"""Used to generate random Kaleidoscope code"""
def __init__(self, filename):
self.kfile = open(filename, 'w')
self.nextFuncNum = 1
self.lastFuncNum = None
self.callWeighting = 0.1
# A mapping of calls within functions with no duplicates
self.calledFunctionTable = {}
# A list of function calls which will actually be executed
self.calledFunctions = []
# A comprehensive mapping of calls within functions
# used for computing the total number of calls
self.comprehensiveCalledFunctionTable = {}
self.totalCallsExecuted = 0
def updateTotalCallCount(self, callee):
# Count this call
self.totalCallsExecuted += 1
# Then count all the functions it calls
if callee in self.comprehensiveCalledFunctionTable:
for child in self.comprehensiveCalledFunctionTable[callee]:
self.updateTotalCallCount(child)
def updateFunctionCallMap(self, caller, callee):
"""Maintains a map of functions that are called from other functions"""
if not caller in self.calledFunctionTable:
self.calledFunctionTable[caller] = []
if not callee in self.calledFunctionTable[caller]:
self.calledFunctionTable[caller].append(callee)
if not caller in self.comprehensiveCalledFunctionTable:
self.comprehensiveCalledFunctionTable[caller] = []
self.comprehensiveCalledFunctionTable[caller].append(callee)
def updateCalledFunctionList(self, callee):
"""Maintains a list of functions that will actually be called"""
# Update the total call count
self.updateTotalCallCount(callee)
# If this function is already in the list, don't do anything else
if callee in self.calledFunctions:
return
# Add this function to the list of those that will be called.
self.calledFunctions.append(callee)
# If this function calls other functions, add them too
if callee in self.calledFunctionTable:
for subCallee in self.calledFunctionTable[callee]:
self.updateCalledFunctionList(subCallee)
def setCallWeighting(self, weight):
""" Sets the probably of generating a function call"""
self.callWeighting = weight
def writeln(self, line):
self.kfile.write(line + '\n')
def writeComment(self, comment):
self.writeln('# ' + comment)
def writeEmptyLine(self):
self.writeln("")
def writePredefinedFunctions(self):
self.writeComment("Define ':' for sequencing: as a low-precedence operator that ignores operands")
self.writeComment("and just returns the RHS.")
self.writeln("def binary : 1 (x y) y;")
self.writeEmptyLine()
self.writeComment("Helper functions defined within toy")
self.writeln("extern putchard(x);")
self.writeln("extern printd(d);")
self.writeln("extern printlf();")
self.writeEmptyLine()
self.writeComment("Print the result of a function call")
self.writeln("def printresult(N Result)")
self.writeln(" # 'result('")
self.writeln(" putchard(114) : putchard(101) : putchard(115) : putchard(117) : putchard(108) : putchard(116) : putchard(40) :")
self.writeln(" printd(N) :");
self.writeln(" # ') = '")
self.writeln(" putchard(41) : putchard(32) : putchard(61) : putchard(32) :")
self.writeln(" printd(Result) :");
self.writeln(" printlf();")
self.writeEmptyLine()
def writeRandomOperation(self, LValue, LHS, RHS):
shouldCallFunc = (self.lastFuncNum > 2 and random.random() < self.callWeighting)
if shouldCallFunc:
funcToCall = random.randrange(1, self.lastFuncNum - 1)
self.updateFunctionCallMap(self.lastFuncNum, funcToCall)
self.writeln(" %s = func%d(%s, %s) :" % (LValue, funcToCall, LHS, RHS))
else:
possibleOperations = ["+", "-", "*", "/"]
operation = random.choice(possibleOperations)
if operation == "-":
# Don't let our intermediate value become zero
# This is complicated by the fact that '<' is our only comparison operator
self.writeln(" if %s < %s then" % (LHS, RHS))
self.writeln(" %s = %s %s %s" % (LValue, LHS, operation, RHS))
self.writeln(" else if %s < %s then" % (RHS, LHS))
self.writeln(" %s = %s %s %s" % (LValue, LHS, operation, RHS))
self.writeln(" else")
self.writeln(" %s = %s %s %f :" % (LValue, LHS, operation, random.uniform(1, 100)))
else:
self.writeln(" %s = %s %s %s :" % (LValue, LHS, operation, RHS))
def getNextFuncNum(self):
result = self.nextFuncNum
self.nextFuncNum += 1
self.lastFuncNum = result
return result
def writeFunction(self, elements):
funcNum = self.getNextFuncNum()
self.writeComment("Auto-generated function number %d" % funcNum)
self.writeln("def func%d(X Y)" % funcNum)
self.writeln(" var temp1 = X,")
self.writeln(" temp2 = Y,")
self.writeln(" temp3 in")
# Initialize the variable names to be rotated
first = "temp3"
second = "temp1"
third = "temp2"
# Write some random operations
for i in range(elements):
self.writeRandomOperation(first, second, third)
# Rotate the variables
temp = first
first = second
second = third
third = temp
self.writeln(" " + third + ";")
self.writeEmptyLine()
def writeFunctionCall(self):
self.writeComment("Call the last function")
arg1 = random.uniform(1, 100)
arg2 = random.uniform(1, 100)
self.writeln("printresult(%d, func%d(%f, %f) )" % (self.lastFuncNum, self.lastFuncNum, arg1, arg2))
self.writeEmptyLine()
self.updateCalledFunctionList(self.lastFuncNum)
def writeFinalFunctionCounts(self):
self.writeComment("Called %d of %d functions" % (len(self.calledFunctions), self.lastFuncNum))
def generateKScript(filename, numFuncs, elementsPerFunc, funcsBetweenExec, callWeighting, timingScript):
""" Generate a random Kaleidoscope script based on the given parameters """
print "Generating " + filename
print(" %d functions, %d elements per function, %d functions between execution" %
(numFuncs, elementsPerFunc, funcsBetweenExec))
print(" Call weighting = %f" % callWeighting)
script = KScriptGenerator(filename)
script.setCallWeighting(callWeighting)
script.writeComment("===========================================================================")
script.writeComment("Auto-generated script")
script.writeComment(" %d functions, %d elements per function, %d functions between execution"
% (numFuncs, elementsPerFunc, funcsBetweenExec))
script.writeComment(" call weighting = %f" % callWeighting)
script.writeComment("===========================================================================")
script.writeEmptyLine()
script.writePredefinedFunctions()
funcsSinceLastExec = 0
for i in range(numFuncs):
script.writeFunction(elementsPerFunc)
funcsSinceLastExec += 1
if funcsSinceLastExec == funcsBetweenExec:
script.writeFunctionCall()
funcsSinceLastExec = 0
# Always end with a function call
if funcsSinceLastExec > 0:
script.writeFunctionCall()
script.writeEmptyLine()
script.writeFinalFunctionCounts()
funcsCalled = len(script.calledFunctions)
print " Called %d of %d functions, %d total" % (funcsCalled, numFuncs, script.totalCallsExecuted)
timingScript.writeTimingCall(filename, numFuncs, funcsCalled, script.totalCallsExecuted)
# Execution begins here
random.seed()
timingScript = TimingScriptGenerator("time-toy.sh", "timing-data.txt")
dataSets = [(5000, 3, 50, 0.50), (5000, 10, 100, 0.10), (5000, 10, 5, 0.10), (5000, 10, 1, 0.0),
(1000, 3, 10, 0.50), (1000, 10, 100, 0.10), (1000, 10, 5, 0.10), (1000, 10, 1, 0.0),
( 200, 3, 2, 0.50), ( 200, 10, 40, 0.10), ( 200, 10, 2, 0.10), ( 200, 10, 1, 0.0)]
# Generate the code
for (numFuncs, elementsPerFunc, funcsBetweenExec, callWeighting) in dataSets:
filename = "test-%d-%d-%d-%d.k" % (numFuncs, elementsPerFunc, funcsBetweenExec, int(callWeighting * 100))
generateKScript(filename, numFuncs, elementsPerFunc, funcsBetweenExec, callWeighting, timingScript)
print "All done!"
| lgpl-2.1 |
forseti-security/forseti-security | google/cloud/forseti/common/gcp_api/admin_directory.py | 1 | 10459 | # Copyright 2017 The Forseti Security 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.
"""Wrapper for Admin Directory API client."""
from builtins import object
from googleapiclient import errors
from httplib2 import HttpLib2Error
from google.auth.exceptions import RefreshError
from google.cloud.forseti.common.gcp_api import _base_repository
from google.cloud.forseti.common.gcp_api import api_helpers
from google.cloud.forseti.common.gcp_api import errors as api_errors
from google.cloud.forseti.common.gcp_api import repository_mixins
from google.cloud.forseti.common.util import logger
LOGGER = logger.get_logger(__name__)
API_NAME = 'admin'
REQUIRED_SCOPES = frozenset([
'https://www.googleapis.com/auth/admin.directory.group.readonly',
'https://www.googleapis.com/auth/admin.directory.user.readonly'
])
GSUITE_AUTH_FAILURE_MESSAGE = (
'Failed to retrieve G Suite data due to authentication '
'failure. Please make sure your forseti_server_config.yaml '
'file contains the most updated information and enable G '
'Suite Groups Collection if you haven\'t done so. Instructions'
' on how to enable: https://forsetisecurity.org/docs/latest/'
'configure/inventory/gsuite.html')
class AdminDirectoryRepositoryClient(_base_repository.BaseRepositoryClient):
"""Admin Directory API Respository Client."""
def __init__(self,
credentials,
quota_max_calls=None,
quota_period=1.0,
use_rate_limiter=True,
cache_discovery=False,
cache=None):
"""Constructor.
Args:
credentials (object): An google.auth credentials object. The admin
directory API needs a service account credential with delegated
super admin role.
quota_max_calls (int): Allowed requests per <quota_period> for the
API.
quota_period (float): The time period to track requests over.
use_rate_limiter (bool): Set to false to disable the use of a rate
limiter for this service.
cache_discovery (bool): When set to true, googleapiclient will cache
HTTP requests to API discovery endpoints.
cache (googleapiclient.discovery_cache.base.Cache): instance of a
class that can cache API discovery documents. If None,
googleapiclient will attempt to choose a default.
"""
if not quota_max_calls:
use_rate_limiter = False
self._groups = None
self._members = None
self._users = None
super(AdminDirectoryRepositoryClient, self).__init__(
API_NAME, versions=['directory_v1'],
credentials=credentials,
quota_max_calls=quota_max_calls,
quota_period=quota_period,
use_rate_limiter=use_rate_limiter,
cache_discovery=cache_discovery,
cache=cache)
# Turn off docstrings for properties.
# pylint: disable=missing-return-doc, missing-return-type-doc
@property
def groups(self):
"""Returns an _AdminDirectoryGroupsRepository instance."""
if not self._groups:
self._groups = self._init_repository(
_AdminDirectoryGroupsRepository)
return self._groups
@property
def members(self):
"""Returns an _AdminDirectoryMembersRepository instance."""
if not self._members:
self._members = self._init_repository(
_AdminDirectoryMembersRepository)
return self._members
@property
def users(self):
"""Returns an _AdminDirectoryUsersRepository instance."""
if not self._users:
self._users = self._init_repository(
_AdminDirectoryUsersRepository)
return self._users
# pylint: enable=missing-return-doc, missing-return-type-doc
class _AdminDirectoryGroupsRepository(
repository_mixins.ListQueryMixin,
_base_repository.GCPRepository):
"""Implementation of Admin Directory Groups repository."""
def __init__(self, **kwargs):
"""Constructor.
Args:
**kwargs (dict): The args to pass into GCPRepository.__init__()
"""
super(_AdminDirectoryGroupsRepository, self).__init__(
key_field='', component='groups', **kwargs)
class _AdminDirectoryMembersRepository(
repository_mixins.ListQueryMixin,
_base_repository.GCPRepository):
"""Implementation of Admin Directory Members repository."""
def __init__(self, **kwargs):
"""Constructor.
Args:
**kwargs (dict): The args to pass into GCPRepository.__init__()
"""
super(_AdminDirectoryMembersRepository, self).__init__(
key_field='groupKey', component='members', **kwargs)
class _AdminDirectoryUsersRepository(
repository_mixins.ListQueryMixin,
_base_repository.GCPRepository):
"""Implementation of Admin Directory Users repository."""
def __init__(self, **kwargs):
"""Constructor.
Args:
**kwargs (dict): The args to pass into GCPRepository.__init__()
"""
super(_AdminDirectoryUsersRepository, self).__init__(
key_field='', component='users', **kwargs)
class AdminDirectoryClient(object):
"""GSuite Admin Directory API Client."""
def __init__(self, global_configs, **kwargs):
"""Initialize.
Args:
global_configs (dict): Global configurations.
**kwargs (dict): The kwargs.
"""
credentials = api_helpers.get_delegated_credential(
global_configs.get('domain_super_admin_email'),
REQUIRED_SCOPES)
max_calls, quota_period = api_helpers.get_ratelimiter_config(
global_configs, API_NAME)
cache_discovery = global_configs[
'cache_discovery'] if 'cache_discovery' in global_configs else False
self.repository = AdminDirectoryRepositoryClient(
credentials=credentials,
quota_max_calls=max_calls,
quota_period=quota_period,
use_rate_limiter=kwargs.get('use_rate_limiter', True),
cache_discovery=cache_discovery,
cache=global_configs.get('cache'))
def get_group_members(self, group_key):
"""Get all the members for specified groups.
Args:
group_key (str): The group's unique id assigned by the Admin API.
Returns:
list: A list of member objects from the API.
Raises:
api_errors.ApiExecutionError: If group member retrieval fails.
"""
try:
paged_results = self.repository.members.list(group_key)
result = api_helpers.flatten_list_results(paged_results, 'members')
LOGGER.debug('Getting all the members for group_key = %s,'
' result = %s', group_key, result)
return result
except (errors.HttpError, HttpLib2Error) as e:
raise api_errors.ApiExecutionError(group_key, e)
def get_groups(self, customer_id='my_customer'):
"""Get all the groups for a given customer_id.
A note on customer_id='my_customer'. This is a magic string instead
of using the real customer id. See:
https://developers.google.com/admin-sdk/directory/v1/guides/manage-groups#get_all_domain_groups
Args:
customer_id (str): The customer id to scope the request to.
Returns:
list: A list of group objects returned from the API.
Raises:
api_errors.ApiExecutionError: If groups retrieval fails.
RefreshError: If the authentication fails.
"""
try:
paged_results = self.repository.groups.list(customer=customer_id)
flattened_results = api_helpers.flatten_list_results(
paged_results, 'groups')
LOGGER.debug('Getting all the groups for customer_id = %s,'
' flattened_results = %s',
customer_id, flattened_results)
return flattened_results
except RefreshError as e:
# Authentication failed, log before raise.
LOGGER.exception(GSUITE_AUTH_FAILURE_MESSAGE)
raise e
except (errors.HttpError, HttpLib2Error) as e:
raise api_errors.ApiExecutionError('groups', e)
def get_users(self, customer_id='my_customer'):
"""Get all the users for a given customer_id.
A note on customer_id='my_customer'. This is a magic string instead
of using the real customer id. See:
https://developers.google.com/admin-sdk/directory/v1/guides/manage-groups#get_all_domain_groups
Args:
customer_id (str): The customer id to scope the request to.
Returns:
list: A list of user objects returned from the API.
Raises:
api_errors.ApiExecutionError: If groups retrieval fails.
RefreshError: If the authentication fails.
"""
try:
paged_results = self.repository.users.list(customer=customer_id,
viewType='admin_view')
flattened_results = api_helpers.flatten_list_results(
paged_results, 'users')
LOGGER.debug('Getting all the users for customer_id = %s,'
' flattened_results = %s',
customer_id, flattened_results)
return flattened_results
except RefreshError as e:
# Authentication failed, log before raise.
LOGGER.exception(GSUITE_AUTH_FAILURE_MESSAGE)
raise e
except (errors.HttpError, HttpLib2Error) as e:
raise api_errors.ApiExecutionError('users', e)
| apache-2.0 |
kwlzn/pants | src/python/pants/base/payload_field.py | 8 | 4251 | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import json
from abc import abstractmethod
from hashlib import sha1
from twitter.common.collections import OrderedSet
from pants.util.meta import AbstractClass
def stable_json_dumps(obj):
return json.dumps(obj, ensure_ascii=True, allow_nan=False, sort_keys=True)
def stable_json_sha1(obj):
"""
:API: public
"""
return sha1(stable_json_dumps(obj)).hexdigest()
def combine_hashes(hashes):
"""A simple helper function to combine other hashes. Sorts the hashes before rolling them in."""
hasher = sha1()
for h in sorted(hashes):
hasher.update(h)
return hasher.hexdigest()
class PayloadField(AbstractClass):
"""An immutable, hashable structure to be mixed into Payload instances.
:API: public
"""
_fingerprint_memo = None
def fingerprint(self):
"""A memoized sha1 hexdigest hashing the contents of this PayloadField
The fingerprint returns either a bytestring or None. If the return is None, consumers of the
fingerprint may choose to elide this PayloadField from their combined hash computation.
:API: public
"""
if self._fingerprint_memo is None:
self._fingerprint_memo = self._compute_fingerprint()
return self._fingerprint_memo
def mark_dirty(self):
"""Invalidates the memoized fingerprint for this field.
Exposed for testing.
:API: public
"""
self._fingerprint_memo = None
@abstractmethod
def _compute_fingerprint(self):
"""This method will be called and the result memoized for ``PayloadField.fingerprint``."""
pass
@property
def value(self):
"""
:API: public
"""
return self
class FingerprintedMixin(object):
"""Mixin this class to make your class suitable for passing to FingerprintedField.
:API: public
"""
def fingerprint(self):
"""Override this method to implement a fingerprint for your class.
:API: public
:returns: a sha1 hexdigest hashing the contents of this structure."""
raise NotImplementedError()
class FingerprintedField(PayloadField):
"""Use this field to fingerprint any class that mixes in FingerprintedMixin.
The caller must ensure that the class properly implements fingerprint()
to hash the contents of the object.
:API: public
"""
def __init__(self, value):
self._value = value
def _compute_fingerprint(self):
return self._value.fingerprint()
@property
def value(self):
return self._value
class PythonRequirementsField(frozenset, PayloadField):
"""A frozenset subclass that mixes in PayloadField.
Must be initialized with an iterable of PythonRequirement instances.
:API: public
"""
def _compute_fingerprint(self):
def fingerprint_iter():
for req in self:
hash_items = (
repr(req._requirement),
req._repository,
req._name,
req._use_2to3,
req.compatibility,
)
yield stable_json_sha1(hash_items)
return combine_hashes(fingerprint_iter())
class ExcludesField(OrderedSet, PayloadField):
"""An OrderedSet subclass that mixes in PayloadField.
Must be initialized with an iterable of Excludes instances.
:API: public
"""
def _compute_fingerprint(self):
return stable_json_sha1(tuple(repr(exclude) for exclude in self))
class JarsField(tuple, PayloadField):
"""A tuple subclass that mixes in PayloadField.
Must be initialized with an iterable of JarDependency instances.
:API: public
"""
def _compute_fingerprint(self):
return stable_json_sha1(tuple(jar.cache_key() for jar in self))
class PrimitiveField(PayloadField):
"""A general field for primitive types.
As long as the contents are JSON representable, their hash can be stably inferred.
:API: public
"""
def __init__(self, underlying=None):
self._underlying = underlying
@property
def value(self):
return self._underlying
def _compute_fingerprint(self):
return stable_json_sha1(self._underlying)
| apache-2.0 |
shaistaansari/django | django/views/i18n.py | 82 | 11102 | import gettext as gettext_module
import importlib
import json
import os
from django import http
from django.apps import apps
from django.conf import settings
from django.core.urlresolvers import translate_url
from django.template import Context, Engine
from django.utils import six
from django.utils._os import upath
from django.utils.encoding import smart_text
from django.utils.formats import get_format, get_format_modules
from django.utils.http import is_safe_url
from django.utils.translation import (
LANGUAGE_SESSION_KEY, check_for_language, get_language, to_locale,
)
def set_language(request):
"""
Redirect to a given url while setting the chosen language in the
session or cookie. The url and the language code need to be
specified in the request parameters.
Since this view changes how the user will see the rest of the site, it must
only be accessed as a POST request. If called as a GET request, it will
redirect to the page in the request (the 'next' parameter) without changing
any state.
"""
next = request.POST.get('next', request.GET.get('next'))
if not is_safe_url(url=next, host=request.get_host()):
next = request.META.get('HTTP_REFERER')
if not is_safe_url(url=next, host=request.get_host()):
next = '/'
response = http.HttpResponseRedirect(next)
if request.method == 'POST':
lang_code = request.POST.get('language')
if lang_code and check_for_language(lang_code):
next_trans = translate_url(next, lang_code)
if next_trans != next:
response = http.HttpResponseRedirect(next_trans)
if hasattr(request, 'session'):
request.session[LANGUAGE_SESSION_KEY] = lang_code
else:
response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code,
max_age=settings.LANGUAGE_COOKIE_AGE,
path=settings.LANGUAGE_COOKIE_PATH,
domain=settings.LANGUAGE_COOKIE_DOMAIN)
return response
def get_formats():
"""
Returns all formats strings required for i18n to work
"""
FORMAT_SETTINGS = (
'DATE_FORMAT', 'DATETIME_FORMAT', 'TIME_FORMAT',
'YEAR_MONTH_FORMAT', 'MONTH_DAY_FORMAT', 'SHORT_DATE_FORMAT',
'SHORT_DATETIME_FORMAT', 'FIRST_DAY_OF_WEEK', 'DECIMAL_SEPARATOR',
'THOUSAND_SEPARATOR', 'NUMBER_GROUPING',
'DATE_INPUT_FORMATS', 'TIME_INPUT_FORMATS', 'DATETIME_INPUT_FORMATS'
)
result = {}
for module in [settings] + get_format_modules(reverse=True):
for attr in FORMAT_SETTINGS:
result[attr] = get_format(attr)
formats = {}
for k, v in result.items():
if isinstance(v, (six.string_types, int)):
formats[k] = smart_text(v)
elif isinstance(v, (tuple, list)):
formats[k] = [smart_text(value) for value in v]
return formats
js_catalog_template = r"""
{% autoescape off %}
(function(globals) {
var django = globals.django || (globals.django = {});
{% if plural %}
django.pluralidx = function(n) {
var v={{ plural }};
if (typeof(v) == 'boolean') {
return v ? 1 : 0;
} else {
return v;
}
};
{% else %}
django.pluralidx = function(count) { return (count == 1) ? 0 : 1; };
{% endif %}
/* gettext library */
django.catalog = django.catalog || {};
{% if catalog_str %}
var newcatalog = {{ catalog_str }};
for (var key in newcatalog) {
django.catalog[key] = newcatalog[key];
}
{% endif %}
if (!django.jsi18n_initialized) {
django.gettext = function(msgid) {
var value = django.catalog[msgid];
if (typeof(value) == 'undefined') {
return msgid;
} else {
return (typeof(value) == 'string') ? value : value[0];
}
};
django.ngettext = function(singular, plural, count) {
var value = django.catalog[singular];
if (typeof(value) == 'undefined') {
return (count == 1) ? singular : plural;
} else {
return value[django.pluralidx(count)];
}
};
django.gettext_noop = function(msgid) { return msgid; };
django.pgettext = function(context, msgid) {
var value = django.gettext(context + '\x04' + msgid);
if (value.indexOf('\x04') != -1) {
value = msgid;
}
return value;
};
django.npgettext = function(context, singular, plural, count) {
var value = django.ngettext(context + '\x04' + singular, context + '\x04' + plural, count);
if (value.indexOf('\x04') != -1) {
value = django.ngettext(singular, plural, count);
}
return value;
};
django.interpolate = function(fmt, obj, named) {
if (named) {
return fmt.replace(/%\(\w+\)s/g, function(match){return String(obj[match.slice(2,-2)])});
} else {
return fmt.replace(/%s/g, function(match){return String(obj.shift())});
}
};
/* formatting library */
django.formats = {{ formats_str }};
django.get_format = function(format_type) {
var value = django.formats[format_type];
if (typeof(value) == 'undefined') {
return format_type;
} else {
return value;
}
};
/* add to global namespace */
globals.pluralidx = django.pluralidx;
globals.gettext = django.gettext;
globals.ngettext = django.ngettext;
globals.gettext_noop = django.gettext_noop;
globals.pgettext = django.pgettext;
globals.npgettext = django.npgettext;
globals.interpolate = django.interpolate;
globals.get_format = django.get_format;
django.jsi18n_initialized = true;
}
}(this));
{% endautoescape %}
"""
def render_javascript_catalog(catalog=None, plural=None):
template = Engine().from_string(js_catalog_template)
indent = lambda s: s.replace('\n', '\n ')
context = Context({
'catalog_str': indent(json.dumps(
catalog, sort_keys=True, indent=2)) if catalog else None,
'formats_str': indent(json.dumps(
get_formats(), sort_keys=True, indent=2)),
'plural': plural,
})
return http.HttpResponse(template.render(context), 'text/javascript')
def get_javascript_catalog(locale, domain, packages):
default_locale = to_locale(settings.LANGUAGE_CODE)
app_configs = apps.get_app_configs()
allowable_packages = set(app_config.name for app_config in app_configs)
allowable_packages.add('django.conf')
packages = [p for p in packages if p in allowable_packages]
t = {}
paths = []
en_selected = locale.startswith('en')
en_catalog_missing = True
# paths of requested packages
for package in packages:
p = importlib.import_module(package)
path = os.path.join(os.path.dirname(upath(p.__file__)), 'locale')
paths.append(path)
# add the filesystem paths listed in the LOCALE_PATHS setting
paths.extend(reversed(settings.LOCALE_PATHS))
# first load all english languages files for defaults
for path in paths:
try:
catalog = gettext_module.translation(domain, path, ['en'])
t.update(catalog._catalog)
except IOError:
pass
else:
# 'en' is the selected language and at least one of the packages
# listed in `packages` has an 'en' catalog
if en_selected:
en_catalog_missing = False
# next load the settings.LANGUAGE_CODE translations if it isn't english
if default_locale != 'en':
for path in paths:
try:
catalog = gettext_module.translation(domain, path, [default_locale])
except IOError:
catalog = None
if catalog is not None:
t.update(catalog._catalog)
# last load the currently selected language, if it isn't identical to the default.
if locale != default_locale:
# If the currently selected language is English but it doesn't have a
# translation catalog (presumably due to being the language translated
# from) then a wrong language catalog might have been loaded in the
# previous step. It needs to be discarded.
if en_selected and en_catalog_missing:
t = {}
else:
locale_t = {}
for path in paths:
try:
catalog = gettext_module.translation(domain, path, [locale])
except IOError:
catalog = None
if catalog is not None:
locale_t.update(catalog._catalog)
if locale_t:
t = locale_t
plural = None
if '' in t:
for l in t[''].split('\n'):
if l.startswith('Plural-Forms:'):
plural = l.split(':', 1)[1].strip()
if plural is not None:
# this should actually be a compiled function of a typical plural-form:
# Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 :
# n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;
plural = [el.strip() for el in plural.split(';') if el.strip().startswith('plural=')][0].split('=', 1)[1]
pdict = {}
maxcnts = {}
catalog = {}
for k, v in t.items():
if k == '':
continue
if isinstance(k, six.string_types):
catalog[k] = v
elif isinstance(k, tuple):
msgid = k[0]
cnt = k[1]
maxcnts[msgid] = max(cnt, maxcnts.get(msgid, 0))
pdict.setdefault(msgid, {})[cnt] = v
else:
raise TypeError(k)
for k, v in pdict.items():
catalog[k] = [v.get(i, '') for i in range(maxcnts[msgid] + 1)]
return catalog, plural
def null_javascript_catalog(request, domain=None, packages=None):
"""
Returns "identity" versions of the JavaScript i18n functions -- i.e.,
versions that don't actually do anything.
"""
return render_javascript_catalog()
def javascript_catalog(request, domain='djangojs', packages=None):
"""
Returns the selected language catalog as a javascript library.
Receives the list of packages to check for translations in the
packages parameter either from an infodict or as a +-delimited
string from the request. Default is 'django.conf'.
Additionally you can override the gettext domain for this view,
but usually you don't want to do that, as JavaScript messages
go to the djangojs domain. But this might be needed if you
deliver your JavaScript source from Django templates.
"""
locale = to_locale(get_language())
if request.GET and 'language' in request.GET:
if check_for_language(request.GET['language']):
locale = to_locale(request.GET['language'])
if packages is None:
packages = ['django.conf']
if isinstance(packages, six.string_types):
packages = packages.split('+')
catalog, plural = get_javascript_catalog(locale, domain, packages)
return render_javascript_catalog(catalog, plural)
| bsd-3-clause |
qwertyjune/BethSaidaBible | venv/lib/python2.7/site-packages/pip/_vendor/packaging/__about__.py | 257 | 1073 | # Copyright 2014 Donald Stufft
#
# 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.
from __future__ import absolute_import, division, print_function
__all__ = [
"__title__", "__summary__", "__uri__", "__version__", "__author__",
"__email__", "__license__", "__copyright__",
]
__title__ = "packaging"
__summary__ = "Core utilities for Python packages"
__uri__ = "https://github.com/pypa/packaging"
__version__ = "15.0"
__author__ = "Donald Stufft"
__email__ = "[email protected]"
__license__ = "Apache License, Version 2.0"
__copyright__ = "Copyright 2014 %s" % __author__
| gpl-3.0 |
leiferikb/bitpop | build/third_party/twisted_10_2/twisted/persisted/sob.py | 60 | 6366 | # -*- test-case-name: twisted.test.test_sob -*-
# Copyright (c) 2001-2008 Twisted Matrix Laboratories.
# See LICENSE for details.
#
"""
Save and load Small OBjects to and from files, using various formats.
Maintainer: Moshe Zadka
"""
import os, sys
try:
import cPickle as pickle
except ImportError:
import pickle
try:
import cStringIO as StringIO
except ImportError:
import StringIO
from twisted.python import log, runtime
from twisted.python.hashlib import md5
from twisted.persisted import styles
from zope.interface import implements, Interface
# Note:
# These encrypt/decrypt functions only work for data formats
# which are immune to having spaces tucked at the end.
# All data formats which persist saves hold that condition.
def _encrypt(passphrase, data):
from Crypto.Cipher import AES as cipher
leftover = len(data) % cipher.block_size
if leftover:
data += ' '*(cipher.block_size - leftover)
return cipher.new(md5(passphrase).digest()[:16]).encrypt(data)
def _decrypt(passphrase, data):
from Crypto.Cipher import AES
return AES.new(md5(passphrase).digest()[:16]).decrypt(data)
class IPersistable(Interface):
"""An object which can be saved in several formats to a file"""
def setStyle(style):
"""Set desired format.
@type style: string (one of 'pickle' or 'source')
"""
def save(tag=None, filename=None, passphrase=None):
"""Save object to file.
@type tag: string
@type filename: string
@type passphrase: string
"""
class Persistent:
implements(IPersistable)
style = "pickle"
def __init__(self, original, name):
self.original = original
self.name = name
def setStyle(self, style):
"""Set desired format.
@type style: string (one of 'pickle' or 'source')
"""
self.style = style
def _getFilename(self, filename, ext, tag):
if filename:
finalname = filename
filename = finalname + "-2"
elif tag:
filename = "%s-%s-2.%s" % (self.name, tag, ext)
finalname = "%s-%s.%s" % (self.name, tag, ext)
else:
filename = "%s-2.%s" % (self.name, ext)
finalname = "%s.%s" % (self.name, ext)
return finalname, filename
def _saveTemp(self, filename, passphrase, dumpFunc):
f = open(filename, 'wb')
if passphrase is None:
dumpFunc(self.original, f)
else:
s = StringIO.StringIO()
dumpFunc(self.original, s)
f.write(_encrypt(passphrase, s.getvalue()))
f.close()
def _getStyle(self):
if self.style == "source":
from twisted.persisted.aot import jellyToSource as dumpFunc
ext = "tas"
else:
def dumpFunc(obj, file):
pickle.dump(obj, file, 2)
ext = "tap"
return ext, dumpFunc
def save(self, tag=None, filename=None, passphrase=None):
"""Save object to file.
@type tag: string
@type filename: string
@type passphrase: string
"""
ext, dumpFunc = self._getStyle()
if passphrase:
ext = 'e' + ext
finalname, filename = self._getFilename(filename, ext, tag)
log.msg("Saving "+self.name+" application to "+finalname+"...")
self._saveTemp(filename, passphrase, dumpFunc)
if runtime.platformType == "win32" and os.path.isfile(finalname):
os.remove(finalname)
os.rename(filename, finalname)
log.msg("Saved.")
# "Persistant" has been present since 1.0.7, so retain it for compatibility
Persistant = Persistent
class _EverythingEphemeral(styles.Ephemeral):
initRun = 0
def __init__(self, mainMod):
"""
@param mainMod: The '__main__' module that this class will proxy.
"""
self.mainMod = mainMod
def __getattr__(self, key):
try:
return getattr(self.mainMod, key)
except AttributeError:
if self.initRun:
raise
else:
log.msg("Warning! Loading from __main__: %s" % key)
return styles.Ephemeral()
def load(filename, style, passphrase=None):
"""Load an object from a file.
Deserialize an object from a file. The file can be encrypted.
@param filename: string
@param style: string (one of 'pickle' or 'source')
@param passphrase: string
"""
mode = 'r'
if style=='source':
from twisted.persisted.aot import unjellyFromSource as _load
else:
_load, mode = pickle.load, 'rb'
if passphrase:
fp = StringIO.StringIO(_decrypt(passphrase,
open(filename, 'rb').read()))
else:
fp = open(filename, mode)
ee = _EverythingEphemeral(sys.modules['__main__'])
sys.modules['__main__'] = ee
ee.initRun = 1
try:
value = _load(fp)
finally:
# restore __main__ if an exception is raised.
sys.modules['__main__'] = ee.mainMod
styles.doUpgrade()
ee.initRun = 0
persistable = IPersistable(value, None)
if persistable is not None:
persistable.setStyle(style)
return value
def loadValueFromFile(filename, variable, passphrase=None):
"""Load the value of a variable in a Python file.
Run the contents of the file, after decrypting if C{passphrase} is
given, in a namespace and return the result of the variable
named C{variable}.
@param filename: string
@param variable: string
@param passphrase: string
"""
if passphrase:
mode = 'rb'
else:
mode = 'r'
fileObj = open(filename, mode)
d = {'__file__': filename}
if passphrase:
data = fileObj.read()
data = _decrypt(passphrase, data)
exec data in d, d
else:
exec fileObj in d, d
value = d[variable]
return value
def guessType(filename):
ext = os.path.splitext(filename)[1]
return {
'.tac': 'python',
'.etac': 'python',
'.py': 'python',
'.tap': 'pickle',
'.etap': 'pickle',
'.tas': 'source',
'.etas': 'source',
}[ext]
__all__ = ['loadValueFromFile', 'load', 'Persistent', 'Persistant',
'IPersistable', 'guessType']
| gpl-3.0 |
linearregression/socorro | socorro/cron/jobs/truncate_partitions.py | 9 | 1248 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from configman import Namespace
from crontabber.base import BaseCronApp
from crontabber.mixins import (
with_postgres_transactions,
with_single_postgres_transaction,
)
@with_postgres_transactions()
@with_single_postgres_transaction()
class TruncatePartitionsCronApp(BaseCronApp):
app_name = 'truncate-partitions'
app_version = '1.0'
app_description = """See
http://socorro.readthedocs.org/en/latest/development
/databaseadminfunctions.html#truncate-partitions
See https://bugzilla.mozilla.org/show_bug.cgi?id=1117911
"""
required_config = Namespace()
required_config.add_option(
'weeks_to_keep',
default=2, # 2 weeks is sufficient for a backfill range if need be
doc='Number of weeks of raw crash data to keep in Postgres')
def run(self, connection):
cursor = connection.cursor()
# Casting to date because stored procs in psql are strongly typed.
cursor.execute(
"select truncate_partitions(%s)", (self.config.weeks_to_keep,)
)
| mpl-2.0 |
mollstam/UnrealPy | UnrealPyEmbed/Source/Python/Lib/python27/test/test_datetime.py | 12 | 134698 | """Test date/time type.
See http://www.zope.org/Members/fdrake/DateTimeWiki/TestCases
"""
from __future__ import division
import sys
import pickle
import cPickle
import unittest
from test import test_support
from datetime import MINYEAR, MAXYEAR
from datetime import timedelta
from datetime import tzinfo
from datetime import time
from datetime import date, datetime
pickle_choices = [(pickler, unpickler, proto)
for pickler in pickle, cPickle
for unpickler in pickle, cPickle
for proto in range(3)]
assert len(pickle_choices) == 2*2*3
# An arbitrary collection of objects of non-datetime types, for testing
# mixed-type comparisons.
OTHERSTUFF = (10, 10L, 34.5, "abc", {}, [], ())
#############################################################################
# module tests
class TestModule(unittest.TestCase):
def test_constants(self):
import datetime
self.assertEqual(datetime.MINYEAR, 1)
self.assertEqual(datetime.MAXYEAR, 9999)
#############################################################################
# tzinfo tests
class FixedOffset(tzinfo):
def __init__(self, offset, name, dstoffset=42):
if isinstance(offset, int):
offset = timedelta(minutes=offset)
if isinstance(dstoffset, int):
dstoffset = timedelta(minutes=dstoffset)
self.__offset = offset
self.__name = name
self.__dstoffset = dstoffset
def __repr__(self):
return self.__name.lower()
def utcoffset(self, dt):
return self.__offset
def tzname(self, dt):
return self.__name
def dst(self, dt):
return self.__dstoffset
class PicklableFixedOffset(FixedOffset):
def __init__(self, offset=None, name=None, dstoffset=None):
FixedOffset.__init__(self, offset, name, dstoffset)
class TestTZInfo(unittest.TestCase):
def test_non_abstractness(self):
# In order to allow subclasses to get pickled, the C implementation
# wasn't able to get away with having __init__ raise
# NotImplementedError.
useless = tzinfo()
dt = datetime.max
self.assertRaises(NotImplementedError, useless.tzname, dt)
self.assertRaises(NotImplementedError, useless.utcoffset, dt)
self.assertRaises(NotImplementedError, useless.dst, dt)
def test_subclass_must_override(self):
class NotEnough(tzinfo):
def __init__(self, offset, name):
self.__offset = offset
self.__name = name
self.assertTrue(issubclass(NotEnough, tzinfo))
ne = NotEnough(3, "NotByALongShot")
self.assertIsInstance(ne, tzinfo)
dt = datetime.now()
self.assertRaises(NotImplementedError, ne.tzname, dt)
self.assertRaises(NotImplementedError, ne.utcoffset, dt)
self.assertRaises(NotImplementedError, ne.dst, dt)
def test_normal(self):
fo = FixedOffset(3, "Three")
self.assertIsInstance(fo, tzinfo)
for dt in datetime.now(), None:
self.assertEqual(fo.utcoffset(dt), timedelta(minutes=3))
self.assertEqual(fo.tzname(dt), "Three")
self.assertEqual(fo.dst(dt), timedelta(minutes=42))
def test_pickling_base(self):
# There's no point to pickling tzinfo objects on their own (they
# carry no data), but they need to be picklable anyway else
# concrete subclasses can't be pickled.
orig = tzinfo.__new__(tzinfo)
self.assertIs(type(orig), tzinfo)
for pickler, unpickler, proto in pickle_choices:
green = pickler.dumps(orig, proto)
derived = unpickler.loads(green)
self.assertIs(type(derived), tzinfo)
def test_pickling_subclass(self):
# Make sure we can pickle/unpickle an instance of a subclass.
offset = timedelta(minutes=-300)
orig = PicklableFixedOffset(offset, 'cookie')
self.assertIsInstance(orig, tzinfo)
self.assertTrue(type(orig) is PicklableFixedOffset)
self.assertEqual(orig.utcoffset(None), offset)
self.assertEqual(orig.tzname(None), 'cookie')
for pickler, unpickler, proto in pickle_choices:
green = pickler.dumps(orig, proto)
derived = unpickler.loads(green)
self.assertIsInstance(derived, tzinfo)
self.assertTrue(type(derived) is PicklableFixedOffset)
self.assertEqual(derived.utcoffset(None), offset)
self.assertEqual(derived.tzname(None), 'cookie')
#############################################################################
# Base class for testing a particular aspect of timedelta, time, date and
# datetime comparisons.
class HarmlessMixedComparison:
# Test that __eq__ and __ne__ don't complain for mixed-type comparisons.
# Subclasses must define 'theclass', and theclass(1, 1, 1) must be a
# legit constructor.
def test_harmless_mixed_comparison(self):
me = self.theclass(1, 1, 1)
self.assertFalse(me == ())
self.assertTrue(me != ())
self.assertFalse(() == me)
self.assertTrue(() != me)
self.assertIn(me, [1, 20L, [], me])
self.assertIn([], [me, 1, 20L, []])
def test_harmful_mixed_comparison(self):
me = self.theclass(1, 1, 1)
self.assertRaises(TypeError, lambda: me < ())
self.assertRaises(TypeError, lambda: me <= ())
self.assertRaises(TypeError, lambda: me > ())
self.assertRaises(TypeError, lambda: me >= ())
self.assertRaises(TypeError, lambda: () < me)
self.assertRaises(TypeError, lambda: () <= me)
self.assertRaises(TypeError, lambda: () > me)
self.assertRaises(TypeError, lambda: () >= me)
self.assertRaises(TypeError, cmp, (), me)
self.assertRaises(TypeError, cmp, me, ())
#############################################################################
# timedelta tests
class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase):
theclass = timedelta
def test_constructor(self):
eq = self.assertEqual
td = timedelta
# Check keyword args to constructor
eq(td(), td(weeks=0, days=0, hours=0, minutes=0, seconds=0,
milliseconds=0, microseconds=0))
eq(td(1), td(days=1))
eq(td(0, 1), td(seconds=1))
eq(td(0, 0, 1), td(microseconds=1))
eq(td(weeks=1), td(days=7))
eq(td(days=1), td(hours=24))
eq(td(hours=1), td(minutes=60))
eq(td(minutes=1), td(seconds=60))
eq(td(seconds=1), td(milliseconds=1000))
eq(td(milliseconds=1), td(microseconds=1000))
# Check float args to constructor
eq(td(weeks=1.0/7), td(days=1))
eq(td(days=1.0/24), td(hours=1))
eq(td(hours=1.0/60), td(minutes=1))
eq(td(minutes=1.0/60), td(seconds=1))
eq(td(seconds=0.001), td(milliseconds=1))
eq(td(milliseconds=0.001), td(microseconds=1))
def test_computations(self):
eq = self.assertEqual
td = timedelta
a = td(7) # One week
b = td(0, 60) # One minute
c = td(0, 0, 1000) # One millisecond
eq(a+b+c, td(7, 60, 1000))
eq(a-b, td(6, 24*3600 - 60))
eq(-a, td(-7))
eq(+a, td(7))
eq(-b, td(-1, 24*3600 - 60))
eq(-c, td(-1, 24*3600 - 1, 999000))
eq(abs(a), a)
eq(abs(-a), a)
eq(td(6, 24*3600), a)
eq(td(0, 0, 60*1000000), b)
eq(a*10, td(70))
eq(a*10, 10*a)
eq(a*10L, 10*a)
eq(b*10, td(0, 600))
eq(10*b, td(0, 600))
eq(b*10L, td(0, 600))
eq(c*10, td(0, 0, 10000))
eq(10*c, td(0, 0, 10000))
eq(c*10L, td(0, 0, 10000))
eq(a*-1, -a)
eq(b*-2, -b-b)
eq(c*-2, -c+-c)
eq(b*(60*24), (b*60)*24)
eq(b*(60*24), (60*b)*24)
eq(c*1000, td(0, 1))
eq(1000*c, td(0, 1))
eq(a//7, td(1))
eq(b//10, td(0, 6))
eq(c//1000, td(0, 0, 1))
eq(a//10, td(0, 7*24*360))
eq(a//3600000, td(0, 0, 7*24*1000))
# Issue #11576
eq(td(999999999, 86399, 999999) - td(999999999, 86399, 999998),
td(0, 0, 1))
eq(td(999999999, 1, 1) - td(999999999, 1, 0),
td(0, 0, 1))
def test_disallowed_computations(self):
a = timedelta(42)
# Add/sub ints, longs, floats should be illegal
for i in 1, 1L, 1.0:
self.assertRaises(TypeError, lambda: a+i)
self.assertRaises(TypeError, lambda: a-i)
self.assertRaises(TypeError, lambda: i+a)
self.assertRaises(TypeError, lambda: i-a)
# Mul/div by float isn't supported.
x = 2.3
self.assertRaises(TypeError, lambda: a*x)
self.assertRaises(TypeError, lambda: x*a)
self.assertRaises(TypeError, lambda: a/x)
self.assertRaises(TypeError, lambda: x/a)
self.assertRaises(TypeError, lambda: a // x)
self.assertRaises(TypeError, lambda: x // a)
# Division of int by timedelta doesn't make sense.
# Division by zero doesn't make sense.
for zero in 0, 0L:
self.assertRaises(TypeError, lambda: zero // a)
self.assertRaises(ZeroDivisionError, lambda: a // zero)
def test_basic_attributes(self):
days, seconds, us = 1, 7, 31
td = timedelta(days, seconds, us)
self.assertEqual(td.days, days)
self.assertEqual(td.seconds, seconds)
self.assertEqual(td.microseconds, us)
def test_total_seconds(self):
td = timedelta(days=365)
self.assertEqual(td.total_seconds(), 31536000.0)
for total_seconds in [123456.789012, -123456.789012, 0.123456, 0, 1e6]:
td = timedelta(seconds=total_seconds)
self.assertEqual(td.total_seconds(), total_seconds)
# Issue8644: Test that td.total_seconds() has the same
# accuracy as td / timedelta(seconds=1).
for ms in [-1, -2, -123]:
td = timedelta(microseconds=ms)
self.assertEqual(td.total_seconds(),
((24*3600*td.days + td.seconds)*10**6
+ td.microseconds)/10**6)
def test_carries(self):
t1 = timedelta(days=100,
weeks=-7,
hours=-24*(100-49),
minutes=-3,
seconds=12,
microseconds=(3*60 - 12) * 1e6 + 1)
t2 = timedelta(microseconds=1)
self.assertEqual(t1, t2)
def test_hash_equality(self):
t1 = timedelta(days=100,
weeks=-7,
hours=-24*(100-49),
minutes=-3,
seconds=12,
microseconds=(3*60 - 12) * 1000000)
t2 = timedelta()
self.assertEqual(hash(t1), hash(t2))
t1 += timedelta(weeks=7)
t2 += timedelta(days=7*7)
self.assertEqual(t1, t2)
self.assertEqual(hash(t1), hash(t2))
d = {t1: 1}
d[t2] = 2
self.assertEqual(len(d), 1)
self.assertEqual(d[t1], 2)
def test_pickling(self):
args = 12, 34, 56
orig = timedelta(*args)
for pickler, unpickler, proto in pickle_choices:
green = pickler.dumps(orig, proto)
derived = unpickler.loads(green)
self.assertEqual(orig, derived)
def test_compare(self):
t1 = timedelta(2, 3, 4)
t2 = timedelta(2, 3, 4)
self.assertTrue(t1 == t2)
self.assertTrue(t1 <= t2)
self.assertTrue(t1 >= t2)
self.assertFalse(t1 != t2)
self.assertFalse(t1 < t2)
self.assertFalse(t1 > t2)
self.assertEqual(cmp(t1, t2), 0)
self.assertEqual(cmp(t2, t1), 0)
for args in (3, 3, 3), (2, 4, 4), (2, 3, 5):
t2 = timedelta(*args) # this is larger than t1
self.assertTrue(t1 < t2)
self.assertTrue(t2 > t1)
self.assertTrue(t1 <= t2)
self.assertTrue(t2 >= t1)
self.assertTrue(t1 != t2)
self.assertTrue(t2 != t1)
self.assertFalse(t1 == t2)
self.assertFalse(t2 == t1)
self.assertFalse(t1 > t2)
self.assertFalse(t2 < t1)
self.assertFalse(t1 >= t2)
self.assertFalse(t2 <= t1)
self.assertEqual(cmp(t1, t2), -1)
self.assertEqual(cmp(t2, t1), 1)
for badarg in OTHERSTUFF:
self.assertEqual(t1 == badarg, False)
self.assertEqual(t1 != badarg, True)
self.assertEqual(badarg == t1, False)
self.assertEqual(badarg != t1, True)
self.assertRaises(TypeError, lambda: t1 <= badarg)
self.assertRaises(TypeError, lambda: t1 < badarg)
self.assertRaises(TypeError, lambda: t1 > badarg)
self.assertRaises(TypeError, lambda: t1 >= badarg)
self.assertRaises(TypeError, lambda: badarg <= t1)
self.assertRaises(TypeError, lambda: badarg < t1)
self.assertRaises(TypeError, lambda: badarg > t1)
self.assertRaises(TypeError, lambda: badarg >= t1)
def test_str(self):
td = timedelta
eq = self.assertEqual
eq(str(td(1)), "1 day, 0:00:00")
eq(str(td(-1)), "-1 day, 0:00:00")
eq(str(td(2)), "2 days, 0:00:00")
eq(str(td(-2)), "-2 days, 0:00:00")
eq(str(td(hours=12, minutes=58, seconds=59)), "12:58:59")
eq(str(td(hours=2, minutes=3, seconds=4)), "2:03:04")
eq(str(td(weeks=-30, hours=23, minutes=12, seconds=34)),
"-210 days, 23:12:34")
eq(str(td(milliseconds=1)), "0:00:00.001000")
eq(str(td(microseconds=3)), "0:00:00.000003")
eq(str(td(days=999999999, hours=23, minutes=59, seconds=59,
microseconds=999999)),
"999999999 days, 23:59:59.999999")
def test_roundtrip(self):
for td in (timedelta(days=999999999, hours=23, minutes=59,
seconds=59, microseconds=999999),
timedelta(days=-999999999),
timedelta(days=1, seconds=2, microseconds=3)):
# Verify td -> string -> td identity.
s = repr(td)
self.assertTrue(s.startswith('datetime.'))
s = s[9:]
td2 = eval(s)
self.assertEqual(td, td2)
# Verify identity via reconstructing from pieces.
td2 = timedelta(td.days, td.seconds, td.microseconds)
self.assertEqual(td, td2)
def test_resolution_info(self):
self.assertIsInstance(timedelta.min, timedelta)
self.assertIsInstance(timedelta.max, timedelta)
self.assertIsInstance(timedelta.resolution, timedelta)
self.assertTrue(timedelta.max > timedelta.min)
self.assertEqual(timedelta.min, timedelta(-999999999))
self.assertEqual(timedelta.max, timedelta(999999999, 24*3600-1, 1e6-1))
self.assertEqual(timedelta.resolution, timedelta(0, 0, 1))
def test_overflow(self):
tiny = timedelta.resolution
td = timedelta.min + tiny
td -= tiny # no problem
self.assertRaises(OverflowError, td.__sub__, tiny)
self.assertRaises(OverflowError, td.__add__, -tiny)
td = timedelta.max - tiny
td += tiny # no problem
self.assertRaises(OverflowError, td.__add__, tiny)
self.assertRaises(OverflowError, td.__sub__, -tiny)
self.assertRaises(OverflowError, lambda: -timedelta.max)
def test_microsecond_rounding(self):
td = timedelta
eq = self.assertEqual
# Single-field rounding.
eq(td(milliseconds=0.4/1000), td(0)) # rounds to 0
eq(td(milliseconds=-0.4/1000), td(0)) # rounds to 0
eq(td(milliseconds=0.6/1000), td(microseconds=1))
eq(td(milliseconds=-0.6/1000), td(microseconds=-1))
# Rounding due to contributions from more than one field.
us_per_hour = 3600e6
us_per_day = us_per_hour * 24
eq(td(days=.4/us_per_day), td(0))
eq(td(hours=.2/us_per_hour), td(0))
eq(td(days=.4/us_per_day, hours=.2/us_per_hour), td(microseconds=1))
eq(td(days=-.4/us_per_day), td(0))
eq(td(hours=-.2/us_per_hour), td(0))
eq(td(days=-.4/us_per_day, hours=-.2/us_per_hour), td(microseconds=-1))
def test_massive_normalization(self):
td = timedelta(microseconds=-1)
self.assertEqual((td.days, td.seconds, td.microseconds),
(-1, 24*3600-1, 999999))
def test_bool(self):
self.assertTrue(timedelta(1))
self.assertTrue(timedelta(0, 1))
self.assertTrue(timedelta(0, 0, 1))
self.assertTrue(timedelta(microseconds=1))
self.assertFalse(timedelta(0))
def test_subclass_timedelta(self):
class T(timedelta):
@staticmethod
def from_td(td):
return T(td.days, td.seconds, td.microseconds)
def as_hours(self):
sum = (self.days * 24 +
self.seconds / 3600.0 +
self.microseconds / 3600e6)
return round(sum)
t1 = T(days=1)
self.assertIs(type(t1), T)
self.assertEqual(t1.as_hours(), 24)
t2 = T(days=-1, seconds=-3600)
self.assertIs(type(t2), T)
self.assertEqual(t2.as_hours(), -25)
t3 = t1 + t2
self.assertIs(type(t3), timedelta)
t4 = T.from_td(t3)
self.assertIs(type(t4), T)
self.assertEqual(t3.days, t4.days)
self.assertEqual(t3.seconds, t4.seconds)
self.assertEqual(t3.microseconds, t4.microseconds)
self.assertEqual(str(t3), str(t4))
self.assertEqual(t4.as_hours(), -1)
#############################################################################
# date tests
class TestDateOnly(unittest.TestCase):
# Tests here won't pass if also run on datetime objects, so don't
# subclass this to test datetimes too.
def test_delta_non_days_ignored(self):
dt = date(2000, 1, 2)
delta = timedelta(days=1, hours=2, minutes=3, seconds=4,
microseconds=5)
days = timedelta(delta.days)
self.assertEqual(days, timedelta(1))
dt2 = dt + delta
self.assertEqual(dt2, dt + days)
dt2 = delta + dt
self.assertEqual(dt2, dt + days)
dt2 = dt - delta
self.assertEqual(dt2, dt - days)
delta = -delta
days = timedelta(delta.days)
self.assertEqual(days, timedelta(-2))
dt2 = dt + delta
self.assertEqual(dt2, dt + days)
dt2 = delta + dt
self.assertEqual(dt2, dt + days)
dt2 = dt - delta
self.assertEqual(dt2, dt - days)
class SubclassDate(date):
sub_var = 1
class TestDate(HarmlessMixedComparison, unittest.TestCase):
# Tests here should pass for both dates and datetimes, except for a
# few tests that TestDateTime overrides.
theclass = date
def test_basic_attributes(self):
dt = self.theclass(2002, 3, 1)
self.assertEqual(dt.year, 2002)
self.assertEqual(dt.month, 3)
self.assertEqual(dt.day, 1)
def test_roundtrip(self):
for dt in (self.theclass(1, 2, 3),
self.theclass.today()):
# Verify dt -> string -> date identity.
s = repr(dt)
self.assertTrue(s.startswith('datetime.'))
s = s[9:]
dt2 = eval(s)
self.assertEqual(dt, dt2)
# Verify identity via reconstructing from pieces.
dt2 = self.theclass(dt.year, dt.month, dt.day)
self.assertEqual(dt, dt2)
def test_ordinal_conversions(self):
# Check some fixed values.
for y, m, d, n in [(1, 1, 1, 1), # calendar origin
(1, 12, 31, 365),
(2, 1, 1, 366),
# first example from "Calendrical Calculations"
(1945, 11, 12, 710347)]:
d = self.theclass(y, m, d)
self.assertEqual(n, d.toordinal())
fromord = self.theclass.fromordinal(n)
self.assertEqual(d, fromord)
if hasattr(fromord, "hour"):
# if we're checking something fancier than a date, verify
# the extra fields have been zeroed out
self.assertEqual(fromord.hour, 0)
self.assertEqual(fromord.minute, 0)
self.assertEqual(fromord.second, 0)
self.assertEqual(fromord.microsecond, 0)
# Check first and last days of year spottily across the whole
# range of years supported.
for year in xrange(MINYEAR, MAXYEAR+1, 7):
# Verify (year, 1, 1) -> ordinal -> y, m, d is identity.
d = self.theclass(year, 1, 1)
n = d.toordinal()
d2 = self.theclass.fromordinal(n)
self.assertEqual(d, d2)
# Verify that moving back a day gets to the end of year-1.
if year > 1:
d = self.theclass.fromordinal(n-1)
d2 = self.theclass(year-1, 12, 31)
self.assertEqual(d, d2)
self.assertEqual(d2.toordinal(), n-1)
# Test every day in a leap-year and a non-leap year.
dim = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
for year, isleap in (2000, True), (2002, False):
n = self.theclass(year, 1, 1).toordinal()
for month, maxday in zip(range(1, 13), dim):
if month == 2 and isleap:
maxday += 1
for day in range(1, maxday+1):
d = self.theclass(year, month, day)
self.assertEqual(d.toordinal(), n)
self.assertEqual(d, self.theclass.fromordinal(n))
n += 1
def test_extreme_ordinals(self):
a = self.theclass.min
a = self.theclass(a.year, a.month, a.day) # get rid of time parts
aord = a.toordinal()
b = a.fromordinal(aord)
self.assertEqual(a, b)
self.assertRaises(ValueError, lambda: a.fromordinal(aord - 1))
b = a + timedelta(days=1)
self.assertEqual(b.toordinal(), aord + 1)
self.assertEqual(b, self.theclass.fromordinal(aord + 1))
a = self.theclass.max
a = self.theclass(a.year, a.month, a.day) # get rid of time parts
aord = a.toordinal()
b = a.fromordinal(aord)
self.assertEqual(a, b)
self.assertRaises(ValueError, lambda: a.fromordinal(aord + 1))
b = a - timedelta(days=1)
self.assertEqual(b.toordinal(), aord - 1)
self.assertEqual(b, self.theclass.fromordinal(aord - 1))
def test_bad_constructor_arguments(self):
# bad years
self.theclass(MINYEAR, 1, 1) # no exception
self.theclass(MAXYEAR, 1, 1) # no exception
self.assertRaises(ValueError, self.theclass, MINYEAR-1, 1, 1)
self.assertRaises(ValueError, self.theclass, MAXYEAR+1, 1, 1)
# bad months
self.theclass(2000, 1, 1) # no exception
self.theclass(2000, 12, 1) # no exception
self.assertRaises(ValueError, self.theclass, 2000, 0, 1)
self.assertRaises(ValueError, self.theclass, 2000, 13, 1)
# bad days
self.theclass(2000, 2, 29) # no exception
self.theclass(2004, 2, 29) # no exception
self.theclass(2400, 2, 29) # no exception
self.assertRaises(ValueError, self.theclass, 2000, 2, 30)
self.assertRaises(ValueError, self.theclass, 2001, 2, 29)
self.assertRaises(ValueError, self.theclass, 2100, 2, 29)
self.assertRaises(ValueError, self.theclass, 1900, 2, 29)
self.assertRaises(ValueError, self.theclass, 2000, 1, 0)
self.assertRaises(ValueError, self.theclass, 2000, 1, 32)
def test_hash_equality(self):
d = self.theclass(2000, 12, 31)
# same thing
e = self.theclass(2000, 12, 31)
self.assertEqual(d, e)
self.assertEqual(hash(d), hash(e))
dic = {d: 1}
dic[e] = 2
self.assertEqual(len(dic), 1)
self.assertEqual(dic[d], 2)
self.assertEqual(dic[e], 2)
d = self.theclass(2001, 1, 1)
# same thing
e = self.theclass(2001, 1, 1)
self.assertEqual(d, e)
self.assertEqual(hash(d), hash(e))
dic = {d: 1}
dic[e] = 2
self.assertEqual(len(dic), 1)
self.assertEqual(dic[d], 2)
self.assertEqual(dic[e], 2)
def test_computations(self):
a = self.theclass(2002, 1, 31)
b = self.theclass(1956, 1, 31)
diff = a-b
self.assertEqual(diff.days, 46*365 + len(range(1956, 2002, 4)))
self.assertEqual(diff.seconds, 0)
self.assertEqual(diff.microseconds, 0)
day = timedelta(1)
week = timedelta(7)
a = self.theclass(2002, 3, 2)
self.assertEqual(a + day, self.theclass(2002, 3, 3))
self.assertEqual(day + a, self.theclass(2002, 3, 3))
self.assertEqual(a - day, self.theclass(2002, 3, 1))
self.assertEqual(-day + a, self.theclass(2002, 3, 1))
self.assertEqual(a + week, self.theclass(2002, 3, 9))
self.assertEqual(a - week, self.theclass(2002, 2, 23))
self.assertEqual(a + 52*week, self.theclass(2003, 3, 1))
self.assertEqual(a - 52*week, self.theclass(2001, 3, 3))
self.assertEqual((a + week) - a, week)
self.assertEqual((a + day) - a, day)
self.assertEqual((a - week) - a, -week)
self.assertEqual((a - day) - a, -day)
self.assertEqual(a - (a + week), -week)
self.assertEqual(a - (a + day), -day)
self.assertEqual(a - (a - week), week)
self.assertEqual(a - (a - day), day)
# Add/sub ints, longs, floats should be illegal
for i in 1, 1L, 1.0:
self.assertRaises(TypeError, lambda: a+i)
self.assertRaises(TypeError, lambda: a-i)
self.assertRaises(TypeError, lambda: i+a)
self.assertRaises(TypeError, lambda: i-a)
# delta - date is senseless.
self.assertRaises(TypeError, lambda: day - a)
# mixing date and (delta or date) via * or // is senseless
self.assertRaises(TypeError, lambda: day * a)
self.assertRaises(TypeError, lambda: a * day)
self.assertRaises(TypeError, lambda: day // a)
self.assertRaises(TypeError, lambda: a // day)
self.assertRaises(TypeError, lambda: a * a)
self.assertRaises(TypeError, lambda: a // a)
# date + date is senseless
self.assertRaises(TypeError, lambda: a + a)
def test_overflow(self):
tiny = self.theclass.resolution
for delta in [tiny, timedelta(1), timedelta(2)]:
dt = self.theclass.min + delta
dt -= delta # no problem
self.assertRaises(OverflowError, dt.__sub__, delta)
self.assertRaises(OverflowError, dt.__add__, -delta)
dt = self.theclass.max - delta
dt += delta # no problem
self.assertRaises(OverflowError, dt.__add__, delta)
self.assertRaises(OverflowError, dt.__sub__, -delta)
def test_fromtimestamp(self):
import time
# Try an arbitrary fixed value.
year, month, day = 1999, 9, 19
ts = time.mktime((year, month, day, 0, 0, 0, 0, 0, -1))
d = self.theclass.fromtimestamp(ts)
self.assertEqual(d.year, year)
self.assertEqual(d.month, month)
self.assertEqual(d.day, day)
def test_insane_fromtimestamp(self):
# It's possible that some platform maps time_t to double,
# and that this test will fail there. This test should
# exempt such platforms (provided they return reasonable
# results!).
for insane in -1e200, 1e200:
self.assertRaises(ValueError, self.theclass.fromtimestamp,
insane)
def test_today(self):
import time
# We claim that today() is like fromtimestamp(time.time()), so
# prove it.
for dummy in range(3):
today = self.theclass.today()
ts = time.time()
todayagain = self.theclass.fromtimestamp(ts)
if today == todayagain:
break
# There are several legit reasons that could fail:
# 1. It recently became midnight, between the today() and the
# time() calls.
# 2. The platform time() has such fine resolution that we'll
# never get the same value twice.
# 3. The platform time() has poor resolution, and we just
# happened to call today() right before a resolution quantum
# boundary.
# 4. The system clock got fiddled between calls.
# In any case, wait a little while and try again.
time.sleep(0.1)
# It worked or it didn't. If it didn't, assume it's reason #2, and
# let the test pass if they're within half a second of each other.
if today != todayagain:
self.assertAlmostEqual(todayagain, today,
delta=timedelta(seconds=0.5))
def test_weekday(self):
for i in range(7):
# March 4, 2002 is a Monday
self.assertEqual(self.theclass(2002, 3, 4+i).weekday(), i)
self.assertEqual(self.theclass(2002, 3, 4+i).isoweekday(), i+1)
# January 2, 1956 is a Monday
self.assertEqual(self.theclass(1956, 1, 2+i).weekday(), i)
self.assertEqual(self.theclass(1956, 1, 2+i).isoweekday(), i+1)
def test_isocalendar(self):
# Check examples from
# http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
for i in range(7):
d = self.theclass(2003, 12, 22+i)
self.assertEqual(d.isocalendar(), (2003, 52, i+1))
d = self.theclass(2003, 12, 29) + timedelta(i)
self.assertEqual(d.isocalendar(), (2004, 1, i+1))
d = self.theclass(2004, 1, 5+i)
self.assertEqual(d.isocalendar(), (2004, 2, i+1))
d = self.theclass(2009, 12, 21+i)
self.assertEqual(d.isocalendar(), (2009, 52, i+1))
d = self.theclass(2009, 12, 28) + timedelta(i)
self.assertEqual(d.isocalendar(), (2009, 53, i+1))
d = self.theclass(2010, 1, 4+i)
self.assertEqual(d.isocalendar(), (2010, 1, i+1))
def test_iso_long_years(self):
# Calculate long ISO years and compare to table from
# http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
ISO_LONG_YEARS_TABLE = """
4 32 60 88
9 37 65 93
15 43 71 99
20 48 76
26 54 82
105 133 161 189
111 139 167 195
116 144 172
122 150 178
128 156 184
201 229 257 285
207 235 263 291
212 240 268 296
218 246 274
224 252 280
303 331 359 387
308 336 364 392
314 342 370 398
320 348 376
325 353 381
"""
iso_long_years = map(int, ISO_LONG_YEARS_TABLE.split())
iso_long_years.sort()
L = []
for i in range(400):
d = self.theclass(2000+i, 12, 31)
d1 = self.theclass(1600+i, 12, 31)
self.assertEqual(d.isocalendar()[1:], d1.isocalendar()[1:])
if d.isocalendar()[1] == 53:
L.append(i)
self.assertEqual(L, iso_long_years)
def test_isoformat(self):
t = self.theclass(2, 3, 2)
self.assertEqual(t.isoformat(), "0002-03-02")
def test_ctime(self):
t = self.theclass(2002, 3, 2)
self.assertEqual(t.ctime(), "Sat Mar 2 00:00:00 2002")
def test_strftime(self):
t = self.theclass(2005, 3, 2)
self.assertEqual(t.strftime("m:%m d:%d y:%y"), "m:03 d:02 y:05")
self.assertEqual(t.strftime(""), "") # SF bug #761337
self.assertEqual(t.strftime('x'*1000), 'x'*1000) # SF bug #1556784
self.assertRaises(TypeError, t.strftime) # needs an arg
self.assertRaises(TypeError, t.strftime, "one", "two") # too many args
self.assertRaises(TypeError, t.strftime, 42) # arg wrong type
# test that unicode input is allowed (issue 2782)
self.assertEqual(t.strftime(u"%m"), "03")
# A naive object replaces %z and %Z w/ empty strings.
self.assertEqual(t.strftime("'%z' '%Z'"), "'' ''")
#make sure that invalid format specifiers are handled correctly
#self.assertRaises(ValueError, t.strftime, "%e")
#self.assertRaises(ValueError, t.strftime, "%")
#self.assertRaises(ValueError, t.strftime, "%#")
#oh well, some systems just ignore those invalid ones.
#at least, excercise them to make sure that no crashes
#are generated
for f in ["%e", "%", "%#"]:
try:
t.strftime(f)
except ValueError:
pass
#check that this standard extension works
t.strftime("%f")
def test_format(self):
dt = self.theclass(2007, 9, 10)
self.assertEqual(dt.__format__(''), str(dt))
# check that a derived class's __str__() gets called
class A(self.theclass):
def __str__(self):
return 'A'
a = A(2007, 9, 10)
self.assertEqual(a.__format__(''), 'A')
# check that a derived class's strftime gets called
class B(self.theclass):
def strftime(self, format_spec):
return 'B'
b = B(2007, 9, 10)
self.assertEqual(b.__format__(''), str(dt))
for fmt in ["m:%m d:%d y:%y",
"m:%m d:%d y:%y H:%H M:%M S:%S",
"%z %Z",
]:
self.assertEqual(dt.__format__(fmt), dt.strftime(fmt))
self.assertEqual(a.__format__(fmt), dt.strftime(fmt))
self.assertEqual(b.__format__(fmt), 'B')
def test_resolution_info(self):
self.assertIsInstance(self.theclass.min, self.theclass)
self.assertIsInstance(self.theclass.max, self.theclass)
self.assertIsInstance(self.theclass.resolution, timedelta)
self.assertTrue(self.theclass.max > self.theclass.min)
def test_extreme_timedelta(self):
big = self.theclass.max - self.theclass.min
# 3652058 days, 23 hours, 59 minutes, 59 seconds, 999999 microseconds
n = (big.days*24*3600 + big.seconds)*1000000 + big.microseconds
# n == 315537897599999999 ~= 2**58.13
justasbig = timedelta(0, 0, n)
self.assertEqual(big, justasbig)
self.assertEqual(self.theclass.min + big, self.theclass.max)
self.assertEqual(self.theclass.max - big, self.theclass.min)
def test_timetuple(self):
for i in range(7):
# January 2, 1956 is a Monday (0)
d = self.theclass(1956, 1, 2+i)
t = d.timetuple()
self.assertEqual(t, (1956, 1, 2+i, 0, 0, 0, i, 2+i, -1))
# February 1, 1956 is a Wednesday (2)
d = self.theclass(1956, 2, 1+i)
t = d.timetuple()
self.assertEqual(t, (1956, 2, 1+i, 0, 0, 0, (2+i)%7, 32+i, -1))
# March 1, 1956 is a Thursday (3), and is the 31+29+1 = 61st day
# of the year.
d = self.theclass(1956, 3, 1+i)
t = d.timetuple()
self.assertEqual(t, (1956, 3, 1+i, 0, 0, 0, (3+i)%7, 61+i, -1))
self.assertEqual(t.tm_year, 1956)
self.assertEqual(t.tm_mon, 3)
self.assertEqual(t.tm_mday, 1+i)
self.assertEqual(t.tm_hour, 0)
self.assertEqual(t.tm_min, 0)
self.assertEqual(t.tm_sec, 0)
self.assertEqual(t.tm_wday, (3+i)%7)
self.assertEqual(t.tm_yday, 61+i)
self.assertEqual(t.tm_isdst, -1)
def test_pickling(self):
args = 6, 7, 23
orig = self.theclass(*args)
for pickler, unpickler, proto in pickle_choices:
green = pickler.dumps(orig, proto)
derived = unpickler.loads(green)
self.assertEqual(orig, derived)
def test_compare(self):
t1 = self.theclass(2, 3, 4)
t2 = self.theclass(2, 3, 4)
self.assertTrue(t1 == t2)
self.assertTrue(t1 <= t2)
self.assertTrue(t1 >= t2)
self.assertFalse(t1 != t2)
self.assertFalse(t1 < t2)
self.assertFalse(t1 > t2)
self.assertEqual(cmp(t1, t2), 0)
self.assertEqual(cmp(t2, t1), 0)
for args in (3, 3, 3), (2, 4, 4), (2, 3, 5):
t2 = self.theclass(*args) # this is larger than t1
self.assertTrue(t1 < t2)
self.assertTrue(t2 > t1)
self.assertTrue(t1 <= t2)
self.assertTrue(t2 >= t1)
self.assertTrue(t1 != t2)
self.assertTrue(t2 != t1)
self.assertFalse(t1 == t2)
self.assertFalse(t2 == t1)
self.assertFalse(t1 > t2)
self.assertFalse(t2 < t1)
self.assertFalse(t1 >= t2)
self.assertFalse(t2 <= t1)
self.assertEqual(cmp(t1, t2), -1)
self.assertEqual(cmp(t2, t1), 1)
for badarg in OTHERSTUFF:
self.assertEqual(t1 == badarg, False)
self.assertEqual(t1 != badarg, True)
self.assertEqual(badarg == t1, False)
self.assertEqual(badarg != t1, True)
self.assertRaises(TypeError, lambda: t1 < badarg)
self.assertRaises(TypeError, lambda: t1 > badarg)
self.assertRaises(TypeError, lambda: t1 >= badarg)
self.assertRaises(TypeError, lambda: badarg <= t1)
self.assertRaises(TypeError, lambda: badarg < t1)
self.assertRaises(TypeError, lambda: badarg > t1)
self.assertRaises(TypeError, lambda: badarg >= t1)
def test_mixed_compare(self):
our = self.theclass(2000, 4, 5)
self.assertRaises(TypeError, cmp, our, 1)
self.assertRaises(TypeError, cmp, 1, our)
class AnotherDateTimeClass(object):
def __cmp__(self, other):
# Return "equal" so calling this can't be confused with
# compare-by-address (which never says "equal" for distinct
# objects).
return 0
__hash__ = None # Silence Py3k warning
# This still errors, because date and datetime comparison raise
# TypeError instead of NotImplemented when they don't know what to
# do, in order to stop comparison from falling back to the default
# compare-by-address.
their = AnotherDateTimeClass()
self.assertRaises(TypeError, cmp, our, their)
# Oops: The next stab raises TypeError in the C implementation,
# but not in the Python implementation of datetime. The difference
# is due to that the Python implementation defines __cmp__ but
# the C implementation defines tp_richcompare. This is more pain
# to fix than it's worth, so commenting out the test.
# self.assertEqual(cmp(their, our), 0)
# But date and datetime comparison return NotImplemented instead if the
# other object has a timetuple attr. This gives the other object a
# chance to do the comparison.
class Comparable(AnotherDateTimeClass):
def timetuple(self):
return ()
their = Comparable()
self.assertEqual(cmp(our, their), 0)
self.assertEqual(cmp(their, our), 0)
self.assertTrue(our == their)
self.assertTrue(their == our)
def test_bool(self):
# All dates are considered true.
self.assertTrue(self.theclass.min)
self.assertTrue(self.theclass.max)
def test_strftime_out_of_range(self):
# For nasty technical reasons, we can't handle years before 1900.
cls = self.theclass
self.assertEqual(cls(1900, 1, 1).strftime("%Y"), "1900")
for y in 1, 49, 51, 99, 100, 1000, 1899:
self.assertRaises(ValueError, cls(y, 1, 1).strftime, "%Y")
def test_replace(self):
cls = self.theclass
args = [1, 2, 3]
base = cls(*args)
self.assertEqual(base, base.replace())
i = 0
for name, newval in (("year", 2),
("month", 3),
("day", 4)):
newargs = args[:]
newargs[i] = newval
expected = cls(*newargs)
got = base.replace(**{name: newval})
self.assertEqual(expected, got)
i += 1
# Out of bounds.
base = cls(2000, 2, 29)
self.assertRaises(ValueError, base.replace, year=2001)
def test_subclass_date(self):
class C(self.theclass):
theAnswer = 42
def __new__(cls, *args, **kws):
temp = kws.copy()
extra = temp.pop('extra')
result = self.theclass.__new__(cls, *args, **temp)
result.extra = extra
return result
def newmeth(self, start):
return start + self.year + self.month
args = 2003, 4, 14
dt1 = self.theclass(*args)
dt2 = C(*args, **{'extra': 7})
self.assertEqual(dt2.__class__, C)
self.assertEqual(dt2.theAnswer, 42)
self.assertEqual(dt2.extra, 7)
self.assertEqual(dt1.toordinal(), dt2.toordinal())
self.assertEqual(dt2.newmeth(-7), dt1.year + dt1.month - 7)
def test_pickling_subclass_date(self):
args = 6, 7, 23
orig = SubclassDate(*args)
for pickler, unpickler, proto in pickle_choices:
green = pickler.dumps(orig, proto)
derived = unpickler.loads(green)
self.assertEqual(orig, derived)
def test_backdoor_resistance(self):
# For fast unpickling, the constructor accepts a pickle string.
# This is a low-overhead backdoor. A user can (by intent or
# mistake) pass a string directly, which (if it's the right length)
# will get treated like a pickle, and bypass the normal sanity
# checks in the constructor. This can create insane objects.
# The constructor doesn't want to burn the time to validate all
# fields, but does check the month field. This stops, e.g.,
# datetime.datetime('1995-03-25') from yielding an insane object.
base = '1995-03-25'
if not issubclass(self.theclass, datetime):
base = base[:4]
for month_byte in '9', chr(0), chr(13), '\xff':
self.assertRaises(TypeError, self.theclass,
base[:2] + month_byte + base[3:])
for ord_byte in range(1, 13):
# This shouldn't blow up because of the month byte alone. If
# the implementation changes to do more-careful checking, it may
# blow up because other fields are insane.
self.theclass(base[:2] + chr(ord_byte) + base[3:])
#############################################################################
# datetime tests
class SubclassDatetime(datetime):
sub_var = 1
class TestDateTime(TestDate):
theclass = datetime
def test_basic_attributes(self):
dt = self.theclass(2002, 3, 1, 12, 0)
self.assertEqual(dt.year, 2002)
self.assertEqual(dt.month, 3)
self.assertEqual(dt.day, 1)
self.assertEqual(dt.hour, 12)
self.assertEqual(dt.minute, 0)
self.assertEqual(dt.second, 0)
self.assertEqual(dt.microsecond, 0)
def test_basic_attributes_nonzero(self):
# Make sure all attributes are non-zero so bugs in
# bit-shifting access show up.
dt = self.theclass(2002, 3, 1, 12, 59, 59, 8000)
self.assertEqual(dt.year, 2002)
self.assertEqual(dt.month, 3)
self.assertEqual(dt.day, 1)
self.assertEqual(dt.hour, 12)
self.assertEqual(dt.minute, 59)
self.assertEqual(dt.second, 59)
self.assertEqual(dt.microsecond, 8000)
def test_roundtrip(self):
for dt in (self.theclass(1, 2, 3, 4, 5, 6, 7),
self.theclass.now()):
# Verify dt -> string -> datetime identity.
s = repr(dt)
self.assertTrue(s.startswith('datetime.'))
s = s[9:]
dt2 = eval(s)
self.assertEqual(dt, dt2)
# Verify identity via reconstructing from pieces.
dt2 = self.theclass(dt.year, dt.month, dt.day,
dt.hour, dt.minute, dt.second,
dt.microsecond)
self.assertEqual(dt, dt2)
def test_isoformat(self):
t = self.theclass(2, 3, 2, 4, 5, 1, 123)
self.assertEqual(t.isoformat(), "0002-03-02T04:05:01.000123")
self.assertEqual(t.isoformat('T'), "0002-03-02T04:05:01.000123")
self.assertEqual(t.isoformat(' '), "0002-03-02 04:05:01.000123")
self.assertEqual(t.isoformat('\x00'), "0002-03-02\x0004:05:01.000123")
# str is ISO format with the separator forced to a blank.
self.assertEqual(str(t), "0002-03-02 04:05:01.000123")
t = self.theclass(2, 3, 2)
self.assertEqual(t.isoformat(), "0002-03-02T00:00:00")
self.assertEqual(t.isoformat('T'), "0002-03-02T00:00:00")
self.assertEqual(t.isoformat(' '), "0002-03-02 00:00:00")
# str is ISO format with the separator forced to a blank.
self.assertEqual(str(t), "0002-03-02 00:00:00")
def test_format(self):
dt = self.theclass(2007, 9, 10, 4, 5, 1, 123)
self.assertEqual(dt.__format__(''), str(dt))
# check that a derived class's __str__() gets called
class A(self.theclass):
def __str__(self):
return 'A'
a = A(2007, 9, 10, 4, 5, 1, 123)
self.assertEqual(a.__format__(''), 'A')
# check that a derived class's strftime gets called
class B(self.theclass):
def strftime(self, format_spec):
return 'B'
b = B(2007, 9, 10, 4, 5, 1, 123)
self.assertEqual(b.__format__(''), str(dt))
for fmt in ["m:%m d:%d y:%y",
"m:%m d:%d y:%y H:%H M:%M S:%S",
"%z %Z",
]:
self.assertEqual(dt.__format__(fmt), dt.strftime(fmt))
self.assertEqual(a.__format__(fmt), dt.strftime(fmt))
self.assertEqual(b.__format__(fmt), 'B')
def test_more_ctime(self):
# Test fields that TestDate doesn't touch.
import time
t = self.theclass(2002, 3, 2, 18, 3, 5, 123)
self.assertEqual(t.ctime(), "Sat Mar 2 18:03:05 2002")
# Oops! The next line fails on Win2K under MSVC 6, so it's commented
# out. The difference is that t.ctime() produces " 2" for the day,
# but platform ctime() produces "02" for the day. According to
# C99, t.ctime() is correct here.
# self.assertEqual(t.ctime(), time.ctime(time.mktime(t.timetuple())))
# So test a case where that difference doesn't matter.
t = self.theclass(2002, 3, 22, 18, 3, 5, 123)
self.assertEqual(t.ctime(), time.ctime(time.mktime(t.timetuple())))
def test_tz_independent_comparing(self):
dt1 = self.theclass(2002, 3, 1, 9, 0, 0)
dt2 = self.theclass(2002, 3, 1, 10, 0, 0)
dt3 = self.theclass(2002, 3, 1, 9, 0, 0)
self.assertEqual(dt1, dt3)
self.assertTrue(dt2 > dt3)
# Make sure comparison doesn't forget microseconds, and isn't done
# via comparing a float timestamp (an IEEE double doesn't have enough
# precision to span microsecond resolution across years 1 thru 9999,
# so comparing via timestamp necessarily calls some distinct values
# equal).
dt1 = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999998)
us = timedelta(microseconds=1)
dt2 = dt1 + us
self.assertEqual(dt2 - dt1, us)
self.assertTrue(dt1 < dt2)
def test_strftime_with_bad_tzname_replace(self):
# verify ok if tzinfo.tzname().replace() returns a non-string
class MyTzInfo(FixedOffset):
def tzname(self, dt):
class MyStr(str):
def replace(self, *args):
return None
return MyStr('name')
t = self.theclass(2005, 3, 2, 0, 0, 0, 0, MyTzInfo(3, 'name'))
self.assertRaises(TypeError, t.strftime, '%Z')
def test_bad_constructor_arguments(self):
# bad years
self.theclass(MINYEAR, 1, 1) # no exception
self.theclass(MAXYEAR, 1, 1) # no exception
self.assertRaises(ValueError, self.theclass, MINYEAR-1, 1, 1)
self.assertRaises(ValueError, self.theclass, MAXYEAR+1, 1, 1)
# bad months
self.theclass(2000, 1, 1) # no exception
self.theclass(2000, 12, 1) # no exception
self.assertRaises(ValueError, self.theclass, 2000, 0, 1)
self.assertRaises(ValueError, self.theclass, 2000, 13, 1)
# bad days
self.theclass(2000, 2, 29) # no exception
self.theclass(2004, 2, 29) # no exception
self.theclass(2400, 2, 29) # no exception
self.assertRaises(ValueError, self.theclass, 2000, 2, 30)
self.assertRaises(ValueError, self.theclass, 2001, 2, 29)
self.assertRaises(ValueError, self.theclass, 2100, 2, 29)
self.assertRaises(ValueError, self.theclass, 1900, 2, 29)
self.assertRaises(ValueError, self.theclass, 2000, 1, 0)
self.assertRaises(ValueError, self.theclass, 2000, 1, 32)
# bad hours
self.theclass(2000, 1, 31, 0) # no exception
self.theclass(2000, 1, 31, 23) # no exception
self.assertRaises(ValueError, self.theclass, 2000, 1, 31, -1)
self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 24)
# bad minutes
self.theclass(2000, 1, 31, 23, 0) # no exception
self.theclass(2000, 1, 31, 23, 59) # no exception
self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, -1)
self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, 60)
# bad seconds
self.theclass(2000, 1, 31, 23, 59, 0) # no exception
self.theclass(2000, 1, 31, 23, 59, 59) # no exception
self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, 59, -1)
self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, 59, 60)
# bad microseconds
self.theclass(2000, 1, 31, 23, 59, 59, 0) # no exception
self.theclass(2000, 1, 31, 23, 59, 59, 999999) # no exception
self.assertRaises(ValueError, self.theclass,
2000, 1, 31, 23, 59, 59, -1)
self.assertRaises(ValueError, self.theclass,
2000, 1, 31, 23, 59, 59,
1000000)
def test_hash_equality(self):
d = self.theclass(2000, 12, 31, 23, 30, 17)
e = self.theclass(2000, 12, 31, 23, 30, 17)
self.assertEqual(d, e)
self.assertEqual(hash(d), hash(e))
dic = {d: 1}
dic[e] = 2
self.assertEqual(len(dic), 1)
self.assertEqual(dic[d], 2)
self.assertEqual(dic[e], 2)
d = self.theclass(2001, 1, 1, 0, 5, 17)
e = self.theclass(2001, 1, 1, 0, 5, 17)
self.assertEqual(d, e)
self.assertEqual(hash(d), hash(e))
dic = {d: 1}
dic[e] = 2
self.assertEqual(len(dic), 1)
self.assertEqual(dic[d], 2)
self.assertEqual(dic[e], 2)
def test_computations(self):
a = self.theclass(2002, 1, 31)
b = self.theclass(1956, 1, 31)
diff = a-b
self.assertEqual(diff.days, 46*365 + len(range(1956, 2002, 4)))
self.assertEqual(diff.seconds, 0)
self.assertEqual(diff.microseconds, 0)
a = self.theclass(2002, 3, 2, 17, 6)
millisec = timedelta(0, 0, 1000)
hour = timedelta(0, 3600)
day = timedelta(1)
week = timedelta(7)
self.assertEqual(a + hour, self.theclass(2002, 3, 2, 18, 6))
self.assertEqual(hour + a, self.theclass(2002, 3, 2, 18, 6))
self.assertEqual(a + 10*hour, self.theclass(2002, 3, 3, 3, 6))
self.assertEqual(a - hour, self.theclass(2002, 3, 2, 16, 6))
self.assertEqual(-hour + a, self.theclass(2002, 3, 2, 16, 6))
self.assertEqual(a - hour, a + -hour)
self.assertEqual(a - 20*hour, self.theclass(2002, 3, 1, 21, 6))
self.assertEqual(a + day, self.theclass(2002, 3, 3, 17, 6))
self.assertEqual(a - day, self.theclass(2002, 3, 1, 17, 6))
self.assertEqual(a + week, self.theclass(2002, 3, 9, 17, 6))
self.assertEqual(a - week, self.theclass(2002, 2, 23, 17, 6))
self.assertEqual(a + 52*week, self.theclass(2003, 3, 1, 17, 6))
self.assertEqual(a - 52*week, self.theclass(2001, 3, 3, 17, 6))
self.assertEqual((a + week) - a, week)
self.assertEqual((a + day) - a, day)
self.assertEqual((a + hour) - a, hour)
self.assertEqual((a + millisec) - a, millisec)
self.assertEqual((a - week) - a, -week)
self.assertEqual((a - day) - a, -day)
self.assertEqual((a - hour) - a, -hour)
self.assertEqual((a - millisec) - a, -millisec)
self.assertEqual(a - (a + week), -week)
self.assertEqual(a - (a + day), -day)
self.assertEqual(a - (a + hour), -hour)
self.assertEqual(a - (a + millisec), -millisec)
self.assertEqual(a - (a - week), week)
self.assertEqual(a - (a - day), day)
self.assertEqual(a - (a - hour), hour)
self.assertEqual(a - (a - millisec), millisec)
self.assertEqual(a + (week + day + hour + millisec),
self.theclass(2002, 3, 10, 18, 6, 0, 1000))
self.assertEqual(a + (week + day + hour + millisec),
(((a + week) + day) + hour) + millisec)
self.assertEqual(a - (week + day + hour + millisec),
self.theclass(2002, 2, 22, 16, 5, 59, 999000))
self.assertEqual(a - (week + day + hour + millisec),
(((a - week) - day) - hour) - millisec)
# Add/sub ints, longs, floats should be illegal
for i in 1, 1L, 1.0:
self.assertRaises(TypeError, lambda: a+i)
self.assertRaises(TypeError, lambda: a-i)
self.assertRaises(TypeError, lambda: i+a)
self.assertRaises(TypeError, lambda: i-a)
# delta - datetime is senseless.
self.assertRaises(TypeError, lambda: day - a)
# mixing datetime and (delta or datetime) via * or // is senseless
self.assertRaises(TypeError, lambda: day * a)
self.assertRaises(TypeError, lambda: a * day)
self.assertRaises(TypeError, lambda: day // a)
self.assertRaises(TypeError, lambda: a // day)
self.assertRaises(TypeError, lambda: a * a)
self.assertRaises(TypeError, lambda: a // a)
# datetime + datetime is senseless
self.assertRaises(TypeError, lambda: a + a)
def test_pickling(self):
args = 6, 7, 23, 20, 59, 1, 64**2
orig = self.theclass(*args)
for pickler, unpickler, proto in pickle_choices:
green = pickler.dumps(orig, proto)
derived = unpickler.loads(green)
self.assertEqual(orig, derived)
def test_more_pickling(self):
a = self.theclass(2003, 2, 7, 16, 48, 37, 444116)
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
s = pickle.dumps(a, proto)
b = pickle.loads(s)
self.assertEqual(b.year, 2003)
self.assertEqual(b.month, 2)
self.assertEqual(b.day, 7)
def test_pickling_subclass_datetime(self):
args = 6, 7, 23, 20, 59, 1, 64**2
orig = SubclassDatetime(*args)
for pickler, unpickler, proto in pickle_choices:
green = pickler.dumps(orig, proto)
derived = unpickler.loads(green)
self.assertEqual(orig, derived)
def test_more_compare(self):
# The test_compare() inherited from TestDate covers the error cases.
# We just want to test lexicographic ordering on the members datetime
# has that date lacks.
args = [2000, 11, 29, 20, 58, 16, 999998]
t1 = self.theclass(*args)
t2 = self.theclass(*args)
self.assertTrue(t1 == t2)
self.assertTrue(t1 <= t2)
self.assertTrue(t1 >= t2)
self.assertFalse(t1 != t2)
self.assertFalse(t1 < t2)
self.assertFalse(t1 > t2)
self.assertEqual(cmp(t1, t2), 0)
self.assertEqual(cmp(t2, t1), 0)
for i in range(len(args)):
newargs = args[:]
newargs[i] = args[i] + 1
t2 = self.theclass(*newargs) # this is larger than t1
self.assertTrue(t1 < t2)
self.assertTrue(t2 > t1)
self.assertTrue(t1 <= t2)
self.assertTrue(t2 >= t1)
self.assertTrue(t1 != t2)
self.assertTrue(t2 != t1)
self.assertFalse(t1 == t2)
self.assertFalse(t2 == t1)
self.assertFalse(t1 > t2)
self.assertFalse(t2 < t1)
self.assertFalse(t1 >= t2)
self.assertFalse(t2 <= t1)
self.assertEqual(cmp(t1, t2), -1)
self.assertEqual(cmp(t2, t1), 1)
# A helper for timestamp constructor tests.
def verify_field_equality(self, expected, got):
self.assertEqual(expected.tm_year, got.year)
self.assertEqual(expected.tm_mon, got.month)
self.assertEqual(expected.tm_mday, got.day)
self.assertEqual(expected.tm_hour, got.hour)
self.assertEqual(expected.tm_min, got.minute)
self.assertEqual(expected.tm_sec, got.second)
def test_fromtimestamp(self):
import time
ts = time.time()
expected = time.localtime(ts)
got = self.theclass.fromtimestamp(ts)
self.verify_field_equality(expected, got)
def test_utcfromtimestamp(self):
import time
ts = time.time()
expected = time.gmtime(ts)
got = self.theclass.utcfromtimestamp(ts)
self.verify_field_equality(expected, got)
def test_microsecond_rounding(self):
# Test whether fromtimestamp "rounds up" floats that are less
# than one microsecond smaller than an integer.
self.assertEqual(self.theclass.fromtimestamp(0.9999999),
self.theclass.fromtimestamp(1))
def test_insane_fromtimestamp(self):
# It's possible that some platform maps time_t to double,
# and that this test will fail there. This test should
# exempt such platforms (provided they return reasonable
# results!).
for insane in -1e200, 1e200:
self.assertRaises(ValueError, self.theclass.fromtimestamp,
insane)
def test_insane_utcfromtimestamp(self):
# It's possible that some platform maps time_t to double,
# and that this test will fail there. This test should
# exempt such platforms (provided they return reasonable
# results!).
for insane in -1e200, 1e200:
self.assertRaises(ValueError, self.theclass.utcfromtimestamp,
insane)
@unittest.skipIf(sys.platform == "win32", "Windows doesn't accept negative timestamps")
def test_negative_float_fromtimestamp(self):
# The result is tz-dependent; at least test that this doesn't
# fail (like it did before bug 1646728 was fixed).
self.theclass.fromtimestamp(-1.05)
@unittest.skipIf(sys.platform == "win32", "Windows doesn't accept negative timestamps")
def test_negative_float_utcfromtimestamp(self):
d = self.theclass.utcfromtimestamp(-1.05)
self.assertEqual(d, self.theclass(1969, 12, 31, 23, 59, 58, 950000))
def test_utcnow(self):
import time
# Call it a success if utcnow() and utcfromtimestamp() are within
# a second of each other.
tolerance = timedelta(seconds=1)
for dummy in range(3):
from_now = self.theclass.utcnow()
from_timestamp = self.theclass.utcfromtimestamp(time.time())
if abs(from_timestamp - from_now) <= tolerance:
break
# Else try again a few times.
self.assertLessEqual(abs(from_timestamp - from_now), tolerance)
def test_strptime(self):
import _strptime
string = '2004-12-01 13:02:47.197'
format = '%Y-%m-%d %H:%M:%S.%f'
result, frac = _strptime._strptime(string, format)
expected = self.theclass(*(result[0:6]+(frac,)))
got = self.theclass.strptime(string, format)
self.assertEqual(expected, got)
def test_more_timetuple(self):
# This tests fields beyond those tested by the TestDate.test_timetuple.
t = self.theclass(2004, 12, 31, 6, 22, 33)
self.assertEqual(t.timetuple(), (2004, 12, 31, 6, 22, 33, 4, 366, -1))
self.assertEqual(t.timetuple(),
(t.year, t.month, t.day,
t.hour, t.minute, t.second,
t.weekday(),
t.toordinal() - date(t.year, 1, 1).toordinal() + 1,
-1))
tt = t.timetuple()
self.assertEqual(tt.tm_year, t.year)
self.assertEqual(tt.tm_mon, t.month)
self.assertEqual(tt.tm_mday, t.day)
self.assertEqual(tt.tm_hour, t.hour)
self.assertEqual(tt.tm_min, t.minute)
self.assertEqual(tt.tm_sec, t.second)
self.assertEqual(tt.tm_wday, t.weekday())
self.assertEqual(tt.tm_yday, t.toordinal() -
date(t.year, 1, 1).toordinal() + 1)
self.assertEqual(tt.tm_isdst, -1)
def test_more_strftime(self):
# This tests fields beyond those tested by the TestDate.test_strftime.
t = self.theclass(2004, 12, 31, 6, 22, 33, 47)
self.assertEqual(t.strftime("%m %d %y %f %S %M %H %j"),
"12 31 04 000047 33 22 06 366")
def test_extract(self):
dt = self.theclass(2002, 3, 4, 18, 45, 3, 1234)
self.assertEqual(dt.date(), date(2002, 3, 4))
self.assertEqual(dt.time(), time(18, 45, 3, 1234))
def test_combine(self):
d = date(2002, 3, 4)
t = time(18, 45, 3, 1234)
expected = self.theclass(2002, 3, 4, 18, 45, 3, 1234)
combine = self.theclass.combine
dt = combine(d, t)
self.assertEqual(dt, expected)
dt = combine(time=t, date=d)
self.assertEqual(dt, expected)
self.assertEqual(d, dt.date())
self.assertEqual(t, dt.time())
self.assertEqual(dt, combine(dt.date(), dt.time()))
self.assertRaises(TypeError, combine) # need an arg
self.assertRaises(TypeError, combine, d) # need two args
self.assertRaises(TypeError, combine, t, d) # args reversed
self.assertRaises(TypeError, combine, d, t, 1) # too many args
self.assertRaises(TypeError, combine, "date", "time") # wrong types
def test_replace(self):
cls = self.theclass
args = [1, 2, 3, 4, 5, 6, 7]
base = cls(*args)
self.assertEqual(base, base.replace())
i = 0
for name, newval in (("year", 2),
("month", 3),
("day", 4),
("hour", 5),
("minute", 6),
("second", 7),
("microsecond", 8)):
newargs = args[:]
newargs[i] = newval
expected = cls(*newargs)
got = base.replace(**{name: newval})
self.assertEqual(expected, got)
i += 1
# Out of bounds.
base = cls(2000, 2, 29)
self.assertRaises(ValueError, base.replace, year=2001)
def test_astimezone(self):
# Pretty boring! The TZ test is more interesting here. astimezone()
# simply can't be applied to a naive object.
dt = self.theclass.now()
f = FixedOffset(44, "")
self.assertRaises(TypeError, dt.astimezone) # not enough args
self.assertRaises(TypeError, dt.astimezone, f, f) # too many args
self.assertRaises(TypeError, dt.astimezone, dt) # arg wrong type
self.assertRaises(ValueError, dt.astimezone, f) # naive
self.assertRaises(ValueError, dt.astimezone, tz=f) # naive
class Bogus(tzinfo):
def utcoffset(self, dt): return None
def dst(self, dt): return timedelta(0)
bog = Bogus()
self.assertRaises(ValueError, dt.astimezone, bog) # naive
class AlsoBogus(tzinfo):
def utcoffset(self, dt): return timedelta(0)
def dst(self, dt): return None
alsobog = AlsoBogus()
self.assertRaises(ValueError, dt.astimezone, alsobog) # also naive
def test_subclass_datetime(self):
class C(self.theclass):
theAnswer = 42
def __new__(cls, *args, **kws):
temp = kws.copy()
extra = temp.pop('extra')
result = self.theclass.__new__(cls, *args, **temp)
result.extra = extra
return result
def newmeth(self, start):
return start + self.year + self.month + self.second
args = 2003, 4, 14, 12, 13, 41
dt1 = self.theclass(*args)
dt2 = C(*args, **{'extra': 7})
self.assertEqual(dt2.__class__, C)
self.assertEqual(dt2.theAnswer, 42)
self.assertEqual(dt2.extra, 7)
self.assertEqual(dt1.toordinal(), dt2.toordinal())
self.assertEqual(dt2.newmeth(-7), dt1.year + dt1.month +
dt1.second - 7)
class SubclassTime(time):
sub_var = 1
class TestTime(HarmlessMixedComparison, unittest.TestCase):
theclass = time
def test_basic_attributes(self):
t = self.theclass(12, 0)
self.assertEqual(t.hour, 12)
self.assertEqual(t.minute, 0)
self.assertEqual(t.second, 0)
self.assertEqual(t.microsecond, 0)
def test_basic_attributes_nonzero(self):
# Make sure all attributes are non-zero so bugs in
# bit-shifting access show up.
t = self.theclass(12, 59, 59, 8000)
self.assertEqual(t.hour, 12)
self.assertEqual(t.minute, 59)
self.assertEqual(t.second, 59)
self.assertEqual(t.microsecond, 8000)
def test_roundtrip(self):
t = self.theclass(1, 2, 3, 4)
# Verify t -> string -> time identity.
s = repr(t)
self.assertTrue(s.startswith('datetime.'))
s = s[9:]
t2 = eval(s)
self.assertEqual(t, t2)
# Verify identity via reconstructing from pieces.
t2 = self.theclass(t.hour, t.minute, t.second,
t.microsecond)
self.assertEqual(t, t2)
def test_comparing(self):
args = [1, 2, 3, 4]
t1 = self.theclass(*args)
t2 = self.theclass(*args)
self.assertTrue(t1 == t2)
self.assertTrue(t1 <= t2)
self.assertTrue(t1 >= t2)
self.assertFalse(t1 != t2)
self.assertFalse(t1 < t2)
self.assertFalse(t1 > t2)
self.assertEqual(cmp(t1, t2), 0)
self.assertEqual(cmp(t2, t1), 0)
for i in range(len(args)):
newargs = args[:]
newargs[i] = args[i] + 1
t2 = self.theclass(*newargs) # this is larger than t1
self.assertTrue(t1 < t2)
self.assertTrue(t2 > t1)
self.assertTrue(t1 <= t2)
self.assertTrue(t2 >= t1)
self.assertTrue(t1 != t2)
self.assertTrue(t2 != t1)
self.assertFalse(t1 == t2)
self.assertFalse(t2 == t1)
self.assertFalse(t1 > t2)
self.assertFalse(t2 < t1)
self.assertFalse(t1 >= t2)
self.assertFalse(t2 <= t1)
self.assertEqual(cmp(t1, t2), -1)
self.assertEqual(cmp(t2, t1), 1)
for badarg in OTHERSTUFF:
self.assertEqual(t1 == badarg, False)
self.assertEqual(t1 != badarg, True)
self.assertEqual(badarg == t1, False)
self.assertEqual(badarg != t1, True)
self.assertRaises(TypeError, lambda: t1 <= badarg)
self.assertRaises(TypeError, lambda: t1 < badarg)
self.assertRaises(TypeError, lambda: t1 > badarg)
self.assertRaises(TypeError, lambda: t1 >= badarg)
self.assertRaises(TypeError, lambda: badarg <= t1)
self.assertRaises(TypeError, lambda: badarg < t1)
self.assertRaises(TypeError, lambda: badarg > t1)
self.assertRaises(TypeError, lambda: badarg >= t1)
def test_bad_constructor_arguments(self):
# bad hours
self.theclass(0, 0) # no exception
self.theclass(23, 0) # no exception
self.assertRaises(ValueError, self.theclass, -1, 0)
self.assertRaises(ValueError, self.theclass, 24, 0)
# bad minutes
self.theclass(23, 0) # no exception
self.theclass(23, 59) # no exception
self.assertRaises(ValueError, self.theclass, 23, -1)
self.assertRaises(ValueError, self.theclass, 23, 60)
# bad seconds
self.theclass(23, 59, 0) # no exception
self.theclass(23, 59, 59) # no exception
self.assertRaises(ValueError, self.theclass, 23, 59, -1)
self.assertRaises(ValueError, self.theclass, 23, 59, 60)
# bad microseconds
self.theclass(23, 59, 59, 0) # no exception
self.theclass(23, 59, 59, 999999) # no exception
self.assertRaises(ValueError, self.theclass, 23, 59, 59, -1)
self.assertRaises(ValueError, self.theclass, 23, 59, 59, 1000000)
def test_hash_equality(self):
d = self.theclass(23, 30, 17)
e = self.theclass(23, 30, 17)
self.assertEqual(d, e)
self.assertEqual(hash(d), hash(e))
dic = {d: 1}
dic[e] = 2
self.assertEqual(len(dic), 1)
self.assertEqual(dic[d], 2)
self.assertEqual(dic[e], 2)
d = self.theclass(0, 5, 17)
e = self.theclass(0, 5, 17)
self.assertEqual(d, e)
self.assertEqual(hash(d), hash(e))
dic = {d: 1}
dic[e] = 2
self.assertEqual(len(dic), 1)
self.assertEqual(dic[d], 2)
self.assertEqual(dic[e], 2)
def test_isoformat(self):
t = self.theclass(4, 5, 1, 123)
self.assertEqual(t.isoformat(), "04:05:01.000123")
self.assertEqual(t.isoformat(), str(t))
t = self.theclass()
self.assertEqual(t.isoformat(), "00:00:00")
self.assertEqual(t.isoformat(), str(t))
t = self.theclass(microsecond=1)
self.assertEqual(t.isoformat(), "00:00:00.000001")
self.assertEqual(t.isoformat(), str(t))
t = self.theclass(microsecond=10)
self.assertEqual(t.isoformat(), "00:00:00.000010")
self.assertEqual(t.isoformat(), str(t))
t = self.theclass(microsecond=100)
self.assertEqual(t.isoformat(), "00:00:00.000100")
self.assertEqual(t.isoformat(), str(t))
t = self.theclass(microsecond=1000)
self.assertEqual(t.isoformat(), "00:00:00.001000")
self.assertEqual(t.isoformat(), str(t))
t = self.theclass(microsecond=10000)
self.assertEqual(t.isoformat(), "00:00:00.010000")
self.assertEqual(t.isoformat(), str(t))
t = self.theclass(microsecond=100000)
self.assertEqual(t.isoformat(), "00:00:00.100000")
self.assertEqual(t.isoformat(), str(t))
def test_1653736(self):
# verify it doesn't accept extra keyword arguments
t = self.theclass(second=1)
self.assertRaises(TypeError, t.isoformat, foo=3)
def test_strftime(self):
t = self.theclass(1, 2, 3, 4)
self.assertEqual(t.strftime('%H %M %S %f'), "01 02 03 000004")
# A naive object replaces %z and %Z with empty strings.
self.assertEqual(t.strftime("'%z' '%Z'"), "'' ''")
def test_format(self):
t = self.theclass(1, 2, 3, 4)
self.assertEqual(t.__format__(''), str(t))
# check that a derived class's __str__() gets called
class A(self.theclass):
def __str__(self):
return 'A'
a = A(1, 2, 3, 4)
self.assertEqual(a.__format__(''), 'A')
# check that a derived class's strftime gets called
class B(self.theclass):
def strftime(self, format_spec):
return 'B'
b = B(1, 2, 3, 4)
self.assertEqual(b.__format__(''), str(t))
for fmt in ['%H %M %S',
]:
self.assertEqual(t.__format__(fmt), t.strftime(fmt))
self.assertEqual(a.__format__(fmt), t.strftime(fmt))
self.assertEqual(b.__format__(fmt), 'B')
def test_str(self):
self.assertEqual(str(self.theclass(1, 2, 3, 4)), "01:02:03.000004")
self.assertEqual(str(self.theclass(10, 2, 3, 4000)), "10:02:03.004000")
self.assertEqual(str(self.theclass(0, 2, 3, 400000)), "00:02:03.400000")
self.assertEqual(str(self.theclass(12, 2, 3, 0)), "12:02:03")
self.assertEqual(str(self.theclass(23, 15, 0, 0)), "23:15:00")
def test_repr(self):
name = 'datetime.' + self.theclass.__name__
self.assertEqual(repr(self.theclass(1, 2, 3, 4)),
"%s(1, 2, 3, 4)" % name)
self.assertEqual(repr(self.theclass(10, 2, 3, 4000)),
"%s(10, 2, 3, 4000)" % name)
self.assertEqual(repr(self.theclass(0, 2, 3, 400000)),
"%s(0, 2, 3, 400000)" % name)
self.assertEqual(repr(self.theclass(12, 2, 3, 0)),
"%s(12, 2, 3)" % name)
self.assertEqual(repr(self.theclass(23, 15, 0, 0)),
"%s(23, 15)" % name)
def test_resolution_info(self):
self.assertIsInstance(self.theclass.min, self.theclass)
self.assertIsInstance(self.theclass.max, self.theclass)
self.assertIsInstance(self.theclass.resolution, timedelta)
self.assertTrue(self.theclass.max > self.theclass.min)
def test_pickling(self):
args = 20, 59, 16, 64**2
orig = self.theclass(*args)
for pickler, unpickler, proto in pickle_choices:
green = pickler.dumps(orig, proto)
derived = unpickler.loads(green)
self.assertEqual(orig, derived)
def test_pickling_subclass_time(self):
args = 20, 59, 16, 64**2
orig = SubclassTime(*args)
for pickler, unpickler, proto in pickle_choices:
green = pickler.dumps(orig, proto)
derived = unpickler.loads(green)
self.assertEqual(orig, derived)
def test_bool(self):
cls = self.theclass
self.assertTrue(cls(1))
self.assertTrue(cls(0, 1))
self.assertTrue(cls(0, 0, 1))
self.assertTrue(cls(0, 0, 0, 1))
self.assertFalse(cls(0))
self.assertFalse(cls())
def test_replace(self):
cls = self.theclass
args = [1, 2, 3, 4]
base = cls(*args)
self.assertEqual(base, base.replace())
i = 0
for name, newval in (("hour", 5),
("minute", 6),
("second", 7),
("microsecond", 8)):
newargs = args[:]
newargs[i] = newval
expected = cls(*newargs)
got = base.replace(**{name: newval})
self.assertEqual(expected, got)
i += 1
# Out of bounds.
base = cls(1)
self.assertRaises(ValueError, base.replace, hour=24)
self.assertRaises(ValueError, base.replace, minute=-1)
self.assertRaises(ValueError, base.replace, second=100)
self.assertRaises(ValueError, base.replace, microsecond=1000000)
def test_subclass_time(self):
class C(self.theclass):
theAnswer = 42
def __new__(cls, *args, **kws):
temp = kws.copy()
extra = temp.pop('extra')
result = self.theclass.__new__(cls, *args, **temp)
result.extra = extra
return result
def newmeth(self, start):
return start + self.hour + self.second
args = 4, 5, 6
dt1 = self.theclass(*args)
dt2 = C(*args, **{'extra': 7})
self.assertEqual(dt2.__class__, C)
self.assertEqual(dt2.theAnswer, 42)
self.assertEqual(dt2.extra, 7)
self.assertEqual(dt1.isoformat(), dt2.isoformat())
self.assertEqual(dt2.newmeth(-7), dt1.hour + dt1.second - 7)
def test_backdoor_resistance(self):
# see TestDate.test_backdoor_resistance().
base = '2:59.0'
for hour_byte in ' ', '9', chr(24), '\xff':
self.assertRaises(TypeError, self.theclass,
hour_byte + base[1:])
# A mixin for classes with a tzinfo= argument. Subclasses must define
# theclass as a class atribute, and theclass(1, 1, 1, tzinfo=whatever)
# must be legit (which is true for time and datetime).
class TZInfoBase:
def test_argument_passing(self):
cls = self.theclass
# A datetime passes itself on, a time passes None.
class introspective(tzinfo):
def tzname(self, dt): return dt and "real" or "none"
def utcoffset(self, dt):
return timedelta(minutes = dt and 42 or -42)
dst = utcoffset
obj = cls(1, 2, 3, tzinfo=introspective())
expected = cls is time and "none" or "real"
self.assertEqual(obj.tzname(), expected)
expected = timedelta(minutes=(cls is time and -42 or 42))
self.assertEqual(obj.utcoffset(), expected)
self.assertEqual(obj.dst(), expected)
def test_bad_tzinfo_classes(self):
cls = self.theclass
self.assertRaises(TypeError, cls, 1, 1, 1, tzinfo=12)
class NiceTry(object):
def __init__(self): pass
def utcoffset(self, dt): pass
self.assertRaises(TypeError, cls, 1, 1, 1, tzinfo=NiceTry)
class BetterTry(tzinfo):
def __init__(self): pass
def utcoffset(self, dt): pass
b = BetterTry()
t = cls(1, 1, 1, tzinfo=b)
self.assertIs(t.tzinfo, b)
def test_utc_offset_out_of_bounds(self):
class Edgy(tzinfo):
def __init__(self, offset):
self.offset = timedelta(minutes=offset)
def utcoffset(self, dt):
return self.offset
cls = self.theclass
for offset, legit in ((-1440, False),
(-1439, True),
(1439, True),
(1440, False)):
if cls is time:
t = cls(1, 2, 3, tzinfo=Edgy(offset))
elif cls is datetime:
t = cls(6, 6, 6, 1, 2, 3, tzinfo=Edgy(offset))
else:
assert 0, "impossible"
if legit:
aofs = abs(offset)
h, m = divmod(aofs, 60)
tag = "%c%02d:%02d" % (offset < 0 and '-' or '+', h, m)
if isinstance(t, datetime):
t = t.timetz()
self.assertEqual(str(t), "01:02:03" + tag)
else:
self.assertRaises(ValueError, str, t)
def test_tzinfo_classes(self):
cls = self.theclass
class C1(tzinfo):
def utcoffset(self, dt): return None
def dst(self, dt): return None
def tzname(self, dt): return None
for t in (cls(1, 1, 1),
cls(1, 1, 1, tzinfo=None),
cls(1, 1, 1, tzinfo=C1())):
self.assertIsNone(t.utcoffset())
self.assertIsNone(t.dst())
self.assertIsNone(t.tzname())
class C3(tzinfo):
def utcoffset(self, dt): return timedelta(minutes=-1439)
def dst(self, dt): return timedelta(minutes=1439)
def tzname(self, dt): return "aname"
t = cls(1, 1, 1, tzinfo=C3())
self.assertEqual(t.utcoffset(), timedelta(minutes=-1439))
self.assertEqual(t.dst(), timedelta(minutes=1439))
self.assertEqual(t.tzname(), "aname")
# Wrong types.
class C4(tzinfo):
def utcoffset(self, dt): return "aname"
def dst(self, dt): return 7
def tzname(self, dt): return 0
t = cls(1, 1, 1, tzinfo=C4())
self.assertRaises(TypeError, t.utcoffset)
self.assertRaises(TypeError, t.dst)
self.assertRaises(TypeError, t.tzname)
# Offset out of range.
class C6(tzinfo):
def utcoffset(self, dt): return timedelta(hours=-24)
def dst(self, dt): return timedelta(hours=24)
t = cls(1, 1, 1, tzinfo=C6())
self.assertRaises(ValueError, t.utcoffset)
self.assertRaises(ValueError, t.dst)
# Not a whole number of minutes.
class C7(tzinfo):
def utcoffset(self, dt): return timedelta(seconds=61)
def dst(self, dt): return timedelta(microseconds=-81)
t = cls(1, 1, 1, tzinfo=C7())
self.assertRaises(ValueError, t.utcoffset)
self.assertRaises(ValueError, t.dst)
def test_aware_compare(self):
cls = self.theclass
# Ensure that utcoffset() gets ignored if the comparands have
# the same tzinfo member.
class OperandDependentOffset(tzinfo):
def utcoffset(self, t):
if t.minute < 10:
# d0 and d1 equal after adjustment
return timedelta(minutes=t.minute)
else:
# d2 off in the weeds
return timedelta(minutes=59)
base = cls(8, 9, 10, tzinfo=OperandDependentOffset())
d0 = base.replace(minute=3)
d1 = base.replace(minute=9)
d2 = base.replace(minute=11)
for x in d0, d1, d2:
for y in d0, d1, d2:
got = cmp(x, y)
expected = cmp(x.minute, y.minute)
self.assertEqual(got, expected)
# However, if they're different members, uctoffset is not ignored.
# Note that a time can't actually have an operand-depedent offset,
# though (and time.utcoffset() passes None to tzinfo.utcoffset()),
# so skip this test for time.
if cls is not time:
d0 = base.replace(minute=3, tzinfo=OperandDependentOffset())
d1 = base.replace(minute=9, tzinfo=OperandDependentOffset())
d2 = base.replace(minute=11, tzinfo=OperandDependentOffset())
for x in d0, d1, d2:
for y in d0, d1, d2:
got = cmp(x, y)
if (x is d0 or x is d1) and (y is d0 or y is d1):
expected = 0
elif x is y is d2:
expected = 0
elif x is d2:
expected = -1
else:
assert y is d2
expected = 1
self.assertEqual(got, expected)
# Testing time objects with a non-None tzinfo.
class TestTimeTZ(TestTime, TZInfoBase, unittest.TestCase):
theclass = time
def test_empty(self):
t = self.theclass()
self.assertEqual(t.hour, 0)
self.assertEqual(t.minute, 0)
self.assertEqual(t.second, 0)
self.assertEqual(t.microsecond, 0)
self.assertIsNone(t.tzinfo)
def test_zones(self):
est = FixedOffset(-300, "EST", 1)
utc = FixedOffset(0, "UTC", -2)
met = FixedOffset(60, "MET", 3)
t1 = time( 7, 47, tzinfo=est)
t2 = time(12, 47, tzinfo=utc)
t3 = time(13, 47, tzinfo=met)
t4 = time(microsecond=40)
t5 = time(microsecond=40, tzinfo=utc)
self.assertEqual(t1.tzinfo, est)
self.assertEqual(t2.tzinfo, utc)
self.assertEqual(t3.tzinfo, met)
self.assertIsNone(t4.tzinfo)
self.assertEqual(t5.tzinfo, utc)
self.assertEqual(t1.utcoffset(), timedelta(minutes=-300))
self.assertEqual(t2.utcoffset(), timedelta(minutes=0))
self.assertEqual(t3.utcoffset(), timedelta(minutes=60))
self.assertIsNone(t4.utcoffset())
self.assertRaises(TypeError, t1.utcoffset, "no args")
self.assertEqual(t1.tzname(), "EST")
self.assertEqual(t2.tzname(), "UTC")
self.assertEqual(t3.tzname(), "MET")
self.assertIsNone(t4.tzname())
self.assertRaises(TypeError, t1.tzname, "no args")
self.assertEqual(t1.dst(), timedelta(minutes=1))
self.assertEqual(t2.dst(), timedelta(minutes=-2))
self.assertEqual(t3.dst(), timedelta(minutes=3))
self.assertIsNone(t4.dst())
self.assertRaises(TypeError, t1.dst, "no args")
self.assertEqual(hash(t1), hash(t2))
self.assertEqual(hash(t1), hash(t3))
self.assertEqual(hash(t2), hash(t3))
self.assertEqual(t1, t2)
self.assertEqual(t1, t3)
self.assertEqual(t2, t3)
self.assertRaises(TypeError, lambda: t4 == t5) # mixed tz-aware & naive
self.assertRaises(TypeError, lambda: t4 < t5) # mixed tz-aware & naive
self.assertRaises(TypeError, lambda: t5 < t4) # mixed tz-aware & naive
self.assertEqual(str(t1), "07:47:00-05:00")
self.assertEqual(str(t2), "12:47:00+00:00")
self.assertEqual(str(t3), "13:47:00+01:00")
self.assertEqual(str(t4), "00:00:00.000040")
self.assertEqual(str(t5), "00:00:00.000040+00:00")
self.assertEqual(t1.isoformat(), "07:47:00-05:00")
self.assertEqual(t2.isoformat(), "12:47:00+00:00")
self.assertEqual(t3.isoformat(), "13:47:00+01:00")
self.assertEqual(t4.isoformat(), "00:00:00.000040")
self.assertEqual(t5.isoformat(), "00:00:00.000040+00:00")
d = 'datetime.time'
self.assertEqual(repr(t1), d + "(7, 47, tzinfo=est)")
self.assertEqual(repr(t2), d + "(12, 47, tzinfo=utc)")
self.assertEqual(repr(t3), d + "(13, 47, tzinfo=met)")
self.assertEqual(repr(t4), d + "(0, 0, 0, 40)")
self.assertEqual(repr(t5), d + "(0, 0, 0, 40, tzinfo=utc)")
self.assertEqual(t1.strftime("%H:%M:%S %%Z=%Z %%z=%z"),
"07:47:00 %Z=EST %z=-0500")
self.assertEqual(t2.strftime("%H:%M:%S %Z %z"), "12:47:00 UTC +0000")
self.assertEqual(t3.strftime("%H:%M:%S %Z %z"), "13:47:00 MET +0100")
yuck = FixedOffset(-1439, "%z %Z %%z%%Z")
t1 = time(23, 59, tzinfo=yuck)
self.assertEqual(t1.strftime("%H:%M %%Z='%Z' %%z='%z'"),
"23:59 %Z='%z %Z %%z%%Z' %z='-2359'")
# Check that an invalid tzname result raises an exception.
class Badtzname(tzinfo):
def tzname(self, dt): return 42
t = time(2, 3, 4, tzinfo=Badtzname())
self.assertEqual(t.strftime("%H:%M:%S"), "02:03:04")
self.assertRaises(TypeError, t.strftime, "%Z")
def test_hash_edge_cases(self):
# Offsets that overflow a basic time.
t1 = self.theclass(0, 1, 2, 3, tzinfo=FixedOffset(1439, ""))
t2 = self.theclass(0, 0, 2, 3, tzinfo=FixedOffset(1438, ""))
self.assertEqual(hash(t1), hash(t2))
t1 = self.theclass(23, 58, 6, 100, tzinfo=FixedOffset(-1000, ""))
t2 = self.theclass(23, 48, 6, 100, tzinfo=FixedOffset(-1010, ""))
self.assertEqual(hash(t1), hash(t2))
def test_pickling(self):
# Try one without a tzinfo.
args = 20, 59, 16, 64**2
orig = self.theclass(*args)
for pickler, unpickler, proto in pickle_choices:
green = pickler.dumps(orig, proto)
derived = unpickler.loads(green)
self.assertEqual(orig, derived)
# Try one with a tzinfo.
tinfo = PicklableFixedOffset(-300, 'cookie')
orig = self.theclass(5, 6, 7, tzinfo=tinfo)
for pickler, unpickler, proto in pickle_choices:
green = pickler.dumps(orig, proto)
derived = unpickler.loads(green)
self.assertEqual(orig, derived)
self.assertIsInstance(derived.tzinfo, PicklableFixedOffset)
self.assertEqual(derived.utcoffset(), timedelta(minutes=-300))
self.assertEqual(derived.tzname(), 'cookie')
def test_more_bool(self):
# Test cases with non-None tzinfo.
cls = self.theclass
t = cls(0, tzinfo=FixedOffset(-300, ""))
self.assertTrue(t)
t = cls(5, tzinfo=FixedOffset(-300, ""))
self.assertTrue(t)
t = cls(5, tzinfo=FixedOffset(300, ""))
self.assertFalse(t)
t = cls(23, 59, tzinfo=FixedOffset(23*60 + 59, ""))
self.assertFalse(t)
# Mostly ensuring this doesn't overflow internally.
t = cls(0, tzinfo=FixedOffset(23*60 + 59, ""))
self.assertTrue(t)
# But this should yield a value error -- the utcoffset is bogus.
t = cls(0, tzinfo=FixedOffset(24*60, ""))
self.assertRaises(ValueError, lambda: bool(t))
# Likewise.
t = cls(0, tzinfo=FixedOffset(-24*60, ""))
self.assertRaises(ValueError, lambda: bool(t))
def test_replace(self):
cls = self.theclass
z100 = FixedOffset(100, "+100")
zm200 = FixedOffset(timedelta(minutes=-200), "-200")
args = [1, 2, 3, 4, z100]
base = cls(*args)
self.assertEqual(base, base.replace())
i = 0
for name, newval in (("hour", 5),
("minute", 6),
("second", 7),
("microsecond", 8),
("tzinfo", zm200)):
newargs = args[:]
newargs[i] = newval
expected = cls(*newargs)
got = base.replace(**{name: newval})
self.assertEqual(expected, got)
i += 1
# Ensure we can get rid of a tzinfo.
self.assertEqual(base.tzname(), "+100")
base2 = base.replace(tzinfo=None)
self.assertIsNone(base2.tzinfo)
self.assertIsNone(base2.tzname())
# Ensure we can add one.
base3 = base2.replace(tzinfo=z100)
self.assertEqual(base, base3)
self.assertIs(base.tzinfo, base3.tzinfo)
# Out of bounds.
base = cls(1)
self.assertRaises(ValueError, base.replace, hour=24)
self.assertRaises(ValueError, base.replace, minute=-1)
self.assertRaises(ValueError, base.replace, second=100)
self.assertRaises(ValueError, base.replace, microsecond=1000000)
def test_mixed_compare(self):
t1 = time(1, 2, 3)
t2 = time(1, 2, 3)
self.assertEqual(t1, t2)
t2 = t2.replace(tzinfo=None)
self.assertEqual(t1, t2)
t2 = t2.replace(tzinfo=FixedOffset(None, ""))
self.assertEqual(t1, t2)
t2 = t2.replace(tzinfo=FixedOffset(0, ""))
self.assertRaises(TypeError, lambda: t1 == t2)
# In time w/ identical tzinfo objects, utcoffset is ignored.
class Varies(tzinfo):
def __init__(self):
self.offset = timedelta(minutes=22)
def utcoffset(self, t):
self.offset += timedelta(minutes=1)
return self.offset
v = Varies()
t1 = t2.replace(tzinfo=v)
t2 = t2.replace(tzinfo=v)
self.assertEqual(t1.utcoffset(), timedelta(minutes=23))
self.assertEqual(t2.utcoffset(), timedelta(minutes=24))
self.assertEqual(t1, t2)
# But if they're not identical, it isn't ignored.
t2 = t2.replace(tzinfo=Varies())
self.assertTrue(t1 < t2) # t1's offset counter still going up
def test_subclass_timetz(self):
class C(self.theclass):
theAnswer = 42
def __new__(cls, *args, **kws):
temp = kws.copy()
extra = temp.pop('extra')
result = self.theclass.__new__(cls, *args, **temp)
result.extra = extra
return result
def newmeth(self, start):
return start + self.hour + self.second
args = 4, 5, 6, 500, FixedOffset(-300, "EST", 1)
dt1 = self.theclass(*args)
dt2 = C(*args, **{'extra': 7})
self.assertEqual(dt2.__class__, C)
self.assertEqual(dt2.theAnswer, 42)
self.assertEqual(dt2.extra, 7)
self.assertEqual(dt1.utcoffset(), dt2.utcoffset())
self.assertEqual(dt2.newmeth(-7), dt1.hour + dt1.second - 7)
# Testing datetime objects with a non-None tzinfo.
class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase):
theclass = datetime
def test_trivial(self):
dt = self.theclass(1, 2, 3, 4, 5, 6, 7)
self.assertEqual(dt.year, 1)
self.assertEqual(dt.month, 2)
self.assertEqual(dt.day, 3)
self.assertEqual(dt.hour, 4)
self.assertEqual(dt.minute, 5)
self.assertEqual(dt.second, 6)
self.assertEqual(dt.microsecond, 7)
self.assertEqual(dt.tzinfo, None)
def test_even_more_compare(self):
# The test_compare() and test_more_compare() inherited from TestDate
# and TestDateTime covered non-tzinfo cases.
# Smallest possible after UTC adjustment.
t1 = self.theclass(1, 1, 1, tzinfo=FixedOffset(1439, ""))
# Largest possible after UTC adjustment.
t2 = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999999,
tzinfo=FixedOffset(-1439, ""))
# Make sure those compare correctly, and w/o overflow.
self.assertTrue(t1 < t2)
self.assertTrue(t1 != t2)
self.assertTrue(t2 > t1)
self.assertTrue(t1 == t1)
self.assertTrue(t2 == t2)
# Equal afer adjustment.
t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(1, ""))
t2 = self.theclass(2, 1, 1, 3, 13, tzinfo=FixedOffset(3*60+13+2, ""))
self.assertEqual(t1, t2)
# Change t1 not to subtract a minute, and t1 should be larger.
t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(0, ""))
self.assertTrue(t1 > t2)
# Change t1 to subtract 2 minutes, and t1 should be smaller.
t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(2, ""))
self.assertTrue(t1 < t2)
# Back to the original t1, but make seconds resolve it.
t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(1, ""),
second=1)
self.assertTrue(t1 > t2)
# Likewise, but make microseconds resolve it.
t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(1, ""),
microsecond=1)
self.assertTrue(t1 > t2)
# Make t2 naive and it should fail.
t2 = self.theclass.min
self.assertRaises(TypeError, lambda: t1 == t2)
self.assertEqual(t2, t2)
# It's also naive if it has tzinfo but tzinfo.utcoffset() is None.
class Naive(tzinfo):
def utcoffset(self, dt): return None
t2 = self.theclass(5, 6, 7, tzinfo=Naive())
self.assertRaises(TypeError, lambda: t1 == t2)
self.assertEqual(t2, t2)
# OTOH, it's OK to compare two of these mixing the two ways of being
# naive.
t1 = self.theclass(5, 6, 7)
self.assertEqual(t1, t2)
# Try a bogus uctoffset.
class Bogus(tzinfo):
def utcoffset(self, dt):
return timedelta(minutes=1440) # out of bounds
t1 = self.theclass(2, 2, 2, tzinfo=Bogus())
t2 = self.theclass(2, 2, 2, tzinfo=FixedOffset(0, ""))
self.assertRaises(ValueError, lambda: t1 == t2)
def test_pickling(self):
# Try one without a tzinfo.
args = 6, 7, 23, 20, 59, 1, 64**2
orig = self.theclass(*args)
for pickler, unpickler, proto in pickle_choices:
green = pickler.dumps(orig, proto)
derived = unpickler.loads(green)
self.assertEqual(orig, derived)
# Try one with a tzinfo.
tinfo = PicklableFixedOffset(-300, 'cookie')
orig = self.theclass(*args, **{'tzinfo': tinfo})
derived = self.theclass(1, 1, 1, tzinfo=FixedOffset(0, "", 0))
for pickler, unpickler, proto in pickle_choices:
green = pickler.dumps(orig, proto)
derived = unpickler.loads(green)
self.assertEqual(orig, derived)
self.assertIsInstance(derived.tzinfo, PicklableFixedOffset)
self.assertEqual(derived.utcoffset(), timedelta(minutes=-300))
self.assertEqual(derived.tzname(), 'cookie')
def test_extreme_hashes(self):
# If an attempt is made to hash these via subtracting the offset
# then hashing a datetime object, OverflowError results. The
# Python implementation used to blow up here.
t = self.theclass(1, 1, 1, tzinfo=FixedOffset(1439, ""))
hash(t)
t = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999999,
tzinfo=FixedOffset(-1439, ""))
hash(t)
# OTOH, an OOB offset should blow up.
t = self.theclass(5, 5, 5, tzinfo=FixedOffset(-1440, ""))
self.assertRaises(ValueError, hash, t)
def test_zones(self):
est = FixedOffset(-300, "EST")
utc = FixedOffset(0, "UTC")
met = FixedOffset(60, "MET")
t1 = datetime(2002, 3, 19, 7, 47, tzinfo=est)
t2 = datetime(2002, 3, 19, 12, 47, tzinfo=utc)
t3 = datetime(2002, 3, 19, 13, 47, tzinfo=met)
self.assertEqual(t1.tzinfo, est)
self.assertEqual(t2.tzinfo, utc)
self.assertEqual(t3.tzinfo, met)
self.assertEqual(t1.utcoffset(), timedelta(minutes=-300))
self.assertEqual(t2.utcoffset(), timedelta(minutes=0))
self.assertEqual(t3.utcoffset(), timedelta(minutes=60))
self.assertEqual(t1.tzname(), "EST")
self.assertEqual(t2.tzname(), "UTC")
self.assertEqual(t3.tzname(), "MET")
self.assertEqual(hash(t1), hash(t2))
self.assertEqual(hash(t1), hash(t3))
self.assertEqual(hash(t2), hash(t3))
self.assertEqual(t1, t2)
self.assertEqual(t1, t3)
self.assertEqual(t2, t3)
self.assertEqual(str(t1), "2002-03-19 07:47:00-05:00")
self.assertEqual(str(t2), "2002-03-19 12:47:00+00:00")
self.assertEqual(str(t3), "2002-03-19 13:47:00+01:00")
d = 'datetime.datetime(2002, 3, 19, '
self.assertEqual(repr(t1), d + "7, 47, tzinfo=est)")
self.assertEqual(repr(t2), d + "12, 47, tzinfo=utc)")
self.assertEqual(repr(t3), d + "13, 47, tzinfo=met)")
def test_combine(self):
met = FixedOffset(60, "MET")
d = date(2002, 3, 4)
tz = time(18, 45, 3, 1234, tzinfo=met)
dt = datetime.combine(d, tz)
self.assertEqual(dt, datetime(2002, 3, 4, 18, 45, 3, 1234,
tzinfo=met))
def test_extract(self):
met = FixedOffset(60, "MET")
dt = self.theclass(2002, 3, 4, 18, 45, 3, 1234, tzinfo=met)
self.assertEqual(dt.date(), date(2002, 3, 4))
self.assertEqual(dt.time(), time(18, 45, 3, 1234))
self.assertEqual(dt.timetz(), time(18, 45, 3, 1234, tzinfo=met))
def test_tz_aware_arithmetic(self):
import random
now = self.theclass.now()
tz55 = FixedOffset(-330, "west 5:30")
timeaware = now.time().replace(tzinfo=tz55)
nowaware = self.theclass.combine(now.date(), timeaware)
self.assertIs(nowaware.tzinfo, tz55)
self.assertEqual(nowaware.timetz(), timeaware)
# Can't mix aware and non-aware.
self.assertRaises(TypeError, lambda: now - nowaware)
self.assertRaises(TypeError, lambda: nowaware - now)
# And adding datetime's doesn't make sense, aware or not.
self.assertRaises(TypeError, lambda: now + nowaware)
self.assertRaises(TypeError, lambda: nowaware + now)
self.assertRaises(TypeError, lambda: nowaware + nowaware)
# Subtracting should yield 0.
self.assertEqual(now - now, timedelta(0))
self.assertEqual(nowaware - nowaware, timedelta(0))
# Adding a delta should preserve tzinfo.
delta = timedelta(weeks=1, minutes=12, microseconds=5678)
nowawareplus = nowaware + delta
self.assertIs(nowaware.tzinfo, tz55)
nowawareplus2 = delta + nowaware
self.assertIs(nowawareplus2.tzinfo, tz55)
self.assertEqual(nowawareplus, nowawareplus2)
# that - delta should be what we started with, and that - what we
# started with should be delta.
diff = nowawareplus - delta
self.assertIs(diff.tzinfo, tz55)
self.assertEqual(nowaware, diff)
self.assertRaises(TypeError, lambda: delta - nowawareplus)
self.assertEqual(nowawareplus - nowaware, delta)
# Make up a random timezone.
tzr = FixedOffset(random.randrange(-1439, 1440), "randomtimezone")
# Attach it to nowawareplus.
nowawareplus = nowawareplus.replace(tzinfo=tzr)
self.assertIs(nowawareplus.tzinfo, tzr)
# Make sure the difference takes the timezone adjustments into account.
got = nowaware - nowawareplus
# Expected: (nowaware base - nowaware offset) -
# (nowawareplus base - nowawareplus offset) =
# (nowaware base - nowawareplus base) +
# (nowawareplus offset - nowaware offset) =
# -delta + nowawareplus offset - nowaware offset
expected = nowawareplus.utcoffset() - nowaware.utcoffset() - delta
self.assertEqual(got, expected)
# Try max possible difference.
min = self.theclass(1, 1, 1, tzinfo=FixedOffset(1439, "min"))
max = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999999,
tzinfo=FixedOffset(-1439, "max"))
maxdiff = max - min
self.assertEqual(maxdiff, self.theclass.max - self.theclass.min +
timedelta(minutes=2*1439))
def test_tzinfo_now(self):
meth = self.theclass.now
# Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
base = meth()
# Try with and without naming the keyword.
off42 = FixedOffset(42, "42")
another = meth(off42)
again = meth(tz=off42)
self.assertIs(another.tzinfo, again.tzinfo)
self.assertEqual(another.utcoffset(), timedelta(minutes=42))
# Bad argument with and w/o naming the keyword.
self.assertRaises(TypeError, meth, 16)
self.assertRaises(TypeError, meth, tzinfo=16)
# Bad keyword name.
self.assertRaises(TypeError, meth, tinfo=off42)
# Too many args.
self.assertRaises(TypeError, meth, off42, off42)
# We don't know which time zone we're in, and don't have a tzinfo
# class to represent it, so seeing whether a tz argument actually
# does a conversion is tricky.
weirdtz = FixedOffset(timedelta(hours=15, minutes=58), "weirdtz", 0)
utc = FixedOffset(0, "utc", 0)
for dummy in range(3):
now = datetime.now(weirdtz)
self.assertIs(now.tzinfo, weirdtz)
utcnow = datetime.utcnow().replace(tzinfo=utc)
now2 = utcnow.astimezone(weirdtz)
if abs(now - now2) < timedelta(seconds=30):
break
# Else the code is broken, or more than 30 seconds passed between
# calls; assuming the latter, just try again.
else:
# Three strikes and we're out.
self.fail("utcnow(), now(tz), or astimezone() may be broken")
def test_tzinfo_fromtimestamp(self):
import time
meth = self.theclass.fromtimestamp
ts = time.time()
# Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
base = meth(ts)
# Try with and without naming the keyword.
off42 = FixedOffset(42, "42")
another = meth(ts, off42)
again = meth(ts, tz=off42)
self.assertIs(another.tzinfo, again.tzinfo)
self.assertEqual(another.utcoffset(), timedelta(minutes=42))
# Bad argument with and w/o naming the keyword.
self.assertRaises(TypeError, meth, ts, 16)
self.assertRaises(TypeError, meth, ts, tzinfo=16)
# Bad keyword name.
self.assertRaises(TypeError, meth, ts, tinfo=off42)
# Too many args.
self.assertRaises(TypeError, meth, ts, off42, off42)
# Too few args.
self.assertRaises(TypeError, meth)
# Try to make sure tz= actually does some conversion.
timestamp = 1000000000
utcdatetime = datetime.utcfromtimestamp(timestamp)
# In POSIX (epoch 1970), that's 2001-09-09 01:46:40 UTC, give or take.
# But on some flavor of Mac, it's nowhere near that. So we can't have
# any idea here what time that actually is, we can only test that
# relative changes match.
utcoffset = timedelta(hours=-15, minutes=39) # arbitrary, but not zero
tz = FixedOffset(utcoffset, "tz", 0)
expected = utcdatetime + utcoffset
got = datetime.fromtimestamp(timestamp, tz)
self.assertEqual(expected, got.replace(tzinfo=None))
def test_tzinfo_utcnow(self):
meth = self.theclass.utcnow
# Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
base = meth()
# Try with and without naming the keyword; for whatever reason,
# utcnow() doesn't accept a tzinfo argument.
off42 = FixedOffset(42, "42")
self.assertRaises(TypeError, meth, off42)
self.assertRaises(TypeError, meth, tzinfo=off42)
def test_tzinfo_utcfromtimestamp(self):
import time
meth = self.theclass.utcfromtimestamp
ts = time.time()
# Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
base = meth(ts)
# Try with and without naming the keyword; for whatever reason,
# utcfromtimestamp() doesn't accept a tzinfo argument.
off42 = FixedOffset(42, "42")
self.assertRaises(TypeError, meth, ts, off42)
self.assertRaises(TypeError, meth, ts, tzinfo=off42)
def test_tzinfo_timetuple(self):
# TestDateTime tested most of this. datetime adds a twist to the
# DST flag.
class DST(tzinfo):
def __init__(self, dstvalue):
if isinstance(dstvalue, int):
dstvalue = timedelta(minutes=dstvalue)
self.dstvalue = dstvalue
def dst(self, dt):
return self.dstvalue
cls = self.theclass
for dstvalue, flag in (-33, 1), (33, 1), (0, 0), (None, -1):
d = cls(1, 1, 1, 10, 20, 30, 40, tzinfo=DST(dstvalue))
t = d.timetuple()
self.assertEqual(1, t.tm_year)
self.assertEqual(1, t.tm_mon)
self.assertEqual(1, t.tm_mday)
self.assertEqual(10, t.tm_hour)
self.assertEqual(20, t.tm_min)
self.assertEqual(30, t.tm_sec)
self.assertEqual(0, t.tm_wday)
self.assertEqual(1, t.tm_yday)
self.assertEqual(flag, t.tm_isdst)
# dst() returns wrong type.
self.assertRaises(TypeError, cls(1, 1, 1, tzinfo=DST("x")).timetuple)
# dst() at the edge.
self.assertEqual(cls(1,1,1, tzinfo=DST(1439)).timetuple().tm_isdst, 1)
self.assertEqual(cls(1,1,1, tzinfo=DST(-1439)).timetuple().tm_isdst, 1)
# dst() out of range.
self.assertRaises(ValueError, cls(1,1,1, tzinfo=DST(1440)).timetuple)
self.assertRaises(ValueError, cls(1,1,1, tzinfo=DST(-1440)).timetuple)
def test_utctimetuple(self):
class DST(tzinfo):
def __init__(self, dstvalue):
if isinstance(dstvalue, int):
dstvalue = timedelta(minutes=dstvalue)
self.dstvalue = dstvalue
def dst(self, dt):
return self.dstvalue
cls = self.theclass
# This can't work: DST didn't implement utcoffset.
self.assertRaises(NotImplementedError,
cls(1, 1, 1, tzinfo=DST(0)).utcoffset)
class UOFS(DST):
def __init__(self, uofs, dofs=None):
DST.__init__(self, dofs)
self.uofs = timedelta(minutes=uofs)
def utcoffset(self, dt):
return self.uofs
# Ensure tm_isdst is 0 regardless of what dst() says: DST is never
# in effect for a UTC time.
for dstvalue in -33, 33, 0, None:
d = cls(1, 2, 3, 10, 20, 30, 40, tzinfo=UOFS(-53, dstvalue))
t = d.utctimetuple()
self.assertEqual(d.year, t.tm_year)
self.assertEqual(d.month, t.tm_mon)
self.assertEqual(d.day, t.tm_mday)
self.assertEqual(11, t.tm_hour) # 20mm + 53mm = 1hn + 13mm
self.assertEqual(13, t.tm_min)
self.assertEqual(d.second, t.tm_sec)
self.assertEqual(d.weekday(), t.tm_wday)
self.assertEqual(d.toordinal() - date(1, 1, 1).toordinal() + 1,
t.tm_yday)
self.assertEqual(0, t.tm_isdst)
# At the edges, UTC adjustment can normalize into years out-of-range
# for a datetime object. Ensure that a correct timetuple is
# created anyway.
tiny = cls(MINYEAR, 1, 1, 0, 0, 37, tzinfo=UOFS(1439))
# That goes back 1 minute less than a full day.
t = tiny.utctimetuple()
self.assertEqual(t.tm_year, MINYEAR-1)
self.assertEqual(t.tm_mon, 12)
self.assertEqual(t.tm_mday, 31)
self.assertEqual(t.tm_hour, 0)
self.assertEqual(t.tm_min, 1)
self.assertEqual(t.tm_sec, 37)
self.assertEqual(t.tm_yday, 366) # "year 0" is a leap year
self.assertEqual(t.tm_isdst, 0)
huge = cls(MAXYEAR, 12, 31, 23, 59, 37, 999999, tzinfo=UOFS(-1439))
# That goes forward 1 minute less than a full day.
t = huge.utctimetuple()
self.assertEqual(t.tm_year, MAXYEAR+1)
self.assertEqual(t.tm_mon, 1)
self.assertEqual(t.tm_mday, 1)
self.assertEqual(t.tm_hour, 23)
self.assertEqual(t.tm_min, 58)
self.assertEqual(t.tm_sec, 37)
self.assertEqual(t.tm_yday, 1)
self.assertEqual(t.tm_isdst, 0)
def test_tzinfo_isoformat(self):
zero = FixedOffset(0, "+00:00")
plus = FixedOffset(220, "+03:40")
minus = FixedOffset(-231, "-03:51")
unknown = FixedOffset(None, "")
cls = self.theclass
datestr = '0001-02-03'
for ofs in None, zero, plus, minus, unknown:
for us in 0, 987001:
d = cls(1, 2, 3, 4, 5, 59, us, tzinfo=ofs)
timestr = '04:05:59' + (us and '.987001' or '')
ofsstr = ofs is not None and d.tzname() or ''
tailstr = timestr + ofsstr
iso = d.isoformat()
self.assertEqual(iso, datestr + 'T' + tailstr)
self.assertEqual(iso, d.isoformat('T'))
self.assertEqual(d.isoformat('k'), datestr + 'k' + tailstr)
self.assertEqual(str(d), datestr + ' ' + tailstr)
def test_replace(self):
cls = self.theclass
z100 = FixedOffset(100, "+100")
zm200 = FixedOffset(timedelta(minutes=-200), "-200")
args = [1, 2, 3, 4, 5, 6, 7, z100]
base = cls(*args)
self.assertEqual(base, base.replace())
i = 0
for name, newval in (("year", 2),
("month", 3),
("day", 4),
("hour", 5),
("minute", 6),
("second", 7),
("microsecond", 8),
("tzinfo", zm200)):
newargs = args[:]
newargs[i] = newval
expected = cls(*newargs)
got = base.replace(**{name: newval})
self.assertEqual(expected, got)
i += 1
# Ensure we can get rid of a tzinfo.
self.assertEqual(base.tzname(), "+100")
base2 = base.replace(tzinfo=None)
self.assertIsNone(base2.tzinfo)
self.assertIsNone(base2.tzname())
# Ensure we can add one.
base3 = base2.replace(tzinfo=z100)
self.assertEqual(base, base3)
self.assertIs(base.tzinfo, base3.tzinfo)
# Out of bounds.
base = cls(2000, 2, 29)
self.assertRaises(ValueError, base.replace, year=2001)
def test_more_astimezone(self):
# The inherited test_astimezone covered some trivial and error cases.
fnone = FixedOffset(None, "None")
f44m = FixedOffset(44, "44")
fm5h = FixedOffset(-timedelta(hours=5), "m300")
dt = self.theclass.now(tz=f44m)
self.assertIs(dt.tzinfo, f44m)
# Replacing with degenerate tzinfo raises an exception.
self.assertRaises(ValueError, dt.astimezone, fnone)
# Ditto with None tz.
self.assertRaises(TypeError, dt.astimezone, None)
# Replacing with same tzinfo makes no change.
x = dt.astimezone(dt.tzinfo)
self.assertIs(x.tzinfo, f44m)
self.assertEqual(x.date(), dt.date())
self.assertEqual(x.time(), dt.time())
# Replacing with different tzinfo does adjust.
got = dt.astimezone(fm5h)
self.assertIs(got.tzinfo, fm5h)
self.assertEqual(got.utcoffset(), timedelta(hours=-5))
expected = dt - dt.utcoffset() # in effect, convert to UTC
expected += fm5h.utcoffset(dt) # and from there to local time
expected = expected.replace(tzinfo=fm5h) # and attach new tzinfo
self.assertEqual(got.date(), expected.date())
self.assertEqual(got.time(), expected.time())
self.assertEqual(got.timetz(), expected.timetz())
self.assertIs(got.tzinfo, expected.tzinfo)
self.assertEqual(got, expected)
def test_aware_subtract(self):
cls = self.theclass
# Ensure that utcoffset() is ignored when the operands have the
# same tzinfo member.
class OperandDependentOffset(tzinfo):
def utcoffset(self, t):
if t.minute < 10:
# d0 and d1 equal after adjustment
return timedelta(minutes=t.minute)
else:
# d2 off in the weeds
return timedelta(minutes=59)
base = cls(8, 9, 10, 11, 12, 13, 14, tzinfo=OperandDependentOffset())
d0 = base.replace(minute=3)
d1 = base.replace(minute=9)
d2 = base.replace(minute=11)
for x in d0, d1, d2:
for y in d0, d1, d2:
got = x - y
expected = timedelta(minutes=x.minute - y.minute)
self.assertEqual(got, expected)
# OTOH, if the tzinfo members are distinct, utcoffsets aren't
# ignored.
base = cls(8, 9, 10, 11, 12, 13, 14)
d0 = base.replace(minute=3, tzinfo=OperandDependentOffset())
d1 = base.replace(minute=9, tzinfo=OperandDependentOffset())
d2 = base.replace(minute=11, tzinfo=OperandDependentOffset())
for x in d0, d1, d2:
for y in d0, d1, d2:
got = x - y
if (x is d0 or x is d1) and (y is d0 or y is d1):
expected = timedelta(0)
elif x is y is d2:
expected = timedelta(0)
elif x is d2:
expected = timedelta(minutes=(11-59)-0)
else:
assert y is d2
expected = timedelta(minutes=0-(11-59))
self.assertEqual(got, expected)
def test_mixed_compare(self):
t1 = datetime(1, 2, 3, 4, 5, 6, 7)
t2 = datetime(1, 2, 3, 4, 5, 6, 7)
self.assertEqual(t1, t2)
t2 = t2.replace(tzinfo=None)
self.assertEqual(t1, t2)
t2 = t2.replace(tzinfo=FixedOffset(None, ""))
self.assertEqual(t1, t2)
t2 = t2.replace(tzinfo=FixedOffset(0, ""))
self.assertRaises(TypeError, lambda: t1 == t2)
# In datetime w/ identical tzinfo objects, utcoffset is ignored.
class Varies(tzinfo):
def __init__(self):
self.offset = timedelta(minutes=22)
def utcoffset(self, t):
self.offset += timedelta(minutes=1)
return self.offset
v = Varies()
t1 = t2.replace(tzinfo=v)
t2 = t2.replace(tzinfo=v)
self.assertEqual(t1.utcoffset(), timedelta(minutes=23))
self.assertEqual(t2.utcoffset(), timedelta(minutes=24))
self.assertEqual(t1, t2)
# But if they're not identical, it isn't ignored.
t2 = t2.replace(tzinfo=Varies())
self.assertTrue(t1 < t2) # t1's offset counter still going up
def test_subclass_datetimetz(self):
class C(self.theclass):
theAnswer = 42
def __new__(cls, *args, **kws):
temp = kws.copy()
extra = temp.pop('extra')
result = self.theclass.__new__(cls, *args, **temp)
result.extra = extra
return result
def newmeth(self, start):
return start + self.hour + self.year
args = 2002, 12, 31, 4, 5, 6, 500, FixedOffset(-300, "EST", 1)
dt1 = self.theclass(*args)
dt2 = C(*args, **{'extra': 7})
self.assertEqual(dt2.__class__, C)
self.assertEqual(dt2.theAnswer, 42)
self.assertEqual(dt2.extra, 7)
self.assertEqual(dt1.utcoffset(), dt2.utcoffset())
self.assertEqual(dt2.newmeth(-7), dt1.hour + dt1.year - 7)
# Pain to set up DST-aware tzinfo classes.
def first_sunday_on_or_after(dt):
days_to_go = 6 - dt.weekday()
if days_to_go:
dt += timedelta(days_to_go)
return dt
ZERO = timedelta(0)
HOUR = timedelta(hours=1)
DAY = timedelta(days=1)
# In the US, DST starts at 2am (standard time) on the first Sunday in April.
DSTSTART = datetime(1, 4, 1, 2)
# and ends at 2am (DST time; 1am standard time) on the last Sunday of Oct,
# which is the first Sunday on or after Oct 25. Because we view 1:MM as
# being standard time on that day, there is no spelling in local time of
# the last hour of DST (that's 1:MM DST, but 1:MM is taken as standard time).
DSTEND = datetime(1, 10, 25, 1)
class USTimeZone(tzinfo):
def __init__(self, hours, reprname, stdname, dstname):
self.stdoffset = timedelta(hours=hours)
self.reprname = reprname
self.stdname = stdname
self.dstname = dstname
def __repr__(self):
return self.reprname
def tzname(self, dt):
if self.dst(dt):
return self.dstname
else:
return self.stdname
def utcoffset(self, dt):
return self.stdoffset + self.dst(dt)
def dst(self, dt):
if dt is None or dt.tzinfo is None:
# An exception instead may be sensible here, in one or more of
# the cases.
return ZERO
assert dt.tzinfo is self
# Find first Sunday in April.
start = first_sunday_on_or_after(DSTSTART.replace(year=dt.year))
assert start.weekday() == 6 and start.month == 4 and start.day <= 7
# Find last Sunday in October.
end = first_sunday_on_or_after(DSTEND.replace(year=dt.year))
assert end.weekday() == 6 and end.month == 10 and end.day >= 25
# Can't compare naive to aware objects, so strip the timezone from
# dt first.
if start <= dt.replace(tzinfo=None) < end:
return HOUR
else:
return ZERO
Eastern = USTimeZone(-5, "Eastern", "EST", "EDT")
Central = USTimeZone(-6, "Central", "CST", "CDT")
Mountain = USTimeZone(-7, "Mountain", "MST", "MDT")
Pacific = USTimeZone(-8, "Pacific", "PST", "PDT")
utc_real = FixedOffset(0, "UTC", 0)
# For better test coverage, we want another flavor of UTC that's west of
# the Eastern and Pacific timezones.
utc_fake = FixedOffset(-12*60, "UTCfake", 0)
class TestTimezoneConversions(unittest.TestCase):
# The DST switch times for 2002, in std time.
dston = datetime(2002, 4, 7, 2)
dstoff = datetime(2002, 10, 27, 1)
theclass = datetime
# Check a time that's inside DST.
def checkinside(self, dt, tz, utc, dston, dstoff):
self.assertEqual(dt.dst(), HOUR)
# Conversion to our own timezone is always an identity.
self.assertEqual(dt.astimezone(tz), dt)
asutc = dt.astimezone(utc)
there_and_back = asutc.astimezone(tz)
# Conversion to UTC and back isn't always an identity here,
# because there are redundant spellings (in local time) of
# UTC time when DST begins: the clock jumps from 1:59:59
# to 3:00:00, and a local time of 2:MM:SS doesn't really
# make sense then. The classes above treat 2:MM:SS as
# daylight time then (it's "after 2am"), really an alias
# for 1:MM:SS standard time. The latter form is what
# conversion back from UTC produces.
if dt.date() == dston.date() and dt.hour == 2:
# We're in the redundant hour, and coming back from
# UTC gives the 1:MM:SS standard-time spelling.
self.assertEqual(there_and_back + HOUR, dt)
# Although during was considered to be in daylight
# time, there_and_back is not.
self.assertEqual(there_and_back.dst(), ZERO)
# They're the same times in UTC.
self.assertEqual(there_and_back.astimezone(utc),
dt.astimezone(utc))
else:
# We're not in the redundant hour.
self.assertEqual(dt, there_and_back)
# Because we have a redundant spelling when DST begins, there is
# (unfortunately) an hour when DST ends that can't be spelled at all in
# local time. When DST ends, the clock jumps from 1:59 back to 1:00
# again. The hour 1:MM DST has no spelling then: 1:MM is taken to be
# standard time. 1:MM DST == 0:MM EST, but 0:MM is taken to be
# daylight time. The hour 1:MM daylight == 0:MM standard can't be
# expressed in local time. Nevertheless, we want conversion back
# from UTC to mimic the local clock's "repeat an hour" behavior.
nexthour_utc = asutc + HOUR
nexthour_tz = nexthour_utc.astimezone(tz)
if dt.date() == dstoff.date() and dt.hour == 0:
# We're in the hour before the last DST hour. The last DST hour
# is ineffable. We want the conversion back to repeat 1:MM.
self.assertEqual(nexthour_tz, dt.replace(hour=1))
nexthour_utc += HOUR
nexthour_tz = nexthour_utc.astimezone(tz)
self.assertEqual(nexthour_tz, dt.replace(hour=1))
else:
self.assertEqual(nexthour_tz - dt, HOUR)
# Check a time that's outside DST.
def checkoutside(self, dt, tz, utc):
self.assertEqual(dt.dst(), ZERO)
# Conversion to our own timezone is always an identity.
self.assertEqual(dt.astimezone(tz), dt)
# Converting to UTC and back is an identity too.
asutc = dt.astimezone(utc)
there_and_back = asutc.astimezone(tz)
self.assertEqual(dt, there_and_back)
def convert_between_tz_and_utc(self, tz, utc):
dston = self.dston.replace(tzinfo=tz)
# Because 1:MM on the day DST ends is taken as being standard time,
# there is no spelling in tz for the last hour of daylight time.
# For purposes of the test, the last hour of DST is 0:MM, which is
# taken as being daylight time (and 1:MM is taken as being standard
# time).
dstoff = self.dstoff.replace(tzinfo=tz)
for delta in (timedelta(weeks=13),
DAY,
HOUR,
timedelta(minutes=1),
timedelta(microseconds=1)):
self.checkinside(dston, tz, utc, dston, dstoff)
for during in dston + delta, dstoff - delta:
self.checkinside(during, tz, utc, dston, dstoff)
self.checkoutside(dstoff, tz, utc)
for outside in dston - delta, dstoff + delta:
self.checkoutside(outside, tz, utc)
def test_easy(self):
# Despite the name of this test, the endcases are excruciating.
self.convert_between_tz_and_utc(Eastern, utc_real)
self.convert_between_tz_and_utc(Pacific, utc_real)
self.convert_between_tz_and_utc(Eastern, utc_fake)
self.convert_between_tz_and_utc(Pacific, utc_fake)
# The next is really dancing near the edge. It works because
# Pacific and Eastern are far enough apart that their "problem
# hours" don't overlap.
self.convert_between_tz_and_utc(Eastern, Pacific)
self.convert_between_tz_and_utc(Pacific, Eastern)
# OTOH, these fail! Don't enable them. The difficulty is that
# the edge case tests assume that every hour is representable in
# the "utc" class. This is always true for a fixed-offset tzinfo
# class (lke utc_real and utc_fake), but not for Eastern or Central.
# For these adjacent DST-aware time zones, the range of time offsets
# tested ends up creating hours in the one that aren't representable
# in the other. For the same reason, we would see failures in the
# Eastern vs Pacific tests too if we added 3*HOUR to the list of
# offset deltas in convert_between_tz_and_utc().
#
# self.convert_between_tz_and_utc(Eastern, Central) # can't work
# self.convert_between_tz_and_utc(Central, Eastern) # can't work
def test_tricky(self):
# 22:00 on day before daylight starts.
fourback = self.dston - timedelta(hours=4)
ninewest = FixedOffset(-9*60, "-0900", 0)
fourback = fourback.replace(tzinfo=ninewest)
# 22:00-0900 is 7:00 UTC == 2:00 EST == 3:00 DST. Since it's "after
# 2", we should get the 3 spelling.
# If we plug 22:00 the day before into Eastern, it "looks like std
# time", so its offset is returned as -5, and -5 - -9 = 4. Adding 4
# to 22:00 lands on 2:00, which makes no sense in local time (the
# local clock jumps from 1 to 3). The point here is to make sure we
# get the 3 spelling.
expected = self.dston.replace(hour=3)
got = fourback.astimezone(Eastern).replace(tzinfo=None)
self.assertEqual(expected, got)
# Similar, but map to 6:00 UTC == 1:00 EST == 2:00 DST. In that
# case we want the 1:00 spelling.
sixutc = self.dston.replace(hour=6, tzinfo=utc_real)
# Now 6:00 "looks like daylight", so the offset wrt Eastern is -4,
# and adding -4-0 == -4 gives the 2:00 spelling. We want the 1:00 EST
# spelling.
expected = self.dston.replace(hour=1)
got = sixutc.astimezone(Eastern).replace(tzinfo=None)
self.assertEqual(expected, got)
# Now on the day DST ends, we want "repeat an hour" behavior.
# UTC 4:MM 5:MM 6:MM 7:MM checking these
# EST 23:MM 0:MM 1:MM 2:MM
# EDT 0:MM 1:MM 2:MM 3:MM
# wall 0:MM 1:MM 1:MM 2:MM against these
for utc in utc_real, utc_fake:
for tz in Eastern, Pacific:
first_std_hour = self.dstoff - timedelta(hours=2) # 23:MM
# Convert that to UTC.
first_std_hour -= tz.utcoffset(None)
# Adjust for possibly fake UTC.
asutc = first_std_hour + utc.utcoffset(None)
# First UTC hour to convert; this is 4:00 when utc=utc_real &
# tz=Eastern.
asutcbase = asutc.replace(tzinfo=utc)
for tzhour in (0, 1, 1, 2):
expectedbase = self.dstoff.replace(hour=tzhour)
for minute in 0, 30, 59:
expected = expectedbase.replace(minute=minute)
asutc = asutcbase.replace(minute=minute)
astz = asutc.astimezone(tz)
self.assertEqual(astz.replace(tzinfo=None), expected)
asutcbase += HOUR
def test_bogus_dst(self):
class ok(tzinfo):
def utcoffset(self, dt): return HOUR
def dst(self, dt): return HOUR
now = self.theclass.now().replace(tzinfo=utc_real)
# Doesn't blow up.
now.astimezone(ok())
# Does blow up.
class notok(ok):
def dst(self, dt): return None
self.assertRaises(ValueError, now.astimezone, notok())
def test_fromutc(self):
self.assertRaises(TypeError, Eastern.fromutc) # not enough args
now = datetime.utcnow().replace(tzinfo=utc_real)
self.assertRaises(ValueError, Eastern.fromutc, now) # wrong tzinfo
now = now.replace(tzinfo=Eastern) # insert correct tzinfo
enow = Eastern.fromutc(now) # doesn't blow up
self.assertEqual(enow.tzinfo, Eastern) # has right tzinfo member
self.assertRaises(TypeError, Eastern.fromutc, now, now) # too many args
self.assertRaises(TypeError, Eastern.fromutc, date.today()) # wrong type
# Always converts UTC to standard time.
class FauxUSTimeZone(USTimeZone):
def fromutc(self, dt):
return dt + self.stdoffset
FEastern = FauxUSTimeZone(-5, "FEastern", "FEST", "FEDT")
# UTC 4:MM 5:MM 6:MM 7:MM 8:MM 9:MM
# EST 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
# EDT 0:MM 1:MM 2:MM 3:MM 4:MM 5:MM
# Check around DST start.
start = self.dston.replace(hour=4, tzinfo=Eastern)
fstart = start.replace(tzinfo=FEastern)
for wall in 23, 0, 1, 3, 4, 5:
expected = start.replace(hour=wall)
if wall == 23:
expected -= timedelta(days=1)
got = Eastern.fromutc(start)
self.assertEqual(expected, got)
expected = fstart + FEastern.stdoffset
got = FEastern.fromutc(fstart)
self.assertEqual(expected, got)
# Ensure astimezone() calls fromutc() too.
got = fstart.replace(tzinfo=utc_real).astimezone(FEastern)
self.assertEqual(expected, got)
start += HOUR
fstart += HOUR
# Check around DST end.
start = self.dstoff.replace(hour=4, tzinfo=Eastern)
fstart = start.replace(tzinfo=FEastern)
for wall in 0, 1, 1, 2, 3, 4:
expected = start.replace(hour=wall)
got = Eastern.fromutc(start)
self.assertEqual(expected, got)
expected = fstart + FEastern.stdoffset
got = FEastern.fromutc(fstart)
self.assertEqual(expected, got)
# Ensure astimezone() calls fromutc() too.
got = fstart.replace(tzinfo=utc_real).astimezone(FEastern)
self.assertEqual(expected, got)
start += HOUR
fstart += HOUR
#############################################################################
# oddballs
class Oddballs(unittest.TestCase):
def test_bug_1028306(self):
# Trying to compare a date to a datetime should act like a mixed-
# type comparison, despite that datetime is a subclass of date.
as_date = date.today()
as_datetime = datetime.combine(as_date, time())
self.assertTrue(as_date != as_datetime)
self.assertTrue(as_datetime != as_date)
self.assertFalse(as_date == as_datetime)
self.assertFalse(as_datetime == as_date)
self.assertRaises(TypeError, lambda: as_date < as_datetime)
self.assertRaises(TypeError, lambda: as_datetime < as_date)
self.assertRaises(TypeError, lambda: as_date <= as_datetime)
self.assertRaises(TypeError, lambda: as_datetime <= as_date)
self.assertRaises(TypeError, lambda: as_date > as_datetime)
self.assertRaises(TypeError, lambda: as_datetime > as_date)
self.assertRaises(TypeError, lambda: as_date >= as_datetime)
self.assertRaises(TypeError, lambda: as_datetime >= as_date)
# Neverthelss, comparison should work with the base-class (date)
# projection if use of a date method is forced.
self.assertTrue(as_date.__eq__(as_datetime))
different_day = (as_date.day + 1) % 20 + 1
self.assertFalse(as_date.__eq__(as_datetime.replace(day=different_day)))
# And date should compare with other subclasses of date. If a
# subclass wants to stop this, it's up to the subclass to do so.
date_sc = SubclassDate(as_date.year, as_date.month, as_date.day)
self.assertEqual(as_date, date_sc)
self.assertEqual(date_sc, as_date)
# Ditto for datetimes.
datetime_sc = SubclassDatetime(as_datetime.year, as_datetime.month,
as_date.day, 0, 0, 0)
self.assertEqual(as_datetime, datetime_sc)
self.assertEqual(datetime_sc, as_datetime)
def test_main():
test_support.run_unittest(__name__)
if __name__ == "__main__":
test_main()
| mit |
sje397/p2pool | wstools/Utility.py | 292 | 50865 | # Copyright (c) 2003, The Regents of the University of California,
# through Lawrence Berkeley National Laboratory (subject to receipt of
# any required approvals from the U.S. Dept. of Energy). All rights
# reserved.
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
ident = "$Id$"
import sys, types, httplib, urllib, socket, weakref
from os.path import isfile
from string import join, strip, split
from UserDict import UserDict
from cStringIO import StringIO
from TimeoutSocket import TimeoutSocket, TimeoutError
from urlparse import urlparse
from httplib import HTTPConnection, HTTPSConnection
from exceptions import Exception
try:
from ZSI import _get_idstr
except:
def _get_idstr(pyobj):
'''Python 2.3.x generates a FutureWarning for negative IDs, so
we use a different prefix character to ensure uniqueness, and
call abs() to avoid the warning.'''
x = id(pyobj)
if x < 0:
return 'x%x' % abs(x)
return 'o%x' % x
import xml.dom.minidom
from xml.dom import Node
import logging
from c14n import Canonicalize
from Namespaces import SCHEMA, SOAP, XMLNS, ZSI_SCHEMA_URI
try:
from xml.dom.ext import SplitQName
except:
def SplitQName(qname):
'''SplitQName(qname) -> (string, string)
Split Qualified Name into a tuple of len 2, consisting
of the prefix and the local name.
(prefix, localName)
Special Cases:
xmlns -- (localName, 'xmlns')
None -- (None, localName)
'''
l = qname.split(':')
if len(l) == 1:
l.insert(0, None)
elif len(l) == 2:
if l[0] == 'xmlns':
l.reverse()
else:
return
return tuple(l)
#
# python2.3 urllib.basejoin does not remove current directory ./
# from path and this causes problems on subsequent basejoins.
#
basejoin = urllib.basejoin
if sys.version_info[0:2] < (2, 4, 0, 'final', 0)[0:2]:
#basejoin = lambda base,url: urllib.basejoin(base,url.lstrip('./'))
token = './'
def basejoin(base, url):
if url.startswith(token) is True:
return urllib.basejoin(base,url[2:])
return urllib.basejoin(base,url)
class NamespaceError(Exception):
"""Used to indicate a Namespace Error."""
class RecursionError(Exception):
"""Used to indicate a HTTP redirect recursion."""
class ParseError(Exception):
"""Used to indicate a XML parsing error."""
class DOMException(Exception):
"""Used to indicate a problem processing DOM."""
class Base:
"""Base class for instance level Logging"""
def __init__(self, module=__name__):
self.logger = logging.getLogger('%s-%s(%s)' %(module, self.__class__, _get_idstr(self)))
class HTTPResponse:
"""Captures the information in an HTTP response message."""
def __init__(self, response):
self.status = response.status
self.reason = response.reason
self.headers = response.msg
self.body = response.read() or None
response.close()
class TimeoutHTTP(HTTPConnection):
"""A custom http connection object that supports socket timeout."""
def __init__(self, host, port=None, timeout=20):
HTTPConnection.__init__(self, host, port)
self.timeout = timeout
def connect(self):
self.sock = TimeoutSocket(self.timeout)
self.sock.connect((self.host, self.port))
class TimeoutHTTPS(HTTPSConnection):
"""A custom https object that supports socket timeout. Note that this
is not really complete. The builtin SSL support in the Python socket
module requires a real socket (type) to be passed in to be hooked to
SSL. That means our fake socket won't work and our timeout hacks are
bypassed for send and recv calls. Since our hack _is_ in place at
connect() time, it should at least provide some timeout protection."""
def __init__(self, host, port=None, timeout=20, **kwargs):
HTTPSConnection.__init__(self, str(host), port, **kwargs)
self.timeout = timeout
def connect(self):
sock = TimeoutSocket(self.timeout)
sock.connect((self.host, self.port))
realsock = getattr(sock.sock, '_sock', sock.sock)
ssl = socket.ssl(realsock, self.key_file, self.cert_file)
self.sock = httplib.FakeSocket(sock, ssl)
def urlopen(url, timeout=20, redirects=None):
"""A minimal urlopen replacement hack that supports timeouts for http.
Note that this supports GET only."""
scheme, host, path, params, query, frag = urlparse(url)
if not scheme in ('http', 'https'):
return urllib.urlopen(url)
if params: path = '%s;%s' % (path, params)
if query: path = '%s?%s' % (path, query)
if frag: path = '%s#%s' % (path, frag)
if scheme == 'https':
# If ssl is not compiled into Python, you will not get an exception
# until a conn.endheaders() call. We need to know sooner, so use
# getattr.
try:
import M2Crypto
except ImportError:
if not hasattr(socket, 'ssl'):
raise RuntimeError, 'no built-in SSL Support'
conn = TimeoutHTTPS(host, None, timeout)
else:
ctx = M2Crypto.SSL.Context()
ctx.set_session_timeout(timeout)
conn = M2Crypto.httpslib.HTTPSConnection(host, ssl_context=ctx)
conn.set_debuglevel(1)
else:
conn = TimeoutHTTP(host, None, timeout)
conn.putrequest('GET', path)
conn.putheader('Connection', 'close')
conn.endheaders()
response = None
while 1:
response = conn.getresponse()
if response.status != 100:
break
conn._HTTPConnection__state = httplib._CS_REQ_SENT
conn._HTTPConnection__response = None
status = response.status
# If we get an HTTP redirect, we will follow it automatically.
if status >= 300 and status < 400:
location = response.msg.getheader('location')
if location is not None:
response.close()
if redirects is not None and redirects.has_key(location):
raise RecursionError(
'Circular HTTP redirection detected.'
)
if redirects is None:
redirects = {}
redirects[location] = 1
return urlopen(location, timeout, redirects)
raise HTTPResponse(response)
if not (status >= 200 and status < 300):
raise HTTPResponse(response)
body = StringIO(response.read())
response.close()
return body
class DOM:
"""The DOM singleton defines a number of XML related constants and
provides a number of utility methods for DOM related tasks. It
also provides some basic abstractions so that the rest of the
package need not care about actual DOM implementation in use."""
# Namespace stuff related to the SOAP specification.
NS_SOAP_ENV_1_1 = 'http://schemas.xmlsoap.org/soap/envelope/'
NS_SOAP_ENC_1_1 = 'http://schemas.xmlsoap.org/soap/encoding/'
NS_SOAP_ENV_1_2 = 'http://www.w3.org/2001/06/soap-envelope'
NS_SOAP_ENC_1_2 = 'http://www.w3.org/2001/06/soap-encoding'
NS_SOAP_ENV_ALL = (NS_SOAP_ENV_1_1, NS_SOAP_ENV_1_2)
NS_SOAP_ENC_ALL = (NS_SOAP_ENC_1_1, NS_SOAP_ENC_1_2)
NS_SOAP_ENV = NS_SOAP_ENV_1_1
NS_SOAP_ENC = NS_SOAP_ENC_1_1
_soap_uri_mapping = {
NS_SOAP_ENV_1_1 : '1.1',
NS_SOAP_ENV_1_2 : '1.2',
}
SOAP_ACTOR_NEXT_1_1 = 'http://schemas.xmlsoap.org/soap/actor/next'
SOAP_ACTOR_NEXT_1_2 = 'http://www.w3.org/2001/06/soap-envelope/actor/next'
SOAP_ACTOR_NEXT_ALL = (SOAP_ACTOR_NEXT_1_1, SOAP_ACTOR_NEXT_1_2)
def SOAPUriToVersion(self, uri):
"""Return the SOAP version related to an envelope uri."""
value = self._soap_uri_mapping.get(uri)
if value is not None:
return value
raise ValueError(
'Unsupported SOAP envelope uri: %s' % uri
)
def GetSOAPEnvUri(self, version):
"""Return the appropriate SOAP envelope uri for a given
human-friendly SOAP version string (e.g. '1.1')."""
attrname = 'NS_SOAP_ENV_%s' % join(split(version, '.'), '_')
value = getattr(self, attrname, None)
if value is not None:
return value
raise ValueError(
'Unsupported SOAP version: %s' % version
)
def GetSOAPEncUri(self, version):
"""Return the appropriate SOAP encoding uri for a given
human-friendly SOAP version string (e.g. '1.1')."""
attrname = 'NS_SOAP_ENC_%s' % join(split(version, '.'), '_')
value = getattr(self, attrname, None)
if value is not None:
return value
raise ValueError(
'Unsupported SOAP version: %s' % version
)
def GetSOAPActorNextUri(self, version):
"""Return the right special next-actor uri for a given
human-friendly SOAP version string (e.g. '1.1')."""
attrname = 'SOAP_ACTOR_NEXT_%s' % join(split(version, '.'), '_')
value = getattr(self, attrname, None)
if value is not None:
return value
raise ValueError(
'Unsupported SOAP version: %s' % version
)
# Namespace stuff related to XML Schema.
NS_XSD_99 = 'http://www.w3.org/1999/XMLSchema'
NS_XSI_99 = 'http://www.w3.org/1999/XMLSchema-instance'
NS_XSD_00 = 'http://www.w3.org/2000/10/XMLSchema'
NS_XSI_00 = 'http://www.w3.org/2000/10/XMLSchema-instance'
NS_XSD_01 = 'http://www.w3.org/2001/XMLSchema'
NS_XSI_01 = 'http://www.w3.org/2001/XMLSchema-instance'
NS_XSD_ALL = (NS_XSD_99, NS_XSD_00, NS_XSD_01)
NS_XSI_ALL = (NS_XSI_99, NS_XSI_00, NS_XSI_01)
NS_XSD = NS_XSD_01
NS_XSI = NS_XSI_01
_xsd_uri_mapping = {
NS_XSD_99 : NS_XSI_99,
NS_XSD_00 : NS_XSI_00,
NS_XSD_01 : NS_XSI_01,
}
for key, value in _xsd_uri_mapping.items():
_xsd_uri_mapping[value] = key
def InstanceUriForSchemaUri(self, uri):
"""Return the appropriate matching XML Schema instance uri for
the given XML Schema namespace uri."""
return self._xsd_uri_mapping.get(uri)
def SchemaUriForInstanceUri(self, uri):
"""Return the appropriate matching XML Schema namespace uri for
the given XML Schema instance namespace uri."""
return self._xsd_uri_mapping.get(uri)
# Namespace stuff related to WSDL.
NS_WSDL_1_1 = 'http://schemas.xmlsoap.org/wsdl/'
NS_WSDL_ALL = (NS_WSDL_1_1,)
NS_WSDL = NS_WSDL_1_1
NS_SOAP_BINDING_1_1 = 'http://schemas.xmlsoap.org/wsdl/soap/'
NS_HTTP_BINDING_1_1 = 'http://schemas.xmlsoap.org/wsdl/http/'
NS_MIME_BINDING_1_1 = 'http://schemas.xmlsoap.org/wsdl/mime/'
NS_SOAP_BINDING_ALL = (NS_SOAP_BINDING_1_1,)
NS_HTTP_BINDING_ALL = (NS_HTTP_BINDING_1_1,)
NS_MIME_BINDING_ALL = (NS_MIME_BINDING_1_1,)
NS_SOAP_BINDING = NS_SOAP_BINDING_1_1
NS_HTTP_BINDING = NS_HTTP_BINDING_1_1
NS_MIME_BINDING = NS_MIME_BINDING_1_1
NS_SOAP_HTTP_1_1 = 'http://schemas.xmlsoap.org/soap/http'
NS_SOAP_HTTP_ALL = (NS_SOAP_HTTP_1_1,)
NS_SOAP_HTTP = NS_SOAP_HTTP_1_1
_wsdl_uri_mapping = {
NS_WSDL_1_1 : '1.1',
}
def WSDLUriToVersion(self, uri):
"""Return the WSDL version related to a WSDL namespace uri."""
value = self._wsdl_uri_mapping.get(uri)
if value is not None:
return value
raise ValueError(
'Unsupported SOAP envelope uri: %s' % uri
)
def GetWSDLUri(self, version):
attr = 'NS_WSDL_%s' % join(split(version, '.'), '_')
value = getattr(self, attr, None)
if value is not None:
return value
raise ValueError(
'Unsupported WSDL version: %s' % version
)
def GetWSDLSoapBindingUri(self, version):
attr = 'NS_SOAP_BINDING_%s' % join(split(version, '.'), '_')
value = getattr(self, attr, None)
if value is not None:
return value
raise ValueError(
'Unsupported WSDL version: %s' % version
)
def GetWSDLHttpBindingUri(self, version):
attr = 'NS_HTTP_BINDING_%s' % join(split(version, '.'), '_')
value = getattr(self, attr, None)
if value is not None:
return value
raise ValueError(
'Unsupported WSDL version: %s' % version
)
def GetWSDLMimeBindingUri(self, version):
attr = 'NS_MIME_BINDING_%s' % join(split(version, '.'), '_')
value = getattr(self, attr, None)
if value is not None:
return value
raise ValueError(
'Unsupported WSDL version: %s' % version
)
def GetWSDLHttpTransportUri(self, version):
attr = 'NS_SOAP_HTTP_%s' % join(split(version, '.'), '_')
value = getattr(self, attr, None)
if value is not None:
return value
raise ValueError(
'Unsupported WSDL version: %s' % version
)
# Other xml namespace constants.
NS_XMLNS = 'http://www.w3.org/2000/xmlns/'
def isElement(self, node, name, nsuri=None):
"""Return true if the given node is an element with the given
name and optional namespace uri."""
if node.nodeType != node.ELEMENT_NODE:
return 0
return node.localName == name and \
(nsuri is None or self.nsUriMatch(node.namespaceURI, nsuri))
def getElement(self, node, name, nsuri=None, default=join):
"""Return the first child of node with a matching name and
namespace uri, or the default if one is provided."""
nsmatch = self.nsUriMatch
ELEMENT_NODE = node.ELEMENT_NODE
for child in node.childNodes:
if child.nodeType == ELEMENT_NODE:
if ((child.localName == name or name is None) and
(nsuri is None or nsmatch(child.namespaceURI, nsuri))
):
return child
if default is not join:
return default
raise KeyError, name
def getElementById(self, node, id, default=join):
"""Return the first child of node matching an id reference."""
attrget = self.getAttr
ELEMENT_NODE = node.ELEMENT_NODE
for child in node.childNodes:
if child.nodeType == ELEMENT_NODE:
if attrget(child, 'id') == id:
return child
if default is not join:
return default
raise KeyError, name
def getMappingById(self, document, depth=None, element=None,
mapping=None, level=1):
"""Create an id -> element mapping of those elements within a
document that define an id attribute. The depth of the search
may be controlled by using the (1-based) depth argument."""
if document is not None:
element = document.documentElement
mapping = {}
attr = element._attrs.get('id', None)
if attr is not None:
mapping[attr.value] = element
if depth is None or depth > level:
level = level + 1
ELEMENT_NODE = element.ELEMENT_NODE
for child in element.childNodes:
if child.nodeType == ELEMENT_NODE:
self.getMappingById(None, depth, child, mapping, level)
return mapping
def getElements(self, node, name, nsuri=None):
"""Return a sequence of the child elements of the given node that
match the given name and optional namespace uri."""
nsmatch = self.nsUriMatch
result = []
ELEMENT_NODE = node.ELEMENT_NODE
for child in node.childNodes:
if child.nodeType == ELEMENT_NODE:
if ((child.localName == name or name is None) and (
(nsuri is None) or nsmatch(child.namespaceURI, nsuri))):
result.append(child)
return result
def hasAttr(self, node, name, nsuri=None):
"""Return true if element has attribute with the given name and
optional nsuri. If nsuri is not specified, returns true if an
attribute exists with the given name with any namespace."""
if nsuri is None:
if node.hasAttribute(name):
return True
return False
return node.hasAttributeNS(nsuri, name)
def getAttr(self, node, name, nsuri=None, default=join):
"""Return the value of the attribute named 'name' with the
optional nsuri, or the default if one is specified. If
nsuri is not specified, an attribute that matches the
given name will be returned regardless of namespace."""
if nsuri is None:
result = node._attrs.get(name, None)
if result is None:
for item in node._attrsNS.keys():
if item[1] == name:
result = node._attrsNS[item]
break
else:
result = node._attrsNS.get((nsuri, name), None)
if result is not None:
return result.value
if default is not join:
return default
return ''
def getAttrs(self, node):
"""Return a Collection of all attributes
"""
attrs = {}
for k,v in node._attrs.items():
attrs[k] = v.value
return attrs
def getElementText(self, node, preserve_ws=None):
"""Return the text value of an xml element node. Leading and trailing
whitespace is stripped from the value unless the preserve_ws flag
is passed with a true value."""
result = []
for child in node.childNodes:
nodetype = child.nodeType
if nodetype == child.TEXT_NODE or \
nodetype == child.CDATA_SECTION_NODE:
result.append(child.nodeValue)
value = join(result, '')
if preserve_ws is None:
value = strip(value)
return value
def findNamespaceURI(self, prefix, node):
"""Find a namespace uri given a prefix and a context node."""
attrkey = (self.NS_XMLNS, prefix)
DOCUMENT_NODE = node.DOCUMENT_NODE
ELEMENT_NODE = node.ELEMENT_NODE
while 1:
if node is None:
raise DOMException('Value for prefix %s not found.' % prefix)
if node.nodeType != ELEMENT_NODE:
node = node.parentNode
continue
result = node._attrsNS.get(attrkey, None)
if result is not None:
return result.value
if hasattr(node, '__imported__'):
raise DOMException('Value for prefix %s not found.' % prefix)
node = node.parentNode
if node.nodeType == DOCUMENT_NODE:
raise DOMException('Value for prefix %s not found.' % prefix)
def findDefaultNS(self, node):
"""Return the current default namespace uri for the given node."""
attrkey = (self.NS_XMLNS, 'xmlns')
DOCUMENT_NODE = node.DOCUMENT_NODE
ELEMENT_NODE = node.ELEMENT_NODE
while 1:
if node.nodeType != ELEMENT_NODE:
node = node.parentNode
continue
result = node._attrsNS.get(attrkey, None)
if result is not None:
return result.value
if hasattr(node, '__imported__'):
raise DOMException('Cannot determine default namespace.')
node = node.parentNode
if node.nodeType == DOCUMENT_NODE:
raise DOMException('Cannot determine default namespace.')
def findTargetNS(self, node):
"""Return the defined target namespace uri for the given node."""
attrget = self.getAttr
attrkey = (self.NS_XMLNS, 'xmlns')
DOCUMENT_NODE = node.DOCUMENT_NODE
ELEMENT_NODE = node.ELEMENT_NODE
while 1:
if node.nodeType != ELEMENT_NODE:
node = node.parentNode
continue
result = attrget(node, 'targetNamespace', default=None)
if result is not None:
return result
node = node.parentNode
if node.nodeType == DOCUMENT_NODE:
raise DOMException('Cannot determine target namespace.')
def getTypeRef(self, element):
"""Return (namespaceURI, name) for a type attribue of the given
element, or None if the element does not have a type attribute."""
typeattr = self.getAttr(element, 'type', default=None)
if typeattr is None:
return None
parts = typeattr.split(':', 1)
if len(parts) == 2:
nsuri = self.findNamespaceURI(parts[0], element)
else:
nsuri = self.findDefaultNS(element)
return (nsuri, parts[1])
def importNode(self, document, node, deep=0):
"""Implements (well enough for our purposes) DOM node import."""
nodetype = node.nodeType
if nodetype in (node.DOCUMENT_NODE, node.DOCUMENT_TYPE_NODE):
raise DOMException('Illegal node type for importNode')
if nodetype == node.ENTITY_REFERENCE_NODE:
deep = 0
clone = node.cloneNode(deep)
self._setOwnerDoc(document, clone)
clone.__imported__ = 1
return clone
def _setOwnerDoc(self, document, node):
node.ownerDocument = document
for child in node.childNodes:
self._setOwnerDoc(document, child)
def nsUriMatch(self, value, wanted, strict=0, tt=type(())):
"""Return a true value if two namespace uri values match."""
if value == wanted or (type(wanted) is tt) and value in wanted:
return 1
if not strict and value is not None:
wanted = type(wanted) is tt and wanted or (wanted,)
value = value[-1:] != '/' and value or value[:-1]
for item in wanted:
if item == value or item[:-1] == value:
return 1
return 0
def createDocument(self, nsuri, qname, doctype=None):
"""Create a new writable DOM document object."""
impl = xml.dom.minidom.getDOMImplementation()
return impl.createDocument(nsuri, qname, doctype)
def loadDocument(self, data):
"""Load an xml file from a file-like object and return a DOM
document instance."""
return xml.dom.minidom.parse(data)
def loadFromURL(self, url):
"""Load an xml file from a URL and return a DOM document."""
if isfile(url) is True:
file = open(url, 'r')
else:
file = urlopen(url)
try:
result = self.loadDocument(file)
except Exception, ex:
file.close()
raise ParseError(('Failed to load document %s' %url,) + ex.args)
else:
file.close()
return result
DOM = DOM()
class MessageInterface:
'''Higher Level Interface, delegates to DOM singleton, must
be subclassed and implement all methods that throw NotImplementedError.
'''
def __init__(self, sw):
'''Constructor, May be extended, do not override.
sw -- soapWriter instance
'''
self.sw = None
if type(sw) != weakref.ReferenceType and sw is not None:
self.sw = weakref.ref(sw)
else:
self.sw = sw
def AddCallback(self, func, *arglist):
self.sw().AddCallback(func, *arglist)
def Known(self, obj):
return self.sw().Known(obj)
def Forget(self, obj):
return self.sw().Forget(obj)
def canonicalize(self):
'''canonicalize the underlying DOM, and return as string.
'''
raise NotImplementedError, ''
def createDocument(self, namespaceURI=SOAP.ENV, localName='Envelope'):
'''create Document
'''
raise NotImplementedError, ''
def createAppendElement(self, namespaceURI, localName):
'''create and append element(namespaceURI,localName), and return
the node.
'''
raise NotImplementedError, ''
def findNamespaceURI(self, qualifiedName):
raise NotImplementedError, ''
def resolvePrefix(self, prefix):
raise NotImplementedError, ''
def setAttributeNS(self, namespaceURI, localName, value):
'''set attribute (namespaceURI, localName)=value
'''
raise NotImplementedError, ''
def setAttributeType(self, namespaceURI, localName):
'''set attribute xsi:type=(namespaceURI, localName)
'''
raise NotImplementedError, ''
def setNamespaceAttribute(self, namespaceURI, prefix):
'''set namespace attribute xmlns:prefix=namespaceURI
'''
raise NotImplementedError, ''
class ElementProxy(Base, MessageInterface):
'''
'''
_soap_env_prefix = 'SOAP-ENV'
_soap_enc_prefix = 'SOAP-ENC'
_zsi_prefix = 'ZSI'
_xsd_prefix = 'xsd'
_xsi_prefix = 'xsi'
_xml_prefix = 'xml'
_xmlns_prefix = 'xmlns'
_soap_env_nsuri = SOAP.ENV
_soap_enc_nsuri = SOAP.ENC
_zsi_nsuri = ZSI_SCHEMA_URI
_xsd_nsuri = SCHEMA.XSD3
_xsi_nsuri = SCHEMA.XSI3
_xml_nsuri = XMLNS.XML
_xmlns_nsuri = XMLNS.BASE
standard_ns = {\
_xml_prefix:_xml_nsuri,
_xmlns_prefix:_xmlns_nsuri
}
reserved_ns = {\
_soap_env_prefix:_soap_env_nsuri,
_soap_enc_prefix:_soap_enc_nsuri,
_zsi_prefix:_zsi_nsuri,
_xsd_prefix:_xsd_nsuri,
_xsi_prefix:_xsi_nsuri,
}
name = None
namespaceURI = None
def __init__(self, sw, message=None):
'''Initialize.
sw -- SoapWriter
'''
self._indx = 0
MessageInterface.__init__(self, sw)
Base.__init__(self)
self._dom = DOM
self.node = None
if type(message) in (types.StringType,types.UnicodeType):
self.loadFromString(message)
elif isinstance(message, ElementProxy):
self.node = message._getNode()
else:
self.node = message
self.processorNss = self.standard_ns.copy()
self.processorNss.update(self.reserved_ns)
def __str__(self):
return self.toString()
def evaluate(self, expression, processorNss=None):
'''expression -- XPath compiled expression
'''
from Ft.Xml import XPath
if not processorNss:
context = XPath.Context.Context(self.node, processorNss=self.processorNss)
else:
context = XPath.Context.Context(self.node, processorNss=processorNss)
nodes = expression.evaluate(context)
return map(lambda node: ElementProxy(self.sw,node), nodes)
#############################################
# Methods for checking/setting the
# classes (namespaceURI,name) node.
#############################################
def checkNode(self, namespaceURI=None, localName=None):
'''
namespaceURI -- namespace of element
localName -- local name of element
'''
namespaceURI = namespaceURI or self.namespaceURI
localName = localName or self.name
check = False
if localName and self.node:
check = self._dom.isElement(self.node, localName, namespaceURI)
if not check:
raise NamespaceError, 'unexpected node type %s, expecting %s' %(self.node, localName)
def setNode(self, node=None):
if node:
if isinstance(node, ElementProxy):
self.node = node._getNode()
else:
self.node = node
elif self.node:
node = self._dom.getElement(self.node, self.name, self.namespaceURI, default=None)
if not node:
raise NamespaceError, 'cant find element (%s,%s)' %(self.namespaceURI,self.name)
self.node = node
else:
#self.node = self._dom.create(self.node, self.name, self.namespaceURI, default=None)
self.createDocument(self.namespaceURI, localName=self.name, doctype=None)
self.checkNode()
#############################################
# Wrapper Methods for direct DOM Element Node access
#############################################
def _getNode(self):
return self.node
def _getElements(self):
return self._dom.getElements(self.node, name=None)
def _getOwnerDocument(self):
return self.node.ownerDocument or self.node
def _getUniquePrefix(self):
'''I guess we need to resolve all potential prefixes
because when the current node is attached it copies the
namespaces into the parent node.
'''
while 1:
self._indx += 1
prefix = 'ns%d' %self._indx
try:
self._dom.findNamespaceURI(prefix, self._getNode())
except DOMException, ex:
break
return prefix
def _getPrefix(self, node, nsuri):
'''
Keyword arguments:
node -- DOM Element Node
nsuri -- namespace of attribute value
'''
try:
if node and (node.nodeType == node.ELEMENT_NODE) and \
(nsuri == self._dom.findDefaultNS(node)):
return None
except DOMException, ex:
pass
if nsuri == XMLNS.XML:
return self._xml_prefix
if node.nodeType == Node.ELEMENT_NODE:
for attr in node.attributes.values():
if attr.namespaceURI == XMLNS.BASE \
and nsuri == attr.value:
return attr.localName
else:
if node.parentNode:
return self._getPrefix(node.parentNode, nsuri)
raise NamespaceError, 'namespaceURI "%s" is not defined' %nsuri
def _appendChild(self, node):
'''
Keyword arguments:
node -- DOM Element Node
'''
if node is None:
raise TypeError, 'node is None'
self.node.appendChild(node)
def _insertBefore(self, newChild, refChild):
'''
Keyword arguments:
child -- DOM Element Node to insert
refChild -- DOM Element Node
'''
self.node.insertBefore(newChild, refChild)
def _setAttributeNS(self, namespaceURI, qualifiedName, value):
'''
Keyword arguments:
namespaceURI -- namespace of attribute
qualifiedName -- qualified name of new attribute value
value -- value of attribute
'''
self.node.setAttributeNS(namespaceURI, qualifiedName, value)
#############################################
#General Methods
#############################################
def isFault(self):
'''check to see if this is a soap:fault message.
'''
return False
def getPrefix(self, namespaceURI):
try:
prefix = self._getPrefix(node=self.node, nsuri=namespaceURI)
except NamespaceError, ex:
prefix = self._getUniquePrefix()
self.setNamespaceAttribute(prefix, namespaceURI)
return prefix
def getDocument(self):
return self._getOwnerDocument()
def setDocument(self, document):
self.node = document
def importFromString(self, xmlString):
doc = self._dom.loadDocument(StringIO(xmlString))
node = self._dom.getElement(doc, name=None)
clone = self.importNode(node)
self._appendChild(clone)
def importNode(self, node):
if isinstance(node, ElementProxy):
node = node._getNode()
return self._dom.importNode(self._getOwnerDocument(), node, deep=1)
def loadFromString(self, data):
self.node = self._dom.loadDocument(StringIO(data))
def canonicalize(self):
return Canonicalize(self.node)
def toString(self):
return self.canonicalize()
def createDocument(self, namespaceURI, localName, doctype=None):
'''If specified must be a SOAP envelope, else may contruct an empty document.
'''
prefix = self._soap_env_prefix
if namespaceURI == self.reserved_ns[prefix]:
qualifiedName = '%s:%s' %(prefix,localName)
elif namespaceURI is localName is None:
self.node = self._dom.createDocument(None,None,None)
return
else:
raise KeyError, 'only support creation of document in %s' %self.reserved_ns[prefix]
document = self._dom.createDocument(nsuri=namespaceURI, qname=qualifiedName, doctype=doctype)
self.node = document.childNodes[0]
#set up reserved namespace attributes
for prefix,nsuri in self.reserved_ns.items():
self._setAttributeNS(namespaceURI=self._xmlns_nsuri,
qualifiedName='%s:%s' %(self._xmlns_prefix,prefix),
value=nsuri)
#############################################
#Methods for attributes
#############################################
def hasAttribute(self, namespaceURI, localName):
return self._dom.hasAttr(self._getNode(), name=localName, nsuri=namespaceURI)
def setAttributeType(self, namespaceURI, localName):
'''set xsi:type
Keyword arguments:
namespaceURI -- namespace of attribute value
localName -- name of new attribute value
'''
self.logger.debug('setAttributeType: (%s,%s)', namespaceURI, localName)
value = localName
if namespaceURI:
value = '%s:%s' %(self.getPrefix(namespaceURI),localName)
xsi_prefix = self.getPrefix(self._xsi_nsuri)
self._setAttributeNS(self._xsi_nsuri, '%s:type' %xsi_prefix, value)
def createAttributeNS(self, namespace, name, value):
document = self._getOwnerDocument()
##this function doesn't exist!! it has only two arguments
attrNode = document.createAttributeNS(namespace, name, value)
def setAttributeNS(self, namespaceURI, localName, value):
'''
Keyword arguments:
namespaceURI -- namespace of attribute to create, None is for
attributes in no namespace.
localName -- local name of new attribute
value -- value of new attribute
'''
prefix = None
if namespaceURI:
try:
prefix = self.getPrefix(namespaceURI)
except KeyError, ex:
prefix = 'ns2'
self.setNamespaceAttribute(prefix, namespaceURI)
qualifiedName = localName
if prefix:
qualifiedName = '%s:%s' %(prefix, localName)
self._setAttributeNS(namespaceURI, qualifiedName, value)
def setNamespaceAttribute(self, prefix, namespaceURI):
'''
Keyword arguments:
prefix -- xmlns prefix
namespaceURI -- value of prefix
'''
self._setAttributeNS(XMLNS.BASE, 'xmlns:%s' %prefix, namespaceURI)
#############################################
#Methods for elements
#############################################
def createElementNS(self, namespace, qname):
'''
Keyword arguments:
namespace -- namespace of element to create
qname -- qualified name of new element
'''
document = self._getOwnerDocument()
node = document.createElementNS(namespace, qname)
return ElementProxy(self.sw, node)
def createAppendSetElement(self, namespaceURI, localName, prefix=None):
'''Create a new element (namespaceURI,name), append it
to current node, then set it to be the current node.
Keyword arguments:
namespaceURI -- namespace of element to create
localName -- local name of new element
prefix -- if namespaceURI is not defined, declare prefix. defaults
to 'ns1' if left unspecified.
'''
node = self.createAppendElement(namespaceURI, localName, prefix=None)
node=node._getNode()
self._setNode(node._getNode())
def createAppendElement(self, namespaceURI, localName, prefix=None):
'''Create a new element (namespaceURI,name), append it
to current node, and return the newly created node.
Keyword arguments:
namespaceURI -- namespace of element to create
localName -- local name of new element
prefix -- if namespaceURI is not defined, declare prefix. defaults
to 'ns1' if left unspecified.
'''
declare = False
qualifiedName = localName
if namespaceURI:
try:
prefix = self.getPrefix(namespaceURI)
except:
declare = True
prefix = prefix or self._getUniquePrefix()
if prefix:
qualifiedName = '%s:%s' %(prefix, localName)
node = self.createElementNS(namespaceURI, qualifiedName)
if declare:
node._setAttributeNS(XMLNS.BASE, 'xmlns:%s' %prefix, namespaceURI)
self._appendChild(node=node._getNode())
return node
def createInsertBefore(self, namespaceURI, localName, refChild):
qualifiedName = localName
prefix = self.getPrefix(namespaceURI)
if prefix:
qualifiedName = '%s:%s' %(prefix, localName)
node = self.createElementNS(namespaceURI, qualifiedName)
self._insertBefore(newChild=node._getNode(), refChild=refChild._getNode())
return node
def getElement(self, namespaceURI, localName):
'''
Keyword arguments:
namespaceURI -- namespace of element
localName -- local name of element
'''
node = self._dom.getElement(self.node, localName, namespaceURI, default=None)
if node:
return ElementProxy(self.sw, node)
return None
def getAttributeValue(self, namespaceURI, localName):
'''
Keyword arguments:
namespaceURI -- namespace of attribute
localName -- local name of attribute
'''
if self.hasAttribute(namespaceURI, localName):
attr = self.node.getAttributeNodeNS(namespaceURI,localName)
return attr.value
return None
def getValue(self):
return self._dom.getElementText(self.node, preserve_ws=True)
#############################################
#Methods for text nodes
#############################################
def createAppendTextNode(self, pyobj):
node = self.createTextNode(pyobj)
self._appendChild(node=node._getNode())
return node
def createTextNode(self, pyobj):
document = self._getOwnerDocument()
node = document.createTextNode(pyobj)
return ElementProxy(self.sw, node)
#############################################
#Methods for retrieving namespaceURI's
#############################################
def findNamespaceURI(self, qualifiedName):
parts = SplitQName(qualifiedName)
element = self._getNode()
if len(parts) == 1:
return (self._dom.findTargetNS(element), value)
return self._dom.findNamespaceURI(parts[0], element)
def resolvePrefix(self, prefix):
element = self._getNode()
return self._dom.findNamespaceURI(prefix, element)
def getSOAPEnvURI(self):
return self._soap_env_nsuri
def isEmpty(self):
return not self.node
class Collection(UserDict):
"""Helper class for maintaining ordered named collections."""
default = lambda self,k: k.name
def __init__(self, parent, key=None):
UserDict.__init__(self)
self.parent = weakref.ref(parent)
self.list = []
self._func = key or self.default
def __getitem__(self, key):
if type(key) is type(1):
return self.list[key]
return self.data[key]
def __setitem__(self, key, item):
item.parent = weakref.ref(self)
self.list.append(item)
self.data[key] = item
def keys(self):
return map(lambda i: self._func(i), self.list)
def items(self):
return map(lambda i: (self._func(i), i), self.list)
def values(self):
return self.list
class CollectionNS(UserDict):
"""Helper class for maintaining ordered named collections."""
default = lambda self,k: k.name
def __init__(self, parent, key=None):
UserDict.__init__(self)
self.parent = weakref.ref(parent)
self.targetNamespace = None
self.list = []
self._func = key or self.default
def __getitem__(self, key):
self.targetNamespace = self.parent().targetNamespace
if type(key) is types.IntType:
return self.list[key]
elif self.__isSequence(key):
nsuri,name = key
return self.data[nsuri][name]
return self.data[self.parent().targetNamespace][key]
def __setitem__(self, key, item):
item.parent = weakref.ref(self)
self.list.append(item)
targetNamespace = getattr(item, 'targetNamespace', self.parent().targetNamespace)
if not self.data.has_key(targetNamespace):
self.data[targetNamespace] = {}
self.data[targetNamespace][key] = item
def __isSequence(self, key):
return (type(key) in (types.TupleType,types.ListType) and len(key) == 2)
def keys(self):
keys = []
for tns in self.data.keys():
keys.append(map(lambda i: (tns,self._func(i)), self.data[tns].values()))
return keys
def items(self):
return map(lambda i: (self._func(i), i), self.list)
def values(self):
return self.list
# This is a runtime guerilla patch for pulldom (used by minidom) so
# that xml namespace declaration attributes are not lost in parsing.
# We need them to do correct QName linking for XML Schema and WSDL.
# The patch has been submitted to SF for the next Python version.
from xml.dom.pulldom import PullDOM, START_ELEMENT
if 1:
def startPrefixMapping(self, prefix, uri):
if not hasattr(self, '_xmlns_attrs'):
self._xmlns_attrs = []
self._xmlns_attrs.append((prefix or 'xmlns', uri))
self._ns_contexts.append(self._current_context.copy())
self._current_context[uri] = prefix or ''
PullDOM.startPrefixMapping = startPrefixMapping
def startElementNS(self, name, tagName , attrs):
# Retrieve xml namespace declaration attributes.
xmlns_uri = 'http://www.w3.org/2000/xmlns/'
xmlns_attrs = getattr(self, '_xmlns_attrs', None)
if xmlns_attrs is not None:
for aname, value in xmlns_attrs:
attrs._attrs[(xmlns_uri, aname)] = value
self._xmlns_attrs = []
uri, localname = name
if uri:
# When using namespaces, the reader may or may not
# provide us with the original name. If not, create
# *a* valid tagName from the current context.
if tagName is None:
prefix = self._current_context[uri]
if prefix:
tagName = prefix + ":" + localname
else:
tagName = localname
if self.document:
node = self.document.createElementNS(uri, tagName)
else:
node = self.buildDocument(uri, tagName)
else:
# When the tagname is not prefixed, it just appears as
# localname
if self.document:
node = self.document.createElement(localname)
else:
node = self.buildDocument(None, localname)
for aname,value in attrs.items():
a_uri, a_localname = aname
if a_uri == xmlns_uri:
if a_localname == 'xmlns':
qname = a_localname
else:
qname = 'xmlns:' + a_localname
attr = self.document.createAttributeNS(a_uri, qname)
node.setAttributeNodeNS(attr)
elif a_uri:
prefix = self._current_context[a_uri]
if prefix:
qname = prefix + ":" + a_localname
else:
qname = a_localname
attr = self.document.createAttributeNS(a_uri, qname)
node.setAttributeNodeNS(attr)
else:
attr = self.document.createAttribute(a_localname)
node.setAttributeNode(attr)
attr.value = value
self.lastEvent[1] = [(START_ELEMENT, node), None]
self.lastEvent = self.lastEvent[1]
self.push(node)
PullDOM.startElementNS = startElementNS
#
# This is a runtime guerilla patch for minidom so
# that xmlns prefixed attributes dont raise AttributeErrors
# during cloning.
#
# Namespace declarations can appear in any start-tag, must look for xmlns
# prefixed attribute names during cloning.
#
# key (attr.namespaceURI, tag)
# ('http://www.w3.org/2000/xmlns/', u'xsd') <xml.dom.minidom.Attr instance at 0x82227c4>
# ('http://www.w3.org/2000/xmlns/', 'xmlns') <xml.dom.minidom.Attr instance at 0x8414b3c>
#
# xml.dom.minidom.Attr.nodeName = xmlns:xsd
# xml.dom.minidom.Attr.value = = http://www.w3.org/2001/XMLSchema
if 1:
def _clone_node(node, deep, newOwnerDocument):
"""
Clone a node and give it the new owner document.
Called by Node.cloneNode and Document.importNode
"""
if node.ownerDocument.isSameNode(newOwnerDocument):
operation = xml.dom.UserDataHandler.NODE_CLONED
else:
operation = xml.dom.UserDataHandler.NODE_IMPORTED
if node.nodeType == xml.dom.minidom.Node.ELEMENT_NODE:
clone = newOwnerDocument.createElementNS(node.namespaceURI,
node.nodeName)
for attr in node.attributes.values():
clone.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value)
prefix, tag = xml.dom.minidom._nssplit(attr.nodeName)
if prefix == 'xmlns':
a = clone.getAttributeNodeNS(attr.namespaceURI, tag)
elif prefix:
a = clone.getAttributeNodeNS(attr.namespaceURI, tag)
else:
a = clone.getAttributeNodeNS(attr.namespaceURI, attr.nodeName)
a.specified = attr.specified
if deep:
for child in node.childNodes:
c = xml.dom.minidom._clone_node(child, deep, newOwnerDocument)
clone.appendChild(c)
elif node.nodeType == xml.dom.minidom.Node.DOCUMENT_FRAGMENT_NODE:
clone = newOwnerDocument.createDocumentFragment()
if deep:
for child in node.childNodes:
c = xml.dom.minidom._clone_node(child, deep, newOwnerDocument)
clone.appendChild(c)
elif node.nodeType == xml.dom.minidom.Node.TEXT_NODE:
clone = newOwnerDocument.createTextNode(node.data)
elif node.nodeType == xml.dom.minidom.Node.CDATA_SECTION_NODE:
clone = newOwnerDocument.createCDATASection(node.data)
elif node.nodeType == xml.dom.minidom.Node.PROCESSING_INSTRUCTION_NODE:
clone = newOwnerDocument.createProcessingInstruction(node.target,
node.data)
elif node.nodeType == xml.dom.minidom.Node.COMMENT_NODE:
clone = newOwnerDocument.createComment(node.data)
elif node.nodeType == xml.dom.minidom.Node.ATTRIBUTE_NODE:
clone = newOwnerDocument.createAttributeNS(node.namespaceURI,
node.nodeName)
clone.specified = True
clone.value = node.value
elif node.nodeType == xml.dom.minidom.Node.DOCUMENT_TYPE_NODE:
assert node.ownerDocument is not newOwnerDocument
operation = xml.dom.UserDataHandler.NODE_IMPORTED
clone = newOwnerDocument.implementation.createDocumentType(
node.name, node.publicId, node.systemId)
clone.ownerDocument = newOwnerDocument
if deep:
clone.entities._seq = []
clone.notations._seq = []
for n in node.notations._seq:
notation = xml.dom.minidom.Notation(n.nodeName, n.publicId, n.systemId)
notation.ownerDocument = newOwnerDocument
clone.notations._seq.append(notation)
if hasattr(n, '_call_user_data_handler'):
n._call_user_data_handler(operation, n, notation)
for e in node.entities._seq:
entity = xml.dom.minidom.Entity(e.nodeName, e.publicId, e.systemId,
e.notationName)
entity.actualEncoding = e.actualEncoding
entity.encoding = e.encoding
entity.version = e.version
entity.ownerDocument = newOwnerDocument
clone.entities._seq.append(entity)
if hasattr(e, '_call_user_data_handler'):
e._call_user_data_handler(operation, n, entity)
else:
# Note the cloning of Document and DocumentType nodes is
# implemenetation specific. minidom handles those cases
# directly in the cloneNode() methods.
raise xml.dom.NotSupportedErr("Cannot clone node %s" % repr(node))
# Check for _call_user_data_handler() since this could conceivably
# used with other DOM implementations (one of the FourThought
# DOMs, perhaps?).
if hasattr(node, '_call_user_data_handler'):
node._call_user_data_handler(operation, node, clone)
return clone
xml.dom.minidom._clone_node = _clone_node
| gpl-3.0 |
madgik/exareme | Exareme-Docker/src/exareme/exareme-tools/madis/src/functionslocal/vtable/dummycoding.py | 1 | 2450 | import setpath
import functions
import json
registered=True
def convert(data):
if isinstance(data, basestring):
return str(data)
elif isinstance(data, collections.Mapping):
return dict(map(convert, data.iteritems()))
elif isinstance(data, collections.Iterable):
return type(data)(map(convert, data))
else:
return data
class dummycoding(functions.vtable.vtbase.VT):
def VTiter(self, *parsedArgs,**envars):
largs, dictargs = self.full_parse(parsedArgs)
if 'query' not in dictargs:
raise functions.OperatorError(__name__.rsplit('.')[-1],"No query argument ")
query = dictargs['query']
if 'metadata' not in dictargs:
raise functions.OperatorError(__name__.rsplit('.')[-1],"No metadata ")
metadata = json.loads(dictargs['metadata'])
cur = envars['db'].cursor()
c=cur.execute(query)
schema = cur.getdescriptionsafe()
no = 0
for myrow in c:
first_tuple = []
schema1 = []
for item in xrange(len(schema)):
if schema[item][0] in metadata:
vals = metadata[schema[item][0]].split(',')
vals.sort()
for v in vals:
newv = str(schema[item][0]) + '(' + str(v) + ')'
schema1.append(newv)
if myrow[item] == v:
first_tuple.append(1)
else :
first_tuple.append(0)
else:
# print 'no', schema[item][0]
newv = str(schema[item][0])
schema1.append(newv)
first_tuple.append(myrow[item])
if no == 0:
# print tuple((x,) for x in schema1)
yield tuple((x,) for x in schema1)
no =no+1
# print str(first_tuple)
yield tuple(first_tuple,)
def Source():
return functions.vtable.vtbase.VTGenerator(dummycoding)
if not ('.' in __name__):
"""
This is needed to be able to test the function, put it at the end of every
new function you create
"""
import sys
import setpath
from functions import *
testfunction()
if __name__ == "__main__":
reload(sys)
sys.setdefaultencoding('utf-8')
import doctest
doctest.tes | mit |
sloria/TextBlob | tests/test_inflect.py | 2 | 1177 | from nose.tools import assert_equals, assert_true
from unittest import TestCase
from textblob.en.inflect import (
plural_categories,
singular_ie,
singular_irregular,
singular_uncountable,
singular_uninflected,
singularize,
pluralize
)
class InflectTestCase(TestCase):
def s_singular_pluralize_test(self):
assert_equals(pluralize('lens'), 'lenses')
def s_singular_singularize_test(self):
assert_equals(singularize('lenses'), 'lens')
def diagnoses_singularize_test(self):
assert_equals(singularize('diagnoses'), 'diagnosis')
def bus_pluralize_test(self):
assert_equals(pluralize('bus'), 'buses')
def test_all_singular_s(self):
for w in plural_categories['s-singular']:
assert_equals(singularize(pluralize(w)), w)
def test_all_singular_ie(self):
for w in singular_ie:
assert_true(pluralize(w).endswith('ies'))
assert_equals(singularize(pluralize(w)), w)
def test_all_singular_irregular(self):
for singular_w in singular_irregular.values():
assert_equals(singular_irregular[pluralize(singular_w)], singular_w)
| mit |
aquajach/sample_teach | node_modules/node-sass/node_modules/node-gyp/gyp/pylib/gyp/flock_tool.py | 1835 | 1748 | #!/usr/bin/env python
# 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.
"""These functions are executed via gyp-flock-tool when using the Makefile
generator. Used on systems that don't have a built-in flock."""
import fcntl
import os
import struct
import subprocess
import sys
def main(args):
executor = FlockTool()
executor.Dispatch(args)
class FlockTool(object):
"""This class emulates the 'flock' command."""
def Dispatch(self, args):
"""Dispatches a string command to a method."""
if len(args) < 1:
raise Exception("Not enough arguments")
method = "Exec%s" % self._CommandifyName(args[0])
getattr(self, method)(*args[1:])
def _CommandifyName(self, name_string):
"""Transforms a tool name like copy-info-plist to CopyInfoPlist"""
return name_string.title().replace('-', '')
def ExecFlock(self, lockfile, *cmd_list):
"""Emulates the most basic behavior of Linux's flock(1)."""
# Rely on exception handling to report errors.
# Note that the stock python on SunOS has a bug
# where fcntl.flock(fd, LOCK_EX) always fails
# with EBADF, that's why we use this F_SETLK
# hack instead.
fd = os.open(lockfile, os.O_WRONLY|os.O_NOCTTY|os.O_CREAT, 0666)
if sys.platform.startswith('aix'):
# Python on AIX is compiled with LARGEFILE support, which changes the
# struct size.
op = struct.pack('hhIllqq', fcntl.F_WRLCK, 0, 0, 0, 0, 0, 0)
else:
op = struct.pack('hhllhhl', fcntl.F_WRLCK, 0, 0, 0, 0, 0, 0)
fcntl.fcntl(fd, fcntl.F_SETLK, op)
return subprocess.call(cmd_list)
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
| mit |
bjornlevi/5thpower | nefndaralit/env/lib/python3.6/site-packages/requests/cookies.py | 133 | 18430 | # -*- coding: utf-8 -*-
"""
requests.cookies
~~~~~~~~~~~~~~~~
Compatibility code to be able to use `cookielib.CookieJar` with requests.
requests.utils imports from here, so be careful with imports.
"""
import copy
import time
import calendar
from ._internal_utils import to_native_string
from .compat import cookielib, urlparse, urlunparse, Morsel, MutableMapping
try:
import threading
except ImportError:
import dummy_threading as threading
class MockRequest(object):
"""Wraps a `requests.Request` to mimic a `urllib2.Request`.
The code in `cookielib.CookieJar` expects this interface in order to correctly
manage cookie policies, i.e., determine whether a cookie can be set, given the
domains of the request and the cookie.
The original request object is read-only. The client is responsible for collecting
the new headers via `get_new_headers()` and interpreting them appropriately. You
probably want `get_cookie_header`, defined below.
"""
def __init__(self, request):
self._r = request
self._new_headers = {}
self.type = urlparse(self._r.url).scheme
def get_type(self):
return self.type
def get_host(self):
return urlparse(self._r.url).netloc
def get_origin_req_host(self):
return self.get_host()
def get_full_url(self):
# Only return the response's URL if the user hadn't set the Host
# header
if not self._r.headers.get('Host'):
return self._r.url
# If they did set it, retrieve it and reconstruct the expected domain
host = to_native_string(self._r.headers['Host'], encoding='utf-8')
parsed = urlparse(self._r.url)
# Reconstruct the URL as we expect it
return urlunparse([
parsed.scheme, host, parsed.path, parsed.params, parsed.query,
parsed.fragment
])
def is_unverifiable(self):
return True
def has_header(self, name):
return name in self._r.headers or name in self._new_headers
def get_header(self, name, default=None):
return self._r.headers.get(name, self._new_headers.get(name, default))
def add_header(self, key, val):
"""cookielib has no legitimate use for this method; add it back if you find one."""
raise NotImplementedError("Cookie headers should be added with add_unredirected_header()")
def add_unredirected_header(self, name, value):
self._new_headers[name] = value
def get_new_headers(self):
return self._new_headers
@property
def unverifiable(self):
return self.is_unverifiable()
@property
def origin_req_host(self):
return self.get_origin_req_host()
@property
def host(self):
return self.get_host()
class MockResponse(object):
"""Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.
...what? Basically, expose the parsed HTTP headers from the server response
the way `cookielib` expects to see them.
"""
def __init__(self, headers):
"""Make a MockResponse for `cookielib` to read.
:param headers: a httplib.HTTPMessage or analogous carrying the headers
"""
self._headers = headers
def info(self):
return self._headers
def getheaders(self, name):
self._headers.getheaders(name)
def extract_cookies_to_jar(jar, request, response):
"""Extract the cookies from the response into a CookieJar.
:param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar)
:param request: our own requests.Request object
:param response: urllib3.HTTPResponse object
"""
if not (hasattr(response, '_original_response') and
response._original_response):
return
# the _original_response field is the wrapped httplib.HTTPResponse object,
req = MockRequest(request)
# pull out the HTTPMessage with the headers and put it in the mock:
res = MockResponse(response._original_response.msg)
jar.extract_cookies(res, req)
def get_cookie_header(jar, request):
"""
Produce an appropriate Cookie header string to be sent with `request`, or None.
:rtype: str
"""
r = MockRequest(request)
jar.add_cookie_header(r)
return r.get_new_headers().get('Cookie')
def remove_cookie_by_name(cookiejar, name, domain=None, path=None):
"""Unsets a cookie by name, by default over all domains and paths.
Wraps CookieJar.clear(), is O(n).
"""
clearables = []
for cookie in cookiejar:
if cookie.name != name:
continue
if domain is not None and domain != cookie.domain:
continue
if path is not None and path != cookie.path:
continue
clearables.append((cookie.domain, cookie.path, cookie.name))
for domain, path, name in clearables:
cookiejar.clear(domain, path, name)
class CookieConflictError(RuntimeError):
"""There are two cookies that meet the criteria specified in the cookie jar.
Use .get and .set and include domain and path args in order to be more specific.
"""
class RequestsCookieJar(cookielib.CookieJar, MutableMapping):
"""Compatibility class; is a cookielib.CookieJar, but exposes a dict
interface.
This is the CookieJar we create by default for requests and sessions that
don't specify one, since some clients may expect response.cookies and
session.cookies to support dict operations.
Requests does not use the dict interface internally; it's just for
compatibility with external client code. All requests code should work
out of the box with externally provided instances of ``CookieJar``, e.g.
``LWPCookieJar`` and ``FileCookieJar``.
Unlike a regular CookieJar, this class is pickleable.
.. warning:: dictionary operations that are normally O(1) may be O(n).
"""
def get(self, name, default=None, domain=None, path=None):
"""Dict-like get() that also supports optional domain and path args in
order to resolve naming collisions from using one cookie jar over
multiple domains.
.. warning:: operation is O(n), not O(1).
"""
try:
return self._find_no_duplicates(name, domain, path)
except KeyError:
return default
def set(self, name, value, **kwargs):
"""Dict-like set() that also supports optional domain and path args in
order to resolve naming collisions from using one cookie jar over
multiple domains.
"""
# support client code that unsets cookies by assignment of a None value:
if value is None:
remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path'))
return
if isinstance(value, Morsel):
c = morsel_to_cookie(value)
else:
c = create_cookie(name, value, **kwargs)
self.set_cookie(c)
return c
def iterkeys(self):
"""Dict-like iterkeys() that returns an iterator of names of cookies
from the jar.
.. seealso:: itervalues() and iteritems().
"""
for cookie in iter(self):
yield cookie.name
def keys(self):
"""Dict-like keys() that returns a list of names of cookies from the
jar.
.. seealso:: values() and items().
"""
return list(self.iterkeys())
def itervalues(self):
"""Dict-like itervalues() that returns an iterator of values of cookies
from the jar.
.. seealso:: iterkeys() and iteritems().
"""
for cookie in iter(self):
yield cookie.value
def values(self):
"""Dict-like values() that returns a list of values of cookies from the
jar.
.. seealso:: keys() and items().
"""
return list(self.itervalues())
def iteritems(self):
"""Dict-like iteritems() that returns an iterator of name-value tuples
from the jar.
.. seealso:: iterkeys() and itervalues().
"""
for cookie in iter(self):
yield cookie.name, cookie.value
def items(self):
"""Dict-like items() that returns a list of name-value tuples from the
jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a
vanilla python dict of key value pairs.
.. seealso:: keys() and values().
"""
return list(self.iteritems())
def list_domains(self):
"""Utility method to list all the domains in the jar."""
domains = []
for cookie in iter(self):
if cookie.domain not in domains:
domains.append(cookie.domain)
return domains
def list_paths(self):
"""Utility method to list all the paths in the jar."""
paths = []
for cookie in iter(self):
if cookie.path not in paths:
paths.append(cookie.path)
return paths
def multiple_domains(self):
"""Returns True if there are multiple domains in the jar.
Returns False otherwise.
:rtype: bool
"""
domains = []
for cookie in iter(self):
if cookie.domain is not None and cookie.domain in domains:
return True
domains.append(cookie.domain)
return False # there is only one domain in jar
def get_dict(self, domain=None, path=None):
"""Takes as an argument an optional domain and path and returns a plain
old Python dict of name-value pairs of cookies that meet the
requirements.
:rtype: dict
"""
dictionary = {}
for cookie in iter(self):
if (
(domain is None or cookie.domain == domain) and
(path is None or cookie.path == path)
):
dictionary[cookie.name] = cookie.value
return dictionary
def __contains__(self, name):
try:
return super(RequestsCookieJar, self).__contains__(name)
except CookieConflictError:
return True
def __getitem__(self, name):
"""Dict-like __getitem__() for compatibility with client code. Throws
exception if there are more than one cookie with name. In that case,
use the more explicit get() method instead.
.. warning:: operation is O(n), not O(1).
"""
return self._find_no_duplicates(name)
def __setitem__(self, name, value):
"""Dict-like __setitem__ for compatibility with client code. Throws
exception if there is already a cookie of that name in the jar. In that
case, use the more explicit set() method instead.
"""
self.set(name, value)
def __delitem__(self, name):
"""Deletes a cookie given a name. Wraps ``cookielib.CookieJar``'s
``remove_cookie_by_name()``.
"""
remove_cookie_by_name(self, name)
def set_cookie(self, cookie, *args, **kwargs):
if hasattr(cookie.value, 'startswith') and cookie.value.startswith('"') and cookie.value.endswith('"'):
cookie.value = cookie.value.replace('\\"', '')
return super(RequestsCookieJar, self).set_cookie(cookie, *args, **kwargs)
def update(self, other):
"""Updates this jar with cookies from another CookieJar or dict-like"""
if isinstance(other, cookielib.CookieJar):
for cookie in other:
self.set_cookie(copy.copy(cookie))
else:
super(RequestsCookieJar, self).update(other)
def _find(self, name, domain=None, path=None):
"""Requests uses this method internally to get cookie values.
If there are conflicting cookies, _find arbitrarily chooses one.
See _find_no_duplicates if you want an exception thrown if there are
conflicting cookies.
:param name: a string containing name of cookie
:param domain: (optional) string containing domain of cookie
:param path: (optional) string containing path of cookie
:return: cookie.value
"""
for cookie in iter(self):
if cookie.name == name:
if domain is None or cookie.domain == domain:
if path is None or cookie.path == path:
return cookie.value
raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
def _find_no_duplicates(self, name, domain=None, path=None):
"""Both ``__get_item__`` and ``get`` call this function: it's never
used elsewhere in Requests.
:param name: a string containing name of cookie
:param domain: (optional) string containing domain of cookie
:param path: (optional) string containing path of cookie
:raises KeyError: if cookie is not found
:raises CookieConflictError: if there are multiple cookies
that match name and optionally domain and path
:return: cookie.value
"""
toReturn = None
for cookie in iter(self):
if cookie.name == name:
if domain is None or cookie.domain == domain:
if path is None or cookie.path == path:
if toReturn is not None: # if there are multiple cookies that meet passed in criteria
raise CookieConflictError('There are multiple cookies with name, %r' % (name))
toReturn = cookie.value # we will eventually return this as long as no cookie conflict
if toReturn:
return toReturn
raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
def __getstate__(self):
"""Unlike a normal CookieJar, this class is pickleable."""
state = self.__dict__.copy()
# remove the unpickleable RLock object
state.pop('_cookies_lock')
return state
def __setstate__(self, state):
"""Unlike a normal CookieJar, this class is pickleable."""
self.__dict__.update(state)
if '_cookies_lock' not in self.__dict__:
self._cookies_lock = threading.RLock()
def copy(self):
"""Return a copy of this RequestsCookieJar."""
new_cj = RequestsCookieJar()
new_cj.set_policy(self.get_policy())
new_cj.update(self)
return new_cj
def get_policy(self):
"""Return the CookiePolicy instance used."""
return self._policy
def _copy_cookie_jar(jar):
if jar is None:
return None
if hasattr(jar, 'copy'):
# We're dealing with an instance of RequestsCookieJar
return jar.copy()
# We're dealing with a generic CookieJar instance
new_jar = copy.copy(jar)
new_jar.clear()
for cookie in jar:
new_jar.set_cookie(copy.copy(cookie))
return new_jar
def create_cookie(name, value, **kwargs):
"""Make a cookie from underspecified parameters.
By default, the pair of `name` and `value` will be set for the domain ''
and sent on every request (this is sometimes called a "supercookie").
"""
result = {
'version': 0,
'name': name,
'value': value,
'port': None,
'domain': '',
'path': '/',
'secure': False,
'expires': None,
'discard': True,
'comment': None,
'comment_url': None,
'rest': {'HttpOnly': None},
'rfc2109': False,
}
badargs = set(kwargs) - set(result)
if badargs:
err = 'create_cookie() got unexpected keyword arguments: %s'
raise TypeError(err % list(badargs))
result.update(kwargs)
result['port_specified'] = bool(result['port'])
result['domain_specified'] = bool(result['domain'])
result['domain_initial_dot'] = result['domain'].startswith('.')
result['path_specified'] = bool(result['path'])
return cookielib.Cookie(**result)
def morsel_to_cookie(morsel):
"""Convert a Morsel object into a Cookie containing the one k/v pair."""
expires = None
if morsel['max-age']:
try:
expires = int(time.time() + int(morsel['max-age']))
except ValueError:
raise TypeError('max-age: %s must be integer' % morsel['max-age'])
elif morsel['expires']:
time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
expires = calendar.timegm(
time.strptime(morsel['expires'], time_template)
)
return create_cookie(
comment=morsel['comment'],
comment_url=bool(morsel['comment']),
discard=False,
domain=morsel['domain'],
expires=expires,
name=morsel.key,
path=morsel['path'],
port=None,
rest={'HttpOnly': morsel['httponly']},
rfc2109=False,
secure=bool(morsel['secure']),
value=morsel.value,
version=morsel['version'] or 0,
)
def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True):
"""Returns a CookieJar from a key/value dictionary.
:param cookie_dict: Dict of key/values to insert into CookieJar.
:param cookiejar: (optional) A cookiejar to add the cookies to.
:param overwrite: (optional) If False, will not replace cookies
already in the jar with new ones.
:rtype: CookieJar
"""
if cookiejar is None:
cookiejar = RequestsCookieJar()
if cookie_dict is not None:
names_from_jar = [cookie.name for cookie in cookiejar]
for name in cookie_dict:
if overwrite or (name not in names_from_jar):
cookiejar.set_cookie(create_cookie(name, cookie_dict[name]))
return cookiejar
def merge_cookies(cookiejar, cookies):
"""Add cookies to cookiejar and returns a merged CookieJar.
:param cookiejar: CookieJar object to add the cookies to.
:param cookies: Dictionary or CookieJar object to be added.
:rtype: CookieJar
"""
if not isinstance(cookiejar, cookielib.CookieJar):
raise ValueError('You can only merge into CookieJar')
if isinstance(cookies, dict):
cookiejar = cookiejar_from_dict(
cookies, cookiejar=cookiejar, overwrite=False)
elif isinstance(cookies, cookielib.CookieJar):
try:
cookiejar.update(cookies)
except AttributeError:
for cookie_in_jar in cookies:
cookiejar.set_cookie(cookie_in_jar)
return cookiejar
| mit |
ahaym/eden | modules/s3db/cms.py | 4 | 67968 | # -*- coding: utf-8 -*-
""" Sahana Eden Content Management System Model
@copyright: 2012-2015 (c) Sahana Software Foundation
@license: MIT
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, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
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 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS 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.
"""
__all__ = ("S3ContentModel",
"S3ContentMapModel",
"S3ContentOrgModel",
"S3ContentOrgGroupModel",
"S3ContentUserModel",
"cms_index",
"cms_documentation",
"cms_rheader",
"cms_customise_post_fields",
"cms_post_list_layout",
"S3CMS",
)
try:
import json # try stdlib (Python 2.6)
except ImportError:
try:
import simplejson as json # try external module
except:
import gluon.contrib.simplejson as json # fallback to pure-Python module
from gluon import *
from gluon.storage import Storage
from ..s3 import *
from s3layouts import S3AddResourceLink
# Compact JSON encoding
SEPARATORS = (",", ":")
# =============================================================================
class S3ContentModel(S3Model):
"""
Content Management System
"""
names = ("cms_series",
"cms_post",
"cms_post_id",
"cms_post_module",
"cms_tag",
"cms_tag_post",
"cms_comment",
)
def model(self):
T = current.T
db = current.db
add_components = self.add_components
configure = self.configure
crud_strings = current.response.s3.crud_strings
define_table = self.define_table
set_method = self.set_method
settings = current.deployment_settings
# ---------------------------------------------------------------------
# Series
# - lists of Posts displaying in recent-first mode
#
tablename = "cms_series"
define_table(tablename,
Field("name", length=255, notnull=True, unique=True,
label = T("Name"),
),
Field("avatar", "boolean",
default = False,
label = T("Show author picture?"),
represent = s3_yes_no_represent,
),
Field("location", "boolean",
default = False,
label = T("Show Location?"),
represent = s3_yes_no_represent,
),
Field("richtext", "boolean",
default = True,
label = T("Rich Text?"),
represent = s3_yes_no_represent,
),
Field("replies", "boolean",
default = False,
label = T("Comments permitted?"),
represent = s3_yes_no_represent,
),
s3_comments(),
# Multiple Roles (@ToDo: Implement the restriction)
s3_roles_permitted(readable = False,
writable = False
),
*s3_meta_fields())
# CRUD Strings
ADD_SERIES = T("Create Series")
crud_strings[tablename] = Storage(
label_create = ADD_SERIES,
title_display = T("Series Details"),
title_list = T("Series"),
title_update = T("Edit Series"),
title_upload = T("Import Series"),
label_list_button = T("List Series"),
msg_record_created = T("Series added"),
msg_record_modified = T("Series updated"),
msg_record_deleted = T("Series deleted"),
msg_list_empty = T("No series currently defined"))
# Reusable field
translate = settings.get_L10n_translate_cms_series()
represent = S3Represent(lookup=tablename, translate=translate)
series_id = S3ReusableField("series_id", "reference %s" % tablename,
label = T("Type"), # Even if this isn't always the use-case
ondelete = "CASCADE",
readable = False,
writable = False,
represent = represent,
requires = IS_EMPTY_OR(
IS_ONE_OF(db, "cms_series.id",
represent)),
)
# Resource Configuration
configure(tablename,
create_next = URL(f="series", args=["[id]", "post"]),
onaccept = self.cms_series_onaccept,
)
# Components
add_components(tablename,
cms_post = "series_id",
)
# ---------------------------------------------------------------------
# Posts
# - single blocks of [rich] text which can be embedded into a page,
# be viewed as full pages or as part of a Series
#
if settings.get_cms_richtext():
body_represent = lambda body: XML(body)
body_widget = s3_richtext_widget
else:
body_represent = lambda body: XML(s3_URLise(body))
body_widget = None
tablename = "cms_post"
define_table(tablename,
self.super_link("doc_id", "doc_entity"),
series_id(),
Field("name", #notnull=True,
comment = T("This isn't visible to the published site, but is used to allow menu items to point to the page"),
label = T("Name"),
),
Field("title",
comment = T("The title of the page, as seen in the browser (optional)"),
label = T("Title"),
),
Field("body", "text", notnull=True,
label = T("Body"),
represent = body_represent,
widget = body_widget,
),
# @ToDo: Move this to link table?
# - although this makes widget hard!
self.gis_location_id(),
# @ToDo: Move this to link table?
# - although this makes widget hard!
self.pr_person_id(label = T("Contact"),
# Enable only in certain conditions
readable = False,
writable = False,
),
Field("avatar", "boolean",
default = False,
label = T("Show author picture?"),
represent = s3_yes_no_represent,
),
Field("replies", "boolean",
default = False,
label = T("Comments permitted?"),
represent = s3_yes_no_represent,
),
s3_datetime(default = "now"),
# @ToDo: Also have a datetime for 'Expires On'
Field("expired", "boolean",
default = False,
label = T("Expired?"),
represent = s3_yes_no_represent,
),
#Field("published", "boolean",
# default=True,
# label=T("Published")),
s3_comments(),
# Multiple Roles (@ToDo: Implement the restriction)
s3_roles_permitted(readable = False,
writable = False
),
*s3_meta_fields())
# CRUD Strings
ADD_POST = T("Create Post")
crud_strings[tablename] = Storage(
label_create = ADD_POST,
title_display = T("Post Details"),
title_list = T("Posts"),
title_update = T("Edit Post"),
title_upload = T("Import Posts"),
label_list_button = T("List Posts"),
msg_record_created = T("Post added"),
msg_record_modified = T("Post updated"),
msg_record_deleted = T("Post deleted"),
msg_list_empty = T("No posts currently available"))
# Reusable field
represent = S3Represent(lookup=tablename)
post_id = S3ReusableField("post_id", "reference %s" % tablename,
comment = S3AddResourceLink(c="cms", f="post",
title=ADD_POST,
tooltip=T("A block of rich text which could be embedded into a page, viewed as a complete page or viewed as a list of news items.")),
label = T("Post"),
ondelete = "CASCADE",
represent = represent,
requires = IS_EMPTY_OR(
IS_ONE_OF(db, "cms_post.id",
represent)),
sortby = "name",
)
list_fields = ["title",
"body",
"location_id",
"date",
"expired",
"comments"
]
org_field = settings.get_cms_organisation()
if org_field == "created_by$organisation_id":
org_field = "auth_user.organisation_id"
elif org_field == "post_organisation.organisation_id":
org_field = "cms_post_organisation.organisation_id"
if org_field:
list_fields.append(org_field)
filter_widgets = [S3TextFilter(["body"],
label = T("Search"),
_class = "filter-search",
#_placeholder = T("Search").upper(),
),
S3OptionsFilter("series_id",
label = T("Type"),
hidden = True,
),
S3LocationFilter("location_id",
label = T("Location"),
hidden = True,
),
S3OptionsFilter("created_by$organisation_id",
label = T("Organization"),
# Can't use this for integers, use field.represent instead
#represent = "%(name)s",
hidden = True,
),
S3DateFilter("created_on",
label = T("Date"),
hide_time = True,
hidden = True,
),
]
# Resource Configuration
configure(tablename,
context = {"event": "event.id",
"incident": "incident.id",
"location": "location_id",
"organisation": "created_by$organisation_id",
},
deduplicate = self.cms_post_duplicate,
filter_actions = [{"label": "Open Table",
"icon": "table",
"function": "newsfeed",
"method": "datalist",
},
{"label": "Open Map",
"icon": "globe",
"method": "map",
},
{"label": "Open RSS Feed",
"icon": "rss",
"format": "rss",
},
],
filter_widgets = filter_widgets,
list_fields = list_fields,
list_layout = cms_post_list_layout,
list_orderby = "cms_post.date desc",
onaccept = self.cms_post_onaccept,
orderby = "cms_post.date desc",
summary = [{"name": "table",
"label": "Table",
"widgets": [{"method": "datatable"}]
},
#{"name": "report",
# "label": "Report",
# "widgets": [{"method": "report",
# "ajax_init": True}]
# },
{"name": "map",
"label": "Map",
"widgets": [{"method": "map",
"ajax_init": True}],
},
],
super_entity = "doc_entity",
)
# Components
add_components(tablename,
cms_comment = "post_id",
cms_post_layer = "post_id",
cms_post_module = "post_id",
cms_post_user = {"name": "bookmark",
"joinby": "post_id",
},
cms_tag = {"link": "cms_tag_post",
"joinby": "post_id",
"key": "tag_id",
"actuate": "hide",
},
# For filter widget
cms_tag_post = "post_id",
cms_post_organisation = {"joinby": "post_id",
# @ToDo: deployment_setting
"multiple": False,
},
cms_post_organisation_group = {"joinby": "post_id",
# @ToDo: deployment_setting
"multiple": False,
},
# For InlineForm to tag Posts to Events/Incidents/Incident Types
event_post = (# Events
{"name": "event_post",
"joinby": "post_id",
},
# Incidents
{"name": "incident_post",
"joinby": "post_id",
}
),
event_post_incident_type = "post_id",
# For Profile to filter appropriately
event_event = {"link": "event_post",
"joinby": "post_id",
"key": "event_id",
"actuate": "hide",
},
event_incident = {"link": "event_post",
"joinby": "post_id",
"key": "incident_id",
"actuate": "hide",
},
event_incident_type = {"link": "event_post_incident_type",
"joinby": "post_id",
"key": "incident_type_id",
"actuate": "hide",
},
)
# Custom Methods
set_method("cms", "post",
method = "add_tag",
action = self.cms_add_tag)
set_method("cms", "post",
method = "remove_tag",
action = self.cms_remove_tag)
set_method("cms", "post",
method = "add_bookmark",
action = self.cms_add_bookmark)
set_method("cms", "post",
method = "remove_bookmark",
action = self.cms_remove_bookmark)
# ---------------------------------------------------------------------
# Modules/Resources <> Posts link table
#
tablename = "cms_post_module"
define_table(tablename,
post_id(empty=False),
Field("module",
comment = T("If you specify a module then this will be used as the text in that module's index page"),
label = T("Module"),
),
Field("resource",
comment = T("If you specify a resource then this will be used as the text in that resource's summary page"),
label = T("Resource"),
),
#Field("record",
# comment = T("If you specify a record then this will be used as a hyperlink to that resource"),
# label = T("Record"),
# ),
*s3_meta_fields())
# CRUD Strings
crud_strings[tablename] = Storage(
label_create = T("Create Post"),
title_display = T("Post Details"),
title_list = T("Posts"),
title_update = T("Edit Post"),
label_list_button = T("List Posts"),
msg_record_created = T("Post set as Module/Resource homepage"),
msg_record_modified = T("Post updated"),
msg_record_deleted = T("Post removed"),
msg_list_empty = T("No posts currently set as module/resource homepages"))
# ---------------------------------------------------------------------
# Tags
#
tablename = "cms_tag"
define_table(tablename,
Field("name",
label = T("Tag"),
),
s3_comments(),
# Multiple Roles (@ToDo: Implement the restriction)
#s3_roles_permitted(readable = False,
# writable = False
# ),
*s3_meta_fields())
# CRUD Strings
crud_strings[tablename] = Storage(
label_create = T("Create Tag"),
title_display = T("Tag Details"),
title_list = T("Tags"),
title_update = T("Edit Tag"),
title_upload = T("Import Tags"),
label_list_button = T("List Tags"),
msg_record_created = T("Tag added"),
msg_record_modified = T("Tag updated"),
msg_record_deleted = T("Tag deleted"),
msg_list_empty = T("No tags currently defined"))
# Reusable field
represent = S3Represent(lookup=tablename, translate=True)
tag_id = S3ReusableField("tag_id", "reference %s" % tablename,
label = T("Tag"),
ondelete = "CASCADE",
represent = represent,
requires = IS_EMPTY_OR(
IS_ONE_OF(db, "cms_tag.id",
represent)),
sortby = "name",
)
# ---------------------------------------------------------------------
# Tags <> Posts link table
#
tablename = "cms_tag_post"
define_table(tablename,
post_id(empty = False),
tag_id(empty = False),
*s3_meta_fields())
# CRUD Strings
crud_strings[tablename] = Storage(
label_create = T("Tag Post"),
title_display = T("Tag Details"),
title_list = T("Tags"),
title_update = T("Edit Tag"),
title_upload = T("Import Tags"),
label_list_button = T("List Tagged Posts"),
msg_record_created = T("Post Tagged"),
msg_record_modified = T("Tag updated"),
msg_record_deleted = T("Tag removed"),
msg_list_empty = T("No posts currently tagged"))
# ---------------------------------------------------------------------
# Comments
# - threaded comments on Posts
#
# @ToDo: Attachments?
#
# Parent field allows us to:
# * easily filter for top-level threads
# * easily filter for next level of threading
# * hook a new reply into the correct location in the hierarchy
#
tablename = "cms_comment"
define_table(tablename,
Field("parent", "reference cms_comment",
requires = IS_EMPTY_OR(
IS_ONE_OF(db, "cms_comment.id")),
readable = False,
),
post_id(empty=False),
Field("body", "text", notnull=True,
label = T("Comment"),
),
*s3_meta_fields())
# Resource Configuration
configure(tablename,
list_fields = ["id",
"post_id",
"created_by",
"modified_on"
],
)
# ---------------------------------------------------------------------
# Pass names back to global scope (s3.*)
#
return dict(cms_post_id = post_id,
)
# -------------------------------------------------------------------------
def defaults(self):
"""
Safe defaults for model-global names in case module is disabled
"""
dummy = S3ReusableField("dummy_id", "integer",
readable = False,
writable = False)
return dict(cms_post_id = lambda **attr: dummy("post_id"),
)
# -------------------------------------------------------------------------
@staticmethod
def cms_series_onaccept(form):
"""
Cascade values down to all component Posts
"""
form_vars = form.vars
db = current.db
table = db.cms_post
query = (table.series_id == form_vars.id)
db(query).update(avatar = form_vars.avatar,
replies = form_vars.replies,
roles_permitted = form_vars.roles_permitted,
)
# -------------------------------------------------------------------------
@staticmethod
def cms_post_duplicate(item):
"""
CMS Post Import - Update Detection (primarily for non-blog
contents such as homepage, module index pages, summary pages,
or online documentation):
- same name and series => same post
@param item: the import item
@todo: if no name present => use cms_post_module component
to identify updates (also requires deduplication of
cms_post_module component)
"""
data = item.data
name = data.get("name")
series_id = data.get("series_id")
if not name:
return
table = item.table
query = (table.name == name) & \
(table.series_id == series_id)
duplicate = current.db(query).select(table.id,
limitby=(0, 1)).first()
if duplicate:
item.id = duplicate.id
item.method = item.METHOD.UPDATE
# -------------------------------------------------------------------------
@staticmethod
def cms_post_onaccept(form):
"""
Handle the case where the page is for a Module home page,
Resource Summary page or Map Layer
"""
db = current.db
s3db = current.s3db
post_id = form.vars.id
get_vars = current.request.get_vars
module = get_vars.get("module", None)
if module:
table = db.cms_post_module
query = (table.module == module)
resource = get_vars.get("resource", None)
if resource:
# Resource Summary page
query &= (table.resource == resource)
else:
# Module home page
query &= ((table.resource == None) | \
(table.resource == "index"))
result = db(query).update(post_id=post_id)
if not result:
table.insert(post_id=post_id,
module=module,
resource=resource,
)
layer_id = get_vars.get("layer_id", None)
if layer_id:
table = s3db.cms_post_layer
query = (table.layer_id == layer_id)
result = db(query).update(post_id=post_id)
if not result:
table.insert(post_id=post_id,
layer_id=layer_id,
)
# Read record
table = db.cms_post
record = db(table.id == post_id).select(table.person_id,
table.created_by,
limitby=(0, 1)
).first()
if record.created_by and not record.person_id:
# Set from Author
ptable = s3db.pr_person
putable = s3db.pr_person_user
query = (putable.user_id == record.created_by) & \
(putable.pe_id == ptable.pe_id)
person = db(query).select(ptable.id,
limitby=(0, 1)
).first()
if person:
db(table.id == post_id).update(person_id=person.id)
# -----------------------------------------------------------------------------
@staticmethod
def cms_add_tag(r, **attr):
"""
Add a Tag to a Post
S3Method for interactive requests
- designed to be called as an afterTagAdded callback to tag-it.js
"""
post_id = r.id
if not post_id or len(r.args) < 3:
raise HTTP(501, current.ERROR.BAD_METHOD)
tag = r.args[2]
db = current.db
ttable = db.cms_tag
ltable = db.cms_tag_post
exists = db(ttable.name == tag).select(ttable.id,
ttable.deleted,
ttable.deleted_fk,
limitby=(0, 1)
).first()
if exists:
tag_id = exists.id
if exists.deleted:
if exists.deleted_fk:
data = json.loads(exists.deleted_fk)
data["deleted"] = False
else:
data = dict(deleted=False)
db(ttable.id == tag_id).update(**data)
else:
tag_id = ttable.insert(name=tag)
query = (ltable.tag_id == tag_id) & \
(ltable.post_id == post_id)
exists = db(query).select(ltable.id,
ltable.deleted,
ltable.deleted_fk,
limitby=(0, 1)
).first()
if exists:
if exists.deleted:
if exists.deleted_fk:
data = json.loads(exists.deleted_fk)
data["deleted"] = False
else:
data = dict(deleted=False)
db(ltable.id == exists.id).update(**data)
else:
ltable.insert(post_id = post_id,
tag_id = tag_id,
)
output = current.xml.json_message(True, 200, "Tag Added")
current.response.headers["Content-Type"] = "application/json"
return output
# -----------------------------------------------------------------------------
@staticmethod
def cms_remove_tag(r, **attr):
"""
Remove a Tag from a Post
S3Method for interactive requests
- designed to be called as an afterTagRemoved callback to tag-it.js
"""
post_id = r.id
if not post_id or len(r.args) < 3:
raise HTTP(501, current.ERROR.BAD_METHOD)
tag = r.args[2]
db = current.db
ttable = db.cms_tag
exists = db(ttable.name == tag).select(ttable.id,
ttable.deleted,
limitby=(0, 1)
).first()
if exists:
tag_id = exists.id
ltable = db.cms_tag_post
query = (ltable.tag_id == tag_id) & \
(ltable.post_id == post_id)
exists = db(query).select(ltable.id,
ltable.deleted,
limitby=(0, 1)
).first()
if exists and not exists.deleted:
resource = current.s3db.resource("cms_tag_post", id=exists.id)
resource.delete()
output = current.xml.json_message(True, 200, "Tag Removed")
current.response.headers["Content-Type"] = "application/json"
return output
# -----------------------------------------------------------------------------
@staticmethod
def cms_add_bookmark(r, **attr):
"""
Bookmark a Post
S3Method for interactive requests
"""
post_id = r.id
user = current.auth.user
user_id = user and user.id
if not post_id or not user_id:
raise HTTP(501, current.ERROR.BAD_METHOD)
db = current.db
ltable = db.cms_post_user
query = (ltable.post_id == post_id) & \
(ltable.user_id == user_id)
exists = db(query).select(ltable.id,
ltable.deleted,
ltable.deleted_fk,
limitby=(0, 1)
).first()
if exists:
link_id = exists.id
if exists.deleted:
if exists.deleted_fk:
data = json.loads(exists.deleted_fk)
data["deleted"] = False
else:
data = dict(deleted=False)
db(ltable.id == link_id).update(**data)
else:
link_id = ltable.insert(post_id = post_id,
user_id = user_id,
)
output = current.xml.json_message(True, 200, "Bookmark Added")
current.response.headers["Content-Type"] = "application/json"
return output
# -----------------------------------------------------------------------------
@staticmethod
def cms_remove_bookmark(r, **attr):
"""
Remove a Bookmark for a Post
S3Method for interactive requests
"""
post_id = r.id
user = current.auth.user
user_id = user and user.id
if not post_id or not user_id:
raise HTTP(501, current.ERROR.BAD_METHOD)
db = current.db
ltable = db.cms_post_user
query = (ltable.post_id == post_id) & \
(ltable.user_id == user_id)
exists = db(query).select(ltable.id,
ltable.deleted,
limitby=(0, 1)
).first()
if exists and not exists.deleted:
resource = current.s3db.resource("cms_post_user", id=exists.id)
resource.delete()
output = current.xml.json_message(True, 200, "Bookmark Removed")
current.response.headers["Content-Type"] = "application/json"
return output
# =============================================================================
class S3ContentMapModel(S3Model):
"""
Use of the CMS to provide extra data about Map Layers
"""
names = ("cms_post_layer",)
def model(self):
# ---------------------------------------------------------------------
# Layers <> Posts link table
#
tablename = "cms_post_layer"
self.define_table(tablename,
self.cms_post_id(empty = False),
self.super_link("layer_id", "gis_layer_entity"),
*s3_meta_fields())
# ---------------------------------------------------------------------
# Pass names back to global scope (s3.*)
#
return {}
# =============================================================================
class S3ContentOrgModel(S3Model):
"""
Link Posts to Organisations
"""
names = ("cms_post_organisation",)
def model(self):
# ---------------------------------------------------------------------
# Organisations <> Posts link table
#
tablename = "cms_post_organisation"
self.define_table(tablename,
self.cms_post_id(empty = False,
ondelete = "CASCADE",
),
self.org_organisation_id(empty = False,
ondelete = "CASCADE",
),
*s3_meta_fields())
# ---------------------------------------------------------------------
# Pass names back to global scope (s3.*)
#
return {}
# =============================================================================
class S3ContentOrgGroupModel(S3Model):
"""
Link Posts to Organisation Groups (Coalitions/Networks)
"""
names = ("cms_post_organisation_group",)
def model(self):
# ---------------------------------------------------------------------
# Organisation Groups <> Posts link table
#
tablename = "cms_post_organisation_group"
self.define_table(tablename,
self.cms_post_id(empty=False),
self.org_group_id(empty=False),
*s3_meta_fields())
# ---------------------------------------------------------------------
# Pass names back to global scope (s3.*)
#
return {}
# =============================================================================
class S3ContentUserModel(S3Model):
"""
Link Posts to Users to allow Users to Bookmark posts
"""
names = ("cms_post_user",)
def model(self):
# ---------------------------------------------------------------------
# Users <> Posts link table
#
tablename = "cms_post_user"
self.define_table(tablename,
self.cms_post_id(empty=False),
Field("user_id", current.auth.settings.table_user),
*s3_meta_fields())
# ---------------------------------------------------------------------
# Pass names back to global scope (s3.*)
#
return {}
# =============================================================================
def cms_rheader(r, tabs=[]):
""" CMS Resource Headers """
if r.representation != "html":
# RHeaders only used in interactive views
return None
record = r.record
if record is None:
# List or Create form: rheader makes no sense here
return None
table = r.table
resourcename = r.name
T = current.T
if resourcename == "series":
# Tabs
tabs = [(T("Basic Details"), None),
(T("Posts"), "post"),
]
rheader_tabs = s3_rheader_tabs(r, tabs)
rheader = DIV(TABLE(TR(TH("%s: " % table.name.label),
record.name
),
), rheader_tabs)
elif resourcename == "post":
# Tabs
tabs = [(T("Basic Details"), None),
]
if record.replies:
tabs.append((T("Comments"), "discuss"))
rheader_tabs = s3_rheader_tabs(r, tabs)
rheader = DIV(TABLE(TR(TH("%s: " % table.name.label),
record.name
),
), rheader_tabs)
return rheader
# =============================================================================
def cms_index(module, resource=None, page_name=None, alt_function=None):
"""
Return a module index page retrieved from CMS
- or run an alternate function if not found
"""
response = current.response
settings = current.deployment_settings
if not page_name:
page_name = settings.modules[module].name_nice
response.title = page_name
item = None
if settings.has_module("cms") and not settings.get_cms_hide_index(module):
db = current.db
table = current.s3db.cms_post
ltable = db.cms_post_module
query = (ltable.module == module) & \
(ltable.post_id == table.id) & \
(table.deleted != True)
if resource is None:
query &= ((ltable.resource == None) | \
(ltable.resource == "index"))
else:
query &= (ltable.resource == resource)
_item = db(query).select(table.id,
table.body,
table.title,
limitby=(0, 1)).first()
# @ToDo: Replace this crude check with?
#if current.auth.s3_has_permission("update", table, record_id=_item.id):
auth = current.auth
ADMIN = auth.get_system_roles().ADMIN
ADMIN = auth.s3_has_role(ADMIN)
get_vars = {"module": module}
if resource:
get_vars["resource"] = resource
if _item:
if _item.title:
response.title = _item.title
if ADMIN:
item = DIV(XML(_item.body),
BR(),
A(current.T("Edit"),
_href=URL(c="cms", f="post",
args=[_item.id, "update"],
vars=get_vars),
_class="action-btn"))
else:
item = XML(_item.body)
elif ADMIN:
item = DIV(H2(page_name),
A(current.T("Edit"),
_href=URL(c="cms", f="post", args="create",
vars=get_vars),
_class="action-btn"))
if not item:
if alt_function:
# Serve the alternate controller function
# Copied from gluon.main serve_controller()
# (We don't want to re-run models)
from gluon.compileapp import build_environment, run_controller_in, run_view_in
request = current.request
environment = build_environment(request, response, current.session)
environment["settings"] = settings
environment["s3db"] = current.s3db
# Retain certain globals (extend as needed):
g = globals()
environment["s3base"] = g.get("s3base")
environment["s3_redirect_default"] = g.get("s3_redirect_default")
page = run_controller_in(request.controller, alt_function, environment)
if isinstance(page, dict):
response._vars = page
response._view_environment.update(page)
run_view_in(response._view_environment)
page = response.body.getvalue()
# Set default headers if not set
default_headers = [
("Content-Type", contenttype("." + request.extension)),
("Cache-Control",
"no-store, no-cache, must-revalidate, post-check=0, pre-check=0"),
("Expires", time.strftime("%a, %d %b %Y %H:%M:%S GMT",
time.gmtime())),
("Pragma", "no-cache")]
for key, value in default_headers:
response.headers.setdefault(key, value)
raise HTTP(response.status, page, **response.headers)
else:
item = H2(page_name)
# tbc
report = ""
response.view = "index.html"
return dict(item=item, report=report)
# =============================================================================
def cms_documentation(r, default_page, default_url):
"""
Render an online documentation page, to be called from prep
@param r: the S3Request
@param default_page: the default page name
@param default_url: the default URL if no contents found
"""
row = r.record
if not row:
# Find the CMS page
name = r.get_vars.get("name", default_page)
table = r.resource.table
query = (table.name == name) & (table.deleted != True)
row = current.db(query).select(table.id,
table.title,
table.body,
limitby=(0, 1)).first()
if not row:
if name != default_page:
# Error - CMS page not found
r.error(404, current.T("Page not found"),
next=URL(args=current.request.args, vars={}),
)
else:
# No CMS contents for module homepage found at all
# => redirect to default page (preserving all errors)
from s3 import s3_redirect_default
s3_redirect_default(default_url)
# Render the page
from s3 import S3XMLContents
return {"bypass": True,
"output": {"title": row.title,
"contents": S3XMLContents(row.body),
},
}
# =============================================================================
class S3CMS(S3Method):
"""
Class to generate a Rich Text widget to embed in a page
"""
# -------------------------------------------------------------------------
def apply_method(self, r, **attr):
"""
Entry point to apply cms method to S3Requests
- produces a full page with a Richtext widget
@param r: the S3Request
@param attr: dictionary of parameters for the method handler
@return: output object to send to the view
"""
# Not Implemented
r.error(405, current.ERROR.BAD_METHOD)
# -------------------------------------------------------------------------
def widget(self, r, method="cms", widget_id=None, **attr):
"""
Render a Rich Text widget suitable for use in a page such as
S3Summary
@param method: the widget method
@param r: the S3Request
@param attr: controller attributes
@ToDo: Support comments
"""
if not current.deployment_settings.has_module("cms"):
return ""
# This is currently assuming that we're being used in a Summary page or similar
request = current.request
return self.resource_content(request.controller,
request.function,
widget_id)
# -------------------------------------------------------------------------
@staticmethod
def resource_content(module, resource, widget_id=None):
db = current.db
table = current.s3db.cms_post
ltable = db.cms_post_module
query = (ltable.module == module) & \
(ltable.resource == resource) & \
(ltable.post_id == table.id) & \
(table.deleted != True)
_item = db(query).select(table.id,
table.body,
limitby=(0, 1)).first()
# @ToDo: Replace this crude check with?
#if current.auth.s3_has_permission("update", r.table, record_id=r.id):
auth = current.auth
ADMIN = auth.get_system_roles().ADMIN
ADMIN = auth.s3_has_role(ADMIN)
if _item:
if ADMIN:
if current.response.s3.crud.formstyle == "bootstrap":
_class = "btn"
else:
_class = "action-btn"
item = DIV(XML(_item.body),
A(current.T("Edit"),
_href=URL(c="cms", f="post",
args=[_item.id, "update"],
vars={"module": module,
"resource": resource
}),
_class="%s cms-edit" % _class))
else:
item = XML(_item.body)
elif ADMIN:
if current.response.s3.crud.formstyle == "bootstrap":
_class = "btn"
else:
_class = "action-btn"
item = A(current.T("Edit"),
_href=URL(c="cms", f="post", args="create",
vars={"module": module,
"resource": resource
}),
_class="%s cms-edit" % _class)
else:
item = ""
output = DIV(item, _id=widget_id, _class="cms_content")
return output
# =============================================================================
def cms_customise_post_fields():
"""
Customize cms_post fields for the Newsfeed / Home Pages
"""
s3db = current.s3db
s3 = current.response.s3
settings = current.deployment_settings
org_field = settings.get_cms_organisation()
if org_field == "created_by$organisation_id":
current.auth.settings.table_user.organisation_id.represent = \
s3db.org_organisation_represent
elif org_field == "post_organisation.organisation_id":
s3db.cms_post_organisation.organisation_id.label = ""
org_group_field = settings.get_cms_organisation_group()
if org_group_field == "created_by$org_group_id":
current.auth.settings.table_user.org_group_id.represent = \
s3db.org_organisation_group_represent
elif org_group_field == "post_organisation_group.group_id":
s3db.cms_post_organisation_group.group_id.label = ""
table = s3db.cms_post
table.series_id.requires = table.series_id.requires.other
contact_field = settings.get_cms_person()
if contact_field == "created_by":
table.created_by.represent = s3_auth_user_represent_name
elif contact_field == "person_id":
field = table.person_id
field.readable = True
field.writable = True
field.comment = None
# Default now
#field.requires = IS_ADD_PERSON_WIDGET2()
field.widget = S3AddPersonWidget2(controller="pr")
field = table.location_id
field.label = ""
field.represent = s3db.gis_LocationRepresent(sep=" | ")
# Required
field.requires = IS_LOCATION()
list_fields = ["series_id",
"location_id",
"date",
]
lappend = list_fields.append
if settings.get_cms_show_titles():
lappend("title")
lappend("body")
if contact_field:
lappend(contact_field)
if org_field:
lappend(org_field)
if org_group_field:
lappend(org_group_field)
if settings.get_cms_show_attachments():
lappend("document.file")
if settings.get_cms_show_links():
lappend("document.url")
if settings.get_cms_show_events():
lappend("event_post.event_id")
if settings.get_cms_location_click_filters():
script = \
'''S3.filter_location=function(d){var cb
for(var p in d){cb=$('input[name="multiselect_post-cms_post_location_id-location-filter-L'+p+'"][value="'+d[p]+'"]')
if(!cb.prop('checked')){cb.click()}}}'''
s3.jquery_ready.append(script)
# Which levels of Hierarchy are we using?
levels = current.gis.get_relevant_hierarchy_levels()
for level in levels:
lappend("location_id$%s" % level)
if settings.get_cms_show_tags():
lappend("tag.name")
if s3.debug:
s3.scripts.append("/%s/static/scripts/tag-it.js" % current.request.application)
else:
s3.scripts.append("/%s/static/scripts/tag-it.min.js" % current.request.application)
if current.auth.s3_has_permission("update", current.db.cms_tag_post):
readonly = '''afterTagAdded:function(event,ui){
if(ui.duringInitialization){return}
var post_id=$(this).attr('data-post_id')
var url=S3.Ap.concat('/cms/post/',post_id,'/add_tag/',ui.tagLabel)
$.getS3(url)
},afterTagRemoved:function(event,ui){
var post_id=$(this).attr('data-post_id')
var url=S3.Ap.concat('/cms/post/',post_id,'/remove_tag/',ui.tagLabel)
$.getS3(url)
},'''
else:
readonly = '''readOnly:true'''
script = \
'''S3.tagit=function(){$('.s3-tags').tagit({autocomplete:{source:'%s'},%s})}
S3.tagit()
S3.redraw_fns.push('tagit')''' % (URL(c="cms", f="tag",
args="search_ac.json"),
readonly)
s3.jquery_ready.append(script)
s3db.configure("cms_post",
list_fields = list_fields,
)
return table
# =============================================================================
def cms_post_list_layout(list_id, item_id, resource, rfields, record):
"""
Default dataList item renderer for CMS Posts on the
Home & News Feed pages.
@param list_id: the HTML ID of the list
@param item_id: the HTML ID of the item
@param resource: the S3Resource to render
@param rfields: the S3ResourceFields to render
@param record: the record as dict
"""
record_id = record["cms_post.id"]
item_class = "thumbnail"
db = current.db
s3db = current.s3db
settings = current.deployment_settings
NONE = current.messages["NONE"]
org_field = settings.get_cms_organisation()
# Convert to the right format for this context
if org_field == "created_by$organisation_id":
org_field = "auth_user.organisation_id"
elif org_field == "post_organisation.organisation_id":
org_field = "cms_post_organisation.organisation_id"
org_group_field = settings.get_cms_organisation_group()
# Convert to the right format for this context
if org_group_field == "created_by$org_group_id":
org_group_field = "auth_user.org_group_id"
elif org_group_field == "post_organisation_group.group_id":
org_group_field = "cms_post_organisation_group.group_id"
raw = record._row
body = record["cms_post.body"]
series_id = raw["cms_post.series_id"]
title = record["cms_post.title"]
if title and title != NONE:
subtitle = [DIV(title,
_class="card-subtitle"
)
]
else:
subtitle = []
for event_resource in ["event", "incident"]:
label = record["event_post.%s_id" % event_resource]
if label and label != NONE:
link=URL(c="event", f=event_resource,
args=[raw["event_post.%s_id" % event_resource],
"profile"]
)
subtitle.append(DIV(A(ICON(event_resource),
label,
_href=link,
_target="_blank",
),
_class="card-subtitle"
))
if subtitle:
subtitle.append(body)
body = TAG[""](*subtitle)
date = record["cms_post.date"]
date = SPAN(date,
_class="date-title",
)
location_id = raw["cms_post.location_id"]
if location_id:
location = record["cms_post.location_id"]
if settings.get_cms_location_click_filters():
# Which levels of Hierarchy are we using?
levels = current.gis.get_relevant_hierarchy_levels()
data = {}
for level in levels:
data[level[1:]] = raw["gis_location.%s" % level]
onclick = '''S3.filter_location(%s)''' % json.dumps(data, separators=SEPARATORS)
location = SPAN(A(location,
_href="#",
_onclick=onclick,
),
_class="location-title",
)
else:
location_url = URL(c="gis", f="location", args=[location_id, "profile"])
location = SPAN(A(location,
_href=location_url,
),
_class="location-title",
)
else:
location = ""
person = ""
contact_field = settings.get_cms_person()
if contact_field == "created_by":
author_id = raw["cms_post.created_by"]
person = record["cms_post.created_by"]
# @ToDo: Bulk lookup
ltable = s3db.pr_person_user
ptable = db.pr_person
query = (ltable.user_id == author_id) & \
(ltable.pe_id == ptable.pe_id)
row = db(query).select(ptable.id,
limitby=(0, 1)
).first()
if row:
person_id = row.id
else:
person_id = None
elif contact_field == "person_id":
person_id = raw["cms_post.person_id"]
if person_id:
person = record["cms_post.person_id"]
else:
person_id = None
if person:
if person_id:
# @ToDo: deployment_setting for controller to use?
person_url = URL(c="pr", f="person", args=[person_id])
else:
person_url = "#"
person = A(person,
_href=person_url,
)
avatar = ""
organisation = ""
if org_field:
organisation_id = raw[org_field]
if organisation_id:
organisation = record[org_field]
org_url = URL(c="org", f="organisation", args=[organisation_id, "profile"])
organisation = A(organisation,
_href=org_url,
_class="card-organisation",
)
# Avatar
# Try Organisation Logo
otable = db.org_organisation
row = db(otable.id == organisation_id).select(otable.logo,
limitby=(0, 1)
).first()
if row and row.logo:
logo = URL(c="default", f="download", args=[row.logo])
avatar = IMG(_src=logo,
_height=50,
_width=50,
_style="padding-right:5px",
_class="media-object")
else:
avatar = organisation
avatar = A(avatar,
_href=org_url,
_class="pull-left",
)
org_group = ""
if org_group_field:
org_group_id = raw[org_group_field]
if org_group_id:
org_group = record[org_group_field]
org_group_url = URL(c="org", f="group", args=[org_group_id, "profile"])
org_group = A(org_group,
_href=org_group_url,
_class="card-org-group",
)
if not avatar and person_id:
# Personal Avatar
avatar = s3_avatar_represent(person_id,
tablename="pr_person",
_class="media-object")
avatar = A(avatar,
_href=person_url,
_class="pull-left",
)
if person and organisation:
card_person = DIV(person,
" - ",
organisation,
_class="card-person",
)
elif person and org_group:
card_person = DIV(person,
" - ",
org_group,
_class="card-person",
)
elif person:
card_person = DIV(person,
_class="card-person",
)
#elif organisation:
# card_person = DIV(organisation,
# _class="card-person",
# )
elif org_group:
card_person = DIV(org_group,
_class="card-person",
)
else:
card_person = DIV(_class="card-person",
)
permit = current.auth.s3_has_permission
table = db.cms_post
updateable = permit("update", table, record_id=record_id)
if settings.get_cms_show_tags():
tags = raw["cms_tag.name"]
if tags or updateable:
tag_list = UL(_class="s3-tags",
)
tag_list["_data-post_id"] = record_id
else:
tag_list = ""
if tags:
if not isinstance(tags, list):
tags = [tags]#.split(", ")
for tag in tags:
tag_item = LI(tag)
tag_list.append(tag_item)
tags = tag_list
else:
tags = ""
T = current.T
if series_id:
series = record["cms_post.series_id"]
translate = settings.get_L10n_translate_cms_series()
if translate:
series_title = T(series)
else:
series_title = series
else:
series_title = series = ""
request = current.request
# Tool box
if updateable:
if request.function == "newsfeed":
fn = "newsfeed"
else:
fn = "post"
edit_btn = A(ICON("edit"),
_href=URL(c="cms", f=fn,
args=[record_id, "update.popup"],
vars={"refresh": list_id,
"record": record_id}
),
_class="s3_modal",
_title=T("Edit %(type)s") % dict(type=series_title),
)
else:
edit_btn = ""
if permit("delete", table, record_id=record_id):
delete_btn = A(ICON("delete"),
_class="dl-item-delete",
)
else:
delete_btn = ""
user = current.auth.user
if user and settings.get_cms_bookmarks():
ltable = s3db.cms_post_user
query = (ltable.post_id == record_id) & \
(ltable.user_id == user.id)
exists = db(query).select(ltable.id,
limitby=(0, 1)
).first()
if exists:
bookmark_btn = A(ICON("bookmark"),
_onclick="$.getS3('%s',function(){$('#%s').datalist('ajaxReloadItem',%s)})" %
(URL(c="cms", f="post",
args=[record_id, "remove_bookmark"]),
list_id,
record_id),
_title=T("Remove Bookmark"),
)
else:
bookmark_btn = A(ICON("bookmark-empty"),
_onclick="$.getS3('%s',function(){$('#%s').datalist('ajaxReloadItem',%s)})" %
(URL(c="cms", f="post",
args=[record_id, "add_bookmark"]),
list_id,
record_id),
_title=T("Add Bookmark"),
)
else:
bookmark_btn = ""
toolbox = DIV(bookmark_btn,
edit_btn,
delete_btn,
_class="edit-bar fright",
)
# Dropdown of available documents
documents = raw["doc_document.file"]
if documents:
if not isinstance(documents, list):
documents = [documents]
doc_list_id = "attachments-%s" % item_id
doc_list = UL(_class="f-dropdown dropdown-menu",
_role="menu",
_id=doc_list_id,
data={"dropdown-content": ""},
)
retrieve = db.doc_document.file.retrieve
for doc in documents:
try:
doc_name = retrieve(doc)[0]
except (IOError, TypeError):
doc_name = NONE
doc_url = URL(c="default", f="download",
args=[doc])
doc_item = LI(A(ICON("file"),
" ",
doc_name,
_href=doc_url,
),
_role="menuitem",
)
doc_list.append(doc_item)
docs = DIV(A(ICON("attachment"),
SPAN(_class="caret"),
_class="btn dropdown-toggle dropdown",
_href="#",
data={"toggle": "dropdown",
"dropdown": doc_list_id,
},
),
doc_list,
_class="btn-group attachments dropdown pull-right",
)
else:
docs = ""
links = raw["doc_document.url"]
if links:
if not isinstance(links, list):
links = [links]
link_list = DIV(_class="media card-links")
for link in links:
link_item = A(ICON("link"),
" ",
link,
_href=link,
_target="_blank",
_class="card-link",
)
link_list.append(link_item)
else:
link_list = ""
if "profile" in request.args:
# Single resource list
# - don't show series_title
if settings.get_cms_show_titles():
title = raw["cms_post.title"] or ""
else:
title = ""
card_label = SPAN(" %s" % title,
_class="card-title")
else:
# Mixed resource lists (Home, News Feed)
icon = series.lower().replace(" ", "_")
series_title = SPAN(" %s" % series_title,
_class="card-title")
if settings.get_cms_show_titles() and raw["cms_post.title"]:
title = SPAN(raw["cms_post.title"],
_class="card-title2")
card_label = TAG[""](ICON(icon),
series_title,
title)
else:
card_label = TAG[""](ICON(icon),
series_title)
# Type cards
if series == "Alert":
# Apply additional highlighting for Alerts
item_class = "%s disaster" % item_class
# Render the item
if series == "Event" and "newsfeed" not in request.args: # and request.function != "newsfeed"
# Events on Homepage have a different header
date.add_class("event")
header = DIV(date,
location,
toolbox,
_class="card-header",
)
else:
header = DIV(card_label,
location,
date,
toolbox,
_class="card-header",
)
item = DIV(header,
DIV(avatar,
DIV(DIV(body,
card_person,
_class="media",
),
_class="media-body",
),
_class="media",
),
tags,
docs,
link_list,
_class=item_class,
_id=item_id,
)
return item
# END =========================================================================
| mit |
ansible/ansible-modules-extras | windows/win_iis_webapppool.py | 11 | 3662 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2015, Henrik Wallström <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
DOCUMENTATION = '''
---
module: win_iis_webapppool
version_added: "2.0"
short_description: Configures a IIS Web Application Pool.
description:
- Creates, Removes and configures a IIS Web Application Pool
options:
name:
description:
- Names of application pool
required: true
default: null
aliases: []
state:
description:
- State of the binding
choices:
- absent
- stopped
- started
- restarted
required: false
default: null
aliases: []
attributes:
description:
- Application Pool attributes from string where attributes are seperated by a pipe and attribute name/values by colon Ex. "foo:1|bar:2"
required: false
default: null
aliases: []
author: Henrik Wallström
'''
EXAMPLES = '''
# This return information about an existing application pool
$ansible -i inventory -m win_iis_webapppool -a "name='DefaultAppPool'" windows
host | success >> {
"attributes": {},
"changed": false,
"info": {
"attributes": {
"CLRConfigFile": "",
"applicationPoolSid": "S-1-5-82-3006700770-424185619-1745488364-794895919-4004696415",
"autoStart": true,
"enable32BitAppOnWin64": false,
"enableConfigurationOverride": true,
"managedPipelineMode": 0,
"managedRuntimeLoader": "webengine4.dll",
"managedRuntimeVersion": "v4.0",
"name": "DefaultAppPool",
"passAnonymousToken": true,
"queueLength": 1000,
"startMode": 0,
"state": 1
},
"name": "DefaultAppPool",
"state": "Started"
}
}
# This creates a new application pool in 'Started' state
$ ansible -i inventory -m win_iis_webapppool -a "name='AppPool' state=started" windows
# This stoppes an application pool
$ ansible -i inventory -m win_iis_webapppool -a "name='AppPool' state=stopped" windows
# This restarts an application pool
$ ansible -i inventory -m win_iis_webapppool -a "name='AppPool' state=restart" windows
# This restarts an application pool
$ ansible -i inventory -m win_iis_webapppool -a "name='AppPool' state=restart" windows
# This change application pool attributes without touching state
$ ansible -i inventory -m win_iis_webapppool -a "name='AppPool' attributes='managedRuntimeVersion:v4.0|autoStart:false'" windows
# This creates an application pool and sets attributes
$ ansible -i inventory -m win_iis_webapppool -a "name='AnotherAppPool' state=started attributes='managedRuntimeVersion:v4.0|autoStart:false'" windows
# Playbook example
---
- name: App Pool with .NET 4.0
win_iis_webapppool:
name: 'AppPool'
state: started
attributes: managedRuntimeVersion:v4.0
register: webapppool
'''
| gpl-3.0 |
Tennyson53/SUR | magnum/tests/unit/common/cert_manager/test_cert_manager.py | 6 | 1550 | # Copyright 2015 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.
from oslo_config import fixture
from magnum.common import cert_manager
from magnum.common.cert_manager import barbican_cert_manager as bcm
from magnum.common.cert_manager import get_backend
from magnum.common.cert_manager import local_cert_manager as lcm
from magnum.tests import base
class TestCertManager(base.BaseTestCase):
def setUp(self):
cert_manager._CERT_MANAGER_PLUGIN = None
super(TestCertManager, self).setUp()
def test_barbican_cert_manager(self):
fixture.Config().config(group='certificates',
cert_manager_type='barbican')
self.assertEqual(get_backend().CertManager,
bcm.CertManager)
def test_local_cert_manager(self):
fixture.Config().config(group='certificates',
cert_manager_type='local')
self.assertEqual(get_backend().CertManager,
lcm.CertManager)
| apache-2.0 |
0x0all/SASM | Windows/MinGW64/opt/lib/python2.7/encodings/cp1140.py | 593 | 13361 | """ Python Character Mapping Codec cp1140 generated from 'python-mappings/CP1140.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='cp1140',
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'\x9c' # 0x04 -> CONTROL
u'\t' # 0x05 -> HORIZONTAL TABULATION
u'\x86' # 0x06 -> CONTROL
u'\x7f' # 0x07 -> DELETE
u'\x97' # 0x08 -> CONTROL
u'\x8d' # 0x09 -> CONTROL
u'\x8e' # 0x0A -> CONTROL
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'\x9d' # 0x14 -> CONTROL
u'\x85' # 0x15 -> CONTROL
u'\x08' # 0x16 -> BACKSPACE
u'\x87' # 0x17 -> CONTROL
u'\x18' # 0x18 -> CANCEL
u'\x19' # 0x19 -> END OF MEDIUM
u'\x92' # 0x1A -> CONTROL
u'\x8f' # 0x1B -> CONTROL
u'\x1c' # 0x1C -> FILE SEPARATOR
u'\x1d' # 0x1D -> GROUP SEPARATOR
u'\x1e' # 0x1E -> RECORD SEPARATOR
u'\x1f' # 0x1F -> UNIT SEPARATOR
u'\x80' # 0x20 -> CONTROL
u'\x81' # 0x21 -> CONTROL
u'\x82' # 0x22 -> CONTROL
u'\x83' # 0x23 -> CONTROL
u'\x84' # 0x24 -> CONTROL
u'\n' # 0x25 -> LINE FEED
u'\x17' # 0x26 -> END OF TRANSMISSION BLOCK
u'\x1b' # 0x27 -> ESCAPE
u'\x88' # 0x28 -> CONTROL
u'\x89' # 0x29 -> CONTROL
u'\x8a' # 0x2A -> CONTROL
u'\x8b' # 0x2B -> CONTROL
u'\x8c' # 0x2C -> CONTROL
u'\x05' # 0x2D -> ENQUIRY
u'\x06' # 0x2E -> ACKNOWLEDGE
u'\x07' # 0x2F -> BELL
u'\x90' # 0x30 -> CONTROL
u'\x91' # 0x31 -> CONTROL
u'\x16' # 0x32 -> SYNCHRONOUS IDLE
u'\x93' # 0x33 -> CONTROL
u'\x94' # 0x34 -> CONTROL
u'\x95' # 0x35 -> CONTROL
u'\x96' # 0x36 -> CONTROL
u'\x04' # 0x37 -> END OF TRANSMISSION
u'\x98' # 0x38 -> CONTROL
u'\x99' # 0x39 -> CONTROL
u'\x9a' # 0x3A -> CONTROL
u'\x9b' # 0x3B -> CONTROL
u'\x14' # 0x3C -> DEVICE CONTROL FOUR
u'\x15' # 0x3D -> NEGATIVE ACKNOWLEDGE
u'\x9e' # 0x3E -> CONTROL
u'\x1a' # 0x3F -> SUBSTITUTE
u' ' # 0x40 -> SPACE
u'\xa0' # 0x41 -> NO-BREAK SPACE
u'\xe2' # 0x42 -> LATIN SMALL LETTER A WITH CIRCUMFLEX
u'\xe4' # 0x43 -> LATIN SMALL LETTER A WITH DIAERESIS
u'\xe0' # 0x44 -> LATIN SMALL LETTER A WITH GRAVE
u'\xe1' # 0x45 -> LATIN SMALL LETTER A WITH ACUTE
u'\xe3' # 0x46 -> LATIN SMALL LETTER A WITH TILDE
u'\xe5' # 0x47 -> LATIN SMALL LETTER A WITH RING ABOVE
u'\xe7' # 0x48 -> LATIN SMALL LETTER C WITH CEDILLA
u'\xf1' # 0x49 -> LATIN SMALL LETTER N WITH TILDE
u'\xa2' # 0x4A -> CENT SIGN
u'.' # 0x4B -> FULL STOP
u'<' # 0x4C -> LESS-THAN SIGN
u'(' # 0x4D -> LEFT PARENTHESIS
u'+' # 0x4E -> PLUS SIGN
u'|' # 0x4F -> VERTICAL LINE
u'&' # 0x50 -> AMPERSAND
u'\xe9' # 0x51 -> LATIN SMALL LETTER E WITH ACUTE
u'\xea' # 0x52 -> LATIN SMALL LETTER E WITH CIRCUMFLEX
u'\xeb' # 0x53 -> LATIN SMALL LETTER E WITH DIAERESIS
u'\xe8' # 0x54 -> LATIN SMALL LETTER E WITH GRAVE
u'\xed' # 0x55 -> LATIN SMALL LETTER I WITH ACUTE
u'\xee' # 0x56 -> LATIN SMALL LETTER I WITH CIRCUMFLEX
u'\xef' # 0x57 -> LATIN SMALL LETTER I WITH DIAERESIS
u'\xec' # 0x58 -> LATIN SMALL LETTER I WITH GRAVE
u'\xdf' # 0x59 -> LATIN SMALL LETTER SHARP S (GERMAN)
u'!' # 0x5A -> EXCLAMATION MARK
u'$' # 0x5B -> DOLLAR SIGN
u'*' # 0x5C -> ASTERISK
u')' # 0x5D -> RIGHT PARENTHESIS
u';' # 0x5E -> SEMICOLON
u'\xac' # 0x5F -> NOT SIGN
u'-' # 0x60 -> HYPHEN-MINUS
u'/' # 0x61 -> SOLIDUS
u'\xc2' # 0x62 -> LATIN CAPITAL LETTER A WITH CIRCUMFLEX
u'\xc4' # 0x63 -> LATIN CAPITAL LETTER A WITH DIAERESIS
u'\xc0' # 0x64 -> LATIN CAPITAL LETTER A WITH GRAVE
u'\xc1' # 0x65 -> LATIN CAPITAL LETTER A WITH ACUTE
u'\xc3' # 0x66 -> LATIN CAPITAL LETTER A WITH TILDE
u'\xc5' # 0x67 -> LATIN CAPITAL LETTER A WITH RING ABOVE
u'\xc7' # 0x68 -> LATIN CAPITAL LETTER C WITH CEDILLA
u'\xd1' # 0x69 -> LATIN CAPITAL LETTER N WITH TILDE
u'\xa6' # 0x6A -> BROKEN BAR
u',' # 0x6B -> COMMA
u'%' # 0x6C -> PERCENT SIGN
u'_' # 0x6D -> LOW LINE
u'>' # 0x6E -> GREATER-THAN SIGN
u'?' # 0x6F -> QUESTION MARK
u'\xf8' # 0x70 -> LATIN SMALL LETTER O WITH STROKE
u'\xc9' # 0x71 -> LATIN CAPITAL LETTER E WITH ACUTE
u'\xca' # 0x72 -> LATIN CAPITAL LETTER E WITH CIRCUMFLEX
u'\xcb' # 0x73 -> LATIN CAPITAL LETTER E WITH DIAERESIS
u'\xc8' # 0x74 -> LATIN CAPITAL LETTER E WITH GRAVE
u'\xcd' # 0x75 -> LATIN CAPITAL LETTER I WITH ACUTE
u'\xce' # 0x76 -> LATIN CAPITAL LETTER I WITH CIRCUMFLEX
u'\xcf' # 0x77 -> LATIN CAPITAL LETTER I WITH DIAERESIS
u'\xcc' # 0x78 -> LATIN CAPITAL LETTER I WITH GRAVE
u'`' # 0x79 -> GRAVE ACCENT
u':' # 0x7A -> COLON
u'#' # 0x7B -> NUMBER SIGN
u'@' # 0x7C -> COMMERCIAL AT
u"'" # 0x7D -> APOSTROPHE
u'=' # 0x7E -> EQUALS SIGN
u'"' # 0x7F -> QUOTATION MARK
u'\xd8' # 0x80 -> LATIN CAPITAL LETTER O WITH STROKE
u'a' # 0x81 -> LATIN SMALL LETTER A
u'b' # 0x82 -> LATIN SMALL LETTER B
u'c' # 0x83 -> LATIN SMALL LETTER C
u'd' # 0x84 -> LATIN SMALL LETTER D
u'e' # 0x85 -> LATIN SMALL LETTER E
u'f' # 0x86 -> LATIN SMALL LETTER F
u'g' # 0x87 -> LATIN SMALL LETTER G
u'h' # 0x88 -> LATIN SMALL LETTER H
u'i' # 0x89 -> LATIN SMALL LETTER I
u'\xab' # 0x8A -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
u'\xbb' # 0x8B -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
u'\xf0' # 0x8C -> LATIN SMALL LETTER ETH (ICELANDIC)
u'\xfd' # 0x8D -> LATIN SMALL LETTER Y WITH ACUTE
u'\xfe' # 0x8E -> LATIN SMALL LETTER THORN (ICELANDIC)
u'\xb1' # 0x8F -> PLUS-MINUS SIGN
u'\xb0' # 0x90 -> DEGREE SIGN
u'j' # 0x91 -> LATIN SMALL LETTER J
u'k' # 0x92 -> LATIN SMALL LETTER K
u'l' # 0x93 -> LATIN SMALL LETTER L
u'm' # 0x94 -> LATIN SMALL LETTER M
u'n' # 0x95 -> LATIN SMALL LETTER N
u'o' # 0x96 -> LATIN SMALL LETTER O
u'p' # 0x97 -> LATIN SMALL LETTER P
u'q' # 0x98 -> LATIN SMALL LETTER Q
u'r' # 0x99 -> LATIN SMALL LETTER R
u'\xaa' # 0x9A -> FEMININE ORDINAL INDICATOR
u'\xba' # 0x9B -> MASCULINE ORDINAL INDICATOR
u'\xe6' # 0x9C -> LATIN SMALL LIGATURE AE
u'\xb8' # 0x9D -> CEDILLA
u'\xc6' # 0x9E -> LATIN CAPITAL LIGATURE AE
u'\u20ac' # 0x9F -> EURO SIGN
u'\xb5' # 0xA0 -> MICRO SIGN
u'~' # 0xA1 -> TILDE
u's' # 0xA2 -> LATIN SMALL LETTER S
u't' # 0xA3 -> LATIN SMALL LETTER T
u'u' # 0xA4 -> LATIN SMALL LETTER U
u'v' # 0xA5 -> LATIN SMALL LETTER V
u'w' # 0xA6 -> LATIN SMALL LETTER W
u'x' # 0xA7 -> LATIN SMALL LETTER X
u'y' # 0xA8 -> LATIN SMALL LETTER Y
u'z' # 0xA9 -> LATIN SMALL LETTER Z
u'\xa1' # 0xAA -> INVERTED EXCLAMATION MARK
u'\xbf' # 0xAB -> INVERTED QUESTION MARK
u'\xd0' # 0xAC -> LATIN CAPITAL LETTER ETH (ICELANDIC)
u'\xdd' # 0xAD -> LATIN CAPITAL LETTER Y WITH ACUTE
u'\xde' # 0xAE -> LATIN CAPITAL LETTER THORN (ICELANDIC)
u'\xae' # 0xAF -> REGISTERED SIGN
u'^' # 0xB0 -> CIRCUMFLEX ACCENT
u'\xa3' # 0xB1 -> POUND SIGN
u'\xa5' # 0xB2 -> YEN SIGN
u'\xb7' # 0xB3 -> MIDDLE DOT
u'\xa9' # 0xB4 -> COPYRIGHT SIGN
u'\xa7' # 0xB5 -> SECTION SIGN
u'\xb6' # 0xB6 -> PILCROW SIGN
u'\xbc' # 0xB7 -> VULGAR FRACTION ONE QUARTER
u'\xbd' # 0xB8 -> VULGAR FRACTION ONE HALF
u'\xbe' # 0xB9 -> VULGAR FRACTION THREE QUARTERS
u'[' # 0xBA -> LEFT SQUARE BRACKET
u']' # 0xBB -> RIGHT SQUARE BRACKET
u'\xaf' # 0xBC -> MACRON
u'\xa8' # 0xBD -> DIAERESIS
u'\xb4' # 0xBE -> ACUTE ACCENT
u'\xd7' # 0xBF -> MULTIPLICATION SIGN
u'{' # 0xC0 -> LEFT CURLY BRACKET
u'A' # 0xC1 -> LATIN CAPITAL LETTER A
u'B' # 0xC2 -> LATIN CAPITAL LETTER B
u'C' # 0xC3 -> LATIN CAPITAL LETTER C
u'D' # 0xC4 -> LATIN CAPITAL LETTER D
u'E' # 0xC5 -> LATIN CAPITAL LETTER E
u'F' # 0xC6 -> LATIN CAPITAL LETTER F
u'G' # 0xC7 -> LATIN CAPITAL LETTER G
u'H' # 0xC8 -> LATIN CAPITAL LETTER H
u'I' # 0xC9 -> LATIN CAPITAL LETTER I
u'\xad' # 0xCA -> SOFT HYPHEN
u'\xf4' # 0xCB -> LATIN SMALL LETTER O WITH CIRCUMFLEX
u'\xf6' # 0xCC -> LATIN SMALL LETTER O WITH DIAERESIS
u'\xf2' # 0xCD -> LATIN SMALL LETTER O WITH GRAVE
u'\xf3' # 0xCE -> LATIN SMALL LETTER O WITH ACUTE
u'\xf5' # 0xCF -> LATIN SMALL LETTER O WITH TILDE
u'}' # 0xD0 -> RIGHT CURLY BRACKET
u'J' # 0xD1 -> LATIN CAPITAL LETTER J
u'K' # 0xD2 -> LATIN CAPITAL LETTER K
u'L' # 0xD3 -> LATIN CAPITAL LETTER L
u'M' # 0xD4 -> LATIN CAPITAL LETTER M
u'N' # 0xD5 -> LATIN CAPITAL LETTER N
u'O' # 0xD6 -> LATIN CAPITAL LETTER O
u'P' # 0xD7 -> LATIN CAPITAL LETTER P
u'Q' # 0xD8 -> LATIN CAPITAL LETTER Q
u'R' # 0xD9 -> LATIN CAPITAL LETTER R
u'\xb9' # 0xDA -> SUPERSCRIPT ONE
u'\xfb' # 0xDB -> LATIN SMALL LETTER U WITH CIRCUMFLEX
u'\xfc' # 0xDC -> LATIN SMALL LETTER U WITH DIAERESIS
u'\xf9' # 0xDD -> LATIN SMALL LETTER U WITH GRAVE
u'\xfa' # 0xDE -> LATIN SMALL LETTER U WITH ACUTE
u'\xff' # 0xDF -> LATIN SMALL LETTER Y WITH DIAERESIS
u'\\' # 0xE0 -> REVERSE SOLIDUS
u'\xf7' # 0xE1 -> DIVISION SIGN
u'S' # 0xE2 -> LATIN CAPITAL LETTER S
u'T' # 0xE3 -> LATIN CAPITAL LETTER T
u'U' # 0xE4 -> LATIN CAPITAL LETTER U
u'V' # 0xE5 -> LATIN CAPITAL LETTER V
u'W' # 0xE6 -> LATIN CAPITAL LETTER W
u'X' # 0xE7 -> LATIN CAPITAL LETTER X
u'Y' # 0xE8 -> LATIN CAPITAL LETTER Y
u'Z' # 0xE9 -> LATIN CAPITAL LETTER Z
u'\xb2' # 0xEA -> SUPERSCRIPT TWO
u'\xd4' # 0xEB -> LATIN CAPITAL LETTER O WITH CIRCUMFLEX
u'\xd6' # 0xEC -> LATIN CAPITAL LETTER O WITH DIAERESIS
u'\xd2' # 0xED -> LATIN CAPITAL LETTER O WITH GRAVE
u'\xd3' # 0xEE -> LATIN CAPITAL LETTER O WITH ACUTE
u'\xd5' # 0xEF -> LATIN CAPITAL LETTER O WITH TILDE
u'0' # 0xF0 -> DIGIT ZERO
u'1' # 0xF1 -> DIGIT ONE
u'2' # 0xF2 -> DIGIT TWO
u'3' # 0xF3 -> DIGIT THREE
u'4' # 0xF4 -> DIGIT FOUR
u'5' # 0xF5 -> DIGIT FIVE
u'6' # 0xF6 -> DIGIT SIX
u'7' # 0xF7 -> DIGIT SEVEN
u'8' # 0xF8 -> DIGIT EIGHT
u'9' # 0xF9 -> DIGIT NINE
u'\xb3' # 0xFA -> SUPERSCRIPT THREE
u'\xdb' # 0xFB -> LATIN CAPITAL LETTER U WITH CIRCUMFLEX
u'\xdc' # 0xFC -> LATIN CAPITAL LETTER U WITH DIAERESIS
u'\xd9' # 0xFD -> LATIN CAPITAL LETTER U WITH GRAVE
u'\xda' # 0xFE -> LATIN CAPITAL LETTER U WITH ACUTE
u'\x9f' # 0xFF -> CONTROL
)
### Encoding table
encoding_table=codecs.charmap_build(decoding_table)
| gpl-3.0 |
mj10777/QGIS | cmake/FindQsci.py | 77 | 2612 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2012, Larry Shaffer <[email protected]>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Larry Shaffer <[email protected]> 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 Larry Shaffer <[email protected]> ''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 Larry Shaffer <[email protected]> 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.
#
"""Find QScintilla2 PyQt4/PyQt5 module version.
.. note:: Redistribution and use is allowed according to the terms of the BSD
license. For details see the accompanying COPYING-CMAKE-SCRIPTS file.
"""
__author__ = 'Larry Shaffer ([email protected])'
__date__ = '22/10/2012'
__copyright__ = 'Copyright 2012, The QGIS Project'
import sys
VER = ""
if len(sys.argv) > 0:
if sys.argv[1] == "4":
from PyQt4.Qsci import QSCINTILLA_VERSION_STR
VER = QSCINTILLA_VERSION_STR
else:
from PyQt5.Qsci import QSCINTILLA_VERSION_STR
VER = QSCINTILLA_VERSION_STR
else:
try:
from PyQt4.Qsci import QSCINTILLA_VERSION_STR
VER = QSCINTILLA_VERSION_STR
except ImportError:
try:
from PyQt5.Qsci import QSCINTILLA_VERSION_STR
VER = QSCINTILLA_VERSION_STR
except ImportError:
pass
print("qsci_version_str:%s" % VER)
| gpl-2.0 |
ludwiktrammer/odoo | addons/account/report/account_balance.py | 22 | 3313 | # -*- coding: utf-8 -*-
import time
from openerp import api, models
class ReportTrialBalance(models.AbstractModel):
_name = 'report.account.report_trialbalance'
def _get_accounts(self, accounts, display_account):
""" compute the balance, debit and credit for the provided accounts
:Arguments:
`accounts`: list of accounts record,
`display_account`: it's used to display either all accounts or those accounts which balance is > 0
:Returns a list of dictionary of Accounts with following key and value
`name`: Account name,
`code`: Account code,
`credit`: total amount of credit,
`debit`: total amount of debit,
`balance`: total amount of balance,
"""
account_result = {}
# Prepare sql query base on selected parameters from wizard
tables, where_clause, where_params = self.env['account.move.line']._query_get()
tables = tables.replace('"','')
if not tables:
tables = 'account_move_line'
wheres = [""]
if where_clause.strip():
wheres.append(where_clause.strip())
filters = " AND ".join(wheres)
# compute the balance, debit and credit for the provided accounts
request = ("SELECT account_id AS id, SUM(debit) AS debit, SUM(credit) AS credit, (SUM(debit) - SUM(credit)) AS balance" +\
" FROM " + tables + " WHERE account_id IN %s " + filters + " GROUP BY account_id")
params = (tuple(accounts.ids),) + tuple(where_params)
self.env.cr.execute(request, params)
for row in self.env.cr.dictfetchall():
account_result[row.pop('id')] = row
account_res = []
for account in accounts:
res = dict((fn, 0.0) for fn in ['credit', 'debit', 'balance'])
currency = account.currency_id and account.currency_id or account.company_id.currency_id
res['code'] = account.code
res['name'] = account.name
if account.id in account_result.keys():
res['debit'] = account_result[account.id].get('debit')
res['credit'] = account_result[account.id].get('credit')
res['balance'] = account_result[account.id].get('balance')
if display_account == 'all':
account_res.append(res)
if display_account in ['movement', 'not_zero'] and not currency.is_zero(res['balance']):
account_res.append(res)
return account_res
@api.multi
def render_html(self, data):
self.model = self.env.context.get('active_model')
docs = self.env[self.model].browse(self.env.context.get('active_id'))
display_account = data['form'].get('display_account')
accounts = self.env['account.account'].search([])
account_res = self.with_context(data['form'].get('used_context'))._get_accounts(accounts, display_account)
docargs = {
'doc_ids': self.ids,
'doc_model': self.model,
'data': data['form'],
'docs': docs,
'time': time,
'Accounts': account_res,
}
return self.env['report'].render('account.report_trialbalance', docargs)
| agpl-3.0 |
matrix-org/synapse | tests/replication/test_sharded_event_persister.py | 1 | 12377 | # Copyright 2020 The Matrix.org Foundation C.I.C.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
from unittest.mock import patch
from synapse.api.room_versions import RoomVersion
from synapse.rest import admin
from synapse.rest.client.v1 import login, room
from synapse.rest.client.v2_alpha import sync
from tests.replication._base import BaseMultiWorkerStreamTestCase
from tests.server import make_request
from tests.utils import USE_POSTGRES_FOR_TESTS
logger = logging.getLogger(__name__)
class EventPersisterShardTestCase(BaseMultiWorkerStreamTestCase):
"""Checks event persisting sharding works"""
# Event persister sharding requires postgres (due to needing
# `MultiWriterIdGenerator`).
if not USE_POSTGRES_FOR_TESTS:
skip = "Requires Postgres"
servlets = [
admin.register_servlets_for_client_rest_resource,
room.register_servlets,
login.register_servlets,
sync.register_servlets,
]
def prepare(self, reactor, clock, hs):
# Register a user who sends a message that we'll get notified about
self.other_user_id = self.register_user("otheruser", "pass")
self.other_access_token = self.login("otheruser", "pass")
self.room_creator = self.hs.get_room_creation_handler()
self.store = hs.get_datastore()
def default_config(self):
conf = super().default_config()
conf["redis"] = {"enabled": "true"}
conf["stream_writers"] = {"events": ["worker1", "worker2"]}
conf["instance_map"] = {
"worker1": {"host": "testserv", "port": 1001},
"worker2": {"host": "testserv", "port": 1002},
}
return conf
def _create_room(self, room_id: str, user_id: str, tok: str):
"""Create a room with given room_id"""
# We control the room ID generation by patching out the
# `_generate_room_id` method
async def generate_room(
creator_id: str, is_public: bool, room_version: RoomVersion
):
await self.store.store_room(
room_id=room_id,
room_creator_user_id=creator_id,
is_public=is_public,
room_version=room_version,
)
return room_id
with patch(
"synapse.handlers.room.RoomCreationHandler._generate_room_id"
) as mock:
mock.side_effect = generate_room
self.helper.create_room_as(user_id, tok=tok)
def test_basic(self):
"""Simple test to ensure that multiple rooms can be created and joined,
and that different rooms get handled by different instances.
"""
self.make_worker_hs(
"synapse.app.generic_worker",
{"worker_name": "worker1"},
)
self.make_worker_hs(
"synapse.app.generic_worker",
{"worker_name": "worker2"},
)
persisted_on_1 = False
persisted_on_2 = False
store = self.hs.get_datastore()
user_id = self.register_user("user", "pass")
access_token = self.login("user", "pass")
# Keep making new rooms until we see rooms being persisted on both
# workers.
for _ in range(10):
# Create a room
room = self.helper.create_room_as(user_id, tok=access_token)
# The other user joins
self.helper.join(
room=room, user=self.other_user_id, tok=self.other_access_token
)
# The other user sends some messages
rseponse = self.helper.send(room, body="Hi!", tok=self.other_access_token)
event_id = rseponse["event_id"]
# The event position includes which instance persisted the event.
pos = self.get_success(store.get_position_for_event(event_id))
persisted_on_1 |= pos.instance_name == "worker1"
persisted_on_2 |= pos.instance_name == "worker2"
if persisted_on_1 and persisted_on_2:
break
self.assertTrue(persisted_on_1)
self.assertTrue(persisted_on_2)
def test_vector_clock_token(self):
"""Tests that using a stream token with a vector clock component works
correctly with basic /sync and /messages usage.
"""
self.make_worker_hs(
"synapse.app.generic_worker",
{"worker_name": "worker1"},
)
worker_hs2 = self.make_worker_hs(
"synapse.app.generic_worker",
{"worker_name": "worker2"},
)
sync_hs = self.make_worker_hs(
"synapse.app.generic_worker",
{"worker_name": "sync"},
)
sync_hs_site = self._hs_to_site[sync_hs]
# Specially selected room IDs that get persisted on different workers.
room_id1 = "!foo:test"
room_id2 = "!baz:test"
self.assertEqual(
self.hs.config.worker.events_shard_config.get_instance(room_id1), "worker1"
)
self.assertEqual(
self.hs.config.worker.events_shard_config.get_instance(room_id2), "worker2"
)
user_id = self.register_user("user", "pass")
access_token = self.login("user", "pass")
store = self.hs.get_datastore()
# Create two room on the different workers.
self._create_room(room_id1, user_id, access_token)
self._create_room(room_id2, user_id, access_token)
# The other user joins
self.helper.join(
room=room_id1, user=self.other_user_id, tok=self.other_access_token
)
self.helper.join(
room=room_id2, user=self.other_user_id, tok=self.other_access_token
)
# Do an initial sync so that we're up to date.
channel = make_request(
self.reactor, sync_hs_site, "GET", "/sync", access_token=access_token
)
next_batch = channel.json_body["next_batch"]
# We now gut wrench into the events stream MultiWriterIdGenerator on
# worker2 to mimic it getting stuck persisting an event. This ensures
# that when we send an event on worker1 we end up in a state where
# worker2 events stream position lags that on worker1, resulting in a
# RoomStreamToken with a non-empty instance map component.
#
# Worker2's event stream position will not advance until we call
# __aexit__ again.
actx = worker_hs2.get_datastore()._stream_id_gen.get_next()
self.get_success(actx.__aenter__())
response = self.helper.send(room_id1, body="Hi!", tok=self.other_access_token)
first_event_in_room1 = response["event_id"]
# Assert that the current stream token has an instance map component, as
# we are trying to test vector clock tokens.
room_stream_token = store.get_room_max_token()
self.assertNotEqual(len(room_stream_token.instance_map), 0)
# Check that syncing still gets the new event, despite the gap in the
# stream IDs.
channel = make_request(
self.reactor,
sync_hs_site,
"GET",
"/sync?since={}".format(next_batch),
access_token=access_token,
)
# We should only see the new event and nothing else
self.assertIn(room_id1, channel.json_body["rooms"]["join"])
self.assertNotIn(room_id2, channel.json_body["rooms"]["join"])
events = channel.json_body["rooms"]["join"][room_id1]["timeline"]["events"]
self.assertListEqual(
[first_event_in_room1], [event["event_id"] for event in events]
)
# Get the next batch and makes sure its a vector clock style token.
vector_clock_token = channel.json_body["next_batch"]
self.assertTrue(vector_clock_token.startswith("m"))
# Now that we've got a vector clock token we finish the fake persisting
# an event we started above.
self.get_success(actx.__aexit__(None, None, None))
# Now try and send an event to the other rooom so that we can test that
# the vector clock style token works as a `since` token.
response = self.helper.send(room_id2, body="Hi!", tok=self.other_access_token)
first_event_in_room2 = response["event_id"]
channel = make_request(
self.reactor,
sync_hs_site,
"GET",
"/sync?since={}".format(vector_clock_token),
access_token=access_token,
)
self.assertNotIn(room_id1, channel.json_body["rooms"]["join"])
self.assertIn(room_id2, channel.json_body["rooms"]["join"])
events = channel.json_body["rooms"]["join"][room_id2]["timeline"]["events"]
self.assertListEqual(
[first_event_in_room2], [event["event_id"] for event in events]
)
next_batch = channel.json_body["next_batch"]
# We also want to test that the vector clock style token works with
# pagination. We do this by sending a couple of new events into the room
# and syncing again to get a prev_batch token for each room, then
# paginating from there back to the vector clock token.
self.helper.send(room_id1, body="Hi again!", tok=self.other_access_token)
self.helper.send(room_id2, body="Hi again!", tok=self.other_access_token)
channel = make_request(
self.reactor,
sync_hs_site,
"GET",
"/sync?since={}".format(next_batch),
access_token=access_token,
)
prev_batch1 = channel.json_body["rooms"]["join"][room_id1]["timeline"][
"prev_batch"
]
prev_batch2 = channel.json_body["rooms"]["join"][room_id2]["timeline"][
"prev_batch"
]
# Paginating back in the first room should not produce any results, as
# no events have happened in it. This tests that we are correctly
# filtering results based on the vector clock portion.
channel = make_request(
self.reactor,
sync_hs_site,
"GET",
"/rooms/{}/messages?from={}&to={}&dir=b".format(
room_id1, prev_batch1, vector_clock_token
),
access_token=access_token,
)
self.assertListEqual([], channel.json_body["chunk"])
# Paginating back on the second room should produce the first event
# again. This tests that pagination isn't completely broken.
channel = make_request(
self.reactor,
sync_hs_site,
"GET",
"/rooms/{}/messages?from={}&to={}&dir=b".format(
room_id2, prev_batch2, vector_clock_token
),
access_token=access_token,
)
self.assertEqual(len(channel.json_body["chunk"]), 1)
self.assertEqual(
channel.json_body["chunk"][0]["event_id"], first_event_in_room2
)
# Paginating forwards should give the same results
channel = make_request(
self.reactor,
sync_hs_site,
"GET",
"/rooms/{}/messages?from={}&to={}&dir=f".format(
room_id1, vector_clock_token, prev_batch1
),
access_token=access_token,
)
self.assertListEqual([], channel.json_body["chunk"])
channel = make_request(
self.reactor,
sync_hs_site,
"GET",
"/rooms/{}/messages?from={}&to={}&dir=f".format(
room_id2,
vector_clock_token,
prev_batch2,
),
access_token=access_token,
)
self.assertEqual(len(channel.json_body["chunk"]), 1)
self.assertEqual(
channel.json_body["chunk"][0]["event_id"], first_event_in_room2
)
| apache-2.0 |
zsoltdudas/lis-tempest | tempest/api/compute/admin/test_fixed_ips.py | 13 | 2319 | # Copyright 2013 IBM Corp
# 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.
from tempest.api.compute import base
from tempest import config
from tempest import test
CONF = config.CONF
class FixedIPsTestJson(base.BaseV2ComputeAdminTest):
@classmethod
def skip_checks(cls):
super(FixedIPsTestJson, cls).skip_checks()
if CONF.service_available.neutron:
msg = ("%s skipped as neutron is available" % cls.__name__)
raise cls.skipException(msg)
@classmethod
def setup_clients(cls):
super(FixedIPsTestJson, cls).setup_clients()
cls.client = cls.os_adm.fixed_ips_client
@classmethod
def resource_setup(cls):
super(FixedIPsTestJson, cls).resource_setup()
server = cls.create_test_server(wait_until='ACTIVE')
server = cls.servers_client.show_server(server['id'])['server']
for ip_set in server['addresses']:
for ip in server['addresses'][ip_set]:
if ip['OS-EXT-IPS:type'] == 'fixed':
cls.ip = ip['addr']
break
if cls.ip:
break
@test.idempotent_id('16b7d848-2f7c-4709-85a3-2dfb4576cc52')
@test.services('network')
def test_list_fixed_ip_details(self):
fixed_ip = self.client.show_fixed_ip(self.ip)
self.assertEqual(fixed_ip['fixed_ip']['address'], self.ip)
@test.idempotent_id('5485077b-7e46-4cec-b402-91dc3173433b')
@test.services('network')
def test_set_reserve(self):
self.client.reserve_fixed_ip(self.ip, reserve="None")
@test.idempotent_id('7476e322-b9ff-4710-bf82-49d51bac6e2e')
@test.services('network')
def test_set_unreserve(self):
self.client.reserve_fixed_ip(self.ip, unreserve="None")
| apache-2.0 |