repo_name
stringlengths 5
100
| ref
stringlengths 12
67
| path
stringlengths 4
244
| copies
stringlengths 1
8
| content
stringlengths 0
1.05M
⌀ |
|---|---|---|---|---|
SchulzLab/TEPIC
|
refs/heads/master
|
Code/filterInvalidRegions.py
|
1
|
import sys
#argv1 Affinity file
#argv2 Filtered Affinity file
#argv3 pValue Score file
#argv4 Filtered pValue Score file
def isValidAffinity(lineSplit):
for i in range(1,len(lineSplit)):
if (float(lineSplit[i]) != 0):
return True
return False
def isValidpValue(lineSplit):
for i in range(1,len(lineSplit)):
if (float(lineSplit[i]) != 1):
return True
return False
def main():
#Checking Affinity
infile=open(sys.argv[1],"r")
output=open(sys.argv[2],"w")
#Copy header line
output.write(infile.readline())
#Check individual lines
for l in infile:
if (isValidAffinity(l.split())):
output.write(l)
infile.close()
output.close()
if (len(sys.argv) > 3):
#Checking pValue
infile=open(sys.argv[3],"r")
output=open(sys.argv[4],"w")
#Copy header line
output.write(infile.readline())
#Check individual lines
for l in infile:
if (isValidpValue(l.split())):
output.write(l)
infile.close()
output.close()
main()
|
gangadharkadam/shfr
|
refs/heads/master
|
frappe/website/utils.py
|
11
|
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe, re
def delete_page_cache(path):
if not path:
path = ""
cache = frappe.cache()
cache.delete_value("page:" + path)
cache.delete_value("page_context:" + path)
cache.delete_value("sitemap_options:" + path)
def scrub_relative_urls(html):
"""prepend a slash before a relative url"""
html = re.sub("""(src|href)[^\w'"]*['"](?!http|ftp|/|#|%|{)([^'" >]+)['"]""", '\g<1> = "/\g<2>"', html)
html = re.sub("""url\((?!http|ftp|/|#|%|{)([^\(\)]+)\)""", 'url(/\g<1>)', html)
return html
def find_first_image(html):
m = re.finditer("""<img[^>]*src\s?=\s?['"]([^'"]*)['"]""", html)
try:
return m.next().groups()[0]
except StopIteration:
return None
def can_cache(no_cache=False):
return not (frappe.conf.disable_website_cache or no_cache)
def get_comment_list(doctype, name):
return frappe.db.sql("""select
comment, comment_by_fullname, creation
from `tabComment` where comment_doctype=%s
and comment_docname=%s order by creation""", (doctype, name), as_dict=1) or []
def get_home_page():
def _get_home_page():
role_home_page = frappe.get_hooks("role_home_page")
home_page = None
for role in frappe.get_roles():
if role in role_home_page:
home_page = role_home_page[role][0]
break
if not home_page:
home_page = frappe.get_hooks("home_page")
if home_page:
home_page = home_page[0]
if not home_page:
home_page = frappe.db.get_value("Website Settings", None, "home_page") or "login"
return home_page
return frappe.cache().get_value("home_page:" + frappe.session.user, _get_home_page)
def is_signup_enabled():
if getattr(frappe.local, "is_signup_enabled", None) is None:
frappe.local.is_signup_enabled = True
if frappe.utils.cint(frappe.db.get_value("Website Settings",
"Website Settings", "disable_signup")):
frappe.local.is_signup_enabled = False
return frappe.local.is_signup_enabled
def cleanup_page_name(title):
"""make page name from title"""
name = title.lower()
name = re.sub('[~!@#$%^&*+()<>,."\'\?]', '', name)
name = re.sub('[:/]', '-', name)
name = '-'.join(name.split())
# replace repeating hyphens
name = re.sub(r"(-)\1+", r"\1", name)
return name
def get_hex_shade(color, percent):
def p(c):
v = int(c, 16) + int(int('ff', 16) * (float(percent)/100))
if v < 0:
v=0
if v > 255:
v=255
h = hex(v)[2:]
if len(h) < 2:
h = "0" + h
return h
r, g, b = color[0:2], color[2:4], color[4:6]
avg = (float(int(r, 16) + int(g, 16) + int(b, 16)) / 3)
# switch dark and light shades
if avg > 128:
percent = -percent
# stronger diff for darker shades
if percent < 25 and avg < 64:
percent = percent * 2
return p(r) + p(g) + p(b)
|
ecoal95/servo
|
refs/heads/master
|
tests/wpt/web-platform-tests/tools/third_party/pytest/testing/logging/test_fixture.py
|
30
|
# -*- coding: utf-8 -*-
import logging
import pytest
logger = logging.getLogger(__name__)
sublogger = logging.getLogger(__name__ + ".baz")
def test_fixture_help(testdir):
result = testdir.runpytest("--fixtures")
result.stdout.fnmatch_lines(["*caplog*"])
def test_change_level(caplog):
caplog.set_level(logging.INFO)
logger.debug("handler DEBUG level")
logger.info("handler INFO level")
caplog.set_level(logging.CRITICAL, logger=sublogger.name)
sublogger.warning("logger WARNING level")
sublogger.critical("logger CRITICAL level")
assert "DEBUG" not in caplog.text
assert "INFO" in caplog.text
assert "WARNING" not in caplog.text
assert "CRITICAL" in caplog.text
def test_change_level_undo(testdir):
"""Ensure that 'set_level' is undone after the end of the test"""
testdir.makepyfile(
"""
import logging
def test1(caplog):
caplog.set_level(logging.INFO)
# using + operator here so fnmatch_lines doesn't match the code in the traceback
logging.info('log from ' + 'test1')
assert 0
def test2(caplog):
# using + operator here so fnmatch_lines doesn't match the code in the traceback
logging.info('log from ' + 'test2')
assert 0
"""
)
result = testdir.runpytest_subprocess()
result.stdout.fnmatch_lines(["*log from test1*", "*2 failed in *"])
assert "log from test2" not in result.stdout.str()
def test_with_statement(caplog):
with caplog.at_level(logging.INFO):
logger.debug("handler DEBUG level")
logger.info("handler INFO level")
with caplog.at_level(logging.CRITICAL, logger=sublogger.name):
sublogger.warning("logger WARNING level")
sublogger.critical("logger CRITICAL level")
assert "DEBUG" not in caplog.text
assert "INFO" in caplog.text
assert "WARNING" not in caplog.text
assert "CRITICAL" in caplog.text
def test_log_access(caplog):
caplog.set_level(logging.INFO)
logger.info("boo %s", "arg")
assert caplog.records[0].levelname == "INFO"
assert caplog.records[0].msg == "boo %s"
assert "boo arg" in caplog.text
def test_record_tuples(caplog):
caplog.set_level(logging.INFO)
logger.info("boo %s", "arg")
assert caplog.record_tuples == [(__name__, logging.INFO, "boo arg")]
def test_unicode(caplog):
caplog.set_level(logging.INFO)
logger.info(u"bū")
assert caplog.records[0].levelname == "INFO"
assert caplog.records[0].msg == u"bū"
assert u"bū" in caplog.text
def test_clear(caplog):
caplog.set_level(logging.INFO)
logger.info(u"bū")
assert len(caplog.records)
assert caplog.text
caplog.clear()
assert not len(caplog.records)
assert not caplog.text
@pytest.fixture
def logging_during_setup_and_teardown(caplog):
caplog.set_level("INFO")
logger.info("a_setup_log")
yield
logger.info("a_teardown_log")
assert [x.message for x in caplog.get_records("teardown")] == ["a_teardown_log"]
def test_caplog_captures_for_all_stages(caplog, logging_during_setup_and_teardown):
assert not caplog.records
assert not caplog.get_records("call")
logger.info("a_call_log")
assert [x.message for x in caplog.get_records("call")] == ["a_call_log"]
assert [x.message for x in caplog.get_records("setup")] == ["a_setup_log"]
# This reachers into private API, don't use this type of thing in real tests!
assert set(caplog._item.catch_log_handlers.keys()) == {"setup", "call"}
|
tommz9/wrf_runner
|
refs/heads/master
|
src/wrf_runner/exceptions.py
|
1
|
class WrfRunnerException(Exception):
pass
|
cyberden/CouchPotatoServer
|
refs/heads/develop
|
libs/gntp/version.py
|
123
|
# Copyright: 2013 Paul Traylor
# These sources are released under the terms of the MIT license: see LICENSE
__version__ = '1.0.2'
|
sibsibsib/pressureNET-server
|
refs/heads/master
|
home/views.py
|
1
|
from django.conf import settings
from django.views.decorators.cache import cache_page
from django.views.generic.base import TemplateView, RedirectView
index = cache_page(TemplateView.as_view(template_name='home/index.html'), settings.CACHE_TIMEOUT)
about = cache_page(TemplateView.as_view(template_name='home/about.html'), settings.CACHE_TIMEOUT)
map_page = cache_page(TemplateView.as_view(template_name='home/map.html'), settings.CACHE_TIMEOUT)
card_redirect = RedirectView.as_view(url=settings.PLAY_STORE_URL)
|
HiroIshikawa/21playground
|
refs/heads/master
|
visualizer/_app_boilerplate/venv/lib/python3.5/site-packages/wheel/__init__.py
|
219
|
# __variables__ with double-quoted values will be available in setup.py:
__version__ = "0.24.0"
|
RafaelRMachado/qtwebkit
|
refs/heads/dev
|
Tools/Scripts/webkitpy/port/driver_unittest.py
|
117
|
# Copyright (C) 2010 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import unittest2 as unittest
from webkitpy.common.system.systemhost_mock import MockSystemHost
from webkitpy.port import Port, Driver, DriverOutput
from webkitpy.port.server_process_mock import MockServerProcess
# FIXME: remove the dependency on TestWebKitPort
from webkitpy.port.port_testcase import TestWebKitPort
from webkitpy.tool.mocktool import MockOptions
class DriverOutputTest(unittest.TestCase):
def test_strip_metrics(self):
patterns = [
('RenderView at (0,0) size 800x600', 'RenderView '),
('text run at (0,0) width 100: "some text"', '"some text"'),
('RenderBlock {HTML} at (0,0) size 800x600', 'RenderBlock {HTML} '),
('RenderBlock {INPUT} at (29,3) size 12x12 [color=#000000]', 'RenderBlock {INPUT}'),
('RenderBlock (floating) {DT} at (5,5) size 79x310 [border: (5px solid #000000)]',
'RenderBlock (floating) {DT} [border: px solid #000000)]'),
('\n "truncate text "\n', '\n "truncate text"\n'),
('RenderText {#text} at (0,3) size 41x12\n text run at (0,3) width 41: "whimper "\n',
'RenderText {#text} \n "whimper"\n'),
("""text run at (0,0) width 109: ".one {color: green;}"
text run at (109,0) width 0: " "
text run at (0,17) width 81: ".1 {color: red;}"
text run at (81,17) width 0: " "
text run at (0,34) width 102: ".a1 {color: green;}"
text run at (102,34) width 0: " "
text run at (0,51) width 120: "P.two {color: purple;}"
text run at (120,51) width 0: " "\n""",
'".one {color: green;} .1 {color: red;} .a1 {color: green;} P.two {color: purple;}"\n'),
('text-- other text', 'text--other text'),
(' some output "truncate trailing spaces at end of line after text" \n',
' some output "truncate trailing spaces at end of line after text"\n'),
(r'scrollWidth 120', r'scrollWidth'),
(r'scrollHeight 120', r'scrollHeight'),
]
for pattern in patterns:
driver_output = DriverOutput(pattern[0], None, None, None)
driver_output.strip_metrics()
self.assertEqual(driver_output.text, pattern[1])
class DriverTest(unittest.TestCase):
def make_port(self):
port = Port(MockSystemHost(), 'test', MockOptions(configuration='Release'))
port._config.build_directory = lambda configuration: '/mock-build'
return port
def _assert_wrapper(self, wrapper_string, expected_wrapper):
wrapper = Driver(self.make_port(), None, pixel_tests=False)._command_wrapper(wrapper_string)
self.assertEqual(wrapper, expected_wrapper)
def test_command_wrapper(self):
self._assert_wrapper(None, [])
self._assert_wrapper("valgrind", ["valgrind"])
# Validate that shlex works as expected.
command_with_spaces = "valgrind --smc-check=\"check with spaces!\" --foo"
expected_parse = ["valgrind", "--smc-check=check with spaces!", "--foo"]
self._assert_wrapper(command_with_spaces, expected_parse)
def test_test_to_uri(self):
port = self.make_port()
driver = Driver(port, None, pixel_tests=False)
self.assertEqual(driver.test_to_uri('foo/bar.html'), 'file://%s/foo/bar.html' % port.layout_tests_dir())
self.assertEqual(driver.test_to_uri('http/tests/foo.html'), 'http://127.0.0.1:8000/foo.html')
self.assertEqual(driver.test_to_uri('http/tests/ssl/bar.html'), 'https://127.0.0.1:8443/ssl/bar.html')
def test_uri_to_test(self):
port = self.make_port()
driver = Driver(port, None, pixel_tests=False)
self.assertEqual(driver.uri_to_test('file://%s/foo/bar.html' % port.layout_tests_dir()), 'foo/bar.html')
self.assertEqual(driver.uri_to_test('http://127.0.0.1:8000/foo.html'), 'http/tests/foo.html')
self.assertEqual(driver.uri_to_test('https://127.0.0.1:8443/ssl/bar.html'), 'http/tests/ssl/bar.html')
def test_read_block(self):
port = TestWebKitPort()
driver = Driver(port, 0, pixel_tests=False)
driver._server_process = MockServerProcess(lines=[
'ActualHash: foobar',
'Content-Type: my_type',
'Content-Transfer-Encoding: none',
"#EOF",
])
content_block = driver._read_block(0)
self.assertEqual(content_block.content_type, 'my_type')
self.assertEqual(content_block.encoding, 'none')
self.assertEqual(content_block.content_hash, 'foobar')
driver._server_process = None
def test_read_binary_block(self):
port = TestWebKitPort()
driver = Driver(port, 0, pixel_tests=True)
driver._server_process = MockServerProcess(lines=[
'ActualHash: actual',
'ExpectedHash: expected',
'Content-Type: image/png',
'Content-Length: 9',
"12345678",
"#EOF",
])
content_block = driver._read_block(0)
self.assertEqual(content_block.content_type, 'image/png')
self.assertEqual(content_block.content_hash, 'actual')
self.assertEqual(content_block.content, '12345678\n')
self.assertEqual(content_block.decoded_content, '12345678\n')
driver._server_process = None
def test_read_base64_block(self):
port = TestWebKitPort()
driver = Driver(port, 0, pixel_tests=True)
driver._server_process = MockServerProcess(lines=[
'ActualHash: actual',
'ExpectedHash: expected',
'Content-Type: image/png',
'Content-Transfer-Encoding: base64',
'Content-Length: 12',
'MTIzNDU2NzgK#EOF',
])
content_block = driver._read_block(0)
self.assertEqual(content_block.content_type, 'image/png')
self.assertEqual(content_block.content_hash, 'actual')
self.assertEqual(content_block.encoding, 'base64')
self.assertEqual(content_block.content, 'MTIzNDU2NzgK')
self.assertEqual(content_block.decoded_content, '12345678\n')
def test_no_timeout(self):
port = TestWebKitPort()
port._config.build_directory = lambda configuration: '/mock-build'
driver = Driver(port, 0, pixel_tests=True, no_timeout=True)
self.assertEqual(driver.cmd_line(True, []), ['/mock-build/DumpRenderTree', '--no-timeout', '-'])
def test_check_for_driver_crash(self):
port = TestWebKitPort()
driver = Driver(port, 0, pixel_tests=True)
class FakeServerProcess(object):
def __init__(self, crashed):
self.crashed = crashed
def pid(self):
return 1234
def name(self):
return 'FakeServerProcess'
def has_crashed(self):
return self.crashed
def stop(self, timeout):
pass
def assert_crash(driver, error_line, crashed, name, pid, unresponsive=False):
self.assertEqual(driver._check_for_driver_crash(error_line), crashed)
self.assertEqual(driver._crashed_process_name, name)
self.assertEqual(driver._crashed_pid, pid)
self.assertEqual(driver._subprocess_was_unresponsive, unresponsive)
driver.stop()
driver._server_process = FakeServerProcess(False)
assert_crash(driver, '', False, None, None)
driver._crashed_process_name = None
driver._crashed_pid = None
driver._server_process = FakeServerProcess(False)
driver._subprocess_was_unresponsive = False
assert_crash(driver, '#CRASHED\n', True, 'FakeServerProcess', 1234)
driver._crashed_process_name = None
driver._crashed_pid = None
driver._server_process = FakeServerProcess(False)
driver._subprocess_was_unresponsive = False
assert_crash(driver, '#CRASHED - WebProcess\n', True, 'WebProcess', None)
driver._crashed_process_name = None
driver._crashed_pid = None
driver._server_process = FakeServerProcess(False)
driver._subprocess_was_unresponsive = False
assert_crash(driver, '#CRASHED - WebProcess (pid 8675)\n', True, 'WebProcess', 8675)
driver._crashed_process_name = None
driver._crashed_pid = None
driver._server_process = FakeServerProcess(False)
driver._subprocess_was_unresponsive = False
assert_crash(driver, '#PROCESS UNRESPONSIVE - WebProcess (pid 8675)\n', True, 'WebProcess', 8675, True)
driver._crashed_process_name = None
driver._crashed_pid = None
driver._server_process = FakeServerProcess(False)
driver._subprocess_was_unresponsive = False
assert_crash(driver, '#CRASHED - renderer (pid 8675)\n', True, 'renderer', 8675)
driver._crashed_process_name = None
driver._crashed_pid = None
driver._server_process = FakeServerProcess(True)
driver._subprocess_was_unresponsive = False
assert_crash(driver, '', True, 'FakeServerProcess', 1234)
def test_creating_a_port_does_not_write_to_the_filesystem(self):
port = TestWebKitPort()
driver = Driver(port, 0, pixel_tests=True)
self.assertEqual(port._filesystem.written_files, {})
self.assertEqual(port._filesystem.last_tmpdir, None)
def test_stop_cleans_up_properly(self):
port = TestWebKitPort()
port._server_process_constructor = MockServerProcess
driver = Driver(port, 0, pixel_tests=True)
driver.start(True, [])
last_tmpdir = port._filesystem.last_tmpdir
self.assertNotEquals(last_tmpdir, None)
driver.stop()
self.assertFalse(port._filesystem.isdir(last_tmpdir))
def test_two_starts_cleans_up_properly(self):
port = TestWebKitPort()
port._server_process_constructor = MockServerProcess
driver = Driver(port, 0, pixel_tests=True)
driver.start(True, [])
last_tmpdir = port._filesystem.last_tmpdir
driver._start(True, [])
self.assertFalse(port._filesystem.isdir(last_tmpdir))
def test_start_actually_starts(self):
port = TestWebKitPort()
port._server_process_constructor = MockServerProcess
driver = Driver(port, 0, pixel_tests=True)
driver.start(True, [])
self.assertTrue(driver._server_process.started)
|
mostafamosly/Uraeus
|
refs/heads/master
|
Small/procurement/views.py
|
1
|
from django.views.generic import TemplateView, ListView
from django.shortcuts import *
from django.template import RequestContext
from django.http import HttpResponse
from django.forms import ModelForm
from procurement.models import *
from django.contrib.auth.decorators import login_required
from warehouse.models import *
# Create your views here.
class ProcurementForm(ModelForm):
class Meta:
model = Procurement
@login_required
def Procurement_list(request, template_name='procurement/pro_list.html'):
pros = Procurement.objects.all()
data = {}
data['object_list'] = pros
return render(request, template_name, data)
@login_required
def Procurement_create(request, template_name='procurement/pro_form.html'):
form = ProcurementForm(request.POST or None)
if form.is_valid():
p=inventory.objects.get(product_name = form.data['product'])
p.quantity += int(form.data['quantity'])
p.save()
form.save()
return redirect('procurement_list')
return render(request, template_name, {'form':form})
@login_required
def Procurement_update(request, pk, template_name='procurement/pro_form.html'):
pro = get_object_or_404(Procurement, pk=pk)
form = ProcurementForm(request.POST or None, instance=pro)
if form.is_valid():
form.save()
return redirect('procurement_list')
return render(request, template_name, {'form':form})
@login_required
def Procurement_delete(request, pk, template_name='procurement/pro_confirm_delete.html'):
pro = get_object_or_404(Procurement, pk=pk)
if request.method=='POST':
pro.delete()
return redirect('procurement_list')
return render(request, template_name, {'object':pro})
class ListInvoice(ListView):
model = PurchaseInvoice
#success_url = reverse_lazy('list_invoice')
class PurchaseInvoiceForm(ModelForm):
class Meta:
model = PurchaseInvoice
def PurchaseInvoice_list(request, template_name='procurement/purchaseinvoice_list.html'):
pis = PurchaseInvoice.objects.all()
data = {}
data['object_list'] = pis
return render(request, template_name, data)
def PurchaseInvoice_create(request, template_name='procurement/purchaseinvoice_form.html'):
form = PurchaseInvoiceForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('purchaseinvoice_list')
return render(request, template_name, {'form':form})
def PurchaseInvoice_update(request, pk, template_name='procurement/purchaseinvoice_form.html'):
pi = get_object_or_404(PurchaseInvoice, pk=pk)
form = PurchaseInvoiceForm(request.POST or None, instance=pi)
if form.is_valid():
form.save()
return redirect('purchaseinvoice_list')
return render(request, template_name, {'form':form})
def PurchaseInvoice_delete(request, pk, template_name='procurement/purchaseinvoice_confirm_delete.html'):
pi = get_object_or_404(PurchaseInvoice, pk=pk)
if request.method=='POST':
pi.delete()
return redirect('purchaseinvoice_list')
return render(request, template_name, {'object':pi})
# Requisition Views
class PurchaseRequisionForm(ModelForm):
class Meta:
model = PurchaseRequision
def purchaserequision_list(request, template_name='procurement/purchaserequision_list.html'):
prs = PurchaseRequision.objects.all()
data = {}
data['object_list'] = prs
return render(request, template_name, data)
def purchaserequision_create(request, template_name='procurement/purchaserequision_form.html'):
form = PurchaseRequisionForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('purchaserequision_list')
return render(request, template_name, {'form':form})
def purchaserequision_update(request, pk, template_name='procurement/purchaserequision_form.html'):
pr = get_object_or_404(PurchaseRequision, pk=pk)
form = PurchaseInvoiceForm(request.POST or None, instance=pr)
if form.is_valid():
form.save()
return redirect('purchaserequision_list')
return render(request, template_name, {'form':form})
def purchaserequision_delete(request, pk, template_name='procurement/purchaserequision_confirm_delete.html'):
pr = get_object_or_404(PurchaseRequision, pk=pk)
if request.method=='POST':
pr.delete()
return redirect('purchaserequision_list')
return render(request, template_name, {'object':pr})
# Order Views
class PurchaseOrderForm(ModelForm):
class Meta:
model = PurchaseOrder
def PurchaseOrder_list(request, template_name='procurement/purchaseorder_list.html'):
pis = PurchaseOrder.objects.all()
data = {}
data['object_list'] = pis
return render(request, template_name, data)
def PurchaseOrder_create(request, template_name='procurement/purchaseorder_form.html'):
form = PurchaseOrderForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('purchaseorder_list')
return render(request, template_name, {'form':form})
def PurchaseOrder_update(request, pk, template_name='procurement/purchaseorder_form.html'):
pi = get_object_or_404(PurchaseOrder, pk=pk)
form = PurchaseOrderForm(request.POST or None, instance=pi)
if form.is_valid():
form.save()
return redirect('purchaseorder_list')
return render(request, template_name, {'form':form})
def PurchaseOrder_delete(request, pk, template_name='procurement/purchaseorder_confirm_delete.html'):
pi = get_object_or_404(PurchaseOrder, pk=pk)
if request.method=='POST':
pi.delete()
return redirect('purchaseorder_list')
return render(request, template_name, {'object':pi})
|
aleximplode/d3scraper
|
refs/heads/master
|
src/d3/d3/settings.py
|
1
|
BOT_NAME = 'd3'
BOT_VERSION = '1.0'
SPIDER_MODULES = ['d3.spiders']
NEWSPIDER_MODULE = 'd3.spiders'
USER_AGENT = '%s/%s' % (BOT_NAME, BOT_VERSION)
CONCURRENT_REQUESTS = 24
CONCURRENT_REQUESTS_PER_DOMAIN = 24
ITEM_PIPELINES = ['d3.pipelines.TypeCleanerPipeline',
'd3.pipelines.ItemCleanerPipeline',
'd3.pipelines.MySQLPipeline']
|
LaynePeng/flocker
|
refs/heads/master
|
flocker/common/test/test_ipc.py
|
16
|
# Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Unit tests for IPC.
"""
from __future__ import absolute_import
from unittest import TestCase as PyTestCase
from zope.interface.verify import verifyObject
from .. import INode, FakeNode
from ...testtools import assertNoFDsLeaked
def make_inode_tests(fixture):
"""
Create a TestCase for ``INode``.
:param fixture: A fixture that returns a :class:`INode` provider which
will work with any arbitrary valid program with arguments.
"""
class INodeTests(PyTestCase):
"""Tests for :class:`INode` implementors.
May be functional tests depending on the fixture.
"""
def test_interface(self):
"""
The tested object provides :class:`INode`.
"""
node = fixture(self)
self.assertTrue(verifyObject(INode, node))
def test_run_no_fd_leakage(self):
"""
No file descriptors are leaked by ``run()``.
"""
node = fixture(self)
with assertNoFDsLeaked(self):
with node.run([b"cat"]):
pass
def test_run_exceptions_pass_through(self):
"""
Exceptions raised in the context manager are not swallowed.
"""
node = fixture(self)
with self.assertRaises(RuntimeError):
with node.run([b"cat"]):
raise RuntimeError()
def test_run_no_fd_leakage_exceptions(self):
"""
No file descriptors are leaked by ``run()`` if exception is
raised within the context manager.
"""
node = fixture(self)
with assertNoFDsLeaked(self):
try:
with node.run([b"cat"]):
raise RuntimeError()
except RuntimeError:
pass
def test_run_writeable(self):
"""
The returned object from ``run()`` is writeable.
"""
node = fixture(self)
with node.run([b"python", b"-c",
b"import sys; sys.stdin.read()"]) as writer:
writer.write(b"hello")
writer.write(b"there")
def test_get_output_no_leakage(self):
"""
No file descriptors are leaked by ``get_output()``.
"""
node = fixture(self)
with assertNoFDsLeaked(self):
node.get_output([b"echo", b"hello"])
def test_get_output_result_bytes(self):
"""
``get_output()`` returns a result that is ``bytes``.
"""
node = fixture(self)
result = node.get_output([b"echo", b"hello"])
self.assertIsInstance(result, bytes)
return INodeTests
class FakeINodeTests(make_inode_tests(lambda t: FakeNode([b"hello"]))):
"""``INode`` tests for ``FakeNode``."""
|
Coderhypo/UIAMS
|
refs/heads/master
|
app/decorators.py
|
1
|
from functools import wraps
from flask import abort
from flask.ext.login import current_user
from models import Permission
def permission_required(permission):
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not current_user.can(permission):
abort(403)
return f(*args, **kwargs)
return decorated_function
return decorator
def admin_required(f):
return permission_required(Permission.ADMINISTER)(f)
def query_required(f):
return permission_required(Permission.QUERY)(f)
def commit_required(f):
return permission_required(Permission.COMMIT)(f)
|
MrSenko/Nitrate
|
refs/heads/develop
|
tcms/testcases/migrations/0005_allow_null_to_testcaseattachment_case_run.py
|
1
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('testcases', '0004_add_unique_to_testcasebugsystem_name'),
]
operations = [
migrations.AlterField(
model_name='testcaseattachment',
name='case_run',
field=models.ForeignKey(related_name='case_run_attachment', default=None, blank=True, to='testruns.TestCaseRun', null=True),
),
]
|
altsen/diandiyun-platform
|
refs/heads/master
|
lms/djangoapps/courseware/migrations/0003_done_grade_cache.py
|
194
|
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# NOTE (vshnayder): This constraint has the wrong field order, so it doesn't actually
# do anything in sqlite. Migration 0004 actually removes this index for sqlite.
# Removing unique constraint on 'StudentModule', fields ['module_id', 'module_type', 'student']
db.delete_unique('courseware_studentmodule', ['module_id', 'module_type', 'student_id'])
# Adding field 'StudentModule.max_grade'
db.add_column('courseware_studentmodule', 'max_grade', self.gf('django.db.models.fields.FloatField')(null=True, blank=True), keep_default=False)
# Adding field 'StudentModule.done'
db.add_column('courseware_studentmodule', 'done', self.gf('django.db.models.fields.CharField')(default='na', max_length=8, db_index=True), keep_default=False)
# Adding unique constraint on 'StudentModule', fields ['module_id', 'student']
db.create_unique('courseware_studentmodule', ['module_id', 'student_id'])
def backwards(self, orm):
# Removing unique constraint on 'StudentModule', fields ['module_id', 'student']
db.delete_unique('courseware_studentmodule', ['module_id', 'student_id'])
# Deleting field 'StudentModule.max_grade'
db.delete_column('courseware_studentmodule', 'max_grade')
# Deleting field 'StudentModule.done'
db.delete_column('courseware_studentmodule', 'done')
# Adding unique constraint on 'StudentModule', fields ['module_id', 'module_type', 'student']
db.create_unique('courseware_studentmodule', ['module_id', 'module_type', 'student_id'])
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'about': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'avatar_type': ('django.db.models.fields.CharField', [], {'default': "'n'", 'max_length': '1'}),
'bronze': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
'consecutive_days_visit_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'country': ('django_countries.fields.CountryField', [], {'max_length': '2', 'blank': 'True'}),
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'date_of_birth': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'display_tag_filter_strategy': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'email_isvalid': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'email_key': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True'}),
'email_tag_filter_strategy': ('django.db.models.fields.SmallIntegerField', [], {'default': '1'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'gold': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
'gravatar': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'ignored_tags': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'interesting_tags': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'location': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'new_response_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'questions_per_page': ('django.db.models.fields.SmallIntegerField', [], {'default': '10'}),
'real_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'reputation': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'}),
'seen_response_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'show_country': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'silver': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
'status': ('django.db.models.fields.CharField', [], {'default': "'w'", 'max_length': '2'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}),
'website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'courseware.studentmodule': {
'Meta': {'unique_together': "(('student', 'module_id'),)", 'object_name': 'StudentModule'},
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
'done': ('django.db.models.fields.CharField', [], {'default': "'na'", 'max_length': '8', 'db_index': 'True'}),
'grade': ('django.db.models.fields.FloatField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'max_grade': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}),
'module_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
'module_type': ('django.db.models.fields.CharField', [], {'default': "'problem'", 'max_length': '32', 'db_index': 'True'}),
'state': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'student': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
}
}
complete_apps = ['courseware']
|
ondra-novak/chromium.src
|
refs/heads/nw
|
tools/perf_expectations/tests/perf_expectations_unittest.py
|
178
|
#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Verify perf_expectations.json can be loaded using simplejson.
perf_expectations.json is a JSON-formatted file. This script verifies
that simplejson can load it correctly. It should catch most common
formatting problems.
"""
import subprocess
import sys
import os
import unittest
import re
simplejson = None
def OnTestsLoad():
old_path = sys.path
script_path = os.path.dirname(sys.argv[0])
load_path = None
global simplejson
# This test script should be stored in src/tools/perf_expectations/. That
# directory will most commonly live in 2 locations:
#
# - a regular Chromium checkout, in which case src/third_party
# is where to look for simplejson
#
# - a buildbot checkout, in which case .../pylibs is where
# to look for simplejson
#
# Locate and install the correct path based on what we can find.
#
for path in ('../../../third_party', '../../../../../pylibs'):
path = os.path.join(script_path, path)
if os.path.exists(path) and os.path.isdir(path):
load_path = os.path.abspath(path)
break
if load_path is None:
msg = "%s expects to live within a Chromium checkout" % sys.argv[0]
raise Exception, "Error locating simplejson load path (%s)" % msg
# Try importing simplejson once. If this succeeds, we found it and will
# load it again later properly. Fail if we cannot load it.
sys.path.append(load_path)
try:
import simplejson as Simplejson
simplejson = Simplejson
except ImportError, e:
msg = "%s expects to live within a Chromium checkout" % sys.argv[0]
raise Exception, "Error trying to import simplejson from %s (%s)" % \
(load_path, msg)
finally:
sys.path = old_path
return True
def LoadJsonFile(filename):
f = open(filename, 'r')
try:
data = simplejson.load(f)
except ValueError, e:
f.seek(0)
print "Error reading %s:\n%s" % (filename,
f.read()[:50]+'...')
raise e
f.close()
return data
OnTestsLoad()
CONFIG_JSON = os.path.join(os.path.dirname(sys.argv[0]),
'../chromium_perf_expectations.cfg')
MAKE_EXPECTATIONS = os.path.join(os.path.dirname(sys.argv[0]),
'../make_expectations.py')
PERF_EXPECTATIONS = os.path.join(os.path.dirname(sys.argv[0]),
'../perf_expectations.json')
class PerfExpectationsUnittest(unittest.TestCase):
def testPerfExpectations(self):
# Test data is dictionary.
perf_data = LoadJsonFile(PERF_EXPECTATIONS)
if not isinstance(perf_data, dict):
raise Exception('perf expectations is not a dict')
# Test the 'load' key.
if not 'load' in perf_data:
raise Exception("perf expectations is missing a load key")
if not isinstance(perf_data['load'], bool):
raise Exception("perf expectations load key has non-bool value")
# Test all key values are dictionaries.
bad_keys = []
for key in perf_data:
if key == 'load':
continue
if not isinstance(perf_data[key], dict):
bad_keys.append(key)
if len(bad_keys) > 0:
msg = "perf expectations keys have non-dict values"
raise Exception("%s: %s" % (msg, bad_keys))
# Test all key values have delta and var keys.
for key in perf_data:
if key == 'load':
continue
# First check if regress/improve is in the key's data.
if 'regress' in perf_data[key]:
if 'improve' not in perf_data[key]:
bad_keys.append(key)
if (not isinstance(perf_data[key]['regress'], int) and
not isinstance(perf_data[key]['regress'], float)):
bad_keys.append(key)
if (not isinstance(perf_data[key]['improve'], int) and
not isinstance(perf_data[key]['improve'], float)):
bad_keys.append(key)
else:
# Otherwise check if delta/var is in the key's data.
if 'delta' not in perf_data[key] or 'var' not in perf_data[key]:
bad_keys.append(key)
if (not isinstance(perf_data[key]['delta'], int) and
not isinstance(perf_data[key]['delta'], float)):
bad_keys.append(key)
if (not isinstance(perf_data[key]['var'], int) and
not isinstance(perf_data[key]['var'], float)):
bad_keys.append(key)
if len(bad_keys) > 0:
msg = "perf expectations key values missing or invalid delta/var"
raise Exception("%s: %s" % (msg, bad_keys))
# Test all keys have the correct format.
for key in perf_data:
if key == 'load':
continue
# tools/buildbot/scripts/master/log_parser.py should have a matching
# regular expression.
if not re.match(r"^([\w\.-]+)/([\w\.-]+)/([\w\.-]+)/([\w\.-]+)$", key):
bad_keys.append(key)
if len(bad_keys) > 0:
msg = "perf expectations keys in bad format, expected a/b/c/d"
raise Exception("%s: %s" % (msg, bad_keys))
def testNoUpdatesNeeded(self):
p = subprocess.Popen([MAKE_EXPECTATIONS, '-s'], stdout=subprocess.PIPE)
p.wait();
self.assertEqual(p.returncode, 0,
msg='Update expectations first by running ./make_expectations.py')
def testConfigFile(self):
# Test that the config file can be parsed as JSON.
config = LoadJsonFile(CONFIG_JSON)
# Require the following keys.
if 'base_url' not in config:
raise Exception('base_url not specified in config file')
if 'perf_file' not in config:
raise Exception('perf_file not specified in config file')
if __name__ == '__main__':
unittest.main()
|
Soovox/django-socialregistration
|
refs/heads/master
|
docs/conf.py
|
10
|
# -*- coding: utf-8 -*-
#
# django-socialregistration documentation build configuration file, created by
# sphinx-quickstart on Wed Feb 22 17:25:59 2012.
#
# 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, socialregistration
os.environ['DJANGO_SETTINGS_MODULE'] = 'example.settings'
# 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('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'django-socialregistration'
copyright = u'2012, Alen Mujezinovic'
# 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 = '0.5.1'
# The full version, including alpha/beta/rc tags.
release = '0.5.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'django-socialregistrationdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('fooasdf', 'django-socialregistration.tex', u'django-socialregistration Documentation',
u'Alen Mujezinovic', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('fooasdf', 'django-socialregistration', u'django-socialregistration Documentation',
[u'Alen Mujezinovic'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('fooasdf', 'django-socialregistration', u'django-socialregistration Documentation',
u'Alen Mujezinovic', 'django-socialregistration', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
|
ryuunosukeyoshi/PartnerPoi-Bot
|
refs/heads/master
|
lib/youtube_dl/extractor/vessel.py
|
40
|
# coding: utf-8
from __future__ import unicode_literals
import json
import re
from .common import InfoExtractor
from ..utils import (
ExtractorError,
parse_iso8601,
sanitized_Request,
)
class VesselIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?vessel\.com/(?:videos|embed)/(?P<id>[0-9a-zA-Z-_]+)'
_API_URL_TEMPLATE = 'https://www.vessel.com/api/view/items/%s'
_LOGIN_URL = 'https://www.vessel.com/api/account/login'
_NETRC_MACHINE = 'vessel'
_TESTS = [{
'url': 'https://www.vessel.com/videos/HDN7G5UMs',
'md5': '455cdf8beb71c6dd797fd2f3818d05c4',
'info_dict': {
'id': 'HDN7G5UMs',
'ext': 'mp4',
'title': 'Nvidia GeForce GTX Titan X - The Best Video Card on the Market?',
'thumbnail': r're:^https?://.*\.jpg$',
'upload_date': '20150317',
'description': 'Did Nvidia pull out all the stops on the Titan X, or does its performance leave something to be desired?',
'timestamp': int,
},
}, {
'url': 'https://www.vessel.com/embed/G4U7gUJ6a?w=615&h=346',
'only_matching': True,
}, {
'url': 'https://www.vessel.com/videos/F01_dsLj1',
'only_matching': True,
}, {
'url': 'https://www.vessel.com/videos/RRX-sir-J',
'only_matching': True,
}]
@staticmethod
def _extract_urls(webpage):
return [url for _, url in re.findall(
r'<iframe[^>]+src=(["\'])((?:https?:)?//(?:www\.)?vessel\.com/embed/[0-9a-zA-Z-_]+.*?)\1',
webpage)]
@staticmethod
def make_json_request(url, data):
payload = json.dumps(data).encode('utf-8')
req = sanitized_Request(url, payload)
req.add_header('Content-Type', 'application/json; charset=utf-8')
return req
@staticmethod
def find_assets(data, asset_type, asset_id=None):
for asset in data.get('assets', []):
if not asset.get('type') == asset_type:
continue
elif asset_id is not None and not asset.get('id') == asset_id:
continue
else:
yield asset
def _check_access_rights(self, data):
access_info = data.get('__view', {})
if not access_info.get('allow_access', True):
err_code = access_info.get('error_code') or ''
if err_code == 'ITEM_PAID_ONLY':
raise ExtractorError(
'This video requires subscription.', expected=True)
else:
raise ExtractorError(
'Access to this content is restricted. (%s said: %s)' % (self.IE_NAME, err_code), expected=True)
def _login(self):
(username, password) = self._get_login_info()
if username is None:
return
self.report_login()
data = {
'client_id': 'web',
'type': 'password',
'user_key': username,
'password': password,
}
login_request = VesselIE.make_json_request(self._LOGIN_URL, data)
self._download_webpage(login_request, None, False, 'Wrong login info')
def _real_initialize(self):
self._login()
def _real_extract(self, url):
video_id = self._match_id(url)
webpage = self._download_webpage(url, video_id)
data = self._parse_json(self._search_regex(
r'App\.bootstrapData\((.*?)\);', webpage, 'data'), video_id)
asset_id = data['model']['data']['id']
req = VesselIE.make_json_request(
self._API_URL_TEMPLATE % asset_id, {'client': 'web'})
data = self._download_json(req, video_id)
video_asset_id = data.get('main_video_asset')
self._check_access_rights(data)
try:
video_asset = next(
VesselIE.find_assets(data, 'video', asset_id=video_asset_id))
except StopIteration:
raise ExtractorError('No video assets found')
formats = []
for f in video_asset.get('sources', []):
location = f.get('location')
if not location:
continue
name = f.get('name')
if name == 'hls-index':
formats.extend(self._extract_m3u8_formats(
location, video_id, ext='mp4',
entry_protocol='m3u8_native', m3u8_id='m3u8', fatal=False))
elif name == 'dash-index':
formats.extend(self._extract_mpd_formats(
location, video_id, mpd_id='dash', fatal=False))
else:
formats.append({
'format_id': name,
'tbr': f.get('bitrate'),
'height': f.get('height'),
'width': f.get('width'),
'url': location,
})
self._sort_formats(formats)
thumbnails = []
for im_asset in VesselIE.find_assets(data, 'image'):
thumbnails.append({
'url': im_asset['location'],
'width': im_asset.get('width', 0),
'height': im_asset.get('height', 0),
})
return {
'id': video_id,
'title': data['title'],
'formats': formats,
'thumbnails': thumbnails,
'description': data.get('short_description'),
'duration': data.get('duration'),
'comment_count': data.get('comment_count'),
'like_count': data.get('like_count'),
'view_count': data.get('view_count'),
'timestamp': parse_iso8601(data.get('released_at')),
}
|
JRock007/boxxy
|
refs/heads/master
|
dist/Boxxy.app/Contents/Resources/lib/python2.7/pygame/tests/draw_test.py
|
5
|
#################################### IMPORTS ###################################
if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests import test_utils
from pygame.tests.test_utils \
import test_not_implemented, unordered_equality, unittest
else:
from test import test_utils
from test.test_utils \
import test_not_implemented, unordered_equality, unittest
import pygame
from pygame import draw
################################################################################
class DrawModuleTest(unittest.TestCase):
def setUp(self):
(self.surf_w, self.surf_h) = self.surf_size = (320, 200)
self.surf = pygame.Surface(self.surf_size, pygame.SRCALPHA)
self.color = (1, 13, 24, 205)
def test_rect__fill(self):
# __doc__ (as of 2008-06-25) for pygame.draw.rect:
# pygame.draw.rect(Surface, color, Rect, width=0): return Rect
# draw a rectangle shape
rect = pygame.Rect(10, 10, 25, 20)
drawn = draw.rect(self.surf, self.color, rect, 0)
self.assert_(drawn == rect)
#Should be colored where it's supposed to be
for pt in test_utils.rect_area_pts(rect):
color_at_pt = self.surf.get_at(pt)
self.assert_(color_at_pt == self.color)
#And not where it shouldn't
for pt in test_utils.rect_outer_bounds(rect):
color_at_pt = self.surf.get_at(pt)
self.assert_(color_at_pt != self.color)
def test_rect__one_pixel_lines(self):
# __doc__ (as of 2008-06-25) for pygame.draw.rect:
# pygame.draw.rect(Surface, color, Rect, width=0): return Rect
# draw a rectangle shape
rect = pygame.Rect(10, 10, 56, 20)
drawn = draw.rect(self.surf, self.color, rect, 1)
self.assert_(drawn == rect)
#Should be colored where it's supposed to be
for pt in test_utils.rect_perimeter_pts(drawn):
color_at_pt = self.surf.get_at(pt)
self.assert_(color_at_pt == self.color)
#And not where it shouldn't
for pt in test_utils.rect_outer_bounds(drawn):
color_at_pt = self.surf.get_at(pt)
self.assert_(color_at_pt != self.color)
def test_line(self):
# __doc__ (as of 2008-06-25) for pygame.draw.line:
# pygame.draw.line(Surface, color, start_pos, end_pos, width=1): return Rect
# draw a straight line segment
drawn = draw.line(self.surf, self.color, (1, 0), (200, 0)) #(l, t), (l, t)
self.assert_(drawn.right == 201,
"end point arg should be (or at least was) inclusive"
)
#Should be colored where it's supposed to be
for pt in test_utils.rect_area_pts(drawn):
self.assert_(self.surf.get_at(pt) == self.color)
#And not where it shouldn't
for pt in test_utils.rect_outer_bounds(drawn):
self.assert_(self.surf.get_at(pt) != self.color)
def todo_test_aaline(self):
# __doc__ (as of 2008-08-02) for pygame.draw.aaline:
# pygame.draw.aaline(Surface, color, startpos, endpos, blend=1): return Rect
# draw fine antialiased lines
#
# Draws an anti-aliased line on a surface. This will respect the
# clipping rectangle. A bounding box of the affected area is returned
# returned as a rectangle. If blend is true, the shades will be be
# blended with existing pixel shades instead of overwriting them. This
# function accepts floating point values for the end points.
#
self.fail()
def todo_test_aalines(self):
# __doc__ (as of 2008-08-02) for pygame.draw.aalines:
# pygame.draw.aalines(Surface, color, closed, pointlist, blend=1): return Rect
#
# Draws a sequence on a surface. You must pass at least two points in
# the sequence of points. The closed argument is a simple boolean and
# if true, a line will be draw between the first and last points. The
# boolean blend argument set to true will blend the shades with
# existing shades instead of overwriting them. This function accepts
# floating point values for the end points.
#
self.fail()
def todo_test_arc(self):
# __doc__ (as of 2008-08-02) for pygame.draw.arc:
# pygame.draw.arc(Surface, color, Rect, start_angle, stop_angle,
# width=1): return Rect
#
# draw a partial section of an ellipse
#
# Draws an elliptical arc on the Surface. The rect argument is the
# area that the ellipse will fill. The two angle arguments are the
# initial and final angle in radians, with the zero on the right. The
# width argument is the thickness to draw the outer edge.
#
self.fail()
def todo_test_circle(self):
# __doc__ (as of 2008-08-02) for pygame.draw.circle:
# pygame.draw.circle(Surface, color, pos, radius, width=0): return Rect
# draw a circle around a point
#
# Draws a circular shape on the Surface. The pos argument is the
# center of the circle, and radius is the size. The width argument is
# the thickness to draw the outer edge. If width is zero then the
# circle will be filled.
#
self.fail()
def todo_test_ellipse(self):
# __doc__ (as of 2008-08-02) for pygame.draw.ellipse:
# pygame.draw.ellipse(Surface, color, Rect, width=0): return Rect
# draw a round shape inside a rectangle
#
# Draws an elliptical shape on the Surface. The given rectangle is the
# area that the circle will fill. The width argument is the thickness
# to draw the outer edge. If width is zero then the ellipse will be
# filled.
#
self.fail()
def todo_test_lines(self):
# __doc__ (as of 2008-08-02) for pygame.draw.lines:
# pygame.draw.lines(Surface, color, closed, pointlist, width=1): return Rect
# draw multiple contiguous line segments
#
# Draw a sequence of lines on a Surface. The pointlist argument is a
# series of points that are connected by a line. If the closed
# argument is true an additional line segment is drawn between the
# first and last points.
#
# This does not draw any endcaps or miter joints. Lines with sharp
# corners and wide line widths can have improper looking corners.
#
self.fail()
def todo_test_polygon(self):
# __doc__ (as of 2008-08-02) for pygame.draw.polygon:
# pygame.draw.polygon(Surface, color, pointlist, width=0): return Rect
# draw a shape with any number of sides
#
# Draws a polygonal shape on the Surface. The pointlist argument is
# the vertices of the polygon. The width argument is the thickness to
# draw the outer edge. If width is zero then the polygon will be
# filled.
#
# For aapolygon, use aalines with the 'closed' parameter.
self.fail()
################################################################################
if __name__ == '__main__':
unittest.main()
|
roberzguerra/scout
|
refs/heads/master
|
campotec/migrations/0008_importinscriptions.py
|
1
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('campotec', '0007_auto_20150127_1548'),
]
operations = [
migrations.CreateModel(
name='ImportInscriptions',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('name', models.CharField(max_length=100, null=True, verbose_name='Nome', blank=True)),
('file', models.FileField(help_text='Importe aqui o arquivo .xls com a lista de inscritos.', upload_to=b'campotec/import_inscription', verbose_name='Arquivo .XLS')),
('branch', models.ForeignKey(verbose_name='Ramo', to='campotec.Branch', help_text='Ramo ao qual pertencem os registros do arquivo .xls.')),
],
options={
'ordering': ['updated_at', '-__unicode__', '-file'],
'db_table': 'campotec_import_inscription',
'verbose_name': 'Importa\xe7\xe3o de Inscri\xe7\xf5es',
'verbose_name_plural': 'Importa\xe7\xe3o de Inscri\xe7\xf5es',
},
bases=(models.Model,),
),
]
|
landonb/hamster-briefs
|
refs/heads/release
|
hamster_briefs/version_hamster.py
|
2
|
SCRIPT_VERS = '0.10.0'
|
rmvanhees/pys5p
|
refs/heads/master
|
src/pys5p/tol_colors.py
|
1
|
"""
This file is part of pyS5p
https://github.com/rmvanhees/pys5p.git
Definition of colour schemes for lines and maps that also work for colour-blind
people. See https://personal.sron.nl/~pault/ for background information and
best usage of the schemes.
Reference
---------
https://personal.sron.nl/~pault/
Copyright (c) 2019-2020, Paul Tol (SRON)
All rights reserved.
License: Standard 3-clause BSD
"""
from collections import namedtuple
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.colors import LinearSegmentedColormap, to_rgba_array
def discretemap(colormap, hexclrs):
"""
Produce a colormap from a list of discrete colors without interpolation.
"""
clrs = to_rgba_array(hexclrs)
clrs = np.vstack([clrs[0], clrs, clrs[-1]])
cdict = {}
for ii, key in enumerate(('red', 'green', 'blue')):
cdict[key] = [(jj / (len(clrs)-2.), clrs[jj, ii], clrs[jj+1, ii])
for jj in range(len(clrs)-1)]
return LinearSegmentedColormap(colormap, cdict)
# pylint: disable=invalid-name
class TOLcmaps():
"""
Class TOLcmaps definition.
"""
def __init__(self):
"""
"""
self.cmap = None
self.cname = None
self.namelist = (
'sunset_discrete', 'sunset', 'BuRd_discrete', 'BuRd',
'PRGn_discrete', 'PRGn', 'YlOrBr_discrete', 'YlOrBr', 'WhOrBr',
'iridescent', 'rainbow_PuRd', 'rainbow_PuBr', 'rainbow_WhRd',
'rainbow_WhBr', 'rainbow_WhBr_condense', 'rainbow_discrete')
self.funcdict = dict(
zip(self.namelist,
(self.__sunset_discrete, self.__sunset, self.__BuRd_discrete,
self.__BuRd, self.__PRGn_discrete, self.__PRGn,
self.__YlOrBr_discrete, self.__YlOrBr, self.__WhOrBr,
self.__iridescent, self.__rainbow_PuRd, self.__rainbow_PuBr,
self.__rainbow_WhRd, self.__rainbow_WhBr,
self.__rainbow_WhBr_condense, self.__rainbow_discrete)))
def __sunset_discrete(self):
"""
Define colormap 'sunset_discrete'.
"""
clrs = ['#364B9A', '#4A7BB7', '#6EA6CD', '#98CAE1', '#C2E4EF',
'#EAECCC', '#FEDA8B', '#FDB366', '#F67E4B', '#DD3D2D',
'#A50026']
self.cmap = discretemap(self.cname, clrs)
self.cmap.set_bad('#FFFFFF')
def __sunset(self):
"""
Define colormap 'sunset'.
"""
clrs = ['#364B9A', '#4A7BB7', '#6EA6CD', '#98CAE1', '#C2E4EF',
'#EAECCC', '#FEDA8B', '#FDB366', '#F67E4B', '#DD3D2D',
'#A50026']
self.cmap = LinearSegmentedColormap.from_list(self.cname, clrs)
self.cmap.set_bad('#FFFFFF')
def __BuRd_discrete(self):
"""
Define colormap 'BuRd_discrete'.
"""
clrs = ['#2166AC', '#4393C3', '#92C5DE', '#D1E5F0', '#F7F7F7',
'#FDDBC7', '#F4A582', '#D6604D', '#B2182B']
self.cmap = discretemap(self.cname, clrs)
self.cmap.set_bad('#FFEE99')
def __BuRd(self):
"""
Define colormap 'BuRd'.
"""
clrs = ['#2166AC', '#4393C3', '#92C5DE', '#D1E5F0', '#F7F7F7',
'#FDDBC7', '#F4A582', '#D6604D', '#B2182B']
self.cmap = LinearSegmentedColormap.from_list(self.cname, clrs)
self.cmap.set_bad('#FFEE99')
def __PRGn_discrete(self):
"""
Define colormap 'PRGn_discrete'.
"""
clrs = ['#762A83', '#9970AB', '#C2A5CF', '#E7D4E8', '#F7F7F7',
'#D9F0D3', '#ACD39E', '#5AAE61', '#1B7837']
self.cmap = discretemap(self.cname, clrs)
self.cmap.set_bad('#FFEE99')
def __PRGn(self):
"""
Define colormap 'PRGn'.
"""
clrs = ['#762A83', '#9970AB', '#C2A5CF', '#E7D4E8', '#F7F7F7',
'#D9F0D3', '#ACD39E', '#5AAE61', '#1B7837']
self.cmap = LinearSegmentedColormap.from_list(self.cname, clrs)
self.cmap.set_bad('#FFEE99')
def __YlOrBr_discrete(self):
"""
Define colormap 'YlOrBr_discrete'.
"""
clrs = ['#FFFFE5', '#FFF7BC', '#FEE391', '#FEC44F', '#FB9A29',
'#EC7014', '#CC4C02', '#993404', '#662506']
self.cmap = discretemap(self.cname, clrs)
self.cmap.set_bad('#888888')
def __YlOrBr(self):
"""
Define colormap 'YlOrBr'.
"""
clrs = ['#FFFFE5', '#FFF7BC', '#FEE391', '#FEC44F', '#FB9A29',
'#EC7014', '#CC4C02', '#993404', '#662506']
self.cmap = LinearSegmentedColormap.from_list(self.cname, clrs)
self.cmap.set_bad('#888888')
def __WhOrBr(self):
"""
Define colormap 'WhOrBr'.
"""
clrs = ['#FFFFFF', '#FFF7BC', '#FEE391', '#FEC44F', '#FB9A29',
'#EC7014', '#CC4C02', '#993404', '#662506']
self.cmap = LinearSegmentedColormap.from_list(self.cname, clrs)
self.cmap.set_bad('#888888')
def __iridescent(self):
"""
Define colormap 'iridescent'.
"""
clrs = ['#FEFBE9', '#FCF7D5', '#F5F3C1', '#EAF0B5', '#DDECBF',
'#D0E7CA', '#C2E3D2', '#B5DDD8', '#A8D8DC', '#9BD2E1',
'#8DCBE4', '#81C4E7', '#7BBCE7', '#7EB2E4', '#88A5DD',
'#9398D2', '#9B8AC4', '#9D7DB2', '#9A709E', '#906388',
'#805770', '#684957', '#46353A']
self.cmap = LinearSegmentedColormap.from_list(self.cname, clrs)
self.cmap.set_bad('#999999')
def __rainbow_PuRd(self):
"""
Define colormap 'rainbow_PuRd'.
"""
clrs = ['#6F4C9B', '#6059A9', '#5568B8', '#4E79C5', '#4D8AC6',
'#4E96BC', '#549EB3', '#59A5A9', '#60AB9E', '#69B190',
'#77B77D', '#8CBC68', '#A6BE54', '#BEBC48', '#D1B541',
'#DDAA3C', '#E49C39', '#E78C35', '#E67932', '#E4632D',
'#DF4828', '#DA2222']
self.cmap = LinearSegmentedColormap.from_list(self.cname, clrs)
self.cmap.set_bad('#FFFFFF')
def __rainbow_PuBr(self):
"""
Define colormap 'rainbow_PuBr'.
"""
clrs = ['#6F4C9B', '#6059A9', '#5568B8', '#4E79C5', '#4D8AC6',
'#4E96BC', '#549EB3', '#59A5A9', '#60AB9E', '#69B190',
'#77B77D', '#8CBC68', '#A6BE54', '#BEBC48', '#D1B541',
'#DDAA3C', '#E49C39', '#E78C35', '#E67932', '#E4632D',
'#DF4828', '#DA2222', '#B8221E', '#95211B', '#721E17',
'#521A13']
self.cmap = LinearSegmentedColormap.from_list(self.cname, clrs)
self.cmap.set_bad('#FFFFFF')
def __rainbow_WhRd(self):
"""
Define colormap 'rainbow_WhRd'.
"""
clrs = ['#E8ECFB', '#DDD8EF', '#D1C1E1', '#C3A8D1', '#B58FC2',
'#A778B4', '#9B62A7', '#8C4E99', '#6F4C9B', '#6059A9',
'#5568B8', '#4E79C5', '#4D8AC6', '#4E96BC', '#549EB3',
'#59A5A9', '#60AB9E', '#69B190', '#77B77D', '#8CBC68',
'#A6BE54', '#BEBC48', '#D1B541', '#DDAA3C', '#E49C39',
'#E78C35', '#E67932', '#E4632D', '#DF4828', '#DA2222']
self.cmap = LinearSegmentedColormap.from_list(self.cname, clrs)
self.cmap.set_bad('#666666')
def __rainbow_WhBr(self):
"""
Define colormap 'rainbow_WhBr'.
"""
clrs = ['#E8ECFB', '#DDD8EF', '#D1C1E1', '#C3A8D1', '#B58FC2',
'#A778B4', '#9B62A7', '#8C4E99', '#6F4C9B', '#6059A9',
'#5568B8', '#4E79C5', '#4D8AC6', '#4E96BC', '#549EB3',
'#59A5A9', '#60AB9E', '#69B190', '#77B77D', '#8CBC68',
'#A6BE54', '#BEBC48', '#D1B541', '#DDAA3C', '#E49C39',
'#E78C35', '#E67932', '#E4632D', '#DF4828', '#DA2222',
'#B8221E', '#95211B', '#721E17', '#521A13']
self.cmap = LinearSegmentedColormap.from_list(self.cname, clrs)
self.cmap.set_bad('#666666')
def __rainbow_WhBr_condense(self):
"""
Define colormap 'rainbow_WhBr_condense'.
"""
clrs = ['#E8ECFB', '#E4E5F7', '#E1DFF3', '#DDD8EF', '#D9D0EA',
'#D5C8E5', '#D1C1E1', '#CCB8DB', '#C7B0D6', '#C3A8D1',
'#BEA0CC', '#BA97C7', '#B58FC2', '#B087BD', '#AC80B8',
'#A778B4', '#A371AF', '#9F6AAB', '#9B62A7', '#965CA2',
'#91559E', '#8C4E99', '#824D9A', '#794C9A', '#6F4C9B',
'#6A509F', '#6555A4', '#6059A9', '#5C5EAE', '#5963B3',
'#5568B8', '#526EBC', '#5073C0', '#4E79C5', '#4E7FC5',
'#4D84C6', '#4D8AC6', '#4D8EC3', '#4D92C0', '#4E96BC',
'#5099B9', '#529CB6', '#549EB3', '#56A1AF', '#58A3AC',
'#59A5A9', '#5CA7A5', '#5EA9A1', '#60AB9E', '#63AD99',
'#66AF94', '#69B190', '#6EB38A', '#73B584', '#77B77D',
'#7EB976', '#85BA6F', '#8CBC68', '#95BD61', '#9DBD5B',
'#A6BE54', '#AEBD50', '#B6BD4C', '#BEBC48', '#C4BA45',
'#CAB843', '#D1B541', '#D5B23F', '#D9AE3E', '#DDAA3C',
'#DFA63B', '#E1A13A', '#E49C39', '#E59738', '#E69137',
'#E78C35', '#E68534', '#E67F33', '#E67932', '#E57130',
'#E56A2F', '#E4632D', '#E25A2C', '#E1512A', '#DF4828',
'#DE3B26', '#DC2F24', '#DA2222', '#CF2221', '#C42220',
'#B8221E', '#AC221D', '#A1211C', '#95211B', '#892019',
'#7E1F18', '#721E17', '#681C15', '#5D1B14', '#521A13']
self.cmap = discretemap(self.cname, clrs)
self.cmap.set_bad('#666666')
def __rainbow_discrete(self, lut=None):
"""
Define colormap 'rainbow_discrete'.
"""
clrs = ['#E8ECFB', '#D9CCE3', '#D1BBD7', '#CAACCB', '#BA8DB4',
'#AE76A3', '#AA6F9E', '#994F88', '#882E72', '#1965B0',
'#437DBF', '#5289C7', '#6195CF', '#7BAFDE', '#4EB265',
'#90C987', '#CAE0AB', '#F7F056', '#F7CB45', '#F6C141',
'#F4A736', '#F1932D', '#EE8026', '#E8601C', '#E65518',
'#DC050C', '#A5170E', '#72190E', '#42150A']
indexes = [[9], [9, 25], [9, 17, 25], [9, 14, 17, 25],
[9, 13, 14, 17, 25], [9, 13, 14, 16, 17, 25],
[8, 9, 13, 14, 16, 17, 25], [8, 9, 13, 14, 16, 17, 22, 25],
[8, 9, 13, 14, 16, 17, 22, 25, 27],
[8, 9, 13, 14, 16, 17, 20, 23, 25, 27],
[8, 9, 11, 13, 14, 16, 17, 20, 23, 25, 27],
[2, 5, 8, 9, 11, 13, 14, 16, 17, 20, 23, 25],
[2, 5, 8, 9, 11, 13, 14, 15, 16, 17, 20, 23, 25],
[2, 5, 8, 9, 11, 13, 14, 15, 16, 17, 19, 21, 23, 25],
[2, 5, 8, 9, 11, 13, 14, 15, 16, 17, 19, 21, 23, 25, 27],
[2, 4, 6, 8, 9, 11, 13, 14, 15, 16, 17, 19, 21, 23, 25, 27],
[2, 4, 6, 7, 8, 9, 11, 13, 14, 15, 16, 17, 19, 21, 23, 25,
27],
[2, 4, 6, 7, 8, 9, 11, 13, 14, 15, 16, 17, 19, 21, 23, 25,
26, 27],
[1, 3, 4, 6, 7, 8, 9, 11, 13, 14, 15, 16, 17, 19, 21, 23,
25, 26, 27],
[1, 3, 4, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 19, 21,
23, 25, 26, 27],
[1, 3, 4, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 20,
22, 24, 25, 26, 27],
[1, 3, 4, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 20,
22, 24, 25, 26, 27, 28],
[0, 1, 3, 4, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18,
20, 22, 24, 25, 26, 27, 28]]
if lut is None or lut < 1 or lut > 23:
lut = 22
self.cmap = discretemap(self.cname, [clrs[i] for i in indexes[lut-1]])
if lut == 23:
self.cmap.set_bad('#777777')
else:
self.cmap.set_bad('#FFFFFF')
def show(self):
"""
List names of defined colormaps.
"""
print(' '.join(repr(n) for n in self.namelist))
def get(self, cname='rainbow_PuRd', lut=None):
"""
Return requested colormap, default is 'rainbow_PuRd'.
"""
self.cname = cname
if cname == 'rainbow_discrete':
self.__rainbow_discrete(lut)
else:
self.funcdict[cname]()
return self.cmap
def tol_cmap(colormap=None, lut=None):
"""
Continuous and discrete color sets for ordered data.
Return a matplotlib colormap.
Parameter lut is ignored for all colormaps except 'rainbow_discrete'.
"""
obj = TOLcmaps()
if colormap is None:
return obj.namelist
if colormap not in obj.namelist:
colormap = 'rainbow_PuRd'
print('*** Warning: requested colormap not defined,',
'known colormaps are {}.'.format(obj.namelist),
'Using {}.'.format(colormap))
return obj.get(colormap, lut)
def tol_cset(colorset=None):
"""
Discrete color sets for qualitative data.
Define a namedtuple instance with the colors.
Examples for: cset = tol_cset(<scheme>)
- cset.red and cset[1] give the same color (in default 'bright' colorset)
- cset._fields gives a tuple with all color names
- list(cset) gives a list with all colors
"""
namelist = ('bright', 'high-contrast', 'vibrant', 'muted', 'light')
if colorset is None:
return namelist
if colorset not in namelist:
print('*** Warning: requested colorset not defined,',
'known colorsets are {}.'.format(namelist),
'Using {}.'.format(colorset))
if colorset == 'high-contrast':
cset = namedtuple('Hcset',
'blue yellow red black')
return cset('#004488', '#DDAA33', '#BB5566', '#000000')
if colorset == 'vibrant':
cset = namedtuple('Vcset',
'orange blue cyan magenta red teal grey black')
return cset('#EE7733', '#0077BB', '#33BBEE', '#EE3377', '#CC3311',
'#009988', '#BBBBBB', '#000000')
if colorset == 'muted':
cset = namedtuple('Mcset',
('rose indigo sand green cyan wine teal'
' olive purple pale_grey black'))
return cset('#CC6677', '#332288', '#DDCC77', '#117733', '#88CCEE',
'#882255', '#44AA99', '#999933', '#AA4499', '#DDDDDD',
'#000000')
if colorset == 'light':
cset = namedtuple('Lcset',
('light_blue orange light_yellow pink light_cyan'
' mint pear olive pale_grey black'))
return cset('#77AADD', '#EE8866', '#EEDD88', '#FFAABB', '#99DDFF',
'#44BB99', '#BBCC33', '#AAAA00', '#DDDDDD', '#000000')
# Default: return colorset is 'bright'
cset = namedtuple('Bcset',
'blue red green yellow cyan purple grey black')
return cset('#4477AA', '#EE6677', '#228833', '#CCBB44', '#66CCEE',
'#AA3377', '#BBBBBB', '#000000')
def main():
"""
Show all available colormaps and colorsets
"""
# Change default colorset (for lines) and colormap (for maps).
# plt.rc('axes', prop_cycle=plt.cycler('color', list(tol_cset('bright'))))
# plt.cm.register_cmap('rainbow_PuRd', tol_cmap('rainbow_PuRd'))
# plt.rc('image', cmap='rainbow_PuRd')
# Show colorsets tol_cset(<scheme>).
schemes = tol_cset()
fig, axes = plt.subplots(ncols=len(schemes))
fig.subplots_adjust(top=0.92, bottom=0.02, left=0.0, right=0.91)
for ax, scheme in zip(axes, schemes):
cset = tol_cset(scheme)
names = cset._fields
colors = list(cset)
for name, color in zip(names, colors):
ax.scatter([], [], c=color, s=80, label=name)
ax.set_axis_off()
ax.legend(loc=2)
ax.set_title(scheme)
plt.show()
# Show colormaps tol_cmap(<scheme>).
schemes = tol_cmap()
gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))
fig, axes = plt.subplots(nrows=len(schemes))
fig.subplots_adjust(top=0.98, bottom=0.02, left=0.29, right=0.99)
for ax, scheme in zip(axes, schemes):
pos = list(ax.get_position().bounds)
ax.set_axis_off()
ax.imshow(gradient, aspect=4, cmap=tol_cmap(scheme))
fig.text(pos[0] - 0.01, pos[1] + pos[3]/2.,
scheme, va='center', ha='right', fontsize=10)
plt.show()
# Show colormaps tol_cmap('rainbow_discrete', <lut>).
gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))
fig, axes = plt.subplots(nrows=23)
fig.subplots_adjust(top=0.98, bottom=0.02, left=0.25, right=0.99)
for lut, ax in enumerate(axes, start=1):
pos = list(ax.get_position().bounds)
ax.set_axis_off()
ax.imshow(gradient, aspect=4, cmap=tol_cmap('rainbow_discrete', lut))
fig.text(pos[0] - 0.01, pos[1] + pos[3]/2.,
'rainbow_discrete, ' + str(lut),
va='center', ha='right', fontsize=10)
plt.show()
if __name__ == '__main__':
main()
|
DarthMaulware/EquationGroupLeaks
|
refs/heads/master
|
Leak #5 - Lost In Translation/windows/Resources/Python/Core/Lib/ctypes/macholib/__init__.py
|
1
|
# uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: __init__.py
"""
Enough Mach-O to make your head spin.
See the relevant header files in /usr/include/mach-o
And also Apple's documentation.
"""
__version__ = '1.0'
|
sdhash/sdhash
|
refs/heads/master
|
sdhash-ui/cherrypy/tutorial/tut10_http_errors.py
|
36
|
"""
Tutorial: HTTP errors
HTTPError is used to return an error response to the client.
CherryPy has lots of options regarding how such errors are
logged, displayed, and formatted.
"""
import os
localDir = os.path.dirname(__file__)
curpath = os.path.normpath(os.path.join(os.getcwd(), localDir))
import cherrypy
class HTTPErrorDemo(object):
# Set a custom response for 403 errors.
_cp_config = {'error_page.403' : os.path.join(curpath, "custom_error.html")}
def index(self):
# display some links that will result in errors
tracebacks = cherrypy.request.show_tracebacks
if tracebacks:
trace = 'off'
else:
trace = 'on'
return """
<html><body>
<p>Toggle tracebacks <a href="toggleTracebacks">%s</a></p>
<p><a href="/doesNotExist">Click me; I'm a broken link!</a></p>
<p><a href="/error?code=403">Use a custom error page from a file.</a></p>
<p>These errors are explicitly raised by the application:</p>
<ul>
<li><a href="/error?code=400">400</a></li>
<li><a href="/error?code=401">401</a></li>
<li><a href="/error?code=402">402</a></li>
<li><a href="/error?code=500">500</a></li>
</ul>
<p><a href="/messageArg">You can also set the response body
when you raise an error.</a></p>
</body></html>
""" % trace
index.exposed = True
def toggleTracebacks(self):
# simple function to toggle tracebacks on and off
tracebacks = cherrypy.request.show_tracebacks
cherrypy.config.update({'request.show_tracebacks': not tracebacks})
# redirect back to the index
raise cherrypy.HTTPRedirect('/')
toggleTracebacks.exposed = True
def error(self, code):
# raise an error based on the get query
raise cherrypy.HTTPError(status = code)
error.exposed = True
def messageArg(self):
message = ("If you construct an HTTPError with a 'message' "
"argument, it wil be placed on the error page "
"(underneath the status line by default).")
raise cherrypy.HTTPError(500, message=message)
messageArg.exposed = True
import os.path
tutconf = os.path.join(os.path.dirname(__file__), 'tutorial.conf')
if __name__ == '__main__':
# CherryPy always starts with app.root when trying to map request URIs
# to objects, so we need to mount a request handler root. A request
# to '/' will be mapped to HelloWorld().index().
cherrypy.quickstart(HTTPErrorDemo(), config=tutconf)
else:
# This branch is for the test suite; you can ignore it.
cherrypy.tree.mount(HTTPErrorDemo(), config=tutconf)
|
alazaro/tennis_tournament
|
refs/heads/master
|
django/conf/urls/defaults.py
|
320
|
from django.core.urlresolvers import RegexURLPattern, RegexURLResolver
from django.core.exceptions import ImproperlyConfigured
__all__ = ['handler404', 'handler500', 'include', 'patterns', 'url']
handler404 = 'django.views.defaults.page_not_found'
handler500 = 'django.views.defaults.server_error'
def include(arg, namespace=None, app_name=None):
if isinstance(arg, tuple):
# callable returning a namespace hint
if namespace:
raise ImproperlyConfigured('Cannot override the namespace for a dynamic module that provides a namespace')
urlconf_module, app_name, namespace = arg
else:
# No namespace hint - use manually provided namespace
urlconf_module = arg
return (urlconf_module, app_name, namespace)
def patterns(prefix, *args):
pattern_list = []
for t in args:
if isinstance(t, (list, tuple)):
t = url(prefix=prefix, *t)
elif isinstance(t, RegexURLPattern):
t.add_prefix(prefix)
pattern_list.append(t)
return pattern_list
def url(regex, view, kwargs=None, name=None, prefix=''):
if isinstance(view, (list,tuple)):
# For include(...) processing.
urlconf_module, app_name, namespace = view
return RegexURLResolver(regex, urlconf_module, kwargs, app_name=app_name, namespace=namespace)
else:
if isinstance(view, basestring):
if not view:
raise ImproperlyConfigured('Empty URL pattern view name not permitted (for pattern %r)' % regex)
if prefix:
view = prefix + '.' + view
return RegexURLPattern(regex, view, kwargs, name)
|
louietsai/python-for-android
|
refs/heads/master
|
python-modules/twisted/twisted/words/im/pbsupport.py
|
55
|
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
"""L{twisted.words} support for Instance Messenger."""
from __future__ import nested_scopes
from twisted.internet import defer
from twisted.internet import error
from twisted.python import log
from twisted.python.failure import Failure
from twisted.spread import pb
from twisted.words.im.locals import ONLINE, OFFLINE, AWAY
from twisted.words.im import basesupport, interfaces
from zope.interface import implements
class TwistedWordsPerson(basesupport.AbstractPerson):
"""I a facade for a person you can talk to through a twisted.words service.
"""
def __init__(self, name, wordsAccount):
basesupport.AbstractPerson.__init__(self, name, wordsAccount)
self.status = OFFLINE
def isOnline(self):
return ((self.status == ONLINE) or
(self.status == AWAY))
def getStatus(self):
return self.status
def sendMessage(self, text, metadata):
"""Return a deferred...
"""
if metadata:
d=self.account.client.perspective.directMessage(self.name,
text, metadata)
d.addErrback(self.metadataFailed, "* "+text)
return d
else:
return self.account.client.perspective.callRemote('directMessage',self.name, text)
def metadataFailed(self, result, text):
print "result:",result,"text:",text
return self.account.client.perspective.directMessage(self.name, text)
def setStatus(self, status):
self.status = status
self.chat.getContactsList().setContactStatus(self)
class TwistedWordsGroup(basesupport.AbstractGroup):
implements(interfaces.IGroup)
def __init__(self, name, wordsClient):
basesupport.AbstractGroup.__init__(self, name, wordsClient)
self.joined = 0
def sendGroupMessage(self, text, metadata=None):
"""Return a deferred.
"""
#for backwards compatibility with older twisted.words servers.
if metadata:
d=self.account.client.perspective.callRemote(
'groupMessage', self.name, text, metadata)
d.addErrback(self.metadataFailed, "* "+text)
return d
else:
return self.account.client.perspective.callRemote('groupMessage',
self.name, text)
def setTopic(self, text):
self.account.client.perspective.callRemote(
'setGroupMetadata',
{'topic': text, 'topic_author': self.client.name},
self.name)
def metadataFailed(self, result, text):
print "result:",result,"text:",text
return self.account.client.perspective.callRemote('groupMessage',
self.name, text)
def joining(self):
self.joined = 1
def leaving(self):
self.joined = 0
def leave(self):
return self.account.client.perspective.callRemote('leaveGroup',
self.name)
class TwistedWordsClient(pb.Referenceable, basesupport.AbstractClientMixin):
"""In some cases, this acts as an Account, since it a source of text
messages (multiple Words instances may be on a single PB connection)
"""
def __init__(self, acct, serviceName, perspectiveName, chatui,
_logonDeferred=None):
self.accountName = "%s (%s:%s)" % (acct.accountName, serviceName, perspectiveName)
self.name = perspectiveName
print "HELLO I AM A PB SERVICE", serviceName, perspectiveName
self.chat = chatui
self.account = acct
self._logonDeferred = _logonDeferred
def getPerson(self, name):
return self.chat.getPerson(name, self)
def getGroup(self, name):
return self.chat.getGroup(name, self)
def getGroupConversation(self, name):
return self.chat.getGroupConversation(self.getGroup(name))
def addContact(self, name):
self.perspective.callRemote('addContact', name)
def remote_receiveGroupMembers(self, names, group):
print 'received group members:', names, group
self.getGroupConversation(group).setGroupMembers(names)
def remote_receiveGroupMessage(self, sender, group, message, metadata=None):
print 'received a group message', sender, group, message, metadata
self.getGroupConversation(group).showGroupMessage(sender, message, metadata)
def remote_memberJoined(self, member, group):
print 'member joined', member, group
self.getGroupConversation(group).memberJoined(member)
def remote_memberLeft(self, member, group):
print 'member left'
self.getGroupConversation(group).memberLeft(member)
def remote_notifyStatusChanged(self, name, status):
self.chat.getPerson(name, self).setStatus(status)
def remote_receiveDirectMessage(self, name, message, metadata=None):
self.chat.getConversation(self.chat.getPerson(name, self)).showMessage(message, metadata)
def remote_receiveContactList(self, clist):
for name, status in clist:
self.chat.getPerson(name, self).setStatus(status)
def remote_setGroupMetadata(self, dict_, groupName):
if dict_.has_key("topic"):
self.getGroupConversation(groupName).setTopic(dict_["topic"], dict_.get("topic_author", None))
def joinGroup(self, name):
self.getGroup(name).joining()
return self.perspective.callRemote('joinGroup', name).addCallback(self._cbGroupJoined, name)
def leaveGroup(self, name):
self.getGroup(name).leaving()
return self.perspective.callRemote('leaveGroup', name).addCallback(self._cbGroupLeft, name)
def _cbGroupJoined(self, result, name):
groupConv = self.chat.getGroupConversation(self.getGroup(name))
groupConv.showGroupMessage("sys", "you joined")
self.perspective.callRemote('getGroupMembers', name)
def _cbGroupLeft(self, result, name):
print 'left',name
groupConv = self.chat.getGroupConversation(self.getGroup(name), 1)
groupConv.showGroupMessage("sys", "you left")
def connected(self, perspective):
print 'Connected Words Client!', perspective
if self._logonDeferred is not None:
self._logonDeferred.callback(self)
self.perspective = perspective
self.chat.getContactsList()
pbFrontEnds = {
"twisted.words": TwistedWordsClient,
"twisted.reality": None
}
class PBAccount(basesupport.AbstractAccount):
implements(interfaces.IAccount)
gatewayType = "PB"
_groupFactory = TwistedWordsGroup
_personFactory = TwistedWordsPerson
def __init__(self, accountName, autoLogin, username, password, host, port,
services=None):
"""
@param username: The name of your PB Identity.
@type username: string
"""
basesupport.AbstractAccount.__init__(self, accountName, autoLogin,
username, password, host, port)
self.services = []
if not services:
services = [('twisted.words', 'twisted.words', username)]
for serviceType, serviceName, perspectiveName in services:
self.services.append([pbFrontEnds[serviceType], serviceName,
perspectiveName])
def logOn(self, chatui):
"""
@returns: this breaks with L{interfaces.IAccount}
@returntype: DeferredList of L{interfaces.IClient}s
"""
# Overriding basesupport's implementation on account of the
# fact that _startLogOn tends to return a deferredList rather
# than a simple Deferred, and we need to do registerAccountClient.
if (not self._isConnecting) and (not self._isOnline):
self._isConnecting = 1
d = self._startLogOn(chatui)
d.addErrback(self._loginFailed)
def registerMany(results):
for success, result in results:
if success:
chatui.registerAccountClient(result)
self._cb_logOn(result)
else:
log.err(result)
d.addCallback(registerMany)
return d
else:
raise error.ConnectionError("Connection in progress")
def _startLogOn(self, chatui):
print 'Connecting...',
d = pb.getObjectAt(self.host, self.port)
d.addCallbacks(self._cbConnected, self._ebConnected,
callbackArgs=(chatui,))
return d
def _cbConnected(self, root, chatui):
print 'Connected!'
print 'Identifying...',
d = pb.authIdentity(root, self.username, self.password)
d.addCallbacks(self._cbIdent, self._ebConnected,
callbackArgs=(chatui,))
return d
def _cbIdent(self, ident, chatui):
if not ident:
print 'falsely identified.'
return self._ebConnected(Failure(Exception("username or password incorrect")))
print 'Identified!'
dl = []
for handlerClass, sname, pname in self.services:
d = defer.Deferred()
dl.append(d)
handler = handlerClass(self, sname, pname, chatui, d)
ident.callRemote('attach', sname, pname, handler).addCallback(handler.connected)
return defer.DeferredList(dl)
def _ebConnected(self, error):
print 'Not connected.'
return error
|
wbyne/QGIS
|
refs/heads/master
|
python/plugins/processing/tests/ToolsTest.py
|
3
|
# -*- coding: utf-8 -*-
"""
***************************************************************************
ToolsTest
---------------------
Date : July 2017
Copyright : (C) 2017 by Nyall Dawson
Email : nyall dot dawson at gmail dot com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************
"""
__author__ = 'Nyall Dawson'
__date__ = 'July 2016'
__copyright__ = '(C) 2016, Nyall Dawson'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
from qgis.testing import start_app, unittest
from processing.tests.TestData import points2
from processing.tools import vector
from qgis.core import (QgsVectorLayer, QgsFeatureRequest)
from processing.core.ProcessingConfig import ProcessingConfig
start_app()
class VectorTest(unittest.TestCase):
def testFeatures(self):
ProcessingConfig.initialize()
test_data = points2()
test_layer = QgsVectorLayer(test_data, 'test', 'ogr')
# test with all features
features = vector.features(test_layer)
self.assertEqual(len(features), 8)
self.assertEqual(set([f.id() for f in features]), set([0, 1, 2, 3, 4, 5, 6, 7]))
# test with selected features
previous_value = ProcessingConfig.getSetting(ProcessingConfig.USE_SELECTED)
ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, True)
test_layer.selectByIds([2, 4, 6])
features = vector.features(test_layer)
self.assertEqual(len(features), 3)
self.assertEqual(set([f.id() for f in features]), set([2, 4, 6]))
# selection, but not using selected features
ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, False)
test_layer.selectByIds([2, 4, 6])
features = vector.features(test_layer)
self.assertEqual(len(features), 8)
self.assertEqual(set([f.id() for f in features]), set([0, 1, 2, 3, 4, 5, 6, 7]))
# using selected features, but no selection
ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, True)
test_layer.removeSelection()
features = vector.features(test_layer)
self.assertEqual(len(features), 8)
self.assertEqual(set([f.id() for f in features]), set([0, 1, 2, 3, 4, 5, 6, 7]))
# test that feature request is honored
ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, False)
features = vector.features(test_layer, QgsFeatureRequest().setFilterFids([1, 3, 5]))
self.assertEqual(set([f.id() for f in features]), set([1, 3, 5]))
# test that feature request is honored when using selections
ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, True)
test_layer.selectByIds([2, 4, 6])
features = vector.features(test_layer, QgsFeatureRequest().setFlags(QgsFeatureRequest.NoGeometry))
self.assertTrue(all([not f.hasGeometry() for f in features]))
features = vector.features(test_layer, QgsFeatureRequest().setFlags(QgsFeatureRequest.NoGeometry))
self.assertEqual(set([f.id() for f in features]), set([2, 4, 6]))
ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, previous_value)
if __name__ == '__main__':
unittest.main()
|
anirudhSK/chromium
|
refs/heads/master
|
chrome/test/functional/media/audio_latency_perf.py
|
70
|
#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Audio latency performance test.
Benchmark measuring how fast we can continuously repeat a short sound clip. In
the ideal scenario we'd have zero latency processing script, seeking back to the
beginning of the clip, and resuming audio playback.
Performance is recorded as the average latency of N playbacks. I.e., if we play
a clip 50 times and the ideal duration of all playbacks is 1000ms and the total
duration is 1500ms, the recorded result is (1500ms - 1000ms) / 50 == 10ms.
"""
import os
import pyauto_media
import pyauto_utils
import pyauto
# HTML test path; relative to src/chrome/test/data.
_TEST_HTML_PATH = os.path.join('media', 'html', 'audio_latency_perf.html')
class AudioLatencyPerfTest(pyauto.PyUITest):
"""PyAuto test container. See file doc string for more information."""
def testAudioLatency(self):
"""Launches HTML test which runs the audio latency test."""
self.NavigateToURL(self.GetFileURLForDataPath(_TEST_HTML_PATH))
# Block until the test finishes and notifies us.
self.assertTrue(self.ExecuteJavascript('startTest();'))
latency = float(self.GetDOMValue('averageLatency'))
pyauto_utils.PrintPerfResult('audio_latency', 'latency', latency, 'ms')
if __name__ == '__main__':
pyauto_media.Main()
|
SeaFalcon/Musicool_Pr
|
refs/heads/master
|
lib/wtforms/ext/i18n/form.py
|
38
|
import warnings
from wtforms import form
from wtforms.ext.i18n.utils import get_translations
translations_cache = {}
class Form(form.Form):
"""
Base form for a simple localized WTForms form.
**NOTE** this class is now un-necessary as the i18n features have
been moved into the core of WTForms, and will be removed in WTForms 3.0.
This will use the stdlib gettext library to retrieve an appropriate
translations object for the language, by default using the locale
information from the environment.
If the LANGUAGES class variable is overridden and set to a sequence of
strings, this will be a list of languages by priority to use instead, e.g::
LANGUAGES = ['en_GB', 'en']
One can also provide the languages by passing `LANGUAGES=` to the
constructor of the form.
Translations objects are cached to prevent having to get a new one for the
same languages every instantiation.
"""
LANGUAGES = None
def __init__(self, *args, **kwargs):
warnings.warn('i18n is now in core, wtforms.ext.i18n will be removed in WTForms 3.0', DeprecationWarning)
if 'LANGUAGES' in kwargs:
self.LANGUAGES = kwargs.pop('LANGUAGES')
super(Form, self).__init__(*args, **kwargs)
def _get_translations(self):
languages = tuple(self.LANGUAGES) if self.LANGUAGES else (self.meta.locales or None)
if languages not in translations_cache:
translations_cache[languages] = get_translations(languages)
return translations_cache[languages]
|
danbeam/catapult
|
refs/heads/master
|
perf_insights/perf_insights/progress_reporter.py
|
2
|
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Derived from telemetry ProgressReporter. Should stay close in architecture
# to telemetry ProgressReporter.
class ProgressReporter(object):
def WillRun(self, run_info):
pass
def DidAddValue(self, value):
pass
def DidRun(self, run_info, run_failed):
pass
def DidFinishAllRuns(self, results):
pass
|
geekboxzone/lollipop_external_chromium_org
|
refs/heads/geekbox
|
testing/PRESUBMIT.py
|
134
|
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Top-level presubmit script for testing.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for
details on the presubmit API built into gcl.
"""
def CommonChecks(input_api, output_api):
output = []
blacklist = [r'gmock.*', r'gtest.*']
output.extend(input_api.canned_checks.RunPylint(
input_api, output_api, black_list=blacklist))
return output
def CheckChangeOnUpload(input_api, output_api):
return CommonChecks(input_api, output_api)
def CheckChangeOnCommit(input_api, output_api):
return CommonChecks(input_api, output_api)
|
vcc-LG/brachy-dose-reporter
|
refs/heads/master
|
doseapp/forms.py
|
1
|
from django import forms
from .models import Patient, Fraction
class PatientForm(forms.ModelForm):
class Meta:
model = Patient
fields = ('patient_id',
'first_name',
'last_name',)
class FractionForm(forms.ModelForm):
class Meta:
model = Fraction
fields = ('patient',
'fraction_number',
'D90',)
widgets = {'patient': forms.HiddenInput()} #this is so I can pass the patient ID
#between the patient detail view and
#the new fraction form... not ideal?
|
SakiFu/personal-website
|
refs/heads/master
|
personal/personal/wsgi.py
|
1
|
"""
WSGI config for personal project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "personal.settings")
application = get_wsgi_application()
|
hzlf/openbroadcast
|
refs/heads/master
|
website/apps/registration/urls.py
|
79
|
"""
Backwards-compatible URLconf for existing django-registration
installs; this allows the standard ``include('registration.urls')`` to
continue working, but that usage is deprecated and will be removed for
django-registration 1.0. For new installs, use
``include('registration.backends.default.urls')``.
"""
import warnings
warnings.warn("include('registration.urls') is deprecated; use include('registration.backends.default.urls') instead.",
DeprecationWarning)
from registration.backends.default.urls import *
|
fitzgen/servo
|
refs/heads/master
|
tests/wpt/css-tests/tools/html5lib/html5lib/treeadapters/sax.py
|
1835
|
from __future__ import absolute_import, division, unicode_literals
from xml.sax.xmlreader import AttributesNSImpl
from ..constants import adjustForeignAttributes, unadjustForeignAttributes
prefix_mapping = {}
for prefix, localName, namespace in adjustForeignAttributes.values():
if prefix is not None:
prefix_mapping[prefix] = namespace
def to_sax(walker, handler):
"""Call SAX-like content handler based on treewalker walker"""
handler.startDocument()
for prefix, namespace in prefix_mapping.items():
handler.startPrefixMapping(prefix, namespace)
for token in walker:
type = token["type"]
if type == "Doctype":
continue
elif type in ("StartTag", "EmptyTag"):
attrs = AttributesNSImpl(token["data"],
unadjustForeignAttributes)
handler.startElementNS((token["namespace"], token["name"]),
token["name"],
attrs)
if type == "EmptyTag":
handler.endElementNS((token["namespace"], token["name"]),
token["name"])
elif type == "EndTag":
handler.endElementNS((token["namespace"], token["name"]),
token["name"])
elif type in ("Characters", "SpaceCharacters"):
handler.characters(token["data"])
elif type == "Comment":
pass
else:
assert False, "Unknown token type"
for prefix, namespace in prefix_mapping.items():
handler.endPrefixMapping(prefix)
handler.endDocument()
|
bat-serjo/vivisect
|
refs/heads/master
|
vstruct/defs/windows/win_6_1_amd64/win32k.py
|
4
|
# Version: 6.1
# Architecture: amd64
import vstruct
from vstruct.primitives import *
ETW_THREAD_FLAG = v_enum()
ETW_THREAD_FLAG.ETW_THREAD_FLAG_HAD_INPUT = 0
ETW_THREAD_FLAG.ETW_THREAD_FLAG_HAD_VISIBLE_WINDOWS = 1
ETW_THREAD_FLAG.ETW_THREAD_FLAG_HAS_NEW_INPUT = 2
ETW_THREAD_FLAG.ETW_THREAD_FLAG_MAX = 3
TOUCHSTATE = v_enum()
TOUCHSTATE.TOUCHSTATE_INVALID = -1
TOUCHSTATE.TOUCHSTATE_NONE = 0
TOUCHSTATE.TOUCHSTATE_DOWN = 1
TOUCHSTATE.TOUCHSTATE_MOVE = 2
TOUCHSTATE.TOUCHSTATE_UPOUTOFRANGE = 3
TOUCHSTATE.TOUCHSTATE_INAIR = 4
TOUCHSTATE.TOUCHSTATE_INAIRMOVE = 5
TOUCHSTATE.TOUCHSTATE_INAIROUTOFRANGE = 6
TOUCHSTATE.TOUCHSTATE_COUNT = 7
PS_STD_HANDLE_STATE = v_enum()
PS_STD_HANDLE_STATE.PsNeverDuplicate = 0
PS_STD_HANDLE_STATE.PsRequestDuplicate = 1
PS_STD_HANDLE_STATE.PsAlwaysDuplicate = 2
PS_STD_HANDLE_STATE.PsMaxStdHandleStates = 3
WHEA_ERROR_SEVERITY = v_enum()
WHEA_ERROR_SEVERITY.WheaErrSevRecoverable = 0
WHEA_ERROR_SEVERITY.WheaErrSevFatal = 1
WHEA_ERROR_SEVERITY.WheaErrSevCorrected = 2
WHEA_ERROR_SEVERITY.WheaErrSevInformational = 3
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY_DEPRECATED = v_enum()
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY_DEPRECATED.D3DKMDT_VOT_DEPRECATED_UNINITIALIZED = 0
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY_DEPRECATED.D3DKMDT_VOT_DEPRECATED_HD15 = 1
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY_DEPRECATED.D3DKMDT_VOT_DEPRECATED_DVI = 2
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY_DEPRECATED.D3DKMDT_VOT_DEPRECATED_HDMI = 3
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY_DEPRECATED.D3DKMDT_VOT_DEPRECATED_HDMI2 = 4
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY_DEPRECATED.D3DKMDT_VOT_DEPRECATED_SVIDEO_4PIN = 5
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY_DEPRECATED.D3DKMDT_VOT_DEPRECATED_SVIDEO_7PIN = 6
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY_DEPRECATED.D3DKMDT_VOT_DEPRECATED_RCA_COMPOSITE = 7
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY_DEPRECATED.D3DKMDT_VOT_DEPRECATED_RCA_3COMPONENT = 8
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY_DEPRECATED.D3DKMDT_VOT_DEPRECATED_BNC = 9
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY_DEPRECATED.D3DKMDT_VOT_DEPRECATED_RF = 10
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY_DEPRECATED.D3DKMDT_VOT_DEPRECATED_SDTVDONGLE = 11
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY_DEPRECATED.D3DKMDT_VOT_DEPRECATED_INTERNAL = 12
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY_DEPRECATED.D3DKMDT_VOT_DEPRECATED_OTHER = 255
D3DKMDT_MONITOR_FREQUENCY_RANGE_CONSTRAINT = v_enum()
D3DKMDT_MONITOR_FREQUENCY_RANGE_CONSTRAINT.D3DKMDT_MFRC_UNINITIALIZED = 0
D3DKMDT_MONITOR_FREQUENCY_RANGE_CONSTRAINT.D3DKMDT_MFRC_ACTIVESIZE = 1
D3DKMDT_MONITOR_FREQUENCY_RANGE_CONSTRAINT.D3DKMDT_MFRC_MAXPIXELRATE = 2
WOW64_SHARED_INFORMATION = v_enum()
WOW64_SHARED_INFORMATION.SharedNtdll32LdrInitializeThunk = 0
WOW64_SHARED_INFORMATION.SharedNtdll32KiUserExceptionDispatcher = 1
WOW64_SHARED_INFORMATION.SharedNtdll32KiUserApcDispatcher = 2
WOW64_SHARED_INFORMATION.SharedNtdll32KiUserCallbackDispatcher = 3
WOW64_SHARED_INFORMATION.SharedNtdll32LdrHotPatchRoutine = 4
WOW64_SHARED_INFORMATION.SharedNtdll32ExpInterlockedPopEntrySListFault = 5
WOW64_SHARED_INFORMATION.SharedNtdll32ExpInterlockedPopEntrySListResume = 6
WOW64_SHARED_INFORMATION.SharedNtdll32ExpInterlockedPopEntrySListEnd = 7
WOW64_SHARED_INFORMATION.SharedNtdll32RtlUserThreadStart = 8
WOW64_SHARED_INFORMATION.SharedNtdll32pQueryProcessDebugInformationRemote = 9
WOW64_SHARED_INFORMATION.SharedNtdll32EtwpNotificationThread = 10
WOW64_SHARED_INFORMATION.SharedNtdll32BaseAddress = 11
WOW64_SHARED_INFORMATION.Wow64SharedPageEntriesCount = 12
REG_NOTIFY_CLASS = v_enum()
REG_NOTIFY_CLASS.RegNtDeleteKey = 0
REG_NOTIFY_CLASS.RegNtPreDeleteKey = 0
REG_NOTIFY_CLASS.RegNtSetValueKey = 1
REG_NOTIFY_CLASS.RegNtPreSetValueKey = 1
REG_NOTIFY_CLASS.RegNtDeleteValueKey = 2
REG_NOTIFY_CLASS.RegNtPreDeleteValueKey = 2
REG_NOTIFY_CLASS.RegNtSetInformationKey = 3
REG_NOTIFY_CLASS.RegNtPreSetInformationKey = 3
REG_NOTIFY_CLASS.RegNtRenameKey = 4
REG_NOTIFY_CLASS.RegNtPreRenameKey = 4
REG_NOTIFY_CLASS.RegNtEnumerateKey = 5
REG_NOTIFY_CLASS.RegNtPreEnumerateKey = 5
REG_NOTIFY_CLASS.RegNtEnumerateValueKey = 6
REG_NOTIFY_CLASS.RegNtPreEnumerateValueKey = 6
REG_NOTIFY_CLASS.RegNtQueryKey = 7
REG_NOTIFY_CLASS.RegNtPreQueryKey = 7
REG_NOTIFY_CLASS.RegNtQueryValueKey = 8
REG_NOTIFY_CLASS.RegNtPreQueryValueKey = 8
REG_NOTIFY_CLASS.RegNtQueryMultipleValueKey = 9
REG_NOTIFY_CLASS.RegNtPreQueryMultipleValueKey = 9
REG_NOTIFY_CLASS.RegNtPreCreateKey = 10
REG_NOTIFY_CLASS.RegNtPostCreateKey = 11
REG_NOTIFY_CLASS.RegNtPreOpenKey = 12
REG_NOTIFY_CLASS.RegNtPostOpenKey = 13
REG_NOTIFY_CLASS.RegNtKeyHandleClose = 14
REG_NOTIFY_CLASS.RegNtPreKeyHandleClose = 14
REG_NOTIFY_CLASS.RegNtPostDeleteKey = 15
REG_NOTIFY_CLASS.RegNtPostSetValueKey = 16
REG_NOTIFY_CLASS.RegNtPostDeleteValueKey = 17
REG_NOTIFY_CLASS.RegNtPostSetInformationKey = 18
REG_NOTIFY_CLASS.RegNtPostRenameKey = 19
REG_NOTIFY_CLASS.RegNtPostEnumerateKey = 20
REG_NOTIFY_CLASS.RegNtPostEnumerateValueKey = 21
REG_NOTIFY_CLASS.RegNtPostQueryKey = 22
REG_NOTIFY_CLASS.RegNtPostQueryValueKey = 23
REG_NOTIFY_CLASS.RegNtPostQueryMultipleValueKey = 24
REG_NOTIFY_CLASS.RegNtPostKeyHandleClose = 25
REG_NOTIFY_CLASS.RegNtPreCreateKeyEx = 26
REG_NOTIFY_CLASS.RegNtPostCreateKeyEx = 27
REG_NOTIFY_CLASS.RegNtPreOpenKeyEx = 28
REG_NOTIFY_CLASS.RegNtPostOpenKeyEx = 29
REG_NOTIFY_CLASS.RegNtPreFlushKey = 30
REG_NOTIFY_CLASS.RegNtPostFlushKey = 31
REG_NOTIFY_CLASS.RegNtPreLoadKey = 32
REG_NOTIFY_CLASS.RegNtPostLoadKey = 33
REG_NOTIFY_CLASS.RegNtPreUnLoadKey = 34
REG_NOTIFY_CLASS.RegNtPostUnLoadKey = 35
REG_NOTIFY_CLASS.RegNtPreQueryKeySecurity = 36
REG_NOTIFY_CLASS.RegNtPostQueryKeySecurity = 37
REG_NOTIFY_CLASS.RegNtPreSetKeySecurity = 38
REG_NOTIFY_CLASS.RegNtPostSetKeySecurity = 39
REG_NOTIFY_CLASS.RegNtCallbackObjectContextCleanup = 40
REG_NOTIFY_CLASS.RegNtPreRestoreKey = 41
REG_NOTIFY_CLASS.RegNtPostRestoreKey = 42
REG_NOTIFY_CLASS.RegNtPreSaveKey = 43
REG_NOTIFY_CLASS.RegNtPostSaveKey = 44
REG_NOTIFY_CLASS.RegNtPreReplaceKey = 45
REG_NOTIFY_CLASS.RegNtPostReplaceKey = 46
REG_NOTIFY_CLASS.MaxRegNtNotifyClass = 47
DEVICE_RELATION_TYPE = v_enum()
DEVICE_RELATION_TYPE.BusRelations = 0
DEVICE_RELATION_TYPE.EjectionRelations = 1
DEVICE_RELATION_TYPE.PowerRelations = 2
DEVICE_RELATION_TYPE.RemovalRelations = 3
DEVICE_RELATION_TYPE.TargetDeviceRelation = 4
DEVICE_RELATION_TYPE.SingleBusRelations = 5
DEVICE_RELATION_TYPE.TransportRelations = 6
D3DKMDT_VIDPN_PRESENT_PATH_COPYPROTECTION_TYPE = v_enum()
D3DKMDT_VIDPN_PRESENT_PATH_COPYPROTECTION_TYPE.D3DKMDT_VPPMT_UNINITIALIZED = 0
D3DKMDT_VIDPN_PRESENT_PATH_COPYPROTECTION_TYPE.D3DKMDT_VPPMT_NOPROTECTION = 1
D3DKMDT_VIDPN_PRESENT_PATH_COPYPROTECTION_TYPE.D3DKMDT_VPPMT_MACROVISION_APSTRIGGER = 2
D3DKMDT_VIDPN_PRESENT_PATH_COPYPROTECTION_TYPE.D3DKMDT_VPPMT_MACROVISION_FULLSUPPORT = 3
D3DKMDT_VIDPN_PRESENT_PATH_COPYPROTECTION_TYPE.D3DKMDT_VPPMT_NOTSPECIFIED = 255
IO_ALLOCATION_ACTION = v_enum()
IO_ALLOCATION_ACTION.KeepObject = 1
IO_ALLOCATION_ACTION.DeallocateObject = 2
IO_ALLOCATION_ACTION.DeallocateObjectKeepRegisters = 3
_unnamed_13236 = v_enum()
_unnamed_13236.DMM_DIAG_INFO_VISTA_BETA2_VERSION = 4097
_unnamed_13236.DMM_DIAG_INFO_VISTA_RC1_VERSION = 4098
_unnamed_13236.DMM_DIAG_INFO_VISTA_RTM_VERSION = 4099
_unnamed_13236.DMM_DIAG_INFO_WIN7_MQ_VERSION = 8192
_unnamed_13236.DMM_DIAG_INFO_WIN7_M3_VERSION = 8193
_unnamed_13236.DMM_DIAG_INFO_VERSION = 8193
BUS_QUERY_ID_TYPE = v_enum()
BUS_QUERY_ID_TYPE.BusQueryDeviceID = 0
BUS_QUERY_ID_TYPE.BusQueryHardwareIDs = 1
BUS_QUERY_ID_TYPE.BusQueryCompatibleIDs = 2
BUS_QUERY_ID_TYPE.BusQueryInstanceID = 3
BUS_QUERY_ID_TYPE.BusQueryDeviceSerialNumber = 4
BUS_QUERY_ID_TYPE.BusQueryContainerID = 5
PROFILE_MAP = v_enum()
PROFILE_MAP.PMAP_COLORS = 0
PROFILE_MAP.PMAP_CURSORS = 1
PROFILE_MAP.PMAP_WINDOWSM = 2
PROFILE_MAP.PMAP_WINDOWSU = 3
PROFILE_MAP.PMAP_DESKTOP = 4
PROFILE_MAP.PMAP_ICONS = 5
PROFILE_MAP.PMAP_FONTS = 6
PROFILE_MAP.PMAP_TRUETYPE = 7
PROFILE_MAP.PMAP_KBDLAYOUT = 8
PROFILE_MAP.PMAP_INPUT = 9
PROFILE_MAP.PMAP_SUBSYSTEMS = 10
PROFILE_MAP.PMAP_BEEP = 11
PROFILE_MAP.PMAP_MOUSE = 12
PROFILE_MAP.PMAP_KEYBOARD = 13
PROFILE_MAP.PMAP_STICKYKEYS = 14
PROFILE_MAP.PMAP_KEYBOARDRESPONSE = 15
PROFILE_MAP.PMAP_MOUSEKEYS = 16
PROFILE_MAP.PMAP_TOGGLEKEYS = 17
PROFILE_MAP.PMAP_TIMEOUT = 18
PROFILE_MAP.PMAP_SOUNDSENTRY = 19
PROFILE_MAP.PMAP_SHOWSOUNDS = 20
PROFILE_MAP.PMAP_AEDEBUG = 21
PROFILE_MAP.PMAP_NETWORK = 22
PROFILE_MAP.PMAP_METRICS = 23
PROFILE_MAP.PMAP_UKBDLAYOUT = 24
PROFILE_MAP.PMAP_UKBDLAYOUTTOGGLE = 25
PROFILE_MAP.PMAP_WINLOGON = 26
PROFILE_MAP.PMAP_KEYBOARDPREF = 27
PROFILE_MAP.PMAP_SCREENREADER = 28
PROFILE_MAP.PMAP_HIGHCONTRAST = 29
PROFILE_MAP.PMAP_IMECOMPAT = 30
PROFILE_MAP.PMAP_IMM = 31
PROFILE_MAP.PMAP_POOLLIMITS = 32
PROFILE_MAP.PMAP_COMPAT32 = 33
PROFILE_MAP.PMAP_SETUPPROGRAMNAMES = 34
PROFILE_MAP.PMAP_INPUTMETHOD = 35
PROFILE_MAP.PMAP_MOUCLASS_PARAMS = 36
PROFILE_MAP.PMAP_KBDCLASS_PARAMS = 37
PROFILE_MAP.PMAP_COMPUTERNAME = 38
PROFILE_MAP.PMAP_TS = 39
PROFILE_MAP.PMAP_TABLETPC = 40
PROFILE_MAP.PMAP_MEDIACENTER = 41
PROFILE_MAP.PMAP_TS_EXCLUDE_DESKTOP_VERSION = 42
PROFILE_MAP.PMAP_WOW64_COMPAT32 = 43
PROFILE_MAP.PMAP_WOW64_IMECOMPAT = 44
PROFILE_MAP.PMAP_SERVERR2 = 45
PROFILE_MAP.PMAP_STARTER = 46
PROFILE_MAP.PMAP_ACCESS = 47
PROFILE_MAP.PMAP_AUDIODESCRIPTION = 48
PROFILE_MAP.PMAP_CONTROL = 49
PROFILE_MAP.PMAP_LAST = 49
NT_PRODUCT_TYPE = v_enum()
NT_PRODUCT_TYPE.NtProductWinNt = 1
NT_PRODUCT_TYPE.NtProductLanManNt = 2
NT_PRODUCT_TYPE.NtProductServer = 3
DMM_VIDPNCHANGE_TYPE = v_enum()
DMM_VIDPNCHANGE_TYPE.DMM_CVR_UNINITIALIZED = 0
DMM_VIDPNCHANGE_TYPE.DMM_CVR_UPDATEMODALITY = 1
DMM_VIDPNCHANGE_TYPE.DMM_CVR_ADDPATH = 2
DMM_VIDPNCHANGE_TYPE.DMM_CVR_ADDPATHS = 3
DMM_VIDPNCHANGE_TYPE.DMM_CVR_REMOVEPATH = 4
DMM_VIDPNCHANGE_TYPE.DMM_CVR_REMOVEALLPATHS = 5
DEVICE_POWER_STATE = v_enum()
DEVICE_POWER_STATE.PowerDeviceUnspecified = 0
DEVICE_POWER_STATE.PowerDeviceD0 = 1
DEVICE_POWER_STATE.PowerDeviceD1 = 2
DEVICE_POWER_STATE.PowerDeviceD2 = 3
DEVICE_POWER_STATE.PowerDeviceD3 = 4
DEVICE_POWER_STATE.PowerDeviceMaximum = 5
WHEA_ERROR_SOURCE_TYPE = v_enum()
WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeMCE = 0
WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeCMC = 1
WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeCPE = 2
WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeNMI = 3
WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypePCIe = 4
WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeGeneric = 5
WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeINIT = 6
WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeBOOT = 7
WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeSCIGeneric = 8
WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeIPFMCA = 9
WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeIPFCMC = 10
WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeIPFCPE = 11
WHEA_ERROR_SOURCE_TYPE.WheaErrSrcTypeMax = 12
DXGK_DIAG_CODE_POINT_TYPE = v_enum()
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_NONE = 0
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_RECOMMEND_FUNC_VIDPN = 1
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_OS_RECOMMENDED_VIDPN = 2
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_SDC_LOG_FAILURE = 3
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_SDC_INVALIDATE_ERROR = 4
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_CDS_LOG_FAILURE = 5
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_CDS_FAILURE_DB = 7
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_RETRIEVE_BTL = 8
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_RETRIEVE_DB = 9
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_QDC_LOG_FAILURE = 10
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_POWER_ON_GDI = 11
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_POWER_OFF_GDI = 12
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_POWER_ON_MONITOR = 13
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_POWER_OFF_MONITOR = 14
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_POWER_DIM_MONITOR = 15
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_POWER_UNDIM_MONITOR = 16
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_BML_BACKTRACK = 17
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_BML_CLOSEST_TARGET_MODE = 18
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_BML_NO_EXACT_SOURCE_MODE = 19
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_BML_NO_EXACT_TARGET_MODE = 20
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_BML_SOURCE_MODE_NOT_PINNED = 21
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_BML_TARGET_MODE_NOT_PINNED = 22
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_BML_RESTARTED = 23
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_TDR = 24
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_ACPI_EVENT_NOTIFICATION = 25
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_CREATEMDEV_USE_DEFAULT_MODE = 26
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_CONNECTED_SET_LOG_FAILURE = 27
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_INVALIDATE_DXGK_MODE_CACHE = 28
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_REBUILD_DXGK_MODE_CACHE = 29
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_CREATEFUNVIDPN_RELAX_REFRESH_MATCH = 30
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_CREATEFUNVIDPN_CCDBML_FAIL_VISTABML_SUCCESSED = 31
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_BML_BEST_SOURCE_MODE = 32
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_BML_BEST_TARGET_MODE = 33
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_ADD_DEVICE = 34
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_START_ADAPTER = 35
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_STOP_ADAPTER = 36
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_CHILD_POLLING = 37
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_CHILD_POLLING_TARGET = 38
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_INDICATE_CHILD_STATUS = 39
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_HANDLE_IRP = 40
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_CHANGE_UNSUPPORTED_MONITOR_MODE_FLAG = 41
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_ACPI_NOTIFY_CALLBACK = 42
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_VIDEOPORTCALLOUT_EXCLUDE_EVICTALL_DISABLEGDI = 43
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_VIDEOPORTCALLOUT_EXCLUDE_EVICTALL_ENABLEGDI = 44
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_VIDEOPORTCALLOUT_EXCLUDE_MODESWITCH = 45
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_VIDEOPORTCALLOUT_SYNC_MONITOR_EVENT = 46
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_VIDEOPORTCALLOUT_PNP_NOTIFY_GDI = 47
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_VIDEOPORTCALLOUT_PNP_ENABLE_VGA = 48
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_VIDEOPORTCALLOUT_TDR_SWITCH_GDI = 49
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_VIDEOPORTCALLOUT_CDD_CREATE_DEVICE_FAILED = 50
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_VIDEOPORTCALLOUT_CDD_DEVICE_REMOVED = 51
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_VIDEOPORTCALLOUT_CDD_DRVASSERTMODE_TRUE_FAILED = 52
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_VIDEOPORTCALLOUT_CDD_RECREATE_DEVICE_FAILED = 53
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_CDD_MAPSHADOWBUFFER_FAILED = 54
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_COMMIT_VIDPN_LOG_FAILURE = 55
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_DRIVER_RECOMMEND_LOG_FAILURE = 56
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_SDC_ENFORCED_CLONE_PATH_INVALID_SOURCE_IDX = 57
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_DRVPROBEANDCAPTURE_FAILED = 58
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_DXGKCDDENABLE_OPTIMIZED_MODE_CHANGE = 59
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_DXGKSETDISPLAYMODE_OPTIMIZED_MODE_CHANGE = 60
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_MON_DEPART_GETRECENTTOP_FAIL = 61
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_MON_ARRIVE_INC_ADD_FAIL = 62
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_CCD_DATABASE_PERSIST = 63
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_CCD_DATABASE_PERSIST_NO_CONNECTIVITY_HASH = 64
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_MAX = 64
DXGK_DIAG_CODE_POINT_TYPE.DXGK_DIAG_CODE_POINT_TYPE_FORCE_UINT32 = -1
DMM_VIDPN_MONITOR_TYPE = v_enum()
DMM_VIDPN_MONITOR_TYPE.DMM_VMT_UNINITIALIZED = 0
DMM_VIDPN_MONITOR_TYPE.DMM_VMT_PHYSICAL_MONITOR = 1
DMM_VIDPN_MONITOR_TYPE.DMM_VMT_BOOT_PERSISTENT_MONITOR = 2
DMM_VIDPN_MONITOR_TYPE.DMM_VMT_PERSISTENT_MONITOR = 3
DMM_VIDPN_MONITOR_TYPE.DMM_VMT_TEMPORARY_MONITOR = 4
DMM_VIDPN_MONITOR_TYPE.DMM_VMT_SIMULATED_MONITOR = 5
D3DDDI_VIDEO_SIGNAL_SCANLINE_ORDERING = v_enum()
D3DDDI_VIDEO_SIGNAL_SCANLINE_ORDERING.D3DDDI_VSSLO_UNINITIALIZED = 0
D3DDDI_VIDEO_SIGNAL_SCANLINE_ORDERING.D3DDDI_VSSLO_PROGRESSIVE = 1
D3DDDI_VIDEO_SIGNAL_SCANLINE_ORDERING.D3DDDI_VSSLO_INTERLACED_UPPERFIELDFIRST = 2
D3DDDI_VIDEO_SIGNAL_SCANLINE_ORDERING.D3DDDI_VSSLO_INTERLACED_LOWERFIELDFIRST = 3
D3DDDI_VIDEO_SIGNAL_SCANLINE_ORDERING.D3DDDI_VSSLO_OTHER = 255
D3DKMDT_MONITOR_ORIENTATION = v_enum()
D3DKMDT_MONITOR_ORIENTATION.D3DKMDT_MO_UNINITIALIZED = 0
D3DKMDT_MONITOR_ORIENTATION.D3DKMDT_MO_0DEG = 1
D3DKMDT_MONITOR_ORIENTATION.D3DKMDT_MO_90DEG = 2
D3DKMDT_MONITOR_ORIENTATION.D3DKMDT_MO_180DEG = 3
D3DKMDT_MONITOR_ORIENTATION.D3DKMDT_MO_270DEG = 4
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY = v_enum()
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY.D3DKMDT_VOT_UNINITIALIZED = -2
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY.D3DKMDT_VOT_OTHER = -1
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY.D3DKMDT_VOT_HD15 = 0
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY.D3DKMDT_VOT_SVIDEO = 1
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY.D3DKMDT_VOT_COMPOSITE_VIDEO = 2
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY.D3DKMDT_VOT_COMPONENT_VIDEO = 3
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY.D3DKMDT_VOT_DVI = 4
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY.D3DKMDT_VOT_HDMI = 5
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY.D3DKMDT_VOT_LVDS = 6
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY.D3DKMDT_VOT_D_JPN = 8
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY.D3DKMDT_VOT_SDI = 9
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY.D3DKMDT_VOT_DISPLAYPORT_EXTERNAL = 10
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY.D3DKMDT_VOT_DISPLAYPORT_EMBEDDED = 11
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY.D3DKMDT_VOT_UDI_EXTERNAL = 12
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY.D3DKMDT_VOT_UDI_EMBEDDED = 13
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY.D3DKMDT_VOT_SDTVDONGLE = 14
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY.D3DKMDT_VOT_INTERNAL = -2147483648
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY.D3DKMDT_VOT_SVIDEO_4PIN = 1
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY.D3DKMDT_VOT_SVIDEO_7PIN = 1
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY.D3DKMDT_VOT_RF = 2
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY.D3DKMDT_VOT_RCA_3COMPONENT = 3
D3DKMDT_VIDEO_OUTPUT_TECHNOLOGY.D3DKMDT_VOT_BNC = 3
PS_CREATE_STATE = v_enum()
PS_CREATE_STATE.PsCreateInitialState = 0
PS_CREATE_STATE.PsCreateFailOnFileOpen = 1
PS_CREATE_STATE.PsCreateFailOnSectionCreate = 2
PS_CREATE_STATE.PsCreateFailExeFormat = 3
PS_CREATE_STATE.PsCreateFailMachineMismatch = 4
PS_CREATE_STATE.PsCreateFailExeName = 5
PS_CREATE_STATE.PsCreateSuccess = 6
PS_CREATE_STATE.PsCreateMaximumStates = 7
EVENT_TYPE = v_enum()
EVENT_TYPE.NotificationEvent = 0
EVENT_TYPE.SynchronizationEvent = 1
D3DKMDT_VIDPN_PRESENT_PATH_IMPORTANCE = v_enum()
D3DKMDT_VIDPN_PRESENT_PATH_IMPORTANCE.D3DKMDT_VPPI_UNINITIALIZED = 0
D3DKMDT_VIDPN_PRESENT_PATH_IMPORTANCE.D3DKMDT_VPPI_PRIMARY = 1
D3DKMDT_VIDPN_PRESENT_PATH_IMPORTANCE.D3DKMDT_VPPI_SECONDARY = 2
D3DKMDT_VIDPN_PRESENT_PATH_IMPORTANCE.D3DKMDT_VPPI_TERTIARY = 3
D3DKMDT_VIDPN_PRESENT_PATH_IMPORTANCE.D3DKMDT_VPPI_QUATERNARY = 4
D3DKMDT_VIDPN_PRESENT_PATH_IMPORTANCE.D3DKMDT_VPPI_QUINARY = 5
D3DKMDT_VIDPN_PRESENT_PATH_IMPORTANCE.D3DKMDT_VPPI_SENARY = 6
D3DKMDT_VIDPN_PRESENT_PATH_IMPORTANCE.D3DKMDT_VPPI_SEPTENARY = 7
D3DKMDT_VIDPN_PRESENT_PATH_IMPORTANCE.D3DKMDT_VPPI_OCTONARY = 8
D3DKMDT_VIDPN_PRESENT_PATH_IMPORTANCE.D3DKMDT_VPPI_NONARY = 9
D3DKMDT_VIDPN_PRESENT_PATH_IMPORTANCE.D3DKMDT_VPPI_DENARY = 10
D3DKMDT_VIDPN_PRESENT_PATH_IMPORTANCE.D3DKMDT_VPPI_MAX = 32
D3DKMDT_VIDPN_PRESENT_PATH_IMPORTANCE.D3DKMDT_VPPI_NOTSPECIFIED = 255
PS_IFEO_KEY_STATE = v_enum()
PS_IFEO_KEY_STATE.PsReadIFEOAllValues = 0
PS_IFEO_KEY_STATE.PsSkipIFEODebugger = 1
PS_IFEO_KEY_STATE.PsSkipAllIFEO = 2
PS_IFEO_KEY_STATE.PsMaxIFEOKeyStates = 3
D3DKMT_QUERYSTATISTICS_QUEUE_PACKET_TYPE = v_enum()
D3DKMT_QUERYSTATISTICS_QUEUE_PACKET_TYPE.D3DKMT_RenderCommandBuffer = 0
D3DKMT_QUERYSTATISTICS_QUEUE_PACKET_TYPE.D3DKMT_DeferredCommandBuffer = 1
D3DKMT_QUERYSTATISTICS_QUEUE_PACKET_TYPE.D3DKMT_SystemCommandBuffer = 2
D3DKMT_QUERYSTATISTICS_QUEUE_PACKET_TYPE.D3DKMT_MmIoFlipCommandBuffer = 3
D3DKMT_QUERYSTATISTICS_QUEUE_PACKET_TYPE.D3DKMT_WaitCommandBuffer = 4
D3DKMT_QUERYSTATISTICS_QUEUE_PACKET_TYPE.D3DKMT_SignalCommandBuffer = 5
D3DKMT_QUERYSTATISTICS_QUEUE_PACKET_TYPE.D3DKMT_DeviceCommandBuffer = 6
D3DKMT_QUERYSTATISTICS_QUEUE_PACKET_TYPE.D3DKMT_SoftwareCommandBuffer = 7
D3DKMT_QUERYSTATISTICS_QUEUE_PACKET_TYPE.D3DKMT_QueuePacketTypeMax = 8
INTERLOCKED_RESULT = v_enum()
INTERLOCKED_RESULT.ResultNegative = 1
INTERLOCKED_RESULT.ResultZero = 0
INTERLOCKED_RESULT.ResultPositive = 2
D3DKMDT_VIDPN_PRESENT_PATH_CONTENT = v_enum()
D3DKMDT_VIDPN_PRESENT_PATH_CONTENT.D3DKMDT_VPPC_UNINITIALIZED = 0
D3DKMDT_VIDPN_PRESENT_PATH_CONTENT.D3DKMDT_VPPC_GRAPHICS = 1
D3DKMDT_VIDPN_PRESENT_PATH_CONTENT.D3DKMDT_VPPC_VIDEO = 2
D3DKMDT_VIDPN_PRESENT_PATH_CONTENT.D3DKMDT_VPPC_NOTSPECIFIED = 255
THRESHOLD_SELECTOR = v_enum()
THRESHOLD_SELECTOR.ThresholdMouse = 0
THRESHOLD_SELECTOR.ThresholdPen = 1
THRESHOLD_SELECTOR.ThresholdMouseDragOut = 2
THRESHOLD_SELECTOR.ThresholdPenDragOut = 3
THRESHOLD_SELECTOR.ThresholdMouseSideMove = 4
THRESHOLD_SELECTOR.ThresholdPenSideMove = 5
THRESHOLD_SELECTOR.ThresholdAlways = 6
THRESHOLD_SELECTOR.ThresholdLast = 7
POOL_TYPE = v_enum()
POOL_TYPE.NonPagedPool = 0
POOL_TYPE.PagedPool = 1
POOL_TYPE.NonPagedPoolMustSucceed = 2
POOL_TYPE.DontUseThisType = 3
POOL_TYPE.NonPagedPoolCacheAligned = 4
POOL_TYPE.PagedPoolCacheAligned = 5
POOL_TYPE.NonPagedPoolCacheAlignedMustS = 6
POOL_TYPE.MaxPoolType = 7
POOL_TYPE.NonPagedPoolSession = 32
POOL_TYPE.PagedPoolSession = 33
POOL_TYPE.NonPagedPoolMustSucceedSession = 34
POOL_TYPE.DontUseThisTypeSession = 35
POOL_TYPE.NonPagedPoolCacheAlignedSession = 36
POOL_TYPE.PagedPoolCacheAlignedSession = 37
POOL_TYPE.NonPagedPoolCacheAlignedMustSSession = 38
DMM_CLIENT_TYPE = v_enum()
DMM_CLIENT_TYPE.DMM_CT_UNINITIALIZED = 0
DMM_CLIENT_TYPE.DMM_CT_CDD_NOPATHDATA = 1
DMM_CLIENT_TYPE.DMM_CT_USERMODE = 2
DMM_CLIENT_TYPE.DMM_CT_CDD_PATHDATA = 3
DMM_CLIENT_TYPE.DMM_CT_DXGPORT = 4
FSINFOCLASS = v_enum()
FSINFOCLASS.FileFsVolumeInformation = 1
FSINFOCLASS.FileFsLabelInformation = 2
FSINFOCLASS.FileFsSizeInformation = 3
FSINFOCLASS.FileFsDeviceInformation = 4
FSINFOCLASS.FileFsAttributeInformation = 5
FSINFOCLASS.FileFsControlInformation = 6
FSINFOCLASS.FileFsFullSizeInformation = 7
FSINFOCLASS.FileFsObjectIdInformation = 8
FSINFOCLASS.FileFsDriverPathInformation = 9
FSINFOCLASS.FileFsVolumeFlagsInformation = 10
FSINFOCLASS.FileFsMaximumInformation = 11
D3DKMT_QUERYSTATISTICS_DMA_PACKET_TYPE = v_enum()
D3DKMT_QUERYSTATISTICS_DMA_PACKET_TYPE.D3DKMT_ClientRenderBuffer = 0
D3DKMT_QUERYSTATISTICS_DMA_PACKET_TYPE.D3DKMT_ClientPagingBuffer = 1
D3DKMT_QUERYSTATISTICS_DMA_PACKET_TYPE.D3DKMT_SystemPagingBuffer = 2
D3DKMT_QUERYSTATISTICS_DMA_PACKET_TYPE.D3DKMT_SystemPreemptionBuffer = 3
D3DKMT_QUERYSTATISTICS_DMA_PACKET_TYPE.D3DKMT_DmaPacketTypeMax = 4
MODE = v_enum()
MODE.KernelMode = 0
MODE.UserMode = 1
MODE.MaximumMode = 2
SM_STORAGE_MODIFIER = v_enum()
SM_STORAGE_MODIFIER.SmStorageActual = 0
SM_STORAGE_MODIFIER.SmStorageNonActual = 1
DMM_MONITOR_PRESENCE_EVENT_TYPE = v_enum()
DMM_MONITOR_PRESENCE_EVENT_TYPE.DMM_MPET_UNINITIALIZED = 0
DMM_MONITOR_PRESENCE_EVENT_TYPE.DMM_MPET_ADDMONITOR = 1
DMM_MONITOR_PRESENCE_EVENT_TYPE.DMM_MPET_REMOVEMONITOR = 2
DMM_MONITOR_PRESENCE_EVENT_TYPE.DMM_MPET_DRIVERARRIVAL = 3
DMM_MONITOR_PRESENCE_EVENT_TYPE.DMM_MPET_DRIVERQUERYREMOVE = 4
DMM_MONITOR_PRESENCE_EVENT_TYPE.DMM_MPET_DRIVERREMOVECANCELLED = 5
DMM_MONITOR_PRESENCE_EVENT_TYPE.DMM_MPET_DRIVERREMOVECOMPLETE = 6
DMM_MONITOR_PRESENCE_EVENT_TYPE.DMM_MPET_DEVICENODEREADY = 7
DMM_MONITOR_PRESENCE_EVENT_TYPE.DMM_MPET_EDIDCHANGE = 8
DMM_MONITOR_PRESENCE_EVENT_TYPE.DMM_MPET_MONITORDISABLE = 9
DMM_MONITOR_PRESENCE_EVENT_TYPE.DMM_MPET_MONITORENABLE = 10
DMM_MONITOR_PRESENCE_EVENT_TYPE.DMM_MPET_ADAPTERADD = 11
DMM_MONITOR_PRESENCE_EVENT_TYPE.DMM_MPET_ADAPTERREMOVAL = 12
DMM_MONITOR_PRESENCE_EVENT_TYPE.DMM_MPET_INVALIDATION = 13
DMM_MONITOR_PRESENCE_EVENT_TYPE.DMM_MPET_ADDSIMULATEDMONITOR = 1073741825
DMM_MONITOR_PRESENCE_EVENT_TYPE.DMM_MPET_REMOVESIMULATEDMONITOR = 1073741826
DMM_MONITOR_PRESENCE_EVENT_TYPE.DMM_MPET_MAXVALID = 1073741826
WINDOW_ARRANGEMENT_COMMAND = v_enum()
WINDOW_ARRANGEMENT_COMMAND.WARR_MOVE_FIRST = 10
WINDOW_ARRANGEMENT_COMMAND.WARR_RESTORE_UP = 10
WINDOW_ARRANGEMENT_COMMAND.WARR_RESTORE_DOWN = 11
WINDOW_ARRANGEMENT_COMMAND.WARR_VRESTORE_UP = 12
WINDOW_ARRANGEMENT_COMMAND.WARR_VRESTORE_DOWN = 13
WINDOW_ARRANGEMENT_COMMAND.WARR_VMAXIMIZE_RIGHT = 14
WINDOW_ARRANGEMENT_COMMAND.WARR_VMAXIMIZE_LEFT = 15
WINDOW_ARRANGEMENT_COMMAND.WARR_MOVE_NEXT_MONITOR_LEFT = 16
WINDOW_ARRANGEMENT_COMMAND.WARR_MOVE_NEXT_MONITOR_RIGHT = 17
WINDOW_ARRANGEMENT_COMMAND.WARR_MOVE_LAST = 18
OB_OPEN_REASON = v_enum()
OB_OPEN_REASON.ObCreateHandle = 0
OB_OPEN_REASON.ObOpenHandle = 1
OB_OPEN_REASON.ObDuplicateHandle = 2
OB_OPEN_REASON.ObInheritHandle = 3
OB_OPEN_REASON.ObMaxOpenReason = 4
DMM_MODE_PRUNING_ALGORITHM = v_enum()
DMM_MODE_PRUNING_ALGORITHM.DMM_MPA_UNINITIALIZED = 0
DMM_MODE_PRUNING_ALGORITHM.DMM_MPA_GDI = 1
DMM_MODE_PRUNING_ALGORITHM.DMM_MPA_VISTA = 2
DMM_MODE_PRUNING_ALGORITHM.DMM_MPA_GDI_VISTA_UNION = 3
DMM_MODE_PRUNING_ALGORITHM.DMM_MPA_MAXVALID = 3
DEVICE_TEXT_TYPE = v_enum()
DEVICE_TEXT_TYPE.DeviceTextDescription = 0
DEVICE_TEXT_TYPE.DeviceTextLocationInformation = 1
POWER_STATE_TYPE = v_enum()
POWER_STATE_TYPE.SystemPowerState = 0
POWER_STATE_TYPE.DevicePowerState = 1
PS_ATTRIBUTE_NUM = v_enum()
PS_ATTRIBUTE_NUM.PsAttributeParentProcess = 0
PS_ATTRIBUTE_NUM.PsAttributeDebugObject = 1
PS_ATTRIBUTE_NUM.PsAttributeToken = 2
PS_ATTRIBUTE_NUM.PsAttributeClientId = 3
PS_ATTRIBUTE_NUM.PsAttributeTebAddress = 4
PS_ATTRIBUTE_NUM.PsAttributeImageName = 5
PS_ATTRIBUTE_NUM.PsAttributeImageInfo = 6
PS_ATTRIBUTE_NUM.PsAttributeMemoryReserve = 7
PS_ATTRIBUTE_NUM.PsAttributePriorityClass = 8
PS_ATTRIBUTE_NUM.PsAttributeErrorMode = 9
PS_ATTRIBUTE_NUM.PsAttributeStdHandleInfo = 10
PS_ATTRIBUTE_NUM.PsAttributeHandleList = 11
PS_ATTRIBUTE_NUM.PsAttributeGroupAffinity = 12
PS_ATTRIBUTE_NUM.PsAttributePreferredNode = 13
PS_ATTRIBUTE_NUM.PsAttributeIdealProcessor = 14
PS_ATTRIBUTE_NUM.PsAttributeUmsThread = 15
PS_ATTRIBUTE_NUM.PsAttributeExecuteOptions = 16
PS_ATTRIBUTE_NUM.PsAttributeMax = 17
IRQ_PRIORITY = v_enum()
IRQ_PRIORITY.IrqPriorityUndefined = 0
IRQ_PRIORITY.IrqPriorityLow = 1
IRQ_PRIORITY.IrqPriorityNormal = 2
IRQ_PRIORITY.IrqPriorityHigh = 3
D3DKMT_QUERYSTATISTICS_ALLOCATION_PRIORITY_CLASS = v_enum()
D3DKMT_QUERYSTATISTICS_ALLOCATION_PRIORITY_CLASS.D3DKMT_AllocationPriorityClassMinimum = 0
D3DKMT_QUERYSTATISTICS_ALLOCATION_PRIORITY_CLASS.D3DKMT_AllocationPriorityClassLow = 1
D3DKMT_QUERYSTATISTICS_ALLOCATION_PRIORITY_CLASS.D3DKMT_AllocationPriorityClassNormal = 2
D3DKMT_QUERYSTATISTICS_ALLOCATION_PRIORITY_CLASS.D3DKMT_AllocationPriorityClassHigh = 3
D3DKMT_QUERYSTATISTICS_ALLOCATION_PRIORITY_CLASS.D3DKMT_AllocationPriorityClassMaximum = 4
D3DKMT_QUERYSTATISTICS_ALLOCATION_PRIORITY_CLASS.D3DKMT_MaxAllocationPriorityClass = 5
D3DKMDT_MONITOR_CAPABILITIES_ORIGIN = v_enum()
D3DKMDT_MONITOR_CAPABILITIES_ORIGIN.D3DKMDT_MCO_UNINITIALIZED = 0
D3DKMDT_MONITOR_CAPABILITIES_ORIGIN.D3DKMDT_MCO_DEFAULTMONITORPROFILE = 1
D3DKMDT_MONITOR_CAPABILITIES_ORIGIN.D3DKMDT_MCO_MONITORDESCRIPTOR = 2
D3DKMDT_MONITOR_CAPABILITIES_ORIGIN.D3DKMDT_MCO_MONITORDESCRIPTOR_REGISTRYOVERRIDE = 3
D3DKMDT_MONITOR_CAPABILITIES_ORIGIN.D3DKMDT_MCO_SPECIFICCAP_REGISTRYOVERRIDE = 4
D3DKMDT_MONITOR_CAPABILITIES_ORIGIN.D3DKMDT_MCO_DRIVER = 5
D3DKMDT_MONITOR_CAPABILITIES_ORIGIN.D3DKMDT_MCO_MAXVALID = 5
D3DKMDT_PIXEL_VALUE_ACCESS_MODE = v_enum()
D3DKMDT_PIXEL_VALUE_ACCESS_MODE.D3DKMDT_PVAM_UNINITIALIZED = 0
D3DKMDT_PIXEL_VALUE_ACCESS_MODE.D3DKMDT_PVAM_DIRECT = 1
D3DKMDT_PIXEL_VALUE_ACCESS_MODE.D3DKMDT_PVAM_PRESETPALETTE = 2
D3DKMDT_PIXEL_VALUE_ACCESS_MODE.D3DKMDT_PVAM_SETTABLEPALETTE = 3
D3DKMDT_PIXEL_VALUE_ACCESS_MODE.D3DKMDT_PVAM_MAXVALID = 3
SECURITY_OPERATION_CODE = v_enum()
SECURITY_OPERATION_CODE.SetSecurityDescriptor = 0
SECURITY_OPERATION_CODE.QuerySecurityDescriptor = 1
SECURITY_OPERATION_CODE.DeleteSecurityDescriptor = 2
SECURITY_OPERATION_CODE.AssignSecurityDescriptor = 3
D3DKMDT_TEXT_RENDERING_FORMAT = v_enum()
D3DKMDT_TEXT_RENDERING_FORMAT.D3DKMDT_TRF_UNINITIALIZED = 0
RTL_GENERIC_COMPARE_RESULTS = v_enum()
RTL_GENERIC_COMPARE_RESULTS.GenericLessThan = 0
RTL_GENERIC_COMPARE_RESULTS.GenericGreaterThan = 1
RTL_GENERIC_COMPARE_RESULTS.GenericEqual = 2
SYSTEM_POWER_STATE = v_enum()
SYSTEM_POWER_STATE.PowerSystemUnspecified = 0
SYSTEM_POWER_STATE.PowerSystemWorking = 1
SYSTEM_POWER_STATE.PowerSystemSleeping1 = 2
SYSTEM_POWER_STATE.PowerSystemSleeping2 = 3
SYSTEM_POWER_STATE.PowerSystemSleeping3 = 4
SYSTEM_POWER_STATE.PowerSystemHibernate = 5
SYSTEM_POWER_STATE.PowerSystemShutdown = 6
SYSTEM_POWER_STATE.PowerSystemMaximum = 7
D3DKMDT_VIDPN_SOURCE_MODE_TYPE = v_enum()
D3DKMDT_VIDPN_SOURCE_MODE_TYPE.D3DKMDT_RMT_UNINITIALIZED = 0
D3DKMDT_VIDPN_SOURCE_MODE_TYPE.D3DKMDT_RMT_GRAPHICS = 1
D3DKMDT_VIDPN_SOURCE_MODE_TYPE.D3DKMDT_RMT_TEXT = 2
FILE_INFORMATION_CLASS = v_enum()
FILE_INFORMATION_CLASS.FileDirectoryInformation = 1
FILE_INFORMATION_CLASS.FileFullDirectoryInformation = 2
FILE_INFORMATION_CLASS.FileBothDirectoryInformation = 3
FILE_INFORMATION_CLASS.FileBasicInformation = 4
FILE_INFORMATION_CLASS.FileStandardInformation = 5
FILE_INFORMATION_CLASS.FileInternalInformation = 6
FILE_INFORMATION_CLASS.FileEaInformation = 7
FILE_INFORMATION_CLASS.FileAccessInformation = 8
FILE_INFORMATION_CLASS.FileNameInformation = 9
FILE_INFORMATION_CLASS.FileRenameInformation = 10
FILE_INFORMATION_CLASS.FileLinkInformation = 11
FILE_INFORMATION_CLASS.FileNamesInformation = 12
FILE_INFORMATION_CLASS.FileDispositionInformation = 13
FILE_INFORMATION_CLASS.FilePositionInformation = 14
FILE_INFORMATION_CLASS.FileFullEaInformation = 15
FILE_INFORMATION_CLASS.FileModeInformation = 16
FILE_INFORMATION_CLASS.FileAlignmentInformation = 17
FILE_INFORMATION_CLASS.FileAllInformation = 18
FILE_INFORMATION_CLASS.FileAllocationInformation = 19
FILE_INFORMATION_CLASS.FileEndOfFileInformation = 20
FILE_INFORMATION_CLASS.FileAlternateNameInformation = 21
FILE_INFORMATION_CLASS.FileStreamInformation = 22
FILE_INFORMATION_CLASS.FilePipeInformation = 23
FILE_INFORMATION_CLASS.FilePipeLocalInformation = 24
FILE_INFORMATION_CLASS.FilePipeRemoteInformation = 25
FILE_INFORMATION_CLASS.FileMailslotQueryInformation = 26
FILE_INFORMATION_CLASS.FileMailslotSetInformation = 27
FILE_INFORMATION_CLASS.FileCompressionInformation = 28
FILE_INFORMATION_CLASS.FileObjectIdInformation = 29
FILE_INFORMATION_CLASS.FileCompletionInformation = 30
FILE_INFORMATION_CLASS.FileMoveClusterInformation = 31
FILE_INFORMATION_CLASS.FileQuotaInformation = 32
FILE_INFORMATION_CLASS.FileReparsePointInformation = 33
FILE_INFORMATION_CLASS.FileNetworkOpenInformation = 34
FILE_INFORMATION_CLASS.FileAttributeTagInformation = 35
FILE_INFORMATION_CLASS.FileTrackingInformation = 36
FILE_INFORMATION_CLASS.FileIdBothDirectoryInformation = 37
FILE_INFORMATION_CLASS.FileIdFullDirectoryInformation = 38
FILE_INFORMATION_CLASS.FileValidDataLengthInformation = 39
FILE_INFORMATION_CLASS.FileShortNameInformation = 40
FILE_INFORMATION_CLASS.FileIoCompletionNotificationInformation = 41
FILE_INFORMATION_CLASS.FileIoStatusBlockRangeInformation = 42
FILE_INFORMATION_CLASS.FileIoPriorityHintInformation = 43
FILE_INFORMATION_CLASS.FileSfioReserveInformation = 44
FILE_INFORMATION_CLASS.FileSfioVolumeInformation = 45
FILE_INFORMATION_CLASS.FileHardLinkInformation = 46
FILE_INFORMATION_CLASS.FileProcessIdsUsingFileInformation = 47
FILE_INFORMATION_CLASS.FileNormalizedNameInformation = 48
FILE_INFORMATION_CLASS.FileNetworkPhysicalNameInformation = 49
FILE_INFORMATION_CLASS.FileIdGlobalTxDirectoryInformation = 50
FILE_INFORMATION_CLASS.FileIsRemoteDeviceInformation = 51
FILE_INFORMATION_CLASS.FileAttributeCacheInformation = 52
FILE_INFORMATION_CLASS.FileNumaNodeInformation = 53
FILE_INFORMATION_CLASS.FileStandardLinkInformation = 54
FILE_INFORMATION_CLASS.FileRemoteProtocolInformation = 55
FILE_INFORMATION_CLASS.FileMaximumInformation = 56
EXCEPTION_DISPOSITION = v_enum()
EXCEPTION_DISPOSITION.ExceptionContinueExecution = 0
EXCEPTION_DISPOSITION.ExceptionContinueSearch = 1
EXCEPTION_DISPOSITION.ExceptionNestedException = 2
EXCEPTION_DISPOSITION.ExceptionCollidedUnwind = 3
D3DKMDT_VIDPN_PRESENT_PATH_SCALING = v_enum()
D3DKMDT_VIDPN_PRESENT_PATH_SCALING.D3DKMDT_VPPS_UNINITIALIZED = 0
D3DKMDT_VIDPN_PRESENT_PATH_SCALING.D3DKMDT_VPPS_IDENTITY = 1
D3DKMDT_VIDPN_PRESENT_PATH_SCALING.D3DKMDT_VPPS_CENTERED = 2
D3DKMDT_VIDPN_PRESENT_PATH_SCALING.D3DKMDT_VPPS_STRETCHED = 3
D3DKMDT_VIDPN_PRESENT_PATH_SCALING.D3DKMDT_VPPS_ASPECTRATIOCENTEREDMAX = 4
D3DKMDT_VIDPN_PRESENT_PATH_SCALING.D3DKMDT_VPPS_CUSTOM = 5
D3DKMDT_VIDPN_PRESENT_PATH_SCALING.D3DKMDT_VPPS_RESERVED1 = 253
D3DKMDT_VIDPN_PRESENT_PATH_SCALING.D3DKMDT_VPPS_UNPINNED = 254
D3DKMDT_VIDPN_PRESENT_PATH_SCALING.D3DKMDT_VPPS_NOTSPECIFIED = 255
DEVICE_USAGE_NOTIFICATION_TYPE = v_enum()
DEVICE_USAGE_NOTIFICATION_TYPE.DeviceUsageTypeUndefined = 0
DEVICE_USAGE_NOTIFICATION_TYPE.DeviceUsageTypePaging = 1
DEVICE_USAGE_NOTIFICATION_TYPE.DeviceUsageTypeHibernation = 2
DEVICE_USAGE_NOTIFICATION_TYPE.DeviceUsageTypeDumpFile = 3
D3DDDI_GAMMARAMP_TYPE = v_enum()
D3DDDI_GAMMARAMP_TYPE.D3DDDI_GAMMARAMP_UNINITIALIZED = 0
D3DDDI_GAMMARAMP_TYPE.D3DDDI_GAMMARAMP_DEFAULT = 1
D3DDDI_GAMMARAMP_TYPE.D3DDDI_GAMMARAMP_RGB256x3x16 = 2
D3DDDI_GAMMARAMP_TYPE.D3DDDI_GAMMARAMP_DXGI_1 = 3
EX_POOL_PRIORITY = v_enum()
EX_POOL_PRIORITY.LowPoolPriority = 0
EX_POOL_PRIORITY.LowPoolPrioritySpecialPoolOverrun = 8
EX_POOL_PRIORITY.LowPoolPrioritySpecialPoolUnderrun = 9
EX_POOL_PRIORITY.NormalPoolPriority = 16
EX_POOL_PRIORITY.NormalPoolPrioritySpecialPoolOverrun = 24
EX_POOL_PRIORITY.NormalPoolPrioritySpecialPoolUnderrun = 25
EX_POOL_PRIORITY.HighPoolPriority = 32
EX_POOL_PRIORITY.HighPoolPrioritySpecialPoolOverrun = 40
EX_POOL_PRIORITY.HighPoolPrioritySpecialPoolUnderrun = 41
WHEA_ERROR_PACKET_DATA_FORMAT = v_enum()
WHEA_ERROR_PACKET_DATA_FORMAT.WheaDataFormatIPFSalRecord = 0
WHEA_ERROR_PACKET_DATA_FORMAT.WheaDataFormatXPFMCA = 1
WHEA_ERROR_PACKET_DATA_FORMAT.WheaDataFormatMemory = 2
WHEA_ERROR_PACKET_DATA_FORMAT.WheaDataFormatPCIExpress = 3
WHEA_ERROR_PACKET_DATA_FORMAT.WheaDataFormatNMIPort = 4
WHEA_ERROR_PACKET_DATA_FORMAT.WheaDataFormatPCIXBus = 5
WHEA_ERROR_PACKET_DATA_FORMAT.WheaDataFormatPCIXDevice = 6
WHEA_ERROR_PACKET_DATA_FORMAT.WheaDataFormatGeneric = 7
WHEA_ERROR_PACKET_DATA_FORMAT.WheaDataFormatMax = 8
DISPLAYCONFIG_SCANLINE_ORDERING = v_enum()
DISPLAYCONFIG_SCANLINE_ORDERING.DISPLAYCONFIG_SCANLINE_ORDERING_UNSPECIFIED = 0
DISPLAYCONFIG_SCANLINE_ORDERING.DISPLAYCONFIG_SCANLINE_ORDERING_PROGRESSIVE = 1
DISPLAYCONFIG_SCANLINE_ORDERING.DISPLAYCONFIG_SCANLINE_ORDERING_INTERLACED = 2
DISPLAYCONFIG_SCANLINE_ORDERING.DISPLAYCONFIG_SCANLINE_ORDERING_INTERLACED_UPPERFIELDFIRST = 2
DISPLAYCONFIG_SCANLINE_ORDERING.DISPLAYCONFIG_SCANLINE_ORDERING_INTERLACED_LOWERFIELDFIRST = 3
DISPLAYCONFIG_SCANLINE_ORDERING.DISPLAYCONFIG_SCANLINE_ORDERING_FORCE_UINT32 = -1
TP_CALLBACK_PRIORITY = v_enum()
TP_CALLBACK_PRIORITY.TP_CALLBACK_PRIORITY_HIGH = 0
TP_CALLBACK_PRIORITY.TP_CALLBACK_PRIORITY_NORMAL = 1
TP_CALLBACK_PRIORITY.TP_CALLBACK_PRIORITY_LOW = 2
TP_CALLBACK_PRIORITY.TP_CALLBACK_PRIORITY_INVALID = 3
SECURITY_IMPERSONATION_LEVEL = v_enum()
SECURITY_IMPERSONATION_LEVEL.SecurityAnonymous = 0
SECURITY_IMPERSONATION_LEVEL.SecurityIdentification = 1
SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation = 2
SECURITY_IMPERSONATION_LEVEL.SecurityDelegation = 3
D3DKMDT_VIDEO_SIGNAL_STANDARD = v_enum()
D3DKMDT_VIDEO_SIGNAL_STANDARD.D3DKMDT_VSS_UNINITIALIZED = 0
D3DKMDT_VIDEO_SIGNAL_STANDARD.D3DKMDT_VSS_VESA_DMT = 1
D3DKMDT_VIDEO_SIGNAL_STANDARD.D3DKMDT_VSS_VESA_GTF = 2
D3DKMDT_VIDEO_SIGNAL_STANDARD.D3DKMDT_VSS_VESA_CVT = 3
D3DKMDT_VIDEO_SIGNAL_STANDARD.D3DKMDT_VSS_IBM = 4
D3DKMDT_VIDEO_SIGNAL_STANDARD.D3DKMDT_VSS_APPLE = 5
D3DKMDT_VIDEO_SIGNAL_STANDARD.D3DKMDT_VSS_NTSC_M = 6
D3DKMDT_VIDEO_SIGNAL_STANDARD.D3DKMDT_VSS_NTSC_J = 7
D3DKMDT_VIDEO_SIGNAL_STANDARD.D3DKMDT_VSS_NTSC_443 = 8
D3DKMDT_VIDEO_SIGNAL_STANDARD.D3DKMDT_VSS_PAL_B = 9
D3DKMDT_VIDEO_SIGNAL_STANDARD.D3DKMDT_VSS_PAL_B1 = 10
D3DKMDT_VIDEO_SIGNAL_STANDARD.D3DKMDT_VSS_PAL_G = 11
D3DKMDT_VIDEO_SIGNAL_STANDARD.D3DKMDT_VSS_PAL_H = 12
D3DKMDT_VIDEO_SIGNAL_STANDARD.D3DKMDT_VSS_PAL_I = 13
D3DKMDT_VIDEO_SIGNAL_STANDARD.D3DKMDT_VSS_PAL_D = 14
D3DKMDT_VIDEO_SIGNAL_STANDARD.D3DKMDT_VSS_PAL_N = 15
D3DKMDT_VIDEO_SIGNAL_STANDARD.D3DKMDT_VSS_PAL_NC = 16
D3DKMDT_VIDEO_SIGNAL_STANDARD.D3DKMDT_VSS_SECAM_B = 17
D3DKMDT_VIDEO_SIGNAL_STANDARD.D3DKMDT_VSS_SECAM_D = 18
D3DKMDT_VIDEO_SIGNAL_STANDARD.D3DKMDT_VSS_SECAM_G = 19
D3DKMDT_VIDEO_SIGNAL_STANDARD.D3DKMDT_VSS_SECAM_H = 20
D3DKMDT_VIDEO_SIGNAL_STANDARD.D3DKMDT_VSS_SECAM_K = 21
D3DKMDT_VIDEO_SIGNAL_STANDARD.D3DKMDT_VSS_SECAM_K1 = 22
D3DKMDT_VIDEO_SIGNAL_STANDARD.D3DKMDT_VSS_SECAM_L = 23
D3DKMDT_VIDEO_SIGNAL_STANDARD.D3DKMDT_VSS_SECAM_L1 = 24
D3DKMDT_VIDEO_SIGNAL_STANDARD.D3DKMDT_VSS_EIA_861 = 25
D3DKMDT_VIDEO_SIGNAL_STANDARD.D3DKMDT_VSS_EIA_861A = 26
D3DKMDT_VIDEO_SIGNAL_STANDARD.D3DKMDT_VSS_EIA_861B = 27
D3DKMDT_VIDEO_SIGNAL_STANDARD.D3DKMDT_VSS_PAL_K = 28
D3DKMDT_VIDEO_SIGNAL_STANDARD.D3DKMDT_VSS_PAL_K1 = 29
D3DKMDT_VIDEO_SIGNAL_STANDARD.D3DKMDT_VSS_PAL_L = 30
D3DKMDT_VIDEO_SIGNAL_STANDARD.D3DKMDT_VSS_PAL_M = 31
D3DKMDT_VIDEO_SIGNAL_STANDARD.D3DKMDT_VSS_OTHER = 255
D3DKMDT_COLOR_BASIS = v_enum()
D3DKMDT_COLOR_BASIS.D3DKMDT_CB_UNINITIALIZED = 0
D3DKMDT_COLOR_BASIS.D3DKMDT_CB_INTENSITY = 1
D3DKMDT_COLOR_BASIS.D3DKMDT_CB_SRGB = 2
D3DKMDT_COLOR_BASIS.D3DKMDT_CB_SCRGB = 3
D3DKMDT_COLOR_BASIS.D3DKMDT_CB_YCBCR = 4
D3DKMDT_COLOR_BASIS.D3DKMDT_CB_YPBPR = 5
D3DKMDT_COLOR_BASIS.D3DKMDT_CB_MAXVALID = 5
DXGK_RECOMMENDFUNCTIONALVIDPN_REASON = v_enum()
DXGK_RECOMMENDFUNCTIONALVIDPN_REASON.DXGK_RFVR_UNINITIALIZED = 0
DXGK_RECOMMENDFUNCTIONALVIDPN_REASON.DXGK_RFVR_HOTKEY = 1
DXGK_RECOMMENDFUNCTIONALVIDPN_REASON.DXGK_RFVR_USERMODE = 2
D3DKMT_QUERYRESULT_PREEMPTION_ATTEMPT_RESULT = v_enum()
D3DKMT_QUERYRESULT_PREEMPTION_ATTEMPT_RESULT.D3DKMT_PreemptionAttempt = 0
D3DKMT_QUERYRESULT_PREEMPTION_ATTEMPT_RESULT.D3DKMT_PreemptionAttemptSuccess = 1
D3DKMT_QUERYRESULT_PREEMPTION_ATTEMPT_RESULT.D3DKMT_PreemptionAttemptMissNoCommand = 2
D3DKMT_QUERYRESULT_PREEMPTION_ATTEMPT_RESULT.D3DKMT_PreemptionAttemptMissNotEnabled = 3
D3DKMT_QUERYRESULT_PREEMPTION_ATTEMPT_RESULT.D3DKMT_PreemptionAttemptMissNextFence = 4
D3DKMT_QUERYRESULT_PREEMPTION_ATTEMPT_RESULT.D3DKMT_PreemptionAttemptMissPagingCommand = 5
D3DKMT_QUERYRESULT_PREEMPTION_ATTEMPT_RESULT.D3DKMT_PreemptionAttemptMissSplittedCommand = 6
D3DKMT_QUERYRESULT_PREEMPTION_ATTEMPT_RESULT.D3DKMT_PreemptionAttemptMissFenceCommand = 7
D3DKMT_QUERYRESULT_PREEMPTION_ATTEMPT_RESULT.D3DKMT_PreemptionAttemptMissRenderPendingFlip = 8
D3DKMT_QUERYRESULT_PREEMPTION_ATTEMPT_RESULT.D3DKMT_PreemptionAttemptMissNotMakingProgress = 9
D3DKMT_QUERYRESULT_PREEMPTION_ATTEMPT_RESULT.D3DKMT_PreemptionAttemptMissLessPriority = 10
D3DKMT_QUERYRESULT_PREEMPTION_ATTEMPT_RESULT.D3DKMT_PreemptionAttemptMissRemainingQuantum = 11
D3DKMT_QUERYRESULT_PREEMPTION_ATTEMPT_RESULT.D3DKMT_PreemptionAttemptMissRemainingPreemptionQuantum = 12
D3DKMT_QUERYRESULT_PREEMPTION_ATTEMPT_RESULT.D3DKMT_PreemptionAttemptMissAlreadyPreempting = 13
D3DKMT_QUERYRESULT_PREEMPTION_ATTEMPT_RESULT.D3DKMT_PreemptionAttemptMissGlobalBlock = 14
D3DKMT_QUERYRESULT_PREEMPTION_ATTEMPT_RESULT.D3DKMT_PreemptionAttemptMissAlreadyRunning = 15
D3DKMT_QUERYRESULT_PREEMPTION_ATTEMPT_RESULT.D3DKMT_PreemptionAttemptStatisticsMax = 16
INTERFACE_TYPE = v_enum()
INTERFACE_TYPE.InterfaceTypeUndefined = -1
INTERFACE_TYPE.Internal = 0
INTERFACE_TYPE.Isa = 1
INTERFACE_TYPE.Eisa = 2
INTERFACE_TYPE.MicroChannel = 3
INTERFACE_TYPE.TurboChannel = 4
INTERFACE_TYPE.PCIBus = 5
INTERFACE_TYPE.VMEBus = 6
INTERFACE_TYPE.NuBus = 7
INTERFACE_TYPE.PCMCIABus = 8
INTERFACE_TYPE.CBus = 9
INTERFACE_TYPE.MPIBus = 10
INTERFACE_TYPE.MPSABus = 11
INTERFACE_TYPE.ProcessorInternal = 12
INTERFACE_TYPE.InternalPowerBus = 13
INTERFACE_TYPE.PNPISABus = 14
INTERFACE_TYPE.PNPBus = 15
INTERFACE_TYPE.Vmcs = 16
INTERFACE_TYPE.MaximumInterfaceType = 17
ALTERNATIVE_ARCHITECTURE_TYPE = v_enum()
ALTERNATIVE_ARCHITECTURE_TYPE.StandardDesign = 0
ALTERNATIVE_ARCHITECTURE_TYPE.NEC98x86 = 1
ALTERNATIVE_ARCHITECTURE_TYPE.EndAlternatives = 2
D3DKMDT_VIDPN_PRESENT_PATH_ROTATION = v_enum()
D3DKMDT_VIDPN_PRESENT_PATH_ROTATION.D3DKMDT_VPPR_UNINITIALIZED = 0
D3DKMDT_VIDPN_PRESENT_PATH_ROTATION.D3DKMDT_VPPR_IDENTITY = 1
D3DKMDT_VIDPN_PRESENT_PATH_ROTATION.D3DKMDT_VPPR_ROTATE90 = 2
D3DKMDT_VIDPN_PRESENT_PATH_ROTATION.D3DKMDT_VPPR_ROTATE180 = 3
D3DKMDT_VIDPN_PRESENT_PATH_ROTATION.D3DKMDT_VPPR_ROTATE270 = 4
D3DKMDT_VIDPN_PRESENT_PATH_ROTATION.D3DKMDT_VPPR_UNPINNED = 254
D3DKMDT_VIDPN_PRESENT_PATH_ROTATION.D3DKMDT_VPPR_NOTSPECIFIED = 255
WHEA_ERROR_TYPE = v_enum()
WHEA_ERROR_TYPE.WheaErrTypeProcessor = 0
WHEA_ERROR_TYPE.WheaErrTypeMemory = 1
WHEA_ERROR_TYPE.WheaErrTypePCIExpress = 2
WHEA_ERROR_TYPE.WheaErrTypeNMI = 3
WHEA_ERROR_TYPE.WheaErrTypePCIXBus = 4
WHEA_ERROR_TYPE.WheaErrTypePCIXDevice = 5
WHEA_ERROR_TYPE.WheaErrTypeGeneric = 6
DXGK_DIAG_TYPE = v_enum()
DXGK_DIAG_TYPE.DXGK_DIAG_TYPE_NONE = 0
DXGK_DIAG_TYPE.DXGK_DIAG_TYPE_SDC = 1
DXGK_DIAG_TYPE.DXGK_DIAG_TYPE_HPD = 2
DXGK_DIAG_TYPE.DXGK_DIAG_TYPE_DC_ORIGIN = 3
DXGK_DIAG_TYPE.DXGK_DIAG_TYPE_USER_CDS = 4
DXGK_DIAG_TYPE.DXGK_DIAG_TYPE_DRV_CDS = 5
DXGK_DIAG_TYPE.DXGK_DIAG_TYPE_CODE_POINT = 6
DXGK_DIAG_TYPE.DXGK_DIAG_TYPE_QDC = 7
DXGK_DIAG_TYPE.DXGK_DIAG_TYPE_MONITOR_MGR = 8
DXGK_DIAG_TYPE.DXGK_DIAG_TYPE_CONNECTEDSET_NOT_FOUND = 9
DXGK_DIAG_TYPE.DXGK_DIAG_TYPE_DISPDIAG_COLLECTED = 10
DXGK_DIAG_TYPE.DXGK_DIAG_TYPE_BML_PACKET = 11
DXGK_DIAG_TYPE.DXGK_DIAG_TYPE_BML_PACKET_EX = 12
DXGK_DIAG_TYPE.DXGK_DIAG_TYPE_COMMIT_VIDPN_FAILED = 13
DXGK_DIAG_TYPE.DXGK_DIAG_TYPE_DRIVER_RECOMMEND_VIDPN = 14
DXGK_DIAG_TYPE.DXGK_DIAG_TYPE_MAX = 14
DXGK_DIAG_TYPE.DXGK_DIAG_TYPE_FORCE_UINT32 = -1
ReplacesCorHdrNumericDefines = v_enum()
ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_ILONLY = 1
ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_32BITREQUIRED = 2
ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_IL_LIBRARY = 4
ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_STRONGNAMESIGNED = 8
ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_NATIVE_ENTRYPOINT = 16
ReplacesCorHdrNumericDefines.COMIMAGE_FLAGS_TRACKDEBUGDATA = 65536
ReplacesCorHdrNumericDefines.COR_VERSION_MAJOR_V2 = 2
ReplacesCorHdrNumericDefines.COR_VERSION_MAJOR = 2
ReplacesCorHdrNumericDefines.COR_VERSION_MINOR = 0
ReplacesCorHdrNumericDefines.COR_DELETED_NAME_LENGTH = 8
ReplacesCorHdrNumericDefines.COR_VTABLEGAP_NAME_LENGTH = 8
ReplacesCorHdrNumericDefines.NATIVE_TYPE_MAX_CB = 1
ReplacesCorHdrNumericDefines.COR_ILMETHOD_SECT_SMALL_MAX_DATASIZE = 255
ReplacesCorHdrNumericDefines.IMAGE_COR_MIH_METHODRVA = 1
ReplacesCorHdrNumericDefines.IMAGE_COR_MIH_EHRVA = 2
ReplacesCorHdrNumericDefines.IMAGE_COR_MIH_BASICBLOCK = 8
ReplacesCorHdrNumericDefines.COR_VTABLE_32BIT = 1
ReplacesCorHdrNumericDefines.COR_VTABLE_64BIT = 2
ReplacesCorHdrNumericDefines.COR_VTABLE_FROM_UNMANAGED = 4
ReplacesCorHdrNumericDefines.COR_VTABLE_FROM_UNMANAGED_RETAIN_APPDOMAIN = 8
ReplacesCorHdrNumericDefines.COR_VTABLE_CALL_MOST_DERIVED = 16
ReplacesCorHdrNumericDefines.IMAGE_COR_EATJ_THUNK_SIZE = 32
ReplacesCorHdrNumericDefines.MAX_CLASS_NAME = 1024
ReplacesCorHdrNumericDefines.MAX_PACKAGE_NAME = 1024
D3DKMDT_MODE_PREFERENCE = v_enum()
D3DKMDT_MODE_PREFERENCE.D3DKMDT_MP_UNINITIALIZED = 0
D3DKMDT_MODE_PREFERENCE.D3DKMDT_MP_PREFERRED = 1
D3DKMDT_MODE_PREFERENCE.D3DKMDT_MP_NOTPREFERRED = 2
D3DKMDT_MODE_PREFERENCE.D3DKMDT_MP_MAXVALID = 2
eTHRESHOLD_MARGIN_DIRECTION = v_enum()
eTHRESHOLD_MARGIN_DIRECTION.ThresholdMarginTop = 0
eTHRESHOLD_MARGIN_DIRECTION.ThresholdMarginLeft = 1
eTHRESHOLD_MARGIN_DIRECTION.ThresholdMarginRight = 2
eTHRESHOLD_MARGIN_DIRECTION.ThresholdMarginBottom = 3
eTHRESHOLD_MARGIN_DIRECTION.ThresholdMarginMax = 4
MOVERECT_STYLE = v_enum()
MOVERECT_STYLE.MoveRectKeepPositionAtCursor = 0
MOVERECT_STYLE.MoveRectMidTopAtCursor = 1
MOVERECT_STYLE.MoveRectKeepAspectRatioAtCursor = 2
MOVERECT_STYLE.MoveRectSidewiseKeepPositionAtCursor = 3
D3DKMDT_MONITOR_TIMING_TYPE = v_enum()
D3DKMDT_MONITOR_TIMING_TYPE.D3DKMDT_MTT_UNINITIALIZED = 0
D3DKMDT_MONITOR_TIMING_TYPE.D3DKMDT_MTT_ESTABLISHED = 1
D3DKMDT_MONITOR_TIMING_TYPE.D3DKMDT_MTT_STANDARD = 2
D3DKMDT_MONITOR_TIMING_TYPE.D3DKMDT_MTT_EXTRASTANDARD = 3
D3DKMDT_MONITOR_TIMING_TYPE.D3DKMDT_MTT_DETAILED = 4
D3DKMDT_MONITOR_TIMING_TYPE.D3DKMDT_MTT_DEFAULTMONITORPROFILE = 5
D3DKMDT_MONITOR_TIMING_TYPE.D3DKMDT_MTT_DRIVER = 6
D3DKMDT_MONITOR_TIMING_TYPE.D3DKMDT_MTT_MAXVALID = 6
MEMORY_CACHING_TYPE_ORIG = v_enum()
MEMORY_CACHING_TYPE_ORIG.MmFrameBufferCached = 2
D3DDDIFORMAT = v_enum()
D3DDDIFORMAT.D3DDDIFMT_UNKNOWN = 0
D3DDDIFORMAT.D3DDDIFMT_R8G8B8 = 20
D3DDDIFORMAT.D3DDDIFMT_A8R8G8B8 = 21
D3DDDIFORMAT.D3DDDIFMT_X8R8G8B8 = 22
D3DDDIFORMAT.D3DDDIFMT_R5G6B5 = 23
D3DDDIFORMAT.D3DDDIFMT_X1R5G5B5 = 24
D3DDDIFORMAT.D3DDDIFMT_A1R5G5B5 = 25
D3DDDIFORMAT.D3DDDIFMT_A4R4G4B4 = 26
D3DDDIFORMAT.D3DDDIFMT_R3G3B2 = 27
D3DDDIFORMAT.D3DDDIFMT_A8 = 28
D3DDDIFORMAT.D3DDDIFMT_A8R3G3B2 = 29
D3DDDIFORMAT.D3DDDIFMT_X4R4G4B4 = 30
D3DDDIFORMAT.D3DDDIFMT_A2B10G10R10 = 31
D3DDDIFORMAT.D3DDDIFMT_A8B8G8R8 = 32
D3DDDIFORMAT.D3DDDIFMT_X8B8G8R8 = 33
D3DDDIFORMAT.D3DDDIFMT_G16R16 = 34
D3DDDIFORMAT.D3DDDIFMT_A2R10G10B10 = 35
D3DDDIFORMAT.D3DDDIFMT_A16B16G16R16 = 36
D3DDDIFORMAT.D3DDDIFMT_A8P8 = 40
D3DDDIFORMAT.D3DDDIFMT_P8 = 41
D3DDDIFORMAT.D3DDDIFMT_L8 = 50
D3DDDIFORMAT.D3DDDIFMT_A8L8 = 51
D3DDDIFORMAT.D3DDDIFMT_A4L4 = 52
D3DDDIFORMAT.D3DDDIFMT_V8U8 = 60
D3DDDIFORMAT.D3DDDIFMT_L6V5U5 = 61
D3DDDIFORMAT.D3DDDIFMT_X8L8V8U8 = 62
D3DDDIFORMAT.D3DDDIFMT_Q8W8V8U8 = 63
D3DDDIFORMAT.D3DDDIFMT_V16U16 = 64
D3DDDIFORMAT.D3DDDIFMT_W11V11U10 = 65
D3DDDIFORMAT.D3DDDIFMT_A2W10V10U10 = 67
D3DDDIFORMAT.D3DDDIFMT_UYVY = 1498831189
D3DDDIFORMAT.D3DDDIFMT_R8G8_B8G8 = 1195525970
D3DDDIFORMAT.D3DDDIFMT_YUY2 = 844715353
D3DDDIFORMAT.D3DDDIFMT_G8R8_G8B8 = 1111970375
D3DDDIFORMAT.D3DDDIFMT_DXT1 = 827611204
D3DDDIFORMAT.D3DDDIFMT_DXT2 = 844388420
D3DDDIFORMAT.D3DDDIFMT_DXT3 = 861165636
D3DDDIFORMAT.D3DDDIFMT_DXT4 = 877942852
D3DDDIFORMAT.D3DDDIFMT_DXT5 = 894720068
D3DDDIFORMAT.D3DDDIFMT_D16_LOCKABLE = 70
D3DDDIFORMAT.D3DDDIFMT_D32 = 71
D3DDDIFORMAT.D3DDDIFMT_D15S1 = 73
D3DDDIFORMAT.D3DDDIFMT_D24S8 = 75
D3DDDIFORMAT.D3DDDIFMT_D24X8 = 77
D3DDDIFORMAT.D3DDDIFMT_D24X4S4 = 79
D3DDDIFORMAT.D3DDDIFMT_D16 = 80
D3DDDIFORMAT.D3DDDIFMT_D32F_LOCKABLE = 82
D3DDDIFORMAT.D3DDDIFMT_D24FS8 = 83
D3DDDIFORMAT.D3DDDIFMT_D32_LOCKABLE = 84
D3DDDIFORMAT.D3DDDIFMT_S8_LOCKABLE = 85
D3DDDIFORMAT.D3DDDIFMT_S1D15 = 72
D3DDDIFORMAT.D3DDDIFMT_S8D24 = 74
D3DDDIFORMAT.D3DDDIFMT_X8D24 = 76
D3DDDIFORMAT.D3DDDIFMT_X4S4D24 = 78
D3DDDIFORMAT.D3DDDIFMT_L16 = 81
D3DDDIFORMAT.D3DDDIFMT_VERTEXDATA = 100
D3DDDIFORMAT.D3DDDIFMT_INDEX16 = 101
D3DDDIFORMAT.D3DDDIFMT_INDEX32 = 102
D3DDDIFORMAT.D3DDDIFMT_Q16W16V16U16 = 110
D3DDDIFORMAT.D3DDDIFMT_MULTI2_ARGB8 = 827606349
D3DDDIFORMAT.D3DDDIFMT_R16F = 111
D3DDDIFORMAT.D3DDDIFMT_G16R16F = 112
D3DDDIFORMAT.D3DDDIFMT_A16B16G16R16F = 113
D3DDDIFORMAT.D3DDDIFMT_R32F = 114
D3DDDIFORMAT.D3DDDIFMT_G32R32F = 115
D3DDDIFORMAT.D3DDDIFMT_A32B32G32R32F = 116
D3DDDIFORMAT.D3DDDIFMT_CxV8U8 = 117
D3DDDIFORMAT.D3DDDIFMT_A1 = 118
D3DDDIFORMAT.D3DDDIFMT_A2B10G10R10_XR_BIAS = 119
D3DDDIFORMAT.D3DDDIFMT_DXVACOMPBUFFER_BASE = 150
D3DDDIFORMAT.D3DDDIFMT_PICTUREPARAMSDATA = 150
D3DDDIFORMAT.D3DDDIFMT_MACROBLOCKDATA = 151
D3DDDIFORMAT.D3DDDIFMT_RESIDUALDIFFERENCEDATA = 152
D3DDDIFORMAT.D3DDDIFMT_DEBLOCKINGDATA = 153
D3DDDIFORMAT.D3DDDIFMT_INVERSEQUANTIZATIONDATA = 154
D3DDDIFORMAT.D3DDDIFMT_SLICECONTROLDATA = 155
D3DDDIFORMAT.D3DDDIFMT_BITSTREAMDATA = 156
D3DDDIFORMAT.D3DDDIFMT_MOTIONVECTORBUFFER = 157
D3DDDIFORMAT.D3DDDIFMT_FILMGRAINBUFFER = 158
D3DDDIFORMAT.D3DDDIFMT_DXVA_RESERVED9 = 159
D3DDDIFORMAT.D3DDDIFMT_DXVA_RESERVED10 = 160
D3DDDIFORMAT.D3DDDIFMT_DXVA_RESERVED11 = 161
D3DDDIFORMAT.D3DDDIFMT_DXVA_RESERVED12 = 162
D3DDDIFORMAT.D3DDDIFMT_DXVA_RESERVED13 = 163
D3DDDIFORMAT.D3DDDIFMT_DXVA_RESERVED14 = 164
D3DDDIFORMAT.D3DDDIFMT_DXVA_RESERVED15 = 165
D3DDDIFORMAT.D3DDDIFMT_DXVA_RESERVED16 = 166
D3DDDIFORMAT.D3DDDIFMT_DXVA_RESERVED17 = 167
D3DDDIFORMAT.D3DDDIFMT_DXVA_RESERVED18 = 168
D3DDDIFORMAT.D3DDDIFMT_DXVA_RESERVED19 = 169
D3DDDIFORMAT.D3DDDIFMT_DXVA_RESERVED20 = 170
D3DDDIFORMAT.D3DDDIFMT_DXVA_RESERVED21 = 171
D3DDDIFORMAT.D3DDDIFMT_DXVA_RESERVED22 = 172
D3DDDIFORMAT.D3DDDIFMT_DXVA_RESERVED23 = 173
D3DDDIFORMAT.D3DDDIFMT_DXVA_RESERVED24 = 174
D3DDDIFORMAT.D3DDDIFMT_DXVA_RESERVED25 = 175
D3DDDIFORMAT.D3DDDIFMT_DXVA_RESERVED26 = 176
D3DDDIFORMAT.D3DDDIFMT_DXVA_RESERVED27 = 177
D3DDDIFORMAT.D3DDDIFMT_DXVA_RESERVED28 = 178
D3DDDIFORMAT.D3DDDIFMT_DXVA_RESERVED29 = 179
D3DDDIFORMAT.D3DDDIFMT_DXVA_RESERVED30 = 180
D3DDDIFORMAT.D3DDDIFMT_DXVA_RESERVED31 = 181
D3DDDIFORMAT.D3DDDIFMT_DXVACOMPBUFFER_MAX = 181
D3DDDIFORMAT.D3DDDIFMT_BINARYBUFFER = 199
D3DDDIFORMAT.D3DDDIFMT_FORCE_UINT = 2147483647
POWER_ACTION = v_enum()
POWER_ACTION.PowerActionNone = 0
POWER_ACTION.PowerActionReserved = 1
POWER_ACTION.PowerActionSleep = 2
POWER_ACTION.PowerActionHibernate = 3
POWER_ACTION.PowerActionShutdown = 4
POWER_ACTION.PowerActionShutdownReset = 5
POWER_ACTION.PowerActionShutdownOff = 6
POWER_ACTION.PowerActionWarmEject = 7
D3DKMDT_MONITOR_DESCRIPTOR_TYPE = v_enum()
D3DKMDT_MONITOR_DESCRIPTOR_TYPE.D3DKMDT_MDT_UNINITIALIZED = 0
D3DKMDT_MONITOR_DESCRIPTOR_TYPE.D3DKMDT_MDT_VESA_EDID_V1_BASEBLOCK = 1
D3DKMDT_MONITOR_DESCRIPTOR_TYPE.D3DKMDT_MDT_VESA_EDID_V1_BLOCKMAP = 2
D3DKMDT_MONITOR_DESCRIPTOR_TYPE.D3DKMDT_MDT_OTHER = 255
SM_RANGE_TYPES = v_enum()
SM_RANGE_TYPES.SmRangeSharedInfo = 0
SM_RANGE_TYPES.SmRangeNonSharedInfo = 1
SM_RANGE_TYPES.SmRangeBool = 2
WINDOWCOMPOSITIONATTRIB = v_enum()
WINDOWCOMPOSITIONATTRIB.WCA_UNDEFINED = 0
WINDOWCOMPOSITIONATTRIB.WCA_NCRENDERING_ENABLED = 1
WINDOWCOMPOSITIONATTRIB.WCA_NCRENDERING_POLICY = 2
WINDOWCOMPOSITIONATTRIB.WCA_TRANSITIONS_FORCEDISABLED = 3
WINDOWCOMPOSITIONATTRIB.WCA_ALLOW_NCPAINT = 4
WINDOWCOMPOSITIONATTRIB.WCA_CAPTION_BUTTON_BOUNDS = 5
WINDOWCOMPOSITIONATTRIB.WCA_NONCLIENT_RTL_LAYOUT = 6
WINDOWCOMPOSITIONATTRIB.WCA_FORCE_ICONIC_REPRESENTATION = 7
WINDOWCOMPOSITIONATTRIB.WCA_FLIP3D_POLICY = 8
WINDOWCOMPOSITIONATTRIB.WCA_EXTENDED_FRAME_BOUNDS = 9
WINDOWCOMPOSITIONATTRIB.WCA_HAS_ICONIC_BITMAP = 10
WINDOWCOMPOSITIONATTRIB.WCA_THEME_ATTRIBUTES = 11
WINDOWCOMPOSITIONATTRIB.WCA_NCRENDERING_EXILED = 12
WINDOWCOMPOSITIONATTRIB.WCA_NCADORNMENTINFO = 13
WINDOWCOMPOSITIONATTRIB.WCA_EXCLUDED_FROM_LIVEPREVIEW = 14
WINDOWCOMPOSITIONATTRIB.WCA_VIDEO_OVERLAY_ACTIVE = 15
WINDOWCOMPOSITIONATTRIB.WCA_FORCE_ACTIVEWINDOW_APPEARANCE = 16
WINDOWCOMPOSITIONATTRIB.WCA_DISALLOW_PEEK = 17
WINDOWCOMPOSITIONATTRIB.WCA_LAST = 18
class _unnamed_10519(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.DeviceTextType = v_uint32()
self._pad0008 = v_bytes(size=4)
self.LocaleId = v_uint32()
self._pad0010 = v_bytes(size=4)
class _unnamed_10514(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.IdType = v_uint32()
class _unnamed_14487(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Priority = v_uint32()
self.Reserved1 = v_uint32()
self.Reserved2 = v_uint32()
class _unnamed_14482(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Length = v_uint32()
self.MinBusNumber = v_uint32()
self.MaxBusNumber = v_uint32()
self.Reserved = v_uint32()
class tagTOUCHINPUTINFO(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.head = THROBJHEAD()
self.dwcInputs = v_uint32()
self.uFlags = v_uint32()
self.TouchInput = vstruct.VArray([ tagTOUCHINPUT() for i in range(1) ])
class tagHOOK(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.head = THRDESKHEAD()
self.phkNext = v_ptr64()
self.iHook = v_uint32()
self._pad0038 = v_bytes(size=4)
self.offPfn = v_uint64()
self.flags = v_uint32()
self.ihmod = v_uint32()
self.ptiHooked = v_ptr64()
self.rpdesk = v_ptr64()
self.nTimeout = v_uint32()
self._pad0060 = v_bytes(size=4)
class VK_TO_WCHAR_TABLE(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.pVkToWchars = v_ptr64()
self.nModifications = v_uint8()
self.cbSize = v_uint8()
self._pad0010 = v_bytes(size=6)
class D3DKMDT_2DREGION(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.cx = v_uint32()
self.cy = v_uint32()
class DEADKEY(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.dwBoth = v_uint32()
self.wchComposed = v_uint16()
self.uFlags = v_uint16()
class CURDIR(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.DosPath = UNICODE_STRING()
self.Handle = v_ptr64()
class _unnamed_13900(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Port = _unnamed_14462()
class tagPROPLIST(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.cEntries = v_uint32()
self.iFirstFree = v_uint32()
self.aprop = vstruct.VArray([ tagPROP() for i in range(1) ])
class _unnamed_9808(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.BaseMiddle = v_uint32()
class _unnamed_9807(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.BaseMiddle = v_uint8()
self.Flags1 = v_uint8()
self.Flags2 = v_uint8()
self.BaseHigh = v_uint8()
class tagDESKTOPINFO(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.pvDesktopBase = v_ptr64()
self.pvDesktopLimit = v_ptr64()
self.spwnd = v_ptr64()
self.fsHooks = v_uint32()
self._pad0020 = v_bytes(size=4)
self.aphkStart = vstruct.VArray([ v_ptr64() for i in range(16) ])
self.spwndShell = v_ptr64()
self.ppiShellProcess = v_ptr64()
self.spwndBkGnd = v_ptr64()
self.spwndTaskman = v_ptr64()
self.spwndProgman = v_ptr64()
self.pvwplShellHook = v_ptr64()
self.cntMBox = v_uint32()
self._pad00d8 = v_bytes(size=4)
self.spwndGestureEngine = v_ptr64()
self.pvwplMessagePPHandler = v_ptr64()
self.fComposited = v_uint32()
self._pad00f0 = v_bytes(size=4)
class _unnamed_10207(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.DeviceQueueEntry = KDEVICE_QUEUE_ENTRY()
self._pad0020 = v_bytes(size=8)
self.Thread = v_ptr64()
self.AuxiliaryBuffer = v_ptr64()
self.ListEntry = LIST_ENTRY()
self.CurrentStackLocation = v_ptr64()
self.OriginalFileObject = v_ptr64()
class WHEA_ERROR_RECORD_SECTION_DESCRIPTOR(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.SectionOffset = v_uint32()
self.SectionLength = v_uint32()
self.Revision = WHEA_REVISION()
self.ValidBits = WHEA_ERROR_RECORD_SECTION_DESCRIPTOR_VALIDBITS()
self.Reserved = v_uint8()
self.Flags = WHEA_ERROR_RECORD_SECTION_DESCRIPTOR_FLAGS()
self.SectionType = GUID()
self.FRUId = GUID()
self.SectionSeverity = v_uint32()
self.FRUText = vstruct.VArray([ v_uint8() for i in range(20) ])
class VK_TO_FUNCTION_TABLE(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Vk = v_uint8()
self.NLSFEProcType = v_uint8()
self.NLSFEProcCurrent = v_uint8()
self.NLSFEProcSwitch = v_uint8()
self.NLSFEProc = vstruct.VArray([ VK_FUNCTION_PARAM() for i in range(8) ])
self.NLSFEProcAlt = vstruct.VArray([ VK_FUNCTION_PARAM() for i in range(8) ])
class tagTHREADINFO(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.pEThread = v_ptr64()
self.RefCount = v_uint32()
self._pad0010 = v_bytes(size=4)
self.ptlW32 = v_ptr64()
self.pgdiDcattr = v_ptr64()
self.pgdiBrushAttr = v_ptr64()
self.pUMPDObjs = v_ptr64()
self.pUMPDHeap = v_ptr64()
self.pUMPDObj = v_ptr64()
self.pProxyPort = v_ptr64()
self.pClientID = v_ptr64()
self.GdiTmpTgoList = LIST_ENTRY()
self.pRBRecursionCount = v_uint32()
self.pNonRBRecursionCount = v_uint32()
self.tlSpriteState = TLSPRITESTATE()
self.pSpriteState = v_ptr64()
self.pDevHTInfo = v_ptr64()
self.ulDevHTInfoUniqueness = v_uint32()
self._pad0128 = v_bytes(size=4)
self.pdcoAA = v_ptr64()
self.pdcoRender = v_ptr64()
self.pdcoSrc = v_ptr64()
self.bEnableEngUpdateDeviceSurface = v_uint8()
self.bIncludeSprites = v_uint8()
self._pad0144 = v_bytes(size=2)
self.ulWindowSystemRendering = v_uint32()
self.iVisRgnUniqueness = v_uint32()
self._pad0150 = v_bytes(size=4)
self.ptl = v_ptr64()
self.ppi = v_ptr64()
self.pq = v_ptr64()
self.spklActive = v_ptr64()
self.pcti = v_ptr64()
self.rpdesk = v_ptr64()
self.pDeskInfo = v_ptr64()
self.ulClientDelta = v_uint64()
self.pClientInfo = v_ptr64()
self.TIF_flags = v_uint32()
self._pad01a0 = v_bytes(size=4)
self.pstrAppName = v_ptr64()
self.psmsSent = v_ptr64()
self.psmsCurrent = v_ptr64()
self.psmsReceiveList = v_ptr64()
self.timeLast = v_uint32()
self._pad01c8 = v_bytes(size=4)
self.idLast = v_uint64()
self.exitCode = v_uint32()
self._pad01d8 = v_bytes(size=4)
self.hdesk = v_ptr64()
self.cPaintsReady = v_uint32()
self.cTimersReady = v_uint32()
self.pMenuState = v_ptr64()
self.ptdb = v_ptr64()
self.psiiList = v_ptr64()
self.dwExpWinVer = v_uint32()
self.dwCompatFlags = v_uint32()
self.dwCompatFlags2 = v_uint32()
self._pad0210 = v_bytes(size=4)
self.pqAttach = v_ptr64()
self.ptiSibling = v_ptr64()
self.pmsd = v_ptr64()
self.fsHooks = v_uint32()
self._pad0230 = v_bytes(size=4)
self.sphkCurrent = v_ptr64()
self.lParamHkCurrent = v_uint64()
self.wParamHkCurrent = v_uint64()
self.pSBTrack = v_ptr64()
self.hEventQueueClient = v_ptr64()
self.pEventQueueServer = v_ptr64()
self.PtiLink = LIST_ENTRY()
self.iCursorLevel = v_uint32()
self.ptLast = tagPOINT()
self.ptLastReal = tagPOINT()
self._pad0288 = v_bytes(size=4)
self.spwndDefaultIme = v_ptr64()
self.spDefaultImc = v_ptr64()
self.hklPrev = v_ptr64()
self.cEnterCount = v_uint32()
self._pad02a8 = v_bytes(size=4)
self.mlPost = tagMLIST()
self.fsChangeBitsRemoved = v_uint16()
self.wchInjected = v_uint16()
self.fsReserveKeys = v_uint32()
self.apEvent = v_ptr64()
self.amdesk = v_uint32()
self.cWindows = v_uint32()
self.cVisWindows = v_uint32()
self._pad02e0 = v_bytes(size=4)
self.aphkStart = vstruct.VArray([ v_ptr64() for i in range(16) ])
self.cti = tagCLIENTTHREADINFO()
self.hPrevHidData = v_ptr64()
self.hTouchInputCurrent = v_ptr64()
self.hGestureInfoCurrent = v_ptr64()
self.MsgPPInfo = tagMSGPPINFO()
self.cNestedStableVisRgn = v_uint32()
self.readyHead = LIST_ENTRY()
self.fSpecialInitialization = v_uint32()
self._pad03a8 = v_bytes(size=4)
class D3DKMDT_VIDEO_SIGNAL_INFO(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.VideoStandard = v_uint32()
self.TotalSize = D3DKMDT_2DREGION()
self.ActiveSize = D3DKMDT_2DREGION()
self.VSyncFreq = D3DDDI_RATIONAL()
self.HSyncFreq = D3DDDI_RATIONAL()
self._pad0028 = v_bytes(size=4)
self.PixelRate = v_uint64()
self.ScanLineOrdering = v_uint32()
self._pad0038 = v_bytes(size=4)
class CM_PARTIAL_RESOURCE_LIST(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Version = v_uint16()
self.Revision = v_uint16()
self.Count = v_uint32()
self.PartialDescriptors = vstruct.VArray([ CM_PARTIAL_RESOURCE_DESCRIPTOR() for i in range(1) ])
class HGESTUREINFO(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.unused = v_uint32()
class DEVICE_CAPABILITIES(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Size = v_uint16()
self.Version = v_uint16()
self.DeviceD1 = v_uint32()
self.Address = v_uint32()
self.UINumber = v_uint32()
self.DeviceState = vstruct.VArray([ DEVICE_POWER_STATE() for i in range(7) ])
self.SystemWake = v_uint32()
self.DeviceWake = v_uint32()
self.D1Latency = v_uint32()
self.D2Latency = v_uint32()
self.D3Latency = v_uint32()
class tagMONITOR(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.head = HEAD()
self.pMonitorNext = v_ptr64()
self.dwMONFlags = v_uint32()
self.rcMonitorReal = tagRECT()
self.rcWorkReal = tagRECT()
self._pad0040 = v_bytes(size=4)
self.hrgnMonitorReal = v_ptr64()
self.Spare0 = v_uint16()
self.cWndStack = v_uint16()
self._pad0050 = v_bytes(size=4)
self.hDev = v_ptr64()
self.hDevReal = v_ptr64()
self.DockTargets = vstruct.VArray([ v_uint32() for i in range(7) ])
self._pad0080 = v_bytes(size=4)
self.Flink = v_ptr64()
self.Blink = v_ptr64()
class _unnamed_10363(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Length = v_uint32()
self._pad0008 = v_bytes(size=4)
self.FileInformationClass = v_uint32()
self._pad0010 = v_bytes(size=4)
self.FileObject = v_ptr64()
self.ReplaceIfExists = v_uint8()
self.AdvanceOnly = v_uint8()
self._pad0020 = v_bytes(size=6)
class KPROCESS(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
class DEVICE_OBJECT_POWER_EXTENSION(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
class tagTEXTMETRICW(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.tmHeight = v_uint32()
self.tmAscent = v_uint32()
self.tmDescent = v_uint32()
self.tmInternalLeading = v_uint32()
self.tmExternalLeading = v_uint32()
self.tmAveCharWidth = v_uint32()
self.tmMaxCharWidth = v_uint32()
self.tmWeight = v_uint32()
self.tmOverhang = v_uint32()
self.tmDigitizedAspectX = v_uint32()
self.tmDigitizedAspectY = v_uint32()
self.tmFirstChar = v_uint16()
self.tmLastChar = v_uint16()
self.tmDefaultChar = v_uint16()
self.tmBreakChar = v_uint16()
self.tmItalic = v_uint8()
self.tmUnderlined = v_uint8()
self.tmStruckOut = v_uint8()
self.tmPitchAndFamily = v_uint8()
self.tmCharSet = v_uint8()
self._pad003c = v_bytes(size=3)
class WHEA_ERROR_RECORD_SECTION_DESCRIPTOR_FLAGS(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Primary = v_uint32()
class TP_CALLBACK_ENVIRON_V3(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Version = v_uint32()
self._pad0008 = v_bytes(size=4)
self.Pool = v_ptr64()
self.CleanupGroup = v_ptr64()
self.CleanupGroupCancelCallback = v_ptr64()
self.RaceDll = v_ptr64()
self.ActivationContext = v_ptr64()
self.FinalizationCallback = v_ptr64()
self.u = _unnamed_9312()
self.CallbackPriority = v_uint32()
self.Size = v_uint32()
self._pad0048 = v_bytes(size=4)
class HDESK(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.unused = v_uint32()
class RTL_ACTIVATION_CONTEXT_STACK_FRAME(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Previous = v_ptr64()
self.ActivationContext = v_ptr64()
self.Flags = v_uint32()
self._pad0018 = v_bytes(size=4)
class OBJECT_HANDLE_INFORMATION(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.HandleAttributes = v_uint32()
self.GrantedAccess = v_uint32()
class DMA_OPERATIONS(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Size = v_uint32()
self._pad0008 = v_bytes(size=4)
self.PutDmaAdapter = v_ptr64()
self.AllocateCommonBuffer = v_ptr64()
self.FreeCommonBuffer = v_ptr64()
self.AllocateAdapterChannel = v_ptr64()
self.FlushAdapterBuffers = v_ptr64()
self.FreeAdapterChannel = v_ptr64()
self.FreeMapRegisters = v_ptr64()
self.MapTransfer = v_ptr64()
self.GetDmaAlignment = v_ptr64()
self.ReadDmaCounter = v_ptr64()
self.GetScatterGatherList = v_ptr64()
self.PutScatterGatherList = v_ptr64()
self.CalculateScatterGatherList = v_ptr64()
self.BuildScatterGatherList = v_ptr64()
self.BuildMdlFromScatterGatherList = v_ptr64()
class XSTATE_CONFIGURATION(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.EnabledFeatures = v_uint64()
self.Size = v_uint32()
self.OptimizedSave = v_uint32()
self.Features = vstruct.VArray([ XSTATE_FEATURE() for i in range(64) ])
class _unnamed_10357(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Length = v_uint32()
self._pad0008 = v_bytes(size=4)
self.CompletionFilter = v_uint32()
self._pad0010 = v_bytes(size=4)
class RTL_AVL_TABLE(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.BalancedRoot = RTL_BALANCED_LINKS()
self.OrderedPointer = v_ptr64()
self.WhichOrderedElement = v_uint32()
self.NumberGenericTableElements = v_uint32()
self.DepthOfTree = v_uint32()
self._pad0038 = v_bytes(size=4)
self.RestartKey = v_ptr64()
self.DeleteCount = v_uint32()
self._pad0048 = v_bytes(size=4)
self.CompareRoutine = v_ptr64()
self.AllocateRoutine = v_ptr64()
self.FreeRoutine = v_ptr64()
self.TableContext = v_ptr64()
class tagHID_TLC_INFO(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.link = LIST_ENTRY()
self.usUsagePage = v_uint16()
self.usUsage = v_uint16()
self.cDevices = v_uint32()
self.cDirectRequest = v_uint32()
self.cUsagePageRequest = v_uint32()
self.cExcludeRequest = v_uint32()
self.cExcludeOrphaned = v_uint32()
class WHEA_ERROR_PACKET_V2(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Signature = v_uint32()
self.Version = v_uint32()
self.Length = v_uint32()
self.Flags = WHEA_ERROR_PACKET_FLAGS()
self.ErrorType = v_uint32()
self.ErrorSeverity = v_uint32()
self.ErrorSourceId = v_uint32()
self.ErrorSourceType = v_uint32()
self.NotifyType = GUID()
self.Context = v_uint64()
self.DataFormat = v_uint32()
self.Reserved1 = v_uint32()
self.DataOffset = v_uint32()
self.DataLength = v_uint32()
self.PshedDataOffset = v_uint32()
self.PshedDataLength = v_uint32()
class DXGK_DIAG_HEADER(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Type = v_uint32()
self.Size = v_uint32()
self.LogTimestamp = v_uint64()
self.ProcessName = vstruct.VArray([ v_uint8() for i in range(16) ])
self.ThreadId = v_uint64()
self.Index = v_uint32()
self.WdLogIdx = v_uint32()
class DMM_VIDPNPATHANDTARGETMODESET_SERIALIZATION(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.PathInfo = D3DKMDT_VIDPN_PRESENT_PATH()
self.TargetModeSet = DMM_VIDPNTARGETMODESET_SERIALIZATION()
class VK_TO_WCHARS1(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.VirtualKey = v_uint8()
self.Attributes = v_uint8()
self.wch = vstruct.VArray([ v_uint16() for i in range(1) ])
class OWNER_ENTRY(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.OwnerThread = v_uint64()
self.IoPriorityBoosted = v_uint32()
self._pad0010 = v_bytes(size=4)
class DEVOBJ_EXTENSION(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Type = v_uint16()
self.Size = v_uint16()
self._pad0008 = v_bytes(size=4)
self.DeviceObject = v_ptr64()
self.PowerFlags = v_uint32()
self._pad0018 = v_bytes(size=4)
self.Dope = v_ptr64()
self.ExtensionFlags = v_uint32()
self._pad0028 = v_bytes(size=4)
self.DeviceNode = v_ptr64()
self.AttachedTo = v_ptr64()
self.StartIoCount = v_uint32()
self.StartIoKey = v_uint32()
self.StartIoFlags = v_uint32()
self._pad0048 = v_bytes(size=4)
self.Vpb = v_ptr64()
self.DependentList = LIST_ENTRY()
self.ProviderList = LIST_ENTRY()
class D3DKMDT_MONITOR_FREQUENCY_RANGE(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Origin = v_uint32()
self.RangeLimits = D3DKMDT_FREQUENCY_RANGE()
self.ConstraintType = v_uint32()
self.Constraint = _unnamed_11215()
class tagQ(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.mlInput = tagMLIST()
self.ptiSysLock = v_ptr64()
self.idSysLock = v_uint64()
self.idSysPeek = v_uint64()
self.ptiMouse = v_ptr64()
self.ptiKeyboard = v_ptr64()
self.spwndCapture = v_ptr64()
self.spwndFocus = v_ptr64()
self.spwndActive = v_ptr64()
self.spwndActivePrev = v_ptr64()
self.codeCapture = v_uint32()
self.msgDblClk = v_uint32()
self.xbtnDblClk = v_uint16()
self._pad006c = v_bytes(size=2)
self.timeDblClk = v_uint32()
self.hwndDblClk = v_ptr64()
self.ptDblClk = tagPOINT()
self.ptMouseMove = tagPOINT()
self.afKeyRecentDown = vstruct.VArray([ v_uint8() for i in range(32) ])
self.afKeyState = vstruct.VArray([ v_uint8() for i in range(64) ])
self.caret = tagCARET()
self.spcurCurrent = v_ptr64()
self.iCursorLevel = v_uint32()
self.QF_flags = v_uint32()
self.cThreads = v_uint16()
self.cLockCount = v_uint16()
self.msgJournal = v_uint32()
self.ExtraInfo = v_uint64()
self.ulEtwReserved1 = v_uint32()
self._pad0158 = v_bytes(size=4)
class _unnamed_10148(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.ListEntry = LIST_ENTRY()
self._pad0048 = v_bytes(size=56)
class CALLPROCDATA(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.head = PROCDESKHEAD()
self.spcpdNext = v_ptr64()
self.pfnClientPrevious = v_uint64()
self.wType = v_uint16()
self._pad0040 = v_bytes(size=6)
class WM_VALUES_STRINGS(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.pszName = v_ptr64()
self.fInternal = v_uint8()
self.fDefined = v_uint8()
self._pad0010 = v_bytes(size=6)
class MAILSLOT_CREATE_PARAMETERS(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.MailslotQuota = v_uint32()
self.MaximumMessageSize = v_uint32()
self.ReadTimeout = LARGE_INTEGER()
self.TimeoutSpecified = v_uint8()
self._pad0018 = v_bytes(size=7)
class HIMC(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.unused = v_uint32()
class _unnamed_10417(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Vpb = v_ptr64()
self.DeviceObject = v_ptr64()
class ACCESS_STATE(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.OperationID = LUID()
self.SecurityEvaluated = v_uint8()
self.GenerateAudit = v_uint8()
self.GenerateOnClose = v_uint8()
self.PrivilegesAllocated = v_uint8()
self.Flags = v_uint32()
self.RemainingDesiredAccess = v_uint32()
self.PreviouslyGrantedAccess = v_uint32()
self.OriginalDesiredAccess = v_uint32()
self._pad0020 = v_bytes(size=4)
self.SubjectSecurityContext = SECURITY_SUBJECT_CONTEXT()
self.SecurityDescriptor = v_ptr64()
self.AuxData = v_ptr64()
self.Privileges = _unnamed_10796()
self.AuditPrivileges = v_uint8()
self._pad0080 = v_bytes(size=3)
self.ObjectName = UNICODE_STRING()
self.ObjectTypeName = UNICODE_STRING()
class FILE_STANDARD_INFORMATION(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.AllocationSize = LARGE_INTEGER()
self.EndOfFile = LARGE_INTEGER()
self.NumberOfLinks = v_uint32()
self.DeletePending = v_uint8()
self.Directory = v_uint8()
self._pad0018 = v_bytes(size=2)
class _unnamed_9985(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Depth = v_uint64()
self.HeaderType = v_uint64()
class _unnamed_9984(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Depth = v_uint64()
self.HeaderType = v_uint64()
class _unnamed_9983(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Depth = v_uint64()
self.HeaderType = v_uint64()
class tagRECT(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.left = v_uint32()
self.top = v_uint32()
self.right = v_uint32()
self.bottom = v_uint32()
class GDI_TEB_BATCH(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Offset = v_uint32()
self._pad0008 = v_bytes(size=4)
self.HDC = v_uint64()
self.Buffer = vstruct.VArray([ v_uint32() for i in range(310) ])
class ECP_LIST(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
class _unnamed_13949(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Start = LARGE_INTEGER()
self.Length48 = v_uint32()
class tagMENUSTATE(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.pGlobalPopupMenu = v_ptr64()
self.fMenuStarted = v_uint32()
self.ptMouseLast = tagPOINT()
self.mnFocus = v_uint32()
self.cmdLast = v_uint32()
self._pad0020 = v_bytes(size=4)
self.ptiMenuStateOwner = v_ptr64()
self.dwLockCount = v_uint32()
self._pad0030 = v_bytes(size=4)
self.pmnsPrev = v_ptr64()
self.ptButtonDown = tagPOINT()
self.uButtonDownHitArea = v_uint64()
self.uButtonDownIndex = v_uint32()
self.vkButtonDown = v_uint32()
self.uDraggingHitArea = v_uint64()
self.uDraggingIndex = v_uint32()
self.uDraggingFlags = v_uint32()
self.hdcWndAni = v_ptr64()
self.dwAniStartTime = v_uint32()
self.ixAni = v_uint32()
self.iyAni = v_uint32()
self.cxAni = v_uint32()
self.cyAni = v_uint32()
self._pad0080 = v_bytes(size=4)
self.hbmAni = v_ptr64()
self.hdcAni = v_ptr64()
class SECTION_OBJECT_POINTERS(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.DataSectionObject = v_ptr64()
self.SharedCacheMap = v_ptr64()
self.ImageSectionObject = v_ptr64()
class MDL(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Next = v_ptr64()
self.Size = v_uint16()
self.MdlFlags = v_uint16()
self._pad0010 = v_bytes(size=4)
self.Process = v_ptr64()
self.MappedSystemVa = v_ptr64()
self.StartVa = v_ptr64()
self.ByteCount = v_uint32()
self.ByteOffset = v_uint32()
class tagMSGPPINFO(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.dwIndexMsgPP = v_uint32()
class _unnamed_13942(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.DataSize = v_uint32()
self.Reserved1 = v_uint32()
self.Reserved2 = v_uint32()
class VWPLELEMENT(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.DataOrTag = v_uint64()
self.pwnd = v_ptr64()
class _unnamed_13946(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Start = LARGE_INTEGER()
self.Length40 = v_uint32()
class IO_TIMER(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
class VSC_VK(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Vsc = v_uint8()
self._pad0002 = v_bytes(size=1)
self.Vk = v_uint16()
class WHEA_REVISION(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.MinorRevision = v_uint8()
self.MajorRevision = v_uint8()
class MAGNIFICATION_INPUT_TRANSFORM(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.rcSource = tagRECT()
self.rcScreen = tagRECT()
self.ptiMagThreadInfo = v_ptr64()
self.magFactorX = v_uint32()
self.magFactorY = v_uint32()
class TP_CLEANUP_GROUP(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
class DMM_VIDPNPATHANDTARGETMODE_SERIALIZATION(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.PathInfo = D3DKMDT_VIDPN_PRESENT_PATH()
self.TargetMode = D3DKMDT_VIDPN_TARGET_MODE()
class _unnamed_10483(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Capabilities = v_ptr64()
class D3DKMDT_VIDPN_PRESENT_PATH_COPYPROTECTION_SUPPORT(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.NoProtection = v_uint32()
class D3DDDI_DXGI_RGB(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Red = v_uint32()
self.Green = v_uint32()
self.Blue = v_uint32()
class OBJECT_TYPE_INITIALIZER(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Length = v_uint16()
self.ObjectTypeFlags = v_uint8()
self._pad0004 = v_bytes(size=1)
self.ObjectTypeCode = v_uint32()
self.InvalidAttributes = v_uint32()
self.GenericMapping = GENERIC_MAPPING()
self.ValidAccessMask = v_uint32()
self.RetainAccess = v_uint32()
self.PoolType = v_uint32()
self.DefaultPagedPoolCharge = v_uint32()
self.DefaultNonPagedPoolCharge = v_uint32()
self.DumpProcedure = v_ptr64()
self.OpenProcedure = v_ptr64()
self.CloseProcedure = v_ptr64()
self.DeleteProcedure = v_ptr64()
self.ParseProcedure = v_ptr64()
self.SecurityProcedure = v_ptr64()
self.QueryNameProcedure = v_ptr64()
self.OkayToCloseProcedure = v_ptr64()
class MOVESIZEDATA(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.spwnd = v_ptr64()
self.rcDrag = tagRECT()
self.rcDragCursor = tagRECT()
self.rcPreview = tagRECT()
self.rcPreviewCursor = tagRECT()
self.rcParent = tagRECT()
self.ptMinTrack = tagPOINT()
self.ptMaxTrack = tagPOINT()
self.rcWindow = tagRECT()
self.rcNormalStartCheckPt = tagRECT()
self.dxMouse = v_uint32()
self.dyMouse = v_uint32()
self.cmd = v_uint32()
self.impx = v_uint32()
self.impy = v_uint32()
self.ptRestore = tagPOINT()
self.Flags = v_uint32()
self.pStartMonitorCurrentHitTarget = v_ptr64()
self.StartCurrentHitTarget = v_uint32()
self._pad00b8 = v_bytes(size=4)
self.pMonitorCurrentHitTarget = v_ptr64()
self.CurrentHitTarget = v_uint32()
self.MoveRectStyle = v_uint32()
self.ptHitWindowRelative = tagPOINT()
self.ptStartHitWindowRelative = tagPOINT()
self.ptLastTrack = tagPOINT()
self.ulCountDragOutOfTopTarget = v_uint32()
self.ulCountDragOutOfLeftRightTarget = v_uint32()
self.ulCountSizeOutOfTopBottomTarget = v_uint32()
self._pad00f0 = v_bytes(size=4)
class TP_DIRECT(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Callback = v_ptr64()
self.NumaNode = v_uint32()
self.IdealProcessor = v_uint8()
self._pad0010 = v_bytes(size=3)
class LARGE_INTEGER(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.LowPart = v_uint32()
self.HighPart = v_uint32()
class _unnamed_13938(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Start = v_uint32()
self.Length = v_uint32()
self.Reserved = v_uint32()
class _unnamed_13936(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Data = vstruct.VArray([ v_uint32() for i in range(3) ])
class _unnamed_13932(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Channel = v_uint32()
self.Port = v_uint32()
self.Reserved1 = v_uint32()
class tagQMSG(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.pqmsgNext = v_ptr64()
self.pqmsgPrev = v_ptr64()
self.msg = tagMSG()
self.ExtraInfo = v_uint64()
self.ptMouseReal = tagPOINT()
self.dwQEvent = v_uint32()
self.Wow64Message = v_uint32()
self.pti = v_ptr64()
self.MsgPPInfo = tagMSGPPINFO()
self._pad0068 = v_bytes(size=4)
class PAGED_LOOKASIDE_LIST(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.L = GENERAL_LOOKASIDE()
class RTL_BITMAP(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.SizeOfBitMap = v_uint32()
self._pad0008 = v_bytes(size=4)
self.Buffer = v_ptr64()
class TLSPRITESTATE(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.bInsideDriverCall = v_uint8()
self._pad0004 = v_bytes(size=3)
self.flOriginalSurfFlags = v_uint32()
self.iOriginalType = v_uint32()
self.flSpriteSurfFlags = v_uint32()
self.iSpriteType = v_uint32()
self.flags = v_uint32()
self.iType = v_uint32()
self._pad0020 = v_bytes(size=4)
self.pState = v_ptr64()
self.pfnStrokeAndFillPath = v_ptr64()
self.pfnStrokePath = v_ptr64()
self.pfnFillPath = v_ptr64()
self.pfnPaint = v_ptr64()
self.pfnBitBlt = v_ptr64()
self.pfnCopyBits = v_ptr64()
self.pfnStretchBlt = v_ptr64()
self.pfnTextOut = v_ptr64()
self.pfnLineTo = v_ptr64()
self.pfnTransparentBlt = v_ptr64()
self.pfnAlphaBlend = v_ptr64()
self.pfnPlgBlt = v_ptr64()
self.pfnGradientFill = v_ptr64()
self.pfnSaveScreenBits = v_ptr64()
self.pfnStretchBltROP = v_ptr64()
self.pfnDrawStream = v_ptr64()
class HICON(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.unused = v_uint32()
class NPAGED_LOOKASIDE_LIST(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.L = GENERAL_LOOKASIDE()
class tagWin32PoolHead(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.size = v_uint64()
self.pPrev = v_ptr64()
self.pNext = v_ptr64()
self.pTrace = v_ptr64()
class VPB(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Type = v_uint16()
self.Size = v_uint16()
self.Flags = v_uint16()
self.VolumeLabelLength = v_uint16()
self.DeviceObject = v_ptr64()
self.RealDevice = v_ptr64()
self.SerialNumber = v_uint32()
self.ReferenceCount = v_uint32()
self.VolumeLabel = vstruct.VArray([ v_uint16() for i in range(32) ])
class tagTOUCHINPUT(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.x = v_uint32()
self.y = v_uint32()
self.hSource = v_ptr64()
self.dwID = v_uint32()
self.dwFlags = v_uint32()
self.dwMask = v_uint32()
self.dwTime = v_uint32()
self.dwExtraInfo = v_uint64()
self.cxContact = v_uint32()
self.cyContact = v_uint32()
class HEAD(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.h = v_ptr64()
self.cLockObj = v_uint32()
self._pad0010 = v_bytes(size=4)
class OBJECT_NAME_INFORMATION(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Name = UNICODE_STRING()
class IO_RESOURCE_LIST(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Version = v_uint16()
self.Revision = v_uint16()
self.Count = v_uint32()
self.Descriptors = vstruct.VArray([ IO_RESOURCE_DESCRIPTOR() for i in range(1) ])
class KUSER_SHARED_DATA(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.TickCountLowDeprecated = v_uint32()
self.TickCountMultiplier = v_uint32()
self.InterruptTime = KSYSTEM_TIME()
self.SystemTime = KSYSTEM_TIME()
self.TimeZoneBias = KSYSTEM_TIME()
self.ImageNumberLow = v_uint16()
self.ImageNumberHigh = v_uint16()
self.NtSystemRoot = vstruct.VArray([ v_uint16() for i in range(260) ])
self.MaxStackTraceDepth = v_uint32()
self.CryptoExponent = v_uint32()
self.TimeZoneId = v_uint32()
self.LargePageMinimum = v_uint32()
self.Reserved2 = vstruct.VArray([ v_uint32() for i in range(7) ])
self.NtProductType = v_uint32()
self.ProductTypeIsValid = v_uint8()
self._pad026c = v_bytes(size=3)
self.NtMajorVersion = v_uint32()
self.NtMinorVersion = v_uint32()
self.ProcessorFeatures = vstruct.VArray([ v_uint8() for i in range(64) ])
self.Reserved1 = v_uint32()
self.Reserved3 = v_uint32()
self.TimeSlip = v_uint32()
self.AlternativeArchitecture = v_uint32()
self.AltArchitecturePad = vstruct.VArray([ v_uint32() for i in range(1) ])
self.SystemExpirationDate = LARGE_INTEGER()
self.SuiteMask = v_uint32()
self.KdDebuggerEnabled = v_uint8()
self.NXSupportPolicy = v_uint8()
self._pad02d8 = v_bytes(size=2)
self.ActiveConsoleId = v_uint32()
self.DismountCount = v_uint32()
self.ComPlusPackage = v_uint32()
self.LastSystemRITEventTickCount = v_uint32()
self.NumberOfPhysicalPages = v_uint32()
self.SafeBootMode = v_uint8()
self.TscQpcData = v_uint8()
self.TscQpcPad = vstruct.VArray([ v_uint8() for i in range(2) ])
self.SharedDataFlags = v_uint32()
self.DataFlagsPad = vstruct.VArray([ v_uint32() for i in range(1) ])
self.TestRetInstruction = v_uint64()
self.SystemCall = v_uint32()
self.SystemCallReturn = v_uint32()
self.SystemCallPad = vstruct.VArray([ v_uint64() for i in range(3) ])
self.TickCount = KSYSTEM_TIME()
self.TickCountPad = vstruct.VArray([ v_uint32() for i in range(1) ])
self.Cookie = v_uint32()
self.CookiePad = vstruct.VArray([ v_uint32() for i in range(1) ])
self.ConsoleSessionForegroundProcessId = v_uint64()
self.Wow64SharedInformation = vstruct.VArray([ v_uint32() for i in range(16) ])
self.UserModeGlobalLogger = vstruct.VArray([ v_uint16() for i in range(16) ])
self.ImageFileExecutionOptions = v_uint32()
self.LangGenerationCount = v_uint32()
self.Reserved5 = v_uint64()
self.InterruptTimeBias = v_uint64()
self.TscQpcBias = v_uint64()
self.ActiveProcessorCount = v_uint32()
self.ActiveGroupCount = v_uint16()
self.Reserved4 = v_uint16()
self.AitSamplingValue = v_uint32()
self.AppCompatFlag = v_uint32()
self.SystemDllNativeRelocation = v_uint64()
self.SystemDllWowRelocation = v_uint32()
self.XStatePad = vstruct.VArray([ v_uint32() for i in range(1) ])
self.XState = XSTATE_CONFIGURATION()
class SYSTEM_POWER_STATE_CONTEXT(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Reserved1 = v_uint32()
class IO_STATUS_BLOCK(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Status = v_uint32()
self._pad0008 = v_bytes(size=4)
self.Information = v_uint64()
class PRIVILEGE_SET(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.PrivilegeCount = v_uint32()
self.Control = v_uint32()
self.Privilege = vstruct.VArray([ LUID_AND_ATTRIBUTES() for i in range(1) ])
class CM_RESOURCE_LIST(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Count = v_uint32()
self.List = vstruct.VArray([ CM_FULL_RESOURCE_DESCRIPTOR() for i in range(1) ])
class DMM_MONITOR_SOURCE_MODE_SERIALIZATION(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Info = D3DKMDT_MONITOR_SOURCE_MODE()
self.TimingType = v_uint32()
self._pad0068 = v_bytes(size=4)
class EPROCESS(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
class tagPROFILEVALUEINFO(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.dwValue = v_uint32()
self.uSection = v_uint32()
self.pwszKeyName = v_ptr64()
class tagDISPLAYINFO(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.hDev = v_ptr64()
self.pmdev = v_ptr64()
self.hDevInfo = v_ptr64()
self.hdcScreen = v_ptr64()
self.hdcBits = v_ptr64()
self.hdcGray = v_ptr64()
self.hbmGray = v_ptr64()
self.cxGray = v_uint32()
self.cyGray = v_uint32()
self.pdceFirst = v_ptr64()
self.pspbFirst = v_ptr64()
self.cMonitors = v_uint32()
self._pad0058 = v_bytes(size=4)
self.pMonitorPrimary = v_ptr64()
self.pMonitorFirst = v_ptr64()
self.rcScreenReal = tagRECT()
self.hrgnScreenReal = v_ptr64()
self.dmLogPixels = v_uint16()
self.BitCountMax = v_uint16()
self.fDesktopIsRect = v_uint32()
self.DockThresholdMax = v_uint32()
self._pad0090 = v_bytes(size=4)
self.SpatialListHead = KLIST_ENTRY()
self.cFullScreen = v_uint16()
self.Spare0 = v_uint16()
self._pad00a8 = v_bytes(size=4)
class TP_TASK(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Callbacks = v_ptr64()
self.NumaNode = v_uint32()
self.IdealProcessor = v_uint8()
self._pad0010 = v_bytes(size=3)
self.PostGuard = TP_NBQ_GUARD()
self.NBQNode = v_ptr64()
class PROCDESKHEAD(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.h = v_ptr64()
self.cLockObj = v_uint32()
self._pad0010 = v_bytes(size=4)
self.hTaskWow = v_uint32()
self._pad0018 = v_bytes(size=4)
self.rpdesk = v_ptr64()
self.pSelf = v_ptr64()
class PFNCLIENTWORKER(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.pfnButtonWndProc = v_ptr64()
self.pfnComboBoxWndProc = v_ptr64()
self.pfnComboListBoxProc = v_ptr64()
self.pfnDialogWndProc = v_ptr64()
self.pfnEditWndProc = v_ptr64()
self.pfnListBoxWndProc = v_ptr64()
self.pfnMDIClientWndProc = v_ptr64()
self.pfnStaticWndProc = v_ptr64()
self.pfnImeWndProc = v_ptr64()
self.pfnGhostWndProc = v_ptr64()
self.pfnCtfHookProc = v_ptr64()
class DMM_COMMITVIDPNREQUESTSET_SERIALIZATION(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.NumCommitVidPnRequests = v_uint8()
self._pad0004 = v_bytes(size=3)
self.CommitVidPnRequestOffset = vstruct.VArray([ v_uint32() for i in range(1) ])
class D3DKMDT_MONITOR_SOURCE_MODE(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Id = v_uint32()
self._pad0008 = v_bytes(size=4)
self.VideoSignalInfo = D3DKMDT_VIDEO_SIGNAL_INFO()
self.ColorBasis = v_uint32()
self.ColorCoeffDynamicRanges = D3DKMDT_COLOR_COEFF_DYNAMIC_RANGES()
self.Origin = v_uint32()
self.Preference = v_uint32()
self._pad0060 = v_bytes(size=4)
class _unnamed_11215(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.ActiveSize = D3DKMDT_2DREGION()
class CM_PARTIAL_RESOURCE_DESCRIPTOR(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Type = v_uint8()
self.ShareDisposition = v_uint8()
self.Flags = v_uint16()
self.u = _unnamed_13586()
class TP_CALLBACK_INSTANCE(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
class tagSBCALC(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.posMin = v_uint32()
self.posMax = v_uint32()
self.page = v_uint32()
self.pos = v_uint32()
self.pxTop = v_uint32()
self.pxBottom = v_uint32()
self.pxLeft = v_uint32()
self.pxRight = v_uint32()
self.cpxThumb = v_uint32()
self.pxUpArrow = v_uint32()
self.pxDownArrow = v_uint32()
self.pxStart = v_uint32()
self.pxThumbBottom = v_uint32()
self.pxThumbTop = v_uint32()
self.cpx = v_uint32()
self.pxMin = v_uint32()
class OBJECT_ATTRIBUTES(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Length = v_uint32()
self._pad0008 = v_bytes(size=4)
self.RootDirectory = v_ptr64()
self.ObjectName = v_ptr64()
self.Attributes = v_uint32()
self._pad0020 = v_bytes(size=4)
self.SecurityDescriptor = v_ptr64()
self.SecurityQualityOfService = v_ptr64()
class CM_FULL_RESOURCE_DESCRIPTOR(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.InterfaceType = v_uint32()
self.BusNumber = v_uint32()
self.PartialResourceList = CM_PARTIAL_RESOURCE_LIST()
class FAST_IO_DISPATCH(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.SizeOfFastIoDispatch = v_uint32()
self._pad0008 = v_bytes(size=4)
self.FastIoCheckIfPossible = v_ptr64()
self.FastIoRead = v_ptr64()
self.FastIoWrite = v_ptr64()
self.FastIoQueryBasicInfo = v_ptr64()
self.FastIoQueryStandardInfo = v_ptr64()
self.FastIoLock = v_ptr64()
self.FastIoUnlockSingle = v_ptr64()
self.FastIoUnlockAll = v_ptr64()
self.FastIoUnlockAllByKey = v_ptr64()
self.FastIoDeviceControl = v_ptr64()
self.AcquireFileForNtCreateSection = v_ptr64()
self.ReleaseFileForNtCreateSection = v_ptr64()
self.FastIoDetachDevice = v_ptr64()
self.FastIoQueryNetworkOpenInfo = v_ptr64()
self.AcquireForModWrite = v_ptr64()
self.MdlRead = v_ptr64()
self.MdlReadComplete = v_ptr64()
self.PrepareMdlWrite = v_ptr64()
self.MdlWriteComplete = v_ptr64()
self.FastIoReadCompressed = v_ptr64()
self.FastIoWriteCompressed = v_ptr64()
self.MdlReadCompleteCompressed = v_ptr64()
self.MdlWriteCompleteCompressed = v_ptr64()
self.FastIoQueryOpen = v_ptr64()
self.ReleaseForModWrite = v_ptr64()
self.AcquireForCcFlush = v_ptr64()
self.ReleaseForCcFlush = v_ptr64()
class tagPROCESS_HID_REQUEST(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.link = LIST_ENTRY()
self.usUsagePage = v_uint16()
self.usUsage = v_uint16()
self.fSinkable = v_uint32()
self.pTLCInfo = v_ptr64()
self.spwndTarget = v_ptr64()
class KFLOATING_SAVE(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Dummy = v_uint32()
class RTL_DYNAMIC_HASH_TABLE_CONTEXT(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.ChainHead = v_ptr64()
self.PrevLinkage = v_ptr64()
self.Signature = v_uint64()
class tagSBDATA(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.posMin = v_uint32()
self.posMax = v_uint32()
self.page = v_uint32()
self.pos = v_uint32()
class D3DDDI_GAMMA_RAMP_RGB256x3x16(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Red = vstruct.VArray([ v_uint16() for i in range(256) ])
self.Green = vstruct.VArray([ v_uint16() for i in range(256) ])
self.Blue = vstruct.VArray([ v_uint16() for i in range(256) ])
class tagUAHMENUPOPUPMETRICS(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.rgcx = vstruct.VArray([ v_uint32() for i in range(4) ])
self.fUpdateMaxWidths = v_uint32()
class _unnamed_10527(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.InPath = v_uint8()
self.Reserved = vstruct.VArray([ v_uint8() for i in range(3) ])
self._pad0008 = v_bytes(size=4)
self.Type = v_uint32()
self._pad0010 = v_bytes(size=4)
class THROBJHEAD(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.h = v_ptr64()
self.cLockObj = v_uint32()
self._pad0010 = v_bytes(size=4)
self.pti = v_ptr64()
class DMM_VIDPNTARGETMODESET_SERIALIZATION(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.NumModes = v_uint8()
self._pad0008 = v_bytes(size=7)
self.ModeSerialization = vstruct.VArray([ D3DKMDT_VIDPN_TARGET_MODE() for i in range(1) ])
class KGDTENTRY64(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.LimitLow = v_uint16()
self.BaseLow = v_uint16()
self.Bytes = _unnamed_9807()
self.BaseUpper = v_uint32()
self.MustBeZero = v_uint32()
class KSPECIAL_REGISTERS(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Cr0 = v_uint64()
self.Cr2 = v_uint64()
self.Cr3 = v_uint64()
self.Cr4 = v_uint64()
self.KernelDr0 = v_uint64()
self.KernelDr1 = v_uint64()
self.KernelDr2 = v_uint64()
self.KernelDr3 = v_uint64()
self.KernelDr6 = v_uint64()
self.KernelDr7 = v_uint64()
self.Gdtr = KDESCRIPTOR()
self.Idtr = KDESCRIPTOR()
self.Tr = v_uint16()
self.Ldtr = v_uint16()
self.MxCsr = v_uint32()
self.DebugControl = v_uint64()
self.LastBranchToRip = v_uint64()
self.LastBranchFromRip = v_uint64()
self.LastExceptionToRip = v_uint64()
self.LastExceptionFromRip = v_uint64()
self.Cr8 = v_uint64()
self.MsrGsBase = v_uint64()
self.MsrGsSwap = v_uint64()
self.MsrStar = v_uint64()
self.MsrLStar = v_uint64()
self.MsrCStar = v_uint64()
self.MsrSyscallMask = v_uint64()
class _unnamed_10441(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.InterfaceType = v_ptr64()
self.Size = v_uint16()
self.Version = v_uint16()
self._pad0010 = v_bytes(size=4)
self.Interface = v_ptr64()
self.InterfaceSpecificData = v_ptr64()
class TP_NBQ_GUARD(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.GuardLinks = LIST_ENTRY()
self.Guards = vstruct.VArray([ v_ptr64() for i in range(2) ])
class RTL_CRITICAL_SECTION(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.DebugInfo = v_ptr64()
self.LockCount = v_uint32()
self.RecursionCount = v_uint32()
self.OwningThread = v_ptr64()
self.LockSemaphore = v_ptr64()
self.SpinCount = v_uint64()
class KSYSTEM_TIME(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.LowPart = v_uint32()
self.High1Time = v_uint32()
self.High2Time = v_uint32()
class DMA_ADAPTER(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Version = v_uint16()
self.Size = v_uint16()
self._pad0008 = v_bytes(size=4)
self.DmaOperations = v_ptr64()
class WNDMSG(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.maxMsgs = v_uint32()
self._pad0008 = v_bytes(size=4)
self.abMsgs = v_ptr64()
class D3DDDI_RATIONAL(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Numerator = v_uint32()
self.Denominator = v_uint32()
class LUID_AND_ATTRIBUTES(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Luid = LUID()
self.Attributes = v_uint32()
class IMAGE_NT_HEADERS64(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Signature = v_uint32()
self.FileHeader = IMAGE_FILE_HEADER()
self.OptionalHeader = IMAGE_OPTIONAL_HEADER64()
class tagSBTRACK(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.fHitOld = v_uint32()
self._pad0008 = v_bytes(size=4)
self.spwndTrack = v_ptr64()
self.spwndSB = v_ptr64()
self.spwndSBNotify = v_ptr64()
self.rcTrack = tagRECT()
self.xxxpfnSB = v_ptr64()
self.cmdSB = v_uint32()
self._pad0040 = v_bytes(size=4)
self.hTimerSB = v_uint64()
self.dpxThumb = v_uint32()
self.pxOld = v_uint32()
self.posOld = v_uint32()
self.posNew = v_uint32()
self.nBar = v_uint32()
self._pad0060 = v_bytes(size=4)
self.pSBCalc = v_ptr64()
class KTHREAD(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
class HFONT(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.unused = v_uint32()
class tagDPISERVERINFO(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.gclBorder = v_uint32()
self._pad0008 = v_bytes(size=4)
self.hCaptionFont = v_ptr64()
self.hMsgFont = v_ptr64()
self.cxMsgFontChar = v_uint32()
self.cyMsgFontChar = v_uint32()
self.wMaxBtnSize = v_uint32()
self._pad0028 = v_bytes(size=4)
class HDC(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.unused = v_uint32()
class CONTEXT(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.P1Home = v_uint64()
self.P2Home = v_uint64()
self.P3Home = v_uint64()
self.P4Home = v_uint64()
self.P5Home = v_uint64()
self.P6Home = v_uint64()
self.ContextFlags = v_uint32()
self.MxCsr = v_uint32()
self.SegCs = v_uint16()
self.SegDs = v_uint16()
self.SegEs = v_uint16()
self.SegFs = v_uint16()
self.SegGs = v_uint16()
self.SegSs = v_uint16()
self.EFlags = v_uint32()
self.Dr0 = v_uint64()
self.Dr1 = v_uint64()
self.Dr2 = v_uint64()
self.Dr3 = v_uint64()
self.Dr6 = v_uint64()
self.Dr7 = v_uint64()
self.Rax = v_uint64()
self.Rcx = v_uint64()
self.Rdx = v_uint64()
self.Rbx = v_uint64()
self.Rsp = v_uint64()
self.Rbp = v_uint64()
self.Rsi = v_uint64()
self.Rdi = v_uint64()
self.R8 = v_uint64()
self.R9 = v_uint64()
self.R10 = v_uint64()
self.R11 = v_uint64()
self.R12 = v_uint64()
self.R13 = v_uint64()
self.R14 = v_uint64()
self.R15 = v_uint64()
self.Rip = v_uint64()
self.FltSave = XSAVE_FORMAT()
self.VectorRegister = vstruct.VArray([ M128A() for i in range(26) ])
self.VectorControl = v_uint64()
self.DebugControl = v_uint64()
self.LastBranchToRip = v_uint64()
self.LastBranchFromRip = v_uint64()
self.LastExceptionToRip = v_uint64()
self.LastExceptionFromRip = v_uint64()
class WAIT_CONTEXT_BLOCK(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.WaitQueueEntry = KDEVICE_QUEUE_ENTRY()
self.DeviceRoutine = v_ptr64()
self.DeviceContext = v_ptr64()
self.NumberOfMapRegisters = v_uint32()
self._pad0030 = v_bytes(size=4)
self.DeviceObject = v_ptr64()
self.CurrentIrp = v_ptr64()
self.BufferChainingDpc = v_ptr64()
class AUX_ACCESS_DATA(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.PrivilegesUsed = v_ptr64()
self.GenericMapping = GENERIC_MAPPING()
self.AccessesToAudit = v_uint32()
self.MaximumAuditMask = v_uint32()
self.TransactionId = GUID()
self.NewSecurityDescriptor = v_ptr64()
self.ExistingSecurityDescriptor = v_ptr64()
self.ParentSecurityDescriptor = v_ptr64()
self.DeRefSecurityDescriptor = v_ptr64()
self.SDLock = v_ptr64()
self.AccessReasons = ACCESS_REASONS()
class LIGATURE1(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.VirtualKey = v_uint8()
self._pad0002 = v_bytes(size=1)
self.ModificationNumber = v_uint16()
self.wch = vstruct.VArray([ v_uint16() for i in range(1) ])
class D3DKMDT_VIDPN_PRESENT_PATH_SCALING_SUPPORT(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Identity = v_uint32()
class EVENT_DATA_DESCRIPTOR(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Ptr = v_uint64()
self.Size = v_uint32()
self.Reserved = v_uint32()
class TEB_ACTIVE_FRAME_CONTEXT(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Flags = v_uint32()
self._pad0008 = v_bytes(size=4)
self.FrameName = v_ptr64()
class DRIVER_OBJECT(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Type = v_uint16()
self.Size = v_uint16()
self._pad0008 = v_bytes(size=4)
self.DeviceObject = v_ptr64()
self.Flags = v_uint32()
self._pad0018 = v_bytes(size=4)
self.DriverStart = v_ptr64()
self.DriverSize = v_uint32()
self._pad0028 = v_bytes(size=4)
self.DriverSection = v_ptr64()
self.DriverExtension = v_ptr64()
self.DriverName = UNICODE_STRING()
self.HardwareDatabase = v_ptr64()
self.FastIoDispatch = v_ptr64()
self.DriverInit = v_ptr64()
self.DriverStartIo = v_ptr64()
self.DriverUnload = v_ptr64()
self.MajorFunction = vstruct.VArray([ v_ptr64() for i in range(28) ])
class HMONITOR(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.unused = v_uint32()
class EJOB(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
class D3DKMDT_GAMMA_RAMP(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Type = v_uint32()
self._pad0008 = v_bytes(size=4)
self.DataSize = v_uint64()
self.Data = _unnamed_13776()
class VK_TO_BIT(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Vk = v_uint8()
self.ModBits = v_uint8()
class KPROCESSOR_STATE(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.SpecialRegisters = KSPECIAL_REGISTERS()
self._pad00e0 = v_bytes(size=8)
self.ContextFrame = CONTEXT()
class KAPC(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Type = v_uint8()
self.SpareByte0 = v_uint8()
self.Size = v_uint8()
self.SpareByte1 = v_uint8()
self.SpareLong0 = v_uint32()
self.Thread = v_ptr64()
self.ApcListEntry = LIST_ENTRY()
self.KernelRoutine = v_ptr64()
self.RundownRoutine = v_ptr64()
self.NormalRoutine = v_ptr64()
self.NormalContext = v_ptr64()
self.SystemArgument1 = v_ptr64()
self.SystemArgument2 = v_ptr64()
self.ApcStateIndex = v_uint8()
self.ApcMode = v_uint8()
self.Inserted = v_uint8()
self._pad0058 = v_bytes(size=5)
class tagIMEINFOEX(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.hkl = v_ptr64()
self.ImeInfo = tagIMEINFO()
self.wszUIClass = vstruct.VArray([ v_uint16() for i in range(16) ])
self.fdwInitConvMode = v_uint32()
self.fInitOpen = v_uint32()
self.fLoadFlag = v_uint32()
self.dwProdVersion = v_uint32()
self.dwImeWinVersion = v_uint32()
self.wszImeDescription = vstruct.VArray([ v_uint16() for i in range(50) ])
self.wszImeFile = vstruct.VArray([ v_uint16() for i in range(80) ])
self.fSysWow64Only = v_uint32()
class D3DKMDT_FREQUENCY_RANGE(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.MinVSyncFreq = D3DDDI_RATIONAL()
self.MaxVSyncFreq = D3DDDI_RATIONAL()
self.MinHSyncFreq = D3DDDI_RATIONAL()
self.MaxHSyncFreq = D3DDDI_RATIONAL()
class _unnamed_10432(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Type = v_uint32()
class tagWND(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.head = THRDESKHEAD()
self.state = v_uint32()
self.state2 = v_uint32()
self.ExStyle = v_uint32()
self.style = v_uint32()
self.hModule = v_ptr64()
self.hMod16 = v_uint16()
self.fnid = v_uint16()
self._pad0048 = v_bytes(size=4)
self.spwndNext = v_ptr64()
self.spwndPrev = v_ptr64()
self.spwndParent = v_ptr64()
self.spwndChild = v_ptr64()
self.spwndOwner = v_ptr64()
self.rcWindow = tagRECT()
self.rcClient = tagRECT()
self.lpfnWndProc = v_ptr64()
self.pcls = v_ptr64()
self.hrgnUpdate = v_ptr64()
self.ppropList = v_ptr64()
self.pSBInfo = v_ptr64()
self.spmenuSys = v_ptr64()
self.spmenu = v_ptr64()
self.hrgnClip = v_ptr64()
self.hrgnNewFrame = v_ptr64()
self.strName = LARGE_UNICODE_STRING()
self.cbwndExtra = v_uint32()
self._pad00f0 = v_bytes(size=4)
self.spwndLastActive = v_ptr64()
self.hImc = v_ptr64()
self.dwUserData = v_uint64()
self.pActCtx = v_ptr64()
self.pTransform = v_ptr64()
self.spwndClipboardListenerNext = v_ptr64()
self.ExStyle2 = v_uint32()
self._pad0128 = v_bytes(size=4)
class _unnamed_14496(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Length48 = v_uint32()
self.Alignment48 = v_uint32()
self.MinimumAddress = LARGE_INTEGER()
self.MaximumAddress = LARGE_INTEGER()
class XSTATE_FEATURE(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Offset = v_uint32()
self.Size = v_uint32()
class D3DDDI_GAMMA_RAMP_DXGI_1(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Scale = D3DDDI_DXGI_RGB()
self.Offset = D3DDDI_DXGI_RGB()
self.GammaCurve = vstruct.VArray([ D3DDDI_DXGI_RGB() for i in range(1025) ])
class WHEA_TIMESTAMP(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Seconds = v_uint64()
class ACTIVATION_CONTEXT(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
class tagUAHMENUITEMMETRICS(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.rgsizeBar = vstruct.VArray([ tagSIZE() for i in range(2) ])
self._pad0020 = v_bytes(size=16)
class KLIST_ENTRY(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Flink = v_ptr64()
self.Blink = v_ptr64()
class _unnamed_10401(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.SecurityInformation = v_uint32()
self._pad0008 = v_bytes(size=4)
self.Length = v_uint32()
self._pad0010 = v_bytes(size=4)
class _unnamed_10404(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.SecurityInformation = v_uint32()
self._pad0008 = v_bytes(size=4)
self.SecurityDescriptor = v_ptr64()
class RTL_CRITICAL_SECTION_DEBUG(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Type = v_uint16()
self.CreatorBackTraceIndex = v_uint16()
self._pad0008 = v_bytes(size=4)
self.CriticalSection = v_ptr64()
self.ProcessLocksList = LIST_ENTRY()
self.EntryCount = v_uint32()
self.ContentionCount = v_uint32()
self.Flags = v_uint32()
self.CreatorBackTraceIndexHigh = v_uint16()
self.SpareUSHORT = v_uint16()
class DISPATCHER_HEADER(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Type = v_uint8()
self.TimerControlFlags = v_uint8()
self.ThreadControlFlags = v_uint8()
self.TimerMiscFlags = v_uint8()
self.SignalState = v_uint32()
self.WaitListHead = LIST_ENTRY()
class HBITMAP(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.unused = v_uint32()
class tagW32JOB(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.pNext = v_ptr64()
self.Job = v_ptr64()
self.pAtomTable = v_ptr64()
self.restrictions = v_uint32()
self.uProcessCount = v_uint32()
self.uMaxProcesses = v_uint32()
self._pad0028 = v_bytes(size=4)
self.ppiTable = v_ptr64()
self.ughCrt = v_uint32()
self.ughMax = v_uint32()
self.pgh = v_ptr64()
class ASSEMBLY_STORAGE_MAP(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
class tagMBSTRING(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.szName = vstruct.VArray([ v_uint16() for i in range(15) ])
self._pad0020 = v_bytes(size=2)
self.uID = v_uint32()
self.uStr = v_uint32()
class POWER_SEQUENCE(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.SequenceD1 = v_uint32()
self.SequenceD2 = v_uint32()
self.SequenceD3 = v_uint32()
class DMM_MONITORDESCRIPTOR_SERIALIZATION(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Id = v_uint32()
self.Type = v_uint32()
self.Origin = v_uint32()
self.Data = vstruct.VArray([ v_uint8() for i in range(128) ])
class tagCLS(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.pclsNext = v_ptr64()
self.atomClassName = v_uint16()
self.atomNVClassName = v_uint16()
self.fnid = v_uint16()
self._pad0010 = v_bytes(size=2)
self.rpdeskParent = v_ptr64()
self.pdce = v_ptr64()
self.hTaskWow = v_uint16()
self.CSF_flags = v_uint16()
self._pad0028 = v_bytes(size=4)
self.lpszClientAnsiMenuName = v_ptr64()
self.lpszClientUnicodeMenuName = v_ptr64()
self.spcpdFirst = v_ptr64()
self.pclsBase = v_ptr64()
self.pclsClone = v_ptr64()
self.cWndReferenceCount = v_uint32()
self.style = v_uint32()
self.lpfnWndProc = v_ptr64()
self.cbclsExtra = v_uint32()
self.cbwndExtra = v_uint32()
self.hModule = v_ptr64()
self.spicn = v_ptr64()
self.spcur = v_ptr64()
self.hbrBackground = v_ptr64()
self.lpszMenuName = v_ptr64()
self.lpszAnsiClassName = v_ptr64()
self.spicnSm = v_ptr64()
class SM_VALUES_STRINGS(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.pszName = v_ptr64()
self.ulValue = v_uint32()
self.RangeType = v_uint32()
self.StorageType = v_uint32()
self._pad0018 = v_bytes(size=4)
class HBRUSH(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.unused = v_uint32()
class SECURITY_QUALITY_OF_SERVICE(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Length = v_uint32()
self.ImpersonationLevel = v_uint32()
self.ContextTrackingMode = v_uint8()
self.EffectiveOnly = v_uint8()
self._pad000c = v_bytes(size=2)
class COMPRESSED_DATA_INFO(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.CompressionFormatAndEngine = v_uint16()
self.CompressionUnitShift = v_uint8()
self.ChunkShift = v_uint8()
self.ClusterShift = v_uint8()
self.Reserved = v_uint8()
self.NumberOfChunks = v_uint16()
self.CompressedChunkSizes = vstruct.VArray([ v_uint32() for i in range(1) ])
class WHEA_ERROR_RECORD(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Header = WHEA_ERROR_RECORD_HEADER()
self.SectionDescriptor = vstruct.VArray([ WHEA_ERROR_RECORD_SECTION_DESCRIPTOR() for i in range(1) ])
class _unnamed_10572(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.SystemContext = v_uint32()
self._pad0008 = v_bytes(size=4)
self.Type = v_uint32()
self._pad0010 = v_bytes(size=4)
self.State = POWER_STATE()
self._pad0018 = v_bytes(size=4)
self.ShutdownType = v_uint32()
self._pad0020 = v_bytes(size=4)
class LUID(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.LowPart = v_uint32()
self.HighPart = v_uint32()
class tagDESKTOP(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.dwSessionId = v_uint32()
self._pad0008 = v_bytes(size=4)
self.pDeskInfo = v_ptr64()
self.pDispInfo = v_ptr64()
self.rpdeskNext = v_ptr64()
self.rpwinstaParent = v_ptr64()
self.dwDTFlags = v_uint32()
self._pad0030 = v_bytes(size=4)
self.dwDesktopId = v_uint64()
self.spmenuSys = v_ptr64()
self.spmenuDialogSys = v_ptr64()
self.spmenuHScroll = v_ptr64()
self.spmenuVScroll = v_ptr64()
self.spwndForeground = v_ptr64()
self.spwndTray = v_ptr64()
self.spwndMessage = v_ptr64()
self.spwndTooltip = v_ptr64()
self.hsectionDesktop = v_ptr64()
self.pheapDesktop = v_ptr64()
self.ulHeapSize = v_uint32()
self._pad0090 = v_bytes(size=4)
self.cciConsole = CONSOLE_CARET_INFO()
self.PtiList = LIST_ENTRY()
self.spwndTrack = v_ptr64()
self.htEx = v_uint32()
self.rcMouseHover = tagRECT()
self.dwMouseHoverTime = v_uint32()
self.pMagInputTransform = v_ptr64()
class tagPOOLRECORD(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.ExtraData = v_ptr64()
self.size = v_uint64()
self.trace = vstruct.VArray([ v_ptr64() for i in range(6) ])
class CLIENT_ID(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.UniqueProcess = v_ptr64()
self.UniqueThread = v_ptr64()
class IMAGE_OPTIONAL_HEADER64(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Magic = v_uint16()
self.MajorLinkerVersion = v_uint8()
self.MinorLinkerVersion = v_uint8()
self.SizeOfCode = v_uint32()
self.SizeOfInitializedData = v_uint32()
self.SizeOfUninitializedData = v_uint32()
self.AddressOfEntryPoint = v_uint32()
self.BaseOfCode = v_uint32()
self.ImageBase = v_uint64()
self.SectionAlignment = v_uint32()
self.FileAlignment = v_uint32()
self.MajorOperatingSystemVersion = v_uint16()
self.MinorOperatingSystemVersion = v_uint16()
self.MajorImageVersion = v_uint16()
self.MinorImageVersion = v_uint16()
self.MajorSubsystemVersion = v_uint16()
self.MinorSubsystemVersion = v_uint16()
self.Win32VersionValue = v_uint32()
self.SizeOfImage = v_uint32()
self.SizeOfHeaders = v_uint32()
self.CheckSum = v_uint32()
self.Subsystem = v_uint16()
self.DllCharacteristics = v_uint16()
self.SizeOfStackReserve = v_uint64()
self.SizeOfStackCommit = v_uint64()
self.SizeOfHeapReserve = v_uint64()
self.SizeOfHeapCommit = v_uint64()
self.LoaderFlags = v_uint32()
self.NumberOfRvaAndSizes = v_uint32()
self.DataDirectory = vstruct.VArray([ IMAGE_DATA_DIRECTORY() for i in range(16) ])
class OBJECT_DUMP_CONTROL(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Stream = v_ptr64()
self.Detail = v_uint32()
self._pad0010 = v_bytes(size=4)
class _unnamed_10089(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.AsynchronousParameters = _unnamed_10107()
class GENERAL_LOOKASIDE_POOL(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.ListHead = SLIST_HEADER()
self.Depth = v_uint16()
self.MaximumDepth = v_uint16()
self.TotalAllocates = v_uint32()
self.AllocateMisses = v_uint32()
self.TotalFrees = v_uint32()
self.FreeMisses = v_uint32()
self.Type = v_uint32()
self.Tag = v_uint32()
self.Size = v_uint32()
self.AllocateEx = v_ptr64()
self.FreeEx = v_ptr64()
self.ListEntry = LIST_ENTRY()
self.LastTotalAllocates = v_uint32()
self.LastAllocateMisses = v_uint32()
self.Future = vstruct.VArray([ v_uint32() for i in range(2) ])
class tagSPB(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.pspbNext = v_ptr64()
self.spwnd = v_ptr64()
self.hbm = v_ptr64()
self.rc = tagRECT()
self.hrgn = v_ptr64()
self.flags = v_uint32()
self._pad0038 = v_bytes(size=4)
self.ulSaveId = v_uint64()
class _unnamed_13929(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Raw = _unnamed_13924()
class _unnamed_13924(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Group = v_uint16()
self.MessageCount = v_uint16()
self.Vector = v_uint32()
self.Affinity = v_uint64()
class DMM_VIDPNSET_SERIALIZATION(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.NumVidPns = v_uint8()
self._pad0004 = v_bytes(size=3)
self.VidPnOffset = vstruct.VArray([ v_uint32() for i in range(1) ])
class STRING(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Length = v_uint16()
self.MaximumLength = v_uint16()
self._pad0008 = v_bytes(size=4)
self.Buffer = v_ptr64()
class TP_POOL(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
class _unnamed_9282(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.LowPart = v_uint32()
self.HighPart = v_uint32()
class tagPROP(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.hData = v_ptr64()
self.atomKey = v_uint16()
self.fs = v_uint16()
self._pad0010 = v_bytes(size=4)
class LIST_ENTRY32(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Flink = v_uint32()
self.Blink = v_uint32()
class KDESCRIPTOR(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Pad = vstruct.VArray([ v_uint16() for i in range(3) ])
self.Limit = v_uint16()
self.Base = v_ptr64()
class _unnamed_10583(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.AllocatedResources = v_ptr64()
self.AllocatedResourcesTranslated = v_ptr64()
class SINGLE_LIST_ENTRY(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Next = v_ptr64()
class _unnamed_10587(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.ProviderId = v_uint64()
self.DataPath = v_ptr64()
self.BufferSize = v_uint32()
self._pad0018 = v_bytes(size=4)
self.Buffer = v_ptr64()
class CONTEXT32_UPDATE(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.NumberEntries = v_uint32()
class KDEVICE_QUEUE_ENTRY(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.DeviceListEntry = LIST_ENTRY()
self.SortKey = v_uint32()
self.Inserted = v_uint8()
self._pad0018 = v_bytes(size=3)
class D3DKMDT_VIDPN_SOURCE_MODE(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Id = v_uint32()
self.Type = v_uint32()
self.Format = _unnamed_11143()
class tagCLIENTTHREADINFO(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.CTIF_flags = v_uint32()
self.fsChangeBits = v_uint16()
self.fsWakeBits = v_uint16()
self.fsWakeBitsJournal = v_uint16()
self.fsWakeMask = v_uint16()
self.tickLastMsgChecked = v_uint32()
class tagKbdNlsLayer(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.OEMIdentifier = v_uint16()
self.LayoutInformation = v_uint16()
self.NumOfVkToF = v_uint32()
self.pVkToF = v_ptr64()
self.NumOfMouseVKey = v_uint32()
self._pad0018 = v_bytes(size=4)
self.pusMouseVKey = v_ptr64()
class KSPIN_LOCK_QUEUE(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Next = v_ptr64()
self.Lock = v_ptr64()
class tagPROCESS_HID_TABLE(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.link = LIST_ENTRY()
self.InclusionList = LIST_ENTRY()
self.UsagePageList = LIST_ENTRY()
self.ExclusionList = LIST_ENTRY()
self.spwndTargetMouse = v_ptr64()
self.spwndTargetKbd = v_ptr64()
self.nSinks = v_uint32()
self._pad0058 = v_bytes(size=4)
self.pLastRequest = v_ptr64()
self.UsagePageLast = v_uint16()
self.UsageLast = v_uint16()
self.fRawMouse = v_uint32()
class WHEA_ERROR_PACKET_FLAGS(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.PreviousError = v_uint32()
class _unnamed_10351(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Length = v_uint32()
self._pad0008 = v_bytes(size=4)
self.FileName = v_ptr64()
self.FileInformationClass = v_uint32()
self._pad0018 = v_bytes(size=4)
self.FileIndex = v_uint32()
self._pad0020 = v_bytes(size=4)
class WHEA_PERSISTENCE_INFO(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Signature = v_uint64()
class EX_PUSH_LOCK_CACHE_AWARE(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Locks = vstruct.VArray([ v_ptr64() for i in range(1) ])
class tagMLIST(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.pqmsgRead = v_ptr64()
self.pqmsgWriteLast = v_ptr64()
self.cMsgs = v_uint32()
self._pad0018 = v_bytes(size=4)
class _unnamed_10290(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Length = v_uint32()
self._pad0008 = v_bytes(size=4)
self.Key = v_uint32()
self._pad0010 = v_bytes(size=4)
self.ByteOffset = LARGE_INTEGER()
class DMM_MONITORDESCRIPTORSET_SERIALIZATION(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.NumDescriptors = v_uint8()
self._pad0004 = v_bytes(size=3)
self.DescriptorSerialization = vstruct.VArray([ DMM_MONITORDESCRIPTOR_SERIALIZATION() for i in range(1) ])
class tagCLIP(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.fmt = v_uint32()
self._pad0008 = v_bytes(size=4)
self.hData = v_ptr64()
self.fGlobalHandle = v_uint32()
self._pad0018 = v_bytes(size=4)
class tagSMS(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.psmsNext = v_ptr64()
self.psmsReceiveNext = v_ptr64()
self.ptiSender = v_ptr64()
self.ptiReceiver = v_ptr64()
self.lpResultCallBack = v_ptr64()
self.dwData = v_uint64()
self.ptiCallBackSender = v_ptr64()
self.lRet = v_uint64()
self.tSent = v_uint32()
self.flags = v_uint32()
self.wParam = v_uint64()
self.lParam = v_uint64()
self.message = v_uint32()
self._pad0060 = v_bytes(size=4)
self.spwnd = v_ptr64()
self.pvCapture = v_ptr64()
class SCSI_REQUEST_BLOCK(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
class ETHREAD(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
class FAST_MUTEX(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Count = v_uint32()
self._pad0008 = v_bytes(size=4)
self.Owner = v_ptr64()
self.Contention = v_uint32()
self._pad0018 = v_bytes(size=4)
self.Event = KEVENT()
self.OldIrql = v_uint32()
self._pad0038 = v_bytes(size=4)
class WHEA_ERROR_RECORD_HEADER_VALIDBITS(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.PlatformId = v_uint32()
class D3DKMDT_VIDPN_PRESENT_PATH_TRANSFORMATION(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Scaling = v_uint32()
self.ScalingSupport = D3DKMDT_VIDPN_PRESENT_PATH_SCALING_SUPPORT()
self.Rotation = v_uint32()
self.RotationSupport = D3DKMDT_VIDPN_PRESENT_PATH_ROTATION_SUPPORT()
class KDEVICE_QUEUE(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Type = v_uint16()
self.Size = v_uint16()
self._pad0008 = v_bytes(size=4)
self.DeviceListHead = LIST_ENTRY()
self.Lock = v_uint64()
self.Busy = v_uint8()
self._pad0028 = v_bytes(size=7)
class CALLBACKWND(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.hwnd = v_ptr64()
self.pwnd = v_ptr64()
self.pActCtx = v_ptr64()
class IO_SECURITY_CONTEXT(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.SecurityQos = v_ptr64()
self.AccessState = v_ptr64()
self.DesiredAccess = v_uint32()
self.FullCreateOptions = v_uint32()
class tagSIZE(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.cx = v_uint32()
self.cy = v_uint32()
class tagDESKTOPVIEW(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.pdvNext = v_ptr64()
self.pdesk = v_ptr64()
self.ulClientDelta = v_uint64()
class PROCMARKHEAD(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.h = v_ptr64()
self.cLockObj = v_uint32()
self._pad0010 = v_bytes(size=4)
self.hTaskWow = v_uint32()
self._pad0018 = v_bytes(size=4)
self.ppi = v_ptr64()
class INITIAL_PRIVILEGE_SET(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.PrivilegeCount = v_uint32()
self.Control = v_uint32()
self.Privilege = vstruct.VArray([ LUID_AND_ATTRIBUTES() for i in range(3) ])
class D3DKMDT_COLOR_COEFF_DYNAMIC_RANGES(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.FirstChannel = v_uint32()
self.SecondChannel = v_uint32()
self.ThirdChannel = v_uint32()
self.FourthChannel = v_uint32()
class WHEA_ERROR_RECORD_HEADER_FLAGS(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Recovered = v_uint32()
class MODIFIERS(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.pVkToBit = v_ptr64()
self.wMaxModBits = v_uint16()
self.ModNumber = vstruct.VArray([ v_uint8() for i in range(0) ])
self._pad0010 = v_bytes(size=6)
class _unnamed_14501(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Length64 = v_uint32()
self.Alignment64 = v_uint32()
self.MinimumAddress = LARGE_INTEGER()
self.MaximumAddress = LARGE_INTEGER()
class PFNCLIENT(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.pfnScrollBarWndProc = v_ptr64()
self.pfnTitleWndProc = v_ptr64()
self.pfnMenuWndProc = v_ptr64()
self.pfnDesktopWndProc = v_ptr64()
self.pfnDefWindowProc = v_ptr64()
self.pfnMessageWindowProc = v_ptr64()
self.pfnSwitchWindowProc = v_ptr64()
self.pfnButtonWndProc = v_ptr64()
self.pfnComboBoxWndProc = v_ptr64()
self.pfnComboListBoxProc = v_ptr64()
self.pfnDialogWndProc = v_ptr64()
self.pfnEditWndProc = v_ptr64()
self.pfnListBoxWndProc = v_ptr64()
self.pfnMDIClientWndProc = v_ptr64()
self.pfnStaticWndProc = v_ptr64()
self.pfnImeWndProc = v_ptr64()
self.pfnGhostWndProc = v_ptr64()
self.pfnHkINLPCWPSTRUCT = v_ptr64()
self.pfnHkINLPCWPRETSTRUCT = v_ptr64()
self.pfnDispatchHook = v_ptr64()
self.pfnDispatchDefWindowProc = v_ptr64()
self.pfnDispatchMessage = v_ptr64()
self.pfnMDIActivateDlgProc = v_ptr64()
class _unnamed_10539(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.PowerState = v_uint32()
class ACTIVATION_CONTEXT_DATA(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
class FILE_NETWORK_OPEN_INFORMATION(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.CreationTime = LARGE_INTEGER()
self.LastAccessTime = LARGE_INTEGER()
self.LastWriteTime = LARGE_INTEGER()
self.ChangeTime = LARGE_INTEGER()
self.AllocationSize = LARGE_INTEGER()
self.EndOfFile = LARGE_INTEGER()
self.FileAttributes = v_uint32()
self._pad0038 = v_bytes(size=4)
class tagSVR_INSTANCE_INFO(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.head = THROBJHEAD()
self.next = v_ptr64()
self.nextInThisThread = v_ptr64()
self.afCmd = v_uint32()
self._pad0030 = v_bytes(size=4)
self.spwndEvent = v_ptr64()
self.pcii = v_ptr64()
class _unnamed_14479(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.MinimumChannel = v_uint32()
self.MaximumChannel = v_uint32()
class RTL_DRIVE_LETTER_CURDIR(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Flags = v_uint16()
self.Length = v_uint16()
self.TimeStamp = v_uint32()
self.DosPath = STRING()
class _unnamed_14472(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.MinimumVector = v_uint32()
self.MaximumVector = v_uint32()
self.AffinityPolicy = v_uint16()
self.Group = v_uint16()
self.PriorityPolicy = v_uint32()
self.TargetedProcessors = v_uint64()
class KIDTENTRY64(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.OffsetLow = v_uint16()
self.Selector = v_uint16()
self.IstIndex = v_uint16()
self.OffsetMiddle = v_uint16()
self.OffsetHigh = v_uint32()
self.Reserved1 = v_uint32()
class _unnamed_10386(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.OutputBufferLength = v_uint32()
self._pad0008 = v_bytes(size=4)
self.InputBufferLength = v_uint32()
self._pad0010 = v_bytes(size=4)
self.FsControlCode = v_uint32()
self._pad0018 = v_bytes(size=4)
self.Type3InputBuffer = v_ptr64()
class ULARGE_INTEGER(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.LowPart = v_uint32()
self.HighPart = v_uint32()
class VWPL(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.cPwnd = v_uint32()
self.cElem = v_uint32()
self.cThreshhold = v_uint32()
self.fTagged = v_uint32()
self.aElement = vstruct.VArray([ VWPLELEMENT() for i in range(0) ])
class _unnamed_10383(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Length = v_uint32()
self._pad0008 = v_bytes(size=4)
self.FsInformationClass = v_uint32()
self._pad0010 = v_bytes(size=4)
class TEB_ACTIVE_FRAME(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Flags = v_uint32()
self._pad0008 = v_bytes(size=4)
self.Previous = v_ptr64()
self.Context = v_ptr64()
class GENERAL_LOOKASIDE(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.ListHead = SLIST_HEADER()
self.Depth = v_uint16()
self.MaximumDepth = v_uint16()
self.TotalAllocates = v_uint32()
self.AllocateMisses = v_uint32()
self.TotalFrees = v_uint32()
self.FreeMisses = v_uint32()
self.Type = v_uint32()
self.Tag = v_uint32()
self.Size = v_uint32()
self.AllocateEx = v_ptr64()
self.FreeEx = v_ptr64()
self.ListEntry = LIST_ENTRY()
self.LastTotalAllocates = v_uint32()
self.LastAllocateMisses = v_uint32()
self.Future = vstruct.VArray([ v_uint32() for i in range(2) ])
self._pad0080 = v_bytes(size=32)
class tagCURSOR(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.head = PROCMARKHEAD()
self.pcurNext = v_ptr64()
self.strName = UNICODE_STRING()
self.atomModName = v_uint16()
self.rt = v_uint16()
self._pad0040 = v_bytes(size=4)
self.CURSORF_flags = v_uint32()
self.xHotspot = v_uint16()
self.yHotspot = v_uint16()
self.hbmMask = v_ptr64()
self.hbmColor = v_ptr64()
self.hbmAlpha = v_ptr64()
self.rcBounds = tagRECT()
self.hbmUserAlpha = v_ptr64()
self.bpp = v_uint32()
self.cx = v_uint32()
self.cy = v_uint32()
self._pad0088 = v_bytes(size=4)
class _unnamed_10545(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.PowerSequence = v_ptr64()
class tagDCE(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.pdceNext = v_ptr64()
self.hdc = v_ptr64()
self.pwndOrg = v_ptr64()
self.pwndClip = v_ptr64()
self.pwndRedirect = v_ptr64()
self.hrgnClip = v_ptr64()
self.hrgnClipPublic = v_ptr64()
self.hrgnSavedVis = v_ptr64()
self.DCX_flags = v_uint32()
self._pad0048 = v_bytes(size=4)
self.ptiOwner = v_ptr64()
self.ppiOwner = v_ptr64()
self.pMonitor = v_ptr64()
class VSC_LPWSTR(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.vsc = v_uint8()
self._pad0008 = v_bytes(size=7)
self.pwsz = v_ptr64()
class NAMED_PIPE_CREATE_PARAMETERS(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.NamedPipeType = v_uint32()
self.ReadMode = v_uint32()
self.CompletionMode = v_uint32()
self.MaximumInstances = v_uint32()
self.InboundQuota = v_uint32()
self.OutboundQuota = v_uint32()
self.DefaultTimeout = LARGE_INTEGER()
self.TimeoutSpecified = v_uint8()
self._pad0028 = v_bytes(size=7)
class NT_TIB(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.ExceptionList = v_ptr64()
self.StackBase = v_ptr64()
self.StackLimit = v_ptr64()
self.SubSystemTib = v_ptr64()
self.FiberData = v_ptr64()
self.ArbitraryUserPointer = v_ptr64()
self.Self = v_ptr64()
class SCATTER_GATHER_ELEMENT(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Address = LARGE_INTEGER()
self.Length = v_uint32()
self._pad0010 = v_bytes(size=4)
self.Reserved = v_uint64()
class POWER_STATE(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.SystemState = v_uint32()
class UNICODE_STRING(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Length = v_uint16()
self.MaximumLength = v_uint16()
self._pad0008 = v_bytes(size=4)
self.Buffer = v_ptr64()
class DMM_MONITORSOURCEMODESET_SERIALIZATION(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.NumModes = v_uint8()
self._pad0008 = v_bytes(size=7)
self.ModeSerialization = vstruct.VArray([ DMM_MONITOR_SOURCE_MODE_SERIALIZATION() for i in range(1) ])
class D3DKMDT_VIDPN_TARGET_MODE(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Id = v_uint32()
self._pad0008 = v_bytes(size=4)
self.VideoSignalInfo = D3DKMDT_VIDEO_SIGNAL_INFO()
self.Preference = v_uint32()
self._pad0048 = v_bytes(size=4)
class tagWOWTHREADINFO(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.pwtiNext = v_ptr64()
self.idTask = v_uint32()
self._pad0010 = v_bytes(size=4)
self.idWaitObject = v_uint64()
self.idParentProcess = v_uint32()
self._pad0020 = v_bytes(size=4)
self.pIdleEvent = v_ptr64()
self.fAssigned = v_uint32()
self._pad0030 = v_bytes(size=4)
class _unnamed_10092(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Overlay = _unnamed_10207()
self._pad0058 = v_bytes(size=8)
class ACCESS_REASONS(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Data = vstruct.VArray([ v_uint32() for i in range(32) ])
class _unnamed_10271(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.SecurityContext = v_ptr64()
self.Options = v_uint32()
self._pad0010 = v_bytes(size=4)
self.Reserved = v_uint16()
self.ShareAccess = v_uint16()
self._pad0018 = v_bytes(size=4)
self.Parameters = v_ptr64()
class HANDLEENTRY(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.phead = v_ptr64()
self.pOwner = v_ptr64()
self.bType = v_uint8()
self.bFlags = v_uint8()
self.wUniq = v_uint16()
self._pad0018 = v_bytes(size=4)
class W32THREAD(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.pEThread = v_ptr64()
self.RefCount = v_uint32()
self._pad0010 = v_bytes(size=4)
self.ptlW32 = v_ptr64()
self.pgdiDcattr = v_ptr64()
self.pgdiBrushAttr = v_ptr64()
self.pUMPDObjs = v_ptr64()
self.pUMPDHeap = v_ptr64()
self.pUMPDObj = v_ptr64()
self.pProxyPort = v_ptr64()
self.pClientID = v_ptr64()
self.GdiTmpTgoList = LIST_ENTRY()
self.pRBRecursionCount = v_uint32()
self.pNonRBRecursionCount = v_uint32()
self.tlSpriteState = TLSPRITESTATE()
self.pSpriteState = v_ptr64()
self.pDevHTInfo = v_ptr64()
self.ulDevHTInfoUniqueness = v_uint32()
self._pad0128 = v_bytes(size=4)
self.pdcoAA = v_ptr64()
self.pdcoRender = v_ptr64()
self.pdcoSrc = v_ptr64()
self.bEnableEngUpdateDeviceSurface = v_uint8()
self.bIncludeSprites = v_uint8()
self._pad0144 = v_bytes(size=2)
self.ulWindowSystemRendering = v_uint32()
self.iVisRgnUniqueness = v_uint32()
self._pad0150 = v_bytes(size=4)
class KDPC(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Type = v_uint8()
self.Importance = v_uint8()
self.Number = v_uint16()
self._pad0008 = v_bytes(size=4)
self.DpcListEntry = LIST_ENTRY()
self.DeferredRoutine = v_ptr64()
self.DeferredContext = v_ptr64()
self.SystemArgument1 = v_ptr64()
self.SystemArgument2 = v_ptr64()
self.DpcData = v_ptr64()
class KEVENT(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Header = DISPATCHER_HEADER()
class KSEMAPHORE(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Header = DISPATCHER_HEADER()
self.Limit = v_uint32()
self._pad0020 = v_bytes(size=4)
class OBJECT_TYPE(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.TypeList = LIST_ENTRY()
self.Name = UNICODE_STRING()
self.DefaultObject = v_ptr64()
self.Index = v_uint8()
self._pad002c = v_bytes(size=3)
self.TotalNumberOfObjects = v_uint32()
self.TotalNumberOfHandles = v_uint32()
self.HighWaterNumberOfObjects = v_uint32()
self.HighWaterNumberOfHandles = v_uint32()
self._pad0040 = v_bytes(size=4)
self.TypeInfo = OBJECT_TYPE_INITIALIZER()
self.TypeLock = EX_PUSH_LOCK()
self.Key = v_uint32()
self._pad00c0 = v_bytes(size=4)
self.CallbackList = LIST_ENTRY()
class tagIMEINFO(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.dwPrivateDataSize = v_uint32()
self.fdwProperty = v_uint32()
self.fdwConversionCaps = v_uint32()
self.fdwSentenceCaps = v_uint32()
self.fdwUICaps = v_uint32()
self.fdwSCSCaps = v_uint32()
self.fdwSelectCaps = v_uint32()
class DXGK_DIAG_CODE_POINT_PACKET(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Header = DXGK_DIAG_HEADER()
self.CodePointType = v_uint32()
self.Param1 = v_uint32()
self.Param2 = v_uint32()
self.Param3 = v_uint32()
class _unnamed_10168(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Create = _unnamed_10255()
class W32PROCESS(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Process = v_ptr64()
self.RefCount = v_uint32()
self.W32PF_Flags = v_uint32()
self.InputIdleEvent = v_ptr64()
self.StartCursorHideTime = v_uint32()
self._pad0020 = v_bytes(size=4)
self.NextStart = v_ptr64()
self.pDCAttrList = v_ptr64()
self.pBrushAttrList = v_ptr64()
self.W32Pid = v_uint32()
self.GDIHandleCount = v_uint32()
self.GDIHandleCountPeak = v_uint32()
self.UserHandleCount = v_uint32()
self.UserHandleCountPeak = v_uint32()
self._pad0050 = v_bytes(size=4)
self.GDIPushLock = EX_PUSH_LOCK()
self.GDIEngUserMemAllocTable = RTL_AVL_TABLE()
self.GDIDcAttrFreeList = LIST_ENTRY()
self.GDIBrushAttrFreeList = LIST_ENTRY()
self.GDIW32PIDLockedBitmaps = LIST_ENTRY()
self.hSecureGdiSharedHandleTable = v_ptr64()
self.DxProcess = v_ptr64()
class tagKBDFILE(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.head = HEAD()
self.pkfNext = v_ptr64()
self.hBase = v_ptr64()
self.pKbdTbl = v_ptr64()
self.Size = v_uint32()
self._pad0030 = v_bytes(size=4)
self.pKbdNlsTbl = v_ptr64()
self.awchDllName = vstruct.VArray([ v_uint16() for i in range(32) ])
class DMM_COMMITVIDPNREQUEST_SERIALIZATION(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.AffectedVidPnSourceId = v_uint32()
self.RequestDiagInfo = DMM_COMMITVIDPNREQUEST_DIAGINFO()
self.VidPnSerialization = DMM_VIDPN_SERIALIZATION()
class _unnamed_10360(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Length = v_uint32()
self._pad0008 = v_bytes(size=4)
self.FileInformationClass = v_uint32()
self._pad0010 = v_bytes(size=4)
class _unnamed_13586(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Generic = _unnamed_13916()
self._pad0010 = v_bytes(size=4)
class EXCEPTION_REGISTRATION_RECORD(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Next = v_ptr64()
self.Handler = v_ptr64()
class FILE_BASIC_INFORMATION(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.CreationTime = LARGE_INTEGER()
self.LastAccessTime = LARGE_INTEGER()
self.LastWriteTime = LARGE_INTEGER()
self.ChangeTime = LARGE_INTEGER()
self.FileAttributes = v_uint32()
self._pad0028 = v_bytes(size=4)
class LIST_ENTRY(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Flink = v_ptr64()
self.Blink = v_ptr64()
class M128A(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Low = v_uint64()
self.High = v_uint64()
class tagUSERSTARTUPINFO(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.cb = v_uint32()
self.dwX = v_uint32()
self.dwY = v_uint32()
self.dwXSize = v_uint32()
self.dwYSize = v_uint32()
self.dwFlags = v_uint32()
self.wShowWindow = v_uint16()
self.cbReserved2 = v_uint16()
class _unnamed_13369(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Attrib = v_uint32()
self._pad0008 = v_bytes(size=4)
self.cbData = v_uint64()
class tagHID_PAGEONLY_REQUEST(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.link = LIST_ENTRY()
self.usUsagePage = v_uint16()
self._pad0014 = v_bytes(size=2)
self.cRefCount = v_uint32()
class _unnamed_11143(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Graphics = D3DKMDT_GRAPHICS_RENDERING_FORMAT()
class _unnamed_13366(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Attrib = v_uint32()
self._pad0008 = v_bytes(size=4)
self.cbData = v_uint64()
class RTL_DYNAMIC_HASH_TABLE_ENUMERATOR(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.HashEntry = RTL_DYNAMIC_HASH_TABLE_ENTRY()
self.ChainHead = v_ptr64()
self.BucketIndex = v_uint32()
self._pad0028 = v_bytes(size=4)
class tagWINDOWSTATION(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.dwSessionId = v_uint32()
self._pad0008 = v_bytes(size=4)
self.rpwinstaNext = v_ptr64()
self.rpdeskList = v_ptr64()
self.pTerm = v_ptr64()
self.dwWSF_Flags = v_uint32()
self._pad0028 = v_bytes(size=4)
self.spklList = v_ptr64()
self.ptiClipLock = v_ptr64()
self.ptiDrawingClipboard = v_ptr64()
self.spwndClipOpen = v_ptr64()
self.spwndClipViewer = v_ptr64()
self.spwndClipOwner = v_ptr64()
self.pClipBase = v_ptr64()
self.cNumClipFormats = v_uint32()
self.iClipSerialNumber = v_uint32()
self.iClipSequenceNumber = v_uint32()
self._pad0070 = v_bytes(size=4)
self.spwndClipboardListener = v_ptr64()
self.pGlobalAtomTable = v_ptr64()
self.luidEndSession = LUID()
self.luidUser = LUID()
self.psidUser = v_ptr64()
class DMM_VIDPNPATHSFROMSOURCE_SERIALIZATION(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.SourceMode = D3DKMDT_VIDPN_SOURCE_MODE()
self.NumPathsFromSource = v_uint8()
self._pad0030 = v_bytes(size=7)
self.PathAndTargetModeSerialization = vstruct.VArray([ DMM_VIDPNPATHANDTARGETMODE_SERIALIZATION() for i in range(1) ])
class GUID(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Data1 = v_uint32()
self.Data2 = v_uint16()
self.Data3 = v_uint16()
self.Data4 = vstruct.VArray([ v_uint8() for i in range(8) ])
class D3DKMDT_GRAPHICS_RENDERING_FORMAT(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.PrimSurfSize = D3DKMDT_2DREGION()
self.VisibleRegionSize = D3DKMDT_2DREGION()
self.Stride = v_uint32()
self.PixelFormat = v_uint32()
self.ColorBasis = v_uint32()
self.PixelValueAccessMode = v_uint32()
class SLIST_ENTRY(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Next = v_ptr64()
self._pad0010 = v_bytes(size=8)
class IO_RESOURCE_DESCRIPTOR(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Option = v_uint8()
self.Type = v_uint8()
self.ShareDisposition = v_uint8()
self.Spare1 = v_uint8()
self.Flags = v_uint16()
self.Spare2 = v_uint16()
self.u = _unnamed_13900()
class IO_STATUS_BLOCK32(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Status = v_uint32()
self.Information = v_uint32()
class GENERIC_MAPPING(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.GenericRead = v_uint32()
self.GenericWrite = v_uint32()
self.GenericExecute = v_uint32()
self.GenericAll = v_uint32()
class IRP(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Type = v_uint16()
self.Size = v_uint16()
self._pad0008 = v_bytes(size=4)
self.MdlAddress = v_ptr64()
self.Flags = v_uint32()
self._pad0018 = v_bytes(size=4)
self.AssociatedIrp = _unnamed_10086()
self.ThreadListEntry = LIST_ENTRY()
self.IoStatus = IO_STATUS_BLOCK()
self.RequestorMode = v_uint8()
self.PendingReturned = v_uint8()
self.StackCount = v_uint8()
self.CurrentLocation = v_uint8()
self.Cancel = v_uint8()
self.CancelIrql = v_uint8()
self.ApcEnvironment = v_uint8()
self.AllocationFlags = v_uint8()
self.UserIosb = v_ptr64()
self.UserEvent = v_ptr64()
self.Overlay = _unnamed_10089()
self.CancelRoutine = v_ptr64()
self.UserBuffer = v_ptr64()
self.Tail = _unnamed_10092()
class _unnamed_10500(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.WhichSpace = v_uint32()
self._pad0008 = v_bytes(size=4)
self.Buffer = v_ptr64()
self.Offset = v_uint32()
self._pad0018 = v_bytes(size=4)
self.Length = v_uint32()
self._pad0020 = v_bytes(size=4)
class _unnamed_10505(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Lock = v_uint8()
class D3DKMDT_VIDPN_PRESENT_PATH_COPYPROTECTION(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.CopyProtectionType = v_uint32()
self.APSTriggerBits = v_uint32()
self.OEMCopyProtection = vstruct.VArray([ v_uint8() for i in range(256) ])
self.CopyProtectionSupport = D3DKMDT_VIDPN_PRESENT_PATH_COPYPROTECTION_SUPPORT()
class _unnamed_14491(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Length40 = v_uint32()
self.Alignment40 = v_uint32()
self.MinimumAddress = LARGE_INTEGER()
self.MaximumAddress = LARGE_INTEGER()
class DMM_VIDPN_SERIALIZATION(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Size = v_uint32()
self.NumActiveSources = v_uint8()
self._pad0008 = v_bytes(size=3)
self.PathsFromSourceSerializationOffsets = vstruct.VArray([ v_uint32() for i in range(1) ])
class IO_COMPLETION_CONTEXT(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Port = v_ptr64()
self.Key = v_ptr64()
class DRIVER_EXTENSION(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.DriverObject = v_ptr64()
self.AddDevice = v_ptr64()
self.Count = v_uint32()
self._pad0018 = v_bytes(size=4)
self.ServiceKeyName = UNICODE_STRING()
class _unnamed_13919(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Level = v_uint16()
self.Group = v_uint16()
self.Vector = v_uint32()
self.Affinity = v_uint64()
class DMM_COFUNCPATHSMODALITY_SERIALIZATION(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.NumPathsFromSource = v_uint8()
self._pad0004 = v_bytes(size=3)
self.PathAndTargetModeSetOffset = vstruct.VArray([ v_uint32() for i in range(1) ])
class tagTDB(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.ptdbNext = v_ptr64()
self.nEvents = v_uint32()
self.nPriority = v_uint32()
self.pti = v_ptr64()
self.pwti = v_ptr64()
self.hTaskWow = v_uint16()
self.TDB_Flags = v_uint16()
self._pad0028 = v_bytes(size=4)
class _unnamed_13916(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Start = LARGE_INTEGER()
self.Length = v_uint32()
class KPRCB(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.MxCsr = v_uint32()
self.LegacyNumber = v_uint8()
self.ReservedMustBeZero = v_uint8()
self.InterruptRequest = v_uint8()
self.IdleHalt = v_uint8()
self.CurrentThread = v_ptr64()
self.NextThread = v_ptr64()
self.IdleThread = v_ptr64()
self.NestingLevel = v_uint8()
self.PrcbPad00 = vstruct.VArray([ v_uint8() for i in range(3) ])
self.Number = v_uint32()
self.RspBase = v_uint64()
self.PrcbLock = v_uint64()
self.PrcbPad01 = v_uint64()
self.ProcessorState = KPROCESSOR_STATE()
self.CpuType = v_uint8()
self.CpuID = v_uint8()
self.CpuStep = v_uint16()
self.MHz = v_uint32()
self.HalReserved = vstruct.VArray([ v_uint64() for i in range(8) ])
self.MinorVersion = v_uint16()
self.MajorVersion = v_uint16()
self.BuildType = v_uint8()
self.CpuVendor = v_uint8()
self.CoresPerPhysicalProcessor = v_uint8()
self.LogicalProcessorsPerCore = v_uint8()
self.ApicMask = v_uint32()
self.CFlushSize = v_uint32()
self.AcpiReserved = v_ptr64()
self.InitialApicId = v_uint32()
self.Stride = v_uint32()
self.Group = v_uint16()
self._pad0660 = v_bytes(size=6)
self.GroupSetMember = v_uint64()
self.GroupIndex = v_uint8()
self._pad0670 = v_bytes(size=7)
class WHEA_ERROR_RECORD_SECTION_DESCRIPTOR_VALIDBITS(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.FRUId = v_uint8()
class tagWin32AllocStats(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.dwMaxMem = v_uint64()
self.dwCrtMem = v_uint64()
self.dwMaxAlloc = v_uint32()
self.dwCrtAlloc = v_uint32()
self.pHead = v_ptr64()
class LARGE_UNICODE_STRING(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Length = v_uint32()
self.MaximumLength = v_uint32()
self.Buffer = v_ptr64()
class EXCEPTION_RECORD(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.ExceptionCode = v_uint32()
self.ExceptionFlags = v_uint32()
self.ExceptionRecord = v_ptr64()
self.ExceptionAddress = v_ptr64()
self.NumberParameters = v_uint32()
self._pad0020 = v_bytes(size=4)
self.ExceptionInformation = vstruct.VArray([ v_uint64() for i in range(15) ])
class HTOUCHINPUT(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.unused = v_uint32()
class PROCESSOR_NUMBER(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Group = v_uint16()
self.Number = v_uint8()
self.Reserved = v_uint8()
class _unnamed_10592(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Argument1 = v_ptr64()
self.Argument2 = v_ptr64()
self.Argument3 = v_ptr64()
self.Argument4 = v_ptr64()
class KPCR(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.NtTib = NT_TIB()
self.IdtBase = v_ptr64()
self.Unused = vstruct.VArray([ v_uint64() for i in range(2) ])
self.Irql = v_uint8()
self.SecondLevelCacheAssociativity = v_uint8()
self.ObsoleteNumber = v_uint8()
self.Fill0 = v_uint8()
self.Unused0 = vstruct.VArray([ v_uint32() for i in range(3) ])
self.MajorVersion = v_uint16()
self.MinorVersion = v_uint16()
self.StallScaleFactor = v_uint32()
self.Unused1 = vstruct.VArray([ v_ptr64() for i in range(3) ])
self.KernelReserved = vstruct.VArray([ v_uint32() for i in range(15) ])
self.SecondLevelCacheSize = v_uint32()
self.HalReserved = vstruct.VArray([ v_uint32() for i in range(16) ])
self.Unused2 = v_uint32()
self._pad0108 = v_bytes(size=4)
self.KdVersionBlock = v_ptr64()
self.Unused3 = v_ptr64()
self.PcrAlign1 = vstruct.VArray([ v_uint32() for i in range(24) ])
self._pad0180 = v_bytes(size=8)
self.Prcb = KPRCB()
class IMAGE_FILE_HEADER(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Machine = v_uint16()
self.NumberOfSections = v_uint16()
self.TimeDateStamp = v_uint32()
self.PointerToSymbolTable = v_uint32()
self.NumberOfSymbols = v_uint32()
self.SizeOfOptionalHeader = v_uint16()
self.Characteristics = v_uint16()
class SCATTER_GATHER_LIST(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.NumberOfElements = v_uint32()
self._pad0008 = v_bytes(size=4)
self.Reserved = v_uint64()
self.Elements = vstruct.VArray([ SCATTER_GATHER_ELEMENT() for i in range(0) ])
class tagPROCESSINFO(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Process = v_ptr64()
self.RefCount = v_uint32()
self.W32PF_Flags = v_uint32()
self.InputIdleEvent = v_ptr64()
self.StartCursorHideTime = v_uint32()
self._pad0020 = v_bytes(size=4)
self.NextStart = v_ptr64()
self.pDCAttrList = v_ptr64()
self.pBrushAttrList = v_ptr64()
self.W32Pid = v_uint32()
self.GDIHandleCount = v_uint32()
self.GDIHandleCountPeak = v_uint32()
self.UserHandleCount = v_uint32()
self.UserHandleCountPeak = v_uint32()
self._pad0050 = v_bytes(size=4)
self.GDIPushLock = EX_PUSH_LOCK()
self.GDIEngUserMemAllocTable = RTL_AVL_TABLE()
self.GDIDcAttrFreeList = LIST_ENTRY()
self.GDIBrushAttrFreeList = LIST_ENTRY()
self.GDIW32PIDLockedBitmaps = LIST_ENTRY()
self.hSecureGdiSharedHandleTable = v_ptr64()
self.DxProcess = v_ptr64()
self.ptiList = v_ptr64()
self.ptiMainThread = v_ptr64()
self.rpdeskStartup = v_ptr64()
self.pclsPrivateList = v_ptr64()
self.pclsPublicList = v_ptr64()
self.pwpi = v_ptr64()
self.ppiNext = v_ptr64()
self.ppiNextRunning = v_ptr64()
self.cThreads = v_uint32()
self._pad0148 = v_bytes(size=4)
self.hdeskStartup = v_ptr64()
self.cSysExpunge = v_uint32()
self.dwhmodLibLoadedMask = v_uint32()
self.ahmodLibLoaded = vstruct.VArray([ v_ptr64() for i in range(32) ])
self.rpwinsta = v_ptr64()
self.hwinsta = v_ptr64()
self.amwinsta = v_uint32()
self.dwHotkey = v_uint32()
self.hMonitor = v_ptr64()
self.pdvList = v_ptr64()
self.iClipSerialNumber = v_uint32()
self._pad0288 = v_bytes(size=4)
self.bmHandleFlags = RTL_BITMAP()
self.pCursorCache = v_ptr64()
self.pClientBase = v_ptr64()
self.dwLpkEntryPoints = v_uint32()
self._pad02b0 = v_bytes(size=4)
self.pW32Job = v_ptr64()
self.dwImeCompatFlags = v_uint32()
self.luidSession = LUID()
self.usi = tagUSERSTARTUPINFO()
self.Flags = v_uint32()
self.dwLayout = v_uint32()
self.pHidTable = v_ptr64()
self.dwRegisteredClasses = v_uint32()
self._pad02f8 = v_bytes(size=4)
self.pvwplWndGCList = v_ptr64()
class HKL(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.unused = v_uint32()
class PEB_LDR_DATA(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Length = v_uint32()
self.Initialized = v_uint8()
self._pad0008 = v_bytes(size=3)
self.SsHandle = v_ptr64()
self.InLoadOrderModuleList = LIST_ENTRY()
self.InMemoryOrderModuleList = LIST_ENTRY()
self.InInitializationOrderModuleList = LIST_ENTRY()
self.EntryInProgress = v_ptr64()
self.ShutdownInProgress = v_uint8()
self._pad0050 = v_bytes(size=7)
self.ShutdownThreadId = v_ptr64()
class DMM_MONITORFREQUENCYRANGESET_SERIALIZATION(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.NumFrequencyRanges = v_uint8()
self._pad0008 = v_bytes(size=7)
self.FrequencyRangeSerialization = vstruct.VArray([ D3DKMDT_MONITOR_FREQUENCY_RANGE() for i in range(1) ])
class SECURITY_SUBJECT_CONTEXT(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.ClientToken = v_ptr64()
self.ImpersonationLevel = v_uint32()
self._pad0010 = v_bytes(size=4)
self.PrimaryToken = v_ptr64()
self.ProcessAuditId = v_ptr64()
class DMM_MONITOR_SERIALIZATION(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Size = v_uint32()
self.VideoPresentTargetId = v_uint32()
self.Orientation = v_uint32()
self.IsSimulatedMonitor = v_uint8()
self.IsUsingDefaultProfile = v_uint8()
self._pad0010 = v_bytes(size=2)
self.ModePruningAlgorithm = v_uint32()
self.MonitorPowerState = v_uint32()
self.SourceModeSetOffset = v_uint32()
self.FrequencyRangeSetOffset = v_uint32()
self.DescriptorSetOffset = v_uint32()
self.MonitorType = v_uint32()
class tagKbdLayer(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.pCharModifiers = v_ptr64()
self.pVkToWcharTable = v_ptr64()
self.pDeadKey = v_ptr64()
self.pKeyNames = v_ptr64()
self.pKeyNamesExt = v_ptr64()
self.pKeyNamesDead = v_ptr64()
self.pusVSCtoVK = v_ptr64()
self.bMaxVSCtoVK = v_uint8()
self._pad0040 = v_bytes(size=7)
self.pVSCtoVK_E0 = v_ptr64()
self.pVSCtoVK_E1 = v_ptr64()
self.fLocaleFlags = v_uint32()
self.nLgMax = v_uint8()
self.cbLgEntry = v_uint8()
self._pad0058 = v_bytes(size=2)
self.pLigature = v_ptr64()
self.dwType = v_uint32()
self.dwSubType = v_uint32()
class HWND(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.unused = v_uint32()
class _unnamed_9269(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.LowPart = v_uint32()
self.HighPart = v_uint32()
class tagMSG(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.hwnd = v_ptr64()
self.message = v_uint32()
self._pad0010 = v_bytes(size=4)
self.wParam = v_uint64()
self.lParam = v_uint64()
self.time = v_uint32()
self.pt = tagPOINT()
self._pad0030 = v_bytes(size=4)
class _unnamed_10283(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.SecurityContext = v_ptr64()
self.Options = v_uint32()
self._pad0010 = v_bytes(size=4)
self.Reserved = v_uint16()
self.ShareAccess = v_uint16()
self._pad0018 = v_bytes(size=4)
self.Parameters = v_ptr64()
class INTERFACE(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Size = v_uint16()
self.Version = v_uint16()
self._pad0008 = v_bytes(size=4)
self.Context = v_ptr64()
self.InterfaceReference = v_ptr64()
self.InterfaceDereference = v_ptr64()
class SLIST_HEADER(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Alignment = v_uint64()
self.Region = v_uint64()
class IMAGE_DATA_DIRECTORY(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.VirtualAddress = v_uint32()
self.Size = v_uint32()
class FILE_OBJECT(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Type = v_uint16()
self.Size = v_uint16()
self._pad0008 = v_bytes(size=4)
self.DeviceObject = v_ptr64()
self.Vpb = v_ptr64()
self.FsContext = v_ptr64()
self.FsContext2 = v_ptr64()
self.SectionObjectPointer = v_ptr64()
self.PrivateCacheMap = v_ptr64()
self.FinalStatus = v_uint32()
self._pad0040 = v_bytes(size=4)
self.RelatedFileObject = v_ptr64()
self.LockOperation = v_uint8()
self.DeletePending = v_uint8()
self.ReadAccess = v_uint8()
self.WriteAccess = v_uint8()
self.DeleteAccess = v_uint8()
self.SharedRead = v_uint8()
self.SharedWrite = v_uint8()
self.SharedDelete = v_uint8()
self.Flags = v_uint32()
self._pad0058 = v_bytes(size=4)
self.FileName = UNICODE_STRING()
self.CurrentByteOffset = LARGE_INTEGER()
self.Waiters = v_uint32()
self.Busy = v_uint32()
self.LastLock = v_ptr64()
self.Lock = KEVENT()
self.Event = KEVENT()
self.CompletionContext = v_ptr64()
self.IrpListLock = v_uint64()
self.IrpList = LIST_ENTRY()
self.FileObjectExtension = v_ptr64()
class tagWOWPROCESSINFO(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.pwpiNext = v_ptr64()
self.ptiScheduled = v_ptr64()
self.ptdbHead = v_ptr64()
self.lpfnWowExitTask = v_ptr64()
self.pEventWowExec = v_ptr64()
self.hEventWowExecClient = v_ptr64()
self.nSendLock = v_uint32()
self.nRecvLock = v_uint32()
self.CSOwningThread = v_ptr64()
self.CSLockCount = v_uint32()
self._pad0048 = v_bytes(size=4)
class tagMENU(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.head = PROCDESKHEAD()
self.fFlags = v_uint32()
self.iItem = v_uint32()
self.cAlloced = v_uint32()
self.cItems = v_uint32()
self.cxMenu = v_uint32()
self.cyMenu = v_uint32()
self.cxTextAlign = v_uint32()
self._pad0048 = v_bytes(size=4)
self.spwndNotify = v_ptr64()
self.rgItems = v_ptr64()
self.pParentMenus = v_ptr64()
self.dwContextHelpId = v_uint32()
self.cyMax = v_uint32()
self.dwMenuData = v_uint64()
self.hbrBack = v_ptr64()
self.iTop = v_uint32()
self.iMaxTop = v_uint32()
self.dwArrowsOn = v_uint32()
self.umpm = tagUAHMENUPOPUPMETRICS()
class ERESOURCE(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.SystemResourcesList = LIST_ENTRY()
self.OwnerTable = v_ptr64()
self.ActiveCount = v_uint16()
self.Flag = v_uint16()
self._pad0020 = v_bytes(size=4)
self.SharedWaiters = v_ptr64()
self.ExclusiveWaiters = v_ptr64()
self.OwnerEntry = OWNER_ENTRY()
self.ActiveEntries = v_uint32()
self.ContentionCount = v_uint32()
self.NumberOfSharedWaiters = v_uint32()
self.NumberOfExclusiveWaiters = v_uint32()
self.Reserved2 = v_ptr64()
self.Address = v_ptr64()
self.SpinLock = v_uint64()
class _unnamed_9315(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.LongFunction = v_uint32()
class _unnamed_9312(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Flags = v_uint32()
class PEB(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.InheritedAddressSpace = v_uint8()
self.ReadImageFileExecOptions = v_uint8()
self.BeingDebugged = v_uint8()
self.BitField = v_uint8()
self._pad0008 = v_bytes(size=4)
self.Mutant = v_ptr64()
self.ImageBaseAddress = v_ptr64()
self.Ldr = v_ptr64()
self.ProcessParameters = v_ptr64()
self.SubSystemData = v_ptr64()
self.ProcessHeap = v_ptr64()
self.FastPebLock = v_ptr64()
self.AtlThunkSListPtr = v_ptr64()
self.IFEOKey = v_ptr64()
self.CrossProcessFlags = v_uint32()
self._pad0058 = v_bytes(size=4)
self.KernelCallbackTable = v_ptr64()
self.SystemReserved = vstruct.VArray([ v_uint32() for i in range(1) ])
self.AtlThunkSListPtr32 = v_uint32()
self.ApiSetMap = v_ptr64()
self.TlsExpansionCounter = v_uint32()
self._pad0078 = v_bytes(size=4)
self.TlsBitmap = v_ptr64()
self.TlsBitmapBits = vstruct.VArray([ v_uint32() for i in range(2) ])
self.ReadOnlySharedMemoryBase = v_ptr64()
self.HotpatchInformation = v_ptr64()
self.ReadOnlyStaticServerData = v_ptr64()
self.AnsiCodePageData = v_ptr64()
self.OemCodePageData = v_ptr64()
self.UnicodeCaseTableData = v_ptr64()
self.NumberOfProcessors = v_uint32()
self.NtGlobalFlag = v_uint32()
self.CriticalSectionTimeout = LARGE_INTEGER()
self.HeapSegmentReserve = v_uint64()
self.HeapSegmentCommit = v_uint64()
self.HeapDeCommitTotalFreeThreshold = v_uint64()
self.HeapDeCommitFreeBlockThreshold = v_uint64()
self.NumberOfHeaps = v_uint32()
self.MaximumNumberOfHeaps = v_uint32()
self.ProcessHeaps = v_ptr64()
self.GdiSharedHandleTable = v_ptr64()
self.ProcessStarterHelper = v_ptr64()
self.GdiDCAttributeList = v_uint32()
self._pad0110 = v_bytes(size=4)
self.LoaderLock = v_ptr64()
self.OSMajorVersion = v_uint32()
self.OSMinorVersion = v_uint32()
self.OSBuildNumber = v_uint16()
self.OSCSDVersion = v_uint16()
self.OSPlatformId = v_uint32()
self.ImageSubsystem = v_uint32()
self.ImageSubsystemMajorVersion = v_uint32()
self.ImageSubsystemMinorVersion = v_uint32()
self._pad0138 = v_bytes(size=4)
self.ActiveProcessAffinityMask = v_uint64()
self.GdiHandleBuffer = vstruct.VArray([ v_uint32() for i in range(60) ])
self.PostProcessInitRoutine = v_ptr64()
self.TlsExpansionBitmap = v_ptr64()
self.TlsExpansionBitmapBits = vstruct.VArray([ v_uint32() for i in range(32) ])
self.SessionId = v_uint32()
self._pad02c8 = v_bytes(size=4)
self.AppCompatFlags = ULARGE_INTEGER()
self.AppCompatFlagsUser = ULARGE_INTEGER()
self.pShimData = v_ptr64()
self.AppCompatInfo = v_ptr64()
self.CSDVersion = UNICODE_STRING()
self.ActivationContextData = v_ptr64()
self.ProcessAssemblyStorageMap = v_ptr64()
self.SystemDefaultActivationContextData = v_ptr64()
self.SystemAssemblyStorageMap = v_ptr64()
self.MinimumStackCommit = v_uint64()
self.FlsCallback = v_ptr64()
self.FlsListHead = LIST_ENTRY()
self.FlsBitmap = v_ptr64()
self.FlsBitmapBits = vstruct.VArray([ v_uint32() for i in range(4) ])
self.FlsHighIndex = v_uint32()
self._pad0358 = v_bytes(size=4)
self.WerRegistrationData = v_ptr64()
self.WerShipAssertPtr = v_ptr64()
self.pContextData = v_ptr64()
self.pImageHeaderHash = v_ptr64()
self.TracingFlags = v_uint32()
self._pad0380 = v_bytes(size=4)
class THRDESKHEAD(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.h = v_ptr64()
self.cLockObj = v_uint32()
self._pad0010 = v_bytes(size=4)
self.pti = v_ptr64()
self.rpdesk = v_ptr64()
self.pSelf = v_ptr64()
class tagPOPUPMENU(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.fIsMenuBar = v_uint32()
self._pad0008 = v_bytes(size=4)
self.spwndNotify = v_ptr64()
self.spwndPopupMenu = v_ptr64()
self.spwndNextPopup = v_ptr64()
self.spwndPrevPopup = v_ptr64()
self.spmenu = v_ptr64()
self.spmenuAlternate = v_ptr64()
self.spwndActivePopup = v_ptr64()
self.ppopupmenuRoot = v_ptr64()
self.ppmDelayedFree = v_ptr64()
self.posSelectedItem = v_uint32()
self.posDropped = v_uint32()
class TP_TASK_CALLBACKS(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.ExecuteCallback = v_ptr64()
self.Unposted = v_ptr64()
class RTL_BALANCED_LINKS(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Parent = v_ptr64()
self.LeftChild = v_ptr64()
self.RightChild = v_ptr64()
self.Balance = v_uint8()
self.Reserved = vstruct.VArray([ v_uint8() for i in range(3) ])
self._pad0020 = v_bytes(size=4)
class _unnamed_10421(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Srb = v_ptr64()
class VK_FUNCTION_PARAM(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.NLSFEProcIndex = v_uint8()
self._pad0004 = v_bytes(size=3)
self.NLSFEProcParam = v_uint32()
class EX_PUSH_LOCK(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Locked = v_uint64()
class D3DMATRIX(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self._11 = v_uint32()
self._12 = v_uint32()
self._13 = v_uint32()
self._14 = v_uint32()
self._21 = v_uint32()
self._22 = v_uint32()
self._23 = v_uint32()
self._24 = v_uint32()
self._31 = v_uint32()
self._32 = v_uint32()
self._33 = v_uint32()
self._34 = v_uint32()
self._41 = v_uint32()
self._42 = v_uint32()
self._43 = v_uint32()
self._44 = v_uint32()
class _unnamed_13952(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Start = LARGE_INTEGER()
self.Length64 = v_uint32()
class CONSOLE_CARET_INFO(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.hwnd = v_ptr64()
self.rc = tagRECT()
class D3DKMDT_VIDPN_PRESENT_PATH_ROTATION_SUPPORT(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Identity = v_uint32()
class _unnamed_14462(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Length = v_uint32()
self.Alignment = v_uint32()
self.MinimumAddress = LARGE_INTEGER()
self.MaximumAddress = LARGE_INTEGER()
class WHEA_ERROR_RECORD_HEADER(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Signature = v_uint32()
self.Revision = WHEA_REVISION()
self.SignatureEnd = v_uint32()
self.SectionCount = v_uint16()
self.Severity = v_uint32()
self.ValidBits = WHEA_ERROR_RECORD_HEADER_VALIDBITS()
self.Length = v_uint32()
self.Timestamp = WHEA_TIMESTAMP()
self.PlatformId = GUID()
self.PartitionId = GUID()
self.CreatorId = GUID()
self.NotifyType = GUID()
self.RecordId = v_uint64()
self.Flags = WHEA_ERROR_RECORD_HEADER_FLAGS()
self.PersistenceInfo = WHEA_PERSISTENCE_INFO()
self.Reserved = vstruct.VArray([ v_uint8() for i in range(12) ])
class EVENT_DESCRIPTOR(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Id = v_uint16()
self.Version = v_uint8()
self.Channel = v_uint8()
self.Level = v_uint8()
self.Opcode = v_uint8()
self.Task = v_uint16()
self.Keyword = v_uint64()
class HRGN(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.unused = v_uint32()
class _unnamed_10391(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Length = v_ptr64()
self.Key = v_uint32()
self._pad0010 = v_bytes(size=4)
self.ByteOffset = LARGE_INTEGER()
class _unnamed_10396(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.OutputBufferLength = v_uint32()
self._pad0008 = v_bytes(size=4)
self.InputBufferLength = v_uint32()
self._pad0010 = v_bytes(size=4)
self.IoControlCode = v_uint32()
self._pad0018 = v_bytes(size=4)
self.Type3InputBuffer = v_ptr64()
class tagSBINFO(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.WSBflags = v_uint32()
self.Horz = tagSBDATA()
self.Vert = tagSBDATA()
class FLS_CALLBACK_INFO(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
class _unnamed_10255(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.SecurityContext = v_ptr64()
self.Options = v_uint32()
self._pad0010 = v_bytes(size=4)
self.FileAttributes = v_uint16()
self.ShareAccess = v_uint16()
self._pad0018 = v_bytes(size=4)
self.EaLength = v_uint32()
self._pad0020 = v_bytes(size=4)
class LIST_ENTRY64(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Flink = v_uint64()
self.Blink = v_uint64()
class tagOEMBITMAPINFO(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.x = v_uint32()
self.y = v_uint32()
self.cx = v_uint32()
self.cy = v_uint32()
class _unnamed_10497(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.IoResourceRequirementList = v_ptr64()
class ACTIVATION_CONTEXT_STACK(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.ActiveFrame = v_ptr64()
self.FrameListCache = LIST_ENTRY()
self.Flags = v_uint32()
self.NextCookieSequenceNumber = v_uint32()
self.StackId = v_uint32()
self._pad0028 = v_bytes(size=4)
class tagITEM(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.fType = v_uint32()
self.fState = v_uint32()
self.wID = v_uint32()
self._pad0010 = v_bytes(size=4)
self.spSubMenu = v_ptr64()
self.hbmpChecked = v_ptr64()
self.hbmpUnchecked = v_ptr64()
self.lpstr = v_ptr64()
self.cch = v_uint32()
self._pad0038 = v_bytes(size=4)
self.dwItemData = v_uint64()
self.xItem = v_uint32()
self.yItem = v_uint32()
self.cxItem = v_uint32()
self.cyItem = v_uint32()
self.dxTab = v_uint32()
self.ulX = v_uint32()
self.ulWidth = v_uint32()
self._pad0060 = v_bytes(size=4)
self.hbmp = v_ptr64()
self.cxBmp = v_uint32()
self.cyBmp = v_uint32()
self.umim = tagUAHMENUITEMMETRICS()
class IO_DRIVER_CREATE_CONTEXT(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Size = v_uint16()
self._pad0008 = v_bytes(size=6)
self.ExtraCreateParameter = v_ptr64()
self.DeviceObjectHint = v_ptr64()
self.TxnParameters = v_ptr64()
class LOOKASIDE_LIST_EX(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.L = GENERAL_LOOKASIDE_POOL()
class TEB(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.NtTib = NT_TIB()
self.EnvironmentPointer = v_ptr64()
self.ClientId = CLIENT_ID()
self.ActiveRpcHandle = v_ptr64()
self.ThreadLocalStoragePointer = v_ptr64()
self.ProcessEnvironmentBlock = v_ptr64()
self.LastErrorValue = v_uint32()
self.CountOfOwnedCriticalSections = v_uint32()
self.CsrClientThread = v_ptr64()
self.Win32ThreadInfo = v_ptr64()
self.User32Reserved = vstruct.VArray([ v_uint32() for i in range(26) ])
self.UserReserved = vstruct.VArray([ v_uint32() for i in range(5) ])
self._pad0100 = v_bytes(size=4)
self.WOW32Reserved = v_ptr64()
self.CurrentLocale = v_uint32()
self.FpSoftwareStatusRegister = v_uint32()
self.SystemReserved1 = vstruct.VArray([ v_ptr64() for i in range(54) ])
self.ExceptionCode = v_uint32()
self._pad02c8 = v_bytes(size=4)
self.ActivationContextStackPointer = v_ptr64()
self.SpareBytes = vstruct.VArray([ v_uint8() for i in range(24) ])
self.TxFsContext = v_uint32()
self._pad02f0 = v_bytes(size=4)
self.GdiTebBatch = GDI_TEB_BATCH()
self.RealClientId = CLIENT_ID()
self.GdiCachedProcessHandle = v_ptr64()
self.GdiClientPID = v_uint32()
self.GdiClientTID = v_uint32()
self.GdiThreadLocalInfo = v_ptr64()
self.Win32ClientInfo = vstruct.VArray([ v_uint64() for i in range(62) ])
self.glDispatchTable = vstruct.VArray([ v_ptr64() for i in range(233) ])
self.glReserved1 = vstruct.VArray([ v_uint64() for i in range(29) ])
self.glReserved2 = v_ptr64()
self.glSectionInfo = v_ptr64()
self.glSection = v_ptr64()
self.glTable = v_ptr64()
self.glCurrentRC = v_ptr64()
self.glContext = v_ptr64()
self.LastStatusValue = v_uint32()
self._pad1258 = v_bytes(size=4)
self.StaticUnicodeString = UNICODE_STRING()
self.StaticUnicodeBuffer = vstruct.VArray([ v_uint16() for i in range(261) ])
self._pad1478 = v_bytes(size=6)
self.DeallocationStack = v_ptr64()
self.TlsSlots = vstruct.VArray([ v_ptr64() for i in range(64) ])
self.TlsLinks = LIST_ENTRY()
self.Vdm = v_ptr64()
self.ReservedForNtRpc = v_ptr64()
self.DbgSsReserved = vstruct.VArray([ v_ptr64() for i in range(2) ])
self.HardErrorMode = v_uint32()
self._pad16b8 = v_bytes(size=4)
self.Instrumentation = vstruct.VArray([ v_ptr64() for i in range(11) ])
self.ActivityId = GUID()
self.SubProcessTag = v_ptr64()
self.EtwLocalData = v_ptr64()
self.EtwTraceData = v_ptr64()
self.WinSockData = v_ptr64()
self.GdiBatchCount = v_uint32()
self.CurrentIdealProcessor = PROCESSOR_NUMBER()
self.GuaranteedStackBytes = v_uint32()
self._pad1750 = v_bytes(size=4)
self.ReservedForPerf = v_ptr64()
self.ReservedForOle = v_ptr64()
self.WaitingOnLoaderLock = v_uint32()
self._pad1768 = v_bytes(size=4)
self.SavedPriorityState = v_ptr64()
self.SoftPatchPtr1 = v_uint64()
self.ThreadPoolData = v_ptr64()
self.TlsExpansionSlots = v_ptr64()
self.DeallocationBStore = v_ptr64()
self.BStoreLimit = v_ptr64()
self.MuiGeneration = v_uint32()
self.IsImpersonating = v_uint32()
self.NlsCache = v_ptr64()
self.pShimData = v_ptr64()
self.HeapVirtualAffinity = v_uint32()
self._pad17b8 = v_bytes(size=4)
self.CurrentTransactionHandle = v_ptr64()
self.ActiveFrame = v_ptr64()
self.FlsData = v_ptr64()
self.PreferredLanguages = v_ptr64()
self.UserPrefLanguages = v_ptr64()
self.MergedPrefLanguages = v_ptr64()
self.MuiImpersonation = v_uint32()
self.CrossTebFlags = v_uint16()
self.SameTebFlags = v_uint16()
self.TxnScopeEnterCallback = v_ptr64()
self.TxnScopeExitCallback = v_ptr64()
self.TxnScopeContext = v_ptr64()
self.LockCount = v_uint32()
self.SpareUlong0 = v_uint32()
self.ResourceRetValue = v_ptr64()
class tagWIN32HEAP(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
class XSAVE_FORMAT(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.ControlWord = v_uint16()
self.StatusWord = v_uint16()
self.TagWord = v_uint8()
self.Reserved1 = v_uint8()
self.ErrorOpcode = v_uint16()
self.ErrorOffset = v_uint32()
self.ErrorSelector = v_uint16()
self.Reserved2 = v_uint16()
self.DataOffset = v_uint32()
self.DataSelector = v_uint16()
self.Reserved3 = v_uint16()
self.MxCsr = v_uint32()
self.MxCsr_Mask = v_uint32()
self.FloatRegisters = vstruct.VArray([ M128A() for i in range(8) ])
self.XmmRegisters = vstruct.VArray([ M128A() for i in range(16) ])
self.Reserved4 = vstruct.VArray([ v_uint8() for i in range(96) ])
class DMM_COMMITVIDPNREQUEST_DIAGINFO(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.ClientType = v_uint32()
self.ReclaimClonedTarget = v_uint8()
self._pad0008 = v_bytes(size=3)
self.ModeChangeRequestId = v_uint32()
class IMAGE_DOS_HEADER(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.e_magic = v_uint16()
self.e_cblp = v_uint16()
self.e_cp = v_uint16()
self.e_crlc = v_uint16()
self.e_cparhdr = v_uint16()
self.e_minalloc = v_uint16()
self.e_maxalloc = v_uint16()
self.e_ss = v_uint16()
self.e_sp = v_uint16()
self.e_csum = v_uint16()
self.e_ip = v_uint16()
self.e_cs = v_uint16()
self.e_lfarlc = v_uint16()
self.e_ovno = v_uint16()
self.e_res = vstruct.VArray([ v_uint16() for i in range(4) ])
self.e_oemid = v_uint16()
self.e_oeminfo = v_uint16()
self.e_res2 = vstruct.VArray([ v_uint16() for i in range(10) ])
self.e_lfanew = v_uint32()
class RTL_DYNAMIC_HASH_TABLE_ENTRY(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Linkage = LIST_ENTRY()
self.Signature = v_uint64()
class _unnamed_13776(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.pRgb256x3x16 = v_ptr64()
class _unnamed_10086(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.MasterIrp = v_ptr64()
class TXN_PARAMETER_BLOCK(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Length = v_uint16()
self.TxFsContext = v_uint16()
self._pad0008 = v_bytes(size=4)
self.TransactionObject = v_ptr64()
class _unnamed_10796(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.InitialPrivilegeSet = INITIAL_PRIVILEGE_SET()
class QUAD(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.UseThisFieldToCopy = v_uint64()
class RTL_DYNAMIC_HASH_TABLE(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Flags = v_uint32()
self.Shift = v_uint32()
self.TableSize = v_uint32()
self.Pivot = v_uint32()
self.DivisorMask = v_uint32()
self.NumEntries = v_uint32()
self.NonEmptyBuckets = v_uint32()
self.NumEnumerators = v_uint32()
self.Directory = v_ptr64()
class tagSERVERINFO(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.dwSRVIFlags = v_uint32()
self._pad0008 = v_bytes(size=4)
self.cHandleEntries = v_uint64()
self.mpFnidPfn = vstruct.VArray([ v_ptr64() for i in range(32) ])
self.aStoCidPfn = vstruct.VArray([ v_ptr64() for i in range(7) ])
self.mpFnid_serverCBWndProc = vstruct.VArray([ v_uint16() for i in range(31) ])
self._pad0188 = v_bytes(size=2)
self.apfnClientA = PFNCLIENT()
self.apfnClientW = PFNCLIENT()
self.apfnClientWorker = PFNCLIENTWORKER()
self.cbHandleTable = v_uint32()
self.atomSysClass = vstruct.VArray([ v_uint16() for i in range(25) ])
self._pad0388 = v_bytes(size=2)
self.dwDefaultHeapBase = v_uint32()
self.dwDefaultHeapSize = v_uint32()
self.uiShellMsg = v_uint32()
self.MBStrings = vstruct.VArray([ tagMBSTRING() for i in range(11) ])
self.atomIconSmProp = v_uint16()
self.atomIconProp = v_uint16()
self.atomContextHelpIdProp = v_uint16()
self.atomFrostedWindowProp = v_uint16()
self.acOemToAnsi = vstruct.VArray([ v_uint8() for i in range(256) ])
self.acAnsiToOem = vstruct.VArray([ v_uint8() for i in range(256) ])
self.dwInstalledEventHooks = v_uint32()
self.aiSysMet = vstruct.VArray([ v_uint32() for i in range(97) ])
self.argbSystemUnmatched = vstruct.VArray([ v_uint32() for i in range(31) ])
self.argbSystem = vstruct.VArray([ v_uint32() for i in range(31) ])
self._pad09d8 = v_bytes(size=4)
self.ahbrSystem = vstruct.VArray([ v_ptr64() for i in range(31) ])
self.hbrGray = v_ptr64()
self.ptCursor = tagPOINT()
self.ptCursorReal = tagPOINT()
self.dwLastRITEventTickCount = v_uint32()
self.nEvents = v_uint32()
self.dtScroll = v_uint32()
self.dtLBSearch = v_uint32()
self.dtCaretBlink = v_uint32()
self.ucWheelScrollLines = v_uint32()
self.ucWheelScrollChars = v_uint32()
self.wMaxLeftOverlapChars = v_uint32()
self.wMaxRightOverlapChars = v_uint32()
self.cxSysFontChar = v_uint32()
self.cySysFontChar = v_uint32()
self.tmSysFont = tagTEXTMETRICW()
self.dpiSystem = tagDPISERVERINFO()
self.hIconSmWindows = v_ptr64()
self.hIcoWindows = v_ptr64()
self.dwKeyCache = v_uint32()
self.dwAsyncKeyCache = v_uint32()
self.cCaptures = v_uint32()
self.oembmi = vstruct.VArray([ tagOEMBITMAPINFO() for i in range(93) ])
self.rcScreenReal = tagRECT()
self.BitCount = v_uint16()
self.dmLogPixels = v_uint16()
self.Planes = v_uint8()
self.BitsPixel = v_uint8()
self._pad117c = v_bytes(size=2)
self.PUSIFlags = v_uint32()
self.uCaretWidth = v_uint32()
self.UILangID = v_uint16()
self._pad1188 = v_bytes(size=2)
self.dwLastSystemRITEventTickCountUpdate = v_uint32()
self.adwDBGTAGFlags = vstruct.VArray([ v_uint32() for i in range(35) ])
self.dwTagCount = v_uint32()
self.dwRIPFlags = v_uint32()
class DEVICE_OBJECT(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Type = v_uint16()
self.Size = v_uint16()
self.ReferenceCount = v_uint32()
self.DriverObject = v_ptr64()
self.NextDevice = v_ptr64()
self.AttachedDevice = v_ptr64()
self.CurrentIrp = v_ptr64()
self.Timer = v_ptr64()
self.Flags = v_uint32()
self.Characteristics = v_uint32()
self.Vpb = v_ptr64()
self.DeviceExtension = v_ptr64()
self.DeviceType = v_uint32()
self.StackSize = v_uint8()
self._pad0050 = v_bytes(size=3)
self.Queue = _unnamed_10148()
self.AlignmentRequirement = v_uint32()
self._pad00a0 = v_bytes(size=4)
self.DeviceQueue = KDEVICE_QUEUE()
self.Dpc = KDPC()
self.ActiveThreadCount = v_uint32()
self._pad0110 = v_bytes(size=4)
self.SecurityDescriptor = v_ptr64()
self.DeviceLock = KEVENT()
self.SectorSize = v_uint16()
self.Spare1 = v_uint16()
self._pad0138 = v_bytes(size=4)
self.DeviceObjectExtension = v_ptr64()
self.Reserved = v_ptr64()
self._pad0150 = v_bytes(size=8)
class KTSS64(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.Reserved0 = v_uint32()
self.Rsp0 = v_uint64()
self.Rsp1 = v_uint64()
self.Rsp2 = v_uint64()
self.Ist = vstruct.VArray([ v_uint64() for i in range(8) ])
self.Reserved1 = v_uint64()
self.Reserved2 = v_uint16()
self.IoMapBase = v_uint16()
class tagCLIENTINFO(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.CI_flags = v_uint64()
self.cSpins = v_uint64()
self.dwExpWinVer = v_uint32()
self.dwCompatFlags = v_uint32()
self.dwCompatFlags2 = v_uint32()
self.dwTIFlags = v_uint32()
self.pDeskInfo = v_ptr64()
self.ulClientDelta = v_uint64()
self.phkCurrent = v_ptr64()
self.fsHooks = v_uint32()
self._pad0040 = v_bytes(size=4)
self.CallbackWnd = CALLBACKWND()
self.dwHookCurrent = v_uint32()
self.cInDDEMLCallback = v_uint32()
self.pClientThreadInfo = v_ptr64()
self.dwHookData = v_uint64()
self.dwKeyCache = v_uint32()
self.afKeyState = vstruct.VArray([ v_uint8() for i in range(8) ])
self.dwAsyncKeyCache = v_uint32()
self.afAsyncKeyState = vstruct.VArray([ v_uint8() for i in range(8) ])
self.afAsyncKeyStateRecentDown = vstruct.VArray([ v_uint8() for i in range(8) ])
self.hKL = v_ptr64()
self.CodePage = v_uint16()
self.achDbcsCF = vstruct.VArray([ v_uint8() for i in range(2) ])
self._pad00a0 = v_bytes(size=4)
self.msgDbcsCB = tagMSG()
self.lpdwRegisteredClasses = v_ptr64()
class HWINSTA(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.unused = v_uint32()
class TL(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.next = v_ptr64()
self.pobj = v_ptr64()
self.pfnFree = v_ptr64()
class IO_STACK_LOCATION(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.MajorFunction = v_uint8()
self.MinorFunction = v_uint8()
self.Flags = v_uint8()
self.Control = v_uint8()
self._pad0008 = v_bytes(size=4)
self.Parameters = _unnamed_10168()
self.DeviceObject = v_ptr64()
self.FileObject = v_ptr64()
self.CompletionRoutine = v_ptr64()
self.Context = v_ptr64()
class tagTERMINAL(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.dwTERMF_Flags = v_uint32()
self._pad0008 = v_bytes(size=4)
self.spwndDesktopOwner = v_ptr64()
self.ptiDesktop = v_ptr64()
self.pqDesktop = v_ptr64()
self.dwNestedLevel = v_uint32()
self._pad0028 = v_bytes(size=4)
self.pEventTermInit = v_ptr64()
self.rpdeskDestroy = v_ptr64()
self.pEventInputReady = v_ptr64()
class D3DKMDT_VIDPN_PRESENT_PATH(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.VidPnSourceId = v_uint32()
self.VidPnTargetId = v_uint32()
self.ImportanceOrdinal = v_uint32()
self.ContentTransformation = D3DKMDT_VIDPN_PRESENT_PATH_TRANSFORMATION()
self.VisibleFromActiveTLOffset = D3DKMDT_2DREGION()
self.VisibleFromActiveBROffset = D3DKMDT_2DREGION()
self.VidPnTargetColorBasis = v_uint32()
self.VidPnTargetColorCoeffDynamicRanges = D3DKMDT_COLOR_COEFF_DYNAMIC_RANGES()
self.Content = v_uint32()
self.CopyProtection = D3DKMDT_VIDPN_PRESENT_PATH_COPYPROTECTION()
self.GammaRamp = D3DKMDT_GAMMA_RAMP()
class tagMENULIST(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.pNext = v_ptr64()
self.pMenu = v_ptr64()
class VK_VALUES_STRINGS(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.pszMultiNames = v_ptr64()
self.fReserved = v_uint8()
self._pad0010 = v_bytes(size=7)
class tagKL(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.head = HEAD()
self.pklNext = v_ptr64()
self.pklPrev = v_ptr64()
self.dwKL_Flags = v_uint32()
self._pad0028 = v_bytes(size=4)
self.hkl = v_ptr64()
self.spkf = v_ptr64()
self.spkfPrimary = v_ptr64()
self.dwFontSigs = v_uint32()
self.iBaseCharset = v_uint32()
self.CodePage = v_uint16()
self.wchDiacritic = v_uint16()
self._pad0050 = v_bytes(size=4)
self.piiex = v_ptr64()
self.uNumTbl = v_uint32()
self._pad0060 = v_bytes(size=4)
self.pspkfExtra = v_ptr64()
self.dwLastKbdType = v_uint32()
self.dwLastKbdSubType = v_uint32()
self.dwKLID = v_uint32()
self._pad0078 = v_bytes(size=4)
class tagPOINT(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.x = v_uint32()
self.y = v_uint32()
class RTL_USER_PROCESS_PARAMETERS(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.MaximumLength = v_uint32()
self.Length = v_uint32()
self.Flags = v_uint32()
self.DebugFlags = v_uint32()
self.ConsoleHandle = v_ptr64()
self.ConsoleFlags = v_uint32()
self._pad0020 = v_bytes(size=4)
self.StandardInput = v_ptr64()
self.StandardOutput = v_ptr64()
self.StandardError = v_ptr64()
self.CurrentDirectory = CURDIR()
self.DllPath = UNICODE_STRING()
self.ImagePathName = UNICODE_STRING()
self.CommandLine = UNICODE_STRING()
self.Environment = v_ptr64()
self.StartingX = v_uint32()
self.StartingY = v_uint32()
self.CountX = v_uint32()
self.CountY = v_uint32()
self.CountCharsX = v_uint32()
self.CountCharsY = v_uint32()
self.FillAttribute = v_uint32()
self.WindowFlags = v_uint32()
self.ShowWindowFlags = v_uint32()
self._pad00b0 = v_bytes(size=4)
self.WindowTitle = UNICODE_STRING()
self.DesktopInfo = UNICODE_STRING()
self.ShellInfo = UNICODE_STRING()
self.RuntimeData = UNICODE_STRING()
self.CurrentDirectores = vstruct.VArray([ RTL_DRIVE_LETTER_CURDIR() for i in range(32) ])
self.EnvironmentSize = v_uint64()
self.EnvironmentVersion = v_uint64()
class tagSHAREDINFO(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.psi = v_ptr64()
self.aheList = v_ptr64()
self.HeEntrySize = v_uint32()
self._pad0018 = v_bytes(size=4)
self.pDispInfo = v_ptr64()
self.ulSharedDelta = v_uint64()
self.awmControl = vstruct.VArray([ WNDMSG() for i in range(31) ])
self.DefWindowMsgs = WNDMSG()
self.DefWindowSpecMsgs = WNDMSG()
class _unnamed_10107(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.UserApcRoutine = v_ptr64()
self.UserApcContext = v_ptr64()
class tagIMC(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.head = THRDESKHEAD()
self.pImcNext = v_ptr64()
self.dwClientImcData = v_uint64()
self.hImeWnd = v_ptr64()
class IO_RESOURCE_REQUIREMENTS_LIST(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.ListSize = v_uint32()
self.InterfaceType = v_uint32()
self.BusNumber = v_uint32()
self.SlotNumber = v_uint32()
self.Reserved = vstruct.VArray([ v_uint32() for i in range(3) ])
self.AlternativeLists = v_uint32()
self.List = vstruct.VArray([ IO_RESOURCE_LIST() for i in range(1) ])
class tagCARET(vstruct.VStruct):
def __init__(self):
vstruct.VStruct.__init__(self)
self.spwnd = v_ptr64()
self.fVisible = v_uint32()
self.iHideLevel = v_uint32()
self.x = v_uint32()
self.y = v_uint32()
self.cy = v_uint32()
self.cx = v_uint32()
self.hBitmap = v_ptr64()
self.hTimer = v_uint64()
self.tid = v_uint32()
self.xOwnDc = v_uint32()
self.yOwnDc = v_uint32()
self.cxOwnDc = v_uint32()
self.cyOwnDc = v_uint32()
self._pad0048 = v_bytes(size=4)
|
FlorianLudwig/odoo
|
refs/heads/8.0
|
addons/website/models/ir_ui_view.py
|
161
|
# -*- coding: utf-8 -*-
import copy
from lxml import etree, html
from openerp import SUPERUSER_ID, api
from openerp.addons.website.models import website
from openerp.http import request
from openerp.osv import osv, fields
class view(osv.osv):
_inherit = "ir.ui.view"
_columns = {
'page': fields.boolean("Whether this view is a web page template (complete)"),
'website_meta_title': fields.char("Website meta title", size=70, translate=True),
'website_meta_description': fields.text("Website meta description", size=160, translate=True),
'website_meta_keywords': fields.char("Website meta keywords", translate=True),
'customize_show': fields.boolean("Show As Optional Inherit"),
}
_defaults = {
'page': False,
'customize_show': False,
}
def _view_obj(self, cr, uid, view_id, context=None):
if isinstance(view_id, basestring):
return self.pool['ir.model.data'].xmlid_to_object(
cr, uid, view_id, raise_if_not_found=True, context=context
)
elif isinstance(view_id, (int, long)):
return self.browse(cr, uid, view_id, context=context)
# assume it's already a view object (WTF?)
return view_id
# Returns all views (called and inherited) related to a view
# Used by translation mechanism, SEO and optional templates
def _views_get(self, cr, uid, view_id, options=True, context=None, root=True):
""" For a given view ``view_id``, should return:
* the view itself
* all views inheriting from it, enabled or not
- but not the optional children of a non-enabled child
* all views called from it (via t-call)
"""
try:
view = self._view_obj(cr, uid, view_id, context=context)
except ValueError:
# Shall we log that ?
return []
while root and view.inherit_id:
view = view.inherit_id
result = [view]
node = etree.fromstring(view.arch)
for child in node.xpath("//t[@t-call]"):
try:
called_view = self._view_obj(cr, uid, child.get('t-call'), context=context)
except ValueError:
continue
if called_view not in result:
result += self._views_get(cr, uid, called_view, options=options, context=context)
extensions = view.inherit_children_ids
if not options:
# only active children
extensions = (v for v in view.inherit_children_ids if v.active)
# Keep options in a deterministic order regardless of their applicability
for extension in sorted(extensions, key=lambda v: v.id):
for r in self._views_get(
cr, uid, extension,
# only return optional grandchildren if this child is enabled
options=extension.active,
context=context, root=False):
if r not in result:
result.append(r)
return result
def extract_embedded_fields(self, cr, uid, arch, context=None):
return arch.xpath('//*[@data-oe-model != "ir.ui.view"]')
def save_embedded_field(self, cr, uid, el, context=None):
Model = self.pool[el.get('data-oe-model')]
field = el.get('data-oe-field')
converter = self.pool['website.qweb'].get_converter_for(el.get('data-oe-type'))
value = converter.from_html(cr, uid, Model, Model._fields[field], el)
if value is not None:
# TODO: batch writes?
Model.write(cr, uid, [int(el.get('data-oe-id'))], {
field: value
}, context=context)
def to_field_ref(self, cr, uid, el, context=None):
# filter out meta-information inserted in the document
attributes = dict((k, v) for k, v in el.items()
if not k.startswith('data-oe-'))
attributes['t-field'] = el.get('data-oe-expression')
out = html.html_parser.makeelement(el.tag, attrib=attributes)
out.tail = el.tail
return out
def replace_arch_section(self, cr, uid, view_id, section_xpath, replacement, context=None):
# the root of the arch section shouldn't actually be replaced as it's
# not really editable itself, only the content truly is editable.
[view] = self.browse(cr, uid, [view_id], context=context)
arch = etree.fromstring(view.arch.encode('utf-8'))
# => get the replacement root
if not section_xpath:
root = arch
else:
# ensure there's only one match
[root] = arch.xpath(section_xpath)
root.text = replacement.text
root.tail = replacement.tail
# replace all children
del root[:]
for child in replacement:
root.append(copy.deepcopy(child))
return arch
@api.cr_uid_ids_context
def render(self, cr, uid, id_or_xml_id, values=None, engine='ir.qweb', context=None):
if request and getattr(request, 'website_enabled', False):
engine='website.qweb'
if isinstance(id_or_xml_id, list):
id_or_xml_id = id_or_xml_id[0]
if not context:
context = {}
company = self.pool['res.company'].browse(cr, SUPERUSER_ID, request.website.company_id.id, context=context)
qcontext = dict(
context.copy(),
website=request.website,
url_for=website.url_for,
slug=website.slug,
res_company=company,
user_id=self.pool.get("res.users").browse(cr, uid, uid),
translatable=context.get('lang') != request.website.default_lang_code,
editable=request.website.is_publisher(),
menu_data=self.pool['ir.ui.menu'].load_menus_root(cr, uid, context=context) if request.website.is_user() else None,
)
# add some values
if values:
qcontext.update(values)
# in edit mode ir.ui.view will tag nodes
if qcontext.get('editable'):
context = dict(context, inherit_branding=True)
elif request.registry['res.users'].has_group(cr, uid, 'base.group_website_publisher'):
context = dict(context, inherit_branding_auto=True)
view_obj = request.website.get_template(id_or_xml_id)
if 'main_object' not in qcontext:
qcontext['main_object'] = view_obj
values = qcontext
return super(view, self).render(cr, uid, id_or_xml_id, values=values, engine=engine, context=context)
def _pretty_arch(self, arch):
# remove_blank_string does not seem to work on HTMLParser, and
# pretty-printing with lxml more or less requires stripping
# whitespace: http://lxml.de/FAQ.html#why-doesn-t-the-pretty-print-option-reformat-my-xml-output
# so serialize to XML, parse as XML (remove whitespace) then serialize
# as XML (pretty print)
arch_no_whitespace = etree.fromstring(
etree.tostring(arch, encoding='utf-8'),
parser=etree.XMLParser(encoding='utf-8', remove_blank_text=True))
return etree.tostring(
arch_no_whitespace, encoding='unicode', pretty_print=True)
def save(self, cr, uid, res_id, value, xpath=None, context=None):
""" Update a view section. The view section may embed fields to write
:param str model:
:param int res_id:
:param str xpath: valid xpath to the tag to replace
"""
res_id = int(res_id)
arch_section = html.fromstring(
value, parser=html.HTMLParser(encoding='utf-8'))
if xpath is None:
# value is an embedded field on its own, not a view section
self.save_embedded_field(cr, uid, arch_section, context=context)
return
for el in self.extract_embedded_fields(cr, uid, arch_section, context=context):
self.save_embedded_field(cr, uid, el, context=context)
# transform embedded field back to t-field
el.getparent().replace(el, self.to_field_ref(cr, uid, el, context=context))
arch = self.replace_arch_section(cr, uid, res_id, xpath, arch_section, context=context)
self.write(cr, uid, res_id, {
'arch': self._pretty_arch(arch)
}, context=context)
view = self.browse(cr, SUPERUSER_ID, res_id, context=context)
if view.model_data_id:
view.model_data_id.write({'noupdate': True})
def customize_template_get(self, cr, uid, xml_id, full=False, bundles=False , context=None):
""" Get inherit view's informations of the template ``key``. By default, only
returns ``customize_show`` templates (which can be active or not), if
``full=True`` returns inherit view's informations of the template ``key``.
``bundles=True`` returns also the asset bundles
"""
imd = request.registry['ir.model.data']
view_model, view_theme_id = imd.get_object_reference(cr, uid, 'website', 'theme')
user = request.registry['res.users'].browse(cr, uid, uid, context)
user_groups = set(user.groups_id)
views = self._views_get(cr, uid, xml_id, context=dict(context or {}, active_test=False))
done = set()
result = []
for v in views:
if not user_groups.issuperset(v.groups_id):
continue
if full or (v.customize_show and v.inherit_id.id != view_theme_id):
if v.inherit_id not in done:
result.append({
'name': v.inherit_id.name,
'id': v.id,
'xml_id': v.xml_id,
'inherit_id': v.inherit_id.id,
'header': True,
'active': False
})
done.add(v.inherit_id)
result.append({
'name': v.name,
'id': v.id,
'xml_id': v.xml_id,
'inherit_id': v.inherit_id.id,
'header': False,
'active': v.active,
})
return result
def get_view_translations(self, cr, uid, xml_id, lang, field=['id', 'res_id', 'value', 'state', 'gengo_translation'], context=None):
views = self.customize_template_get(cr, uid, xml_id, full=True, context=context)
views_ids = [view.get('id') for view in views if view.get('active')]
domain = [('type', '=', 'view'), ('res_id', 'in', views_ids), ('lang', '=', lang)]
irt = request.registry.get('ir.translation')
return irt.search_read(cr, uid, domain, field, context=context)
|
nyuwireless/ns3-mmwave
|
refs/heads/master
|
waf-tools/clang_compilation_database.py
|
99
|
#!/usr/bin/env python
# encoding: utf-8
# Christoph Koke, 2013
"""
Writes the c and cpp compile commands into build/compile_commands.json
see http://clang.llvm.org/docs/JSONCompilationDatabase.html
Usage:
def configure(conf):
conf.load('compiler_cxx')
...
conf.load('clang_compilation_database')
"""
import sys, os, json, shlex, pipes
from waflib import Logs, TaskGen
from waflib.Tools import c, cxx
if sys.hexversion >= 0x3030000:
quote = shlex.quote
else:
quote = pipes.quote
@TaskGen.feature('*')
@TaskGen.after_method('process_use')
def collect_compilation_db_tasks(self):
"Add a compilation database entry for compiled tasks"
try:
clang_db = self.bld.clang_compilation_database_tasks
except AttributeError:
clang_db = self.bld.clang_compilation_database_tasks = []
self.bld.add_post_fun(write_compilation_database)
for task in getattr(self, 'compiled_tasks', []):
if isinstance(task, (c.c, cxx.cxx)):
clang_db.append(task)
def write_compilation_database(ctx):
"Write the clang compilation database as JSON"
database_file = ctx.bldnode.make_node('compile_commands.json')
Logs.info("Build commands will be stored in %s" % database_file.path_from(ctx.path))
try:
root = json.load(database_file)
except IOError:
root = []
clang_db = dict((x["file"], x) for x in root)
for task in getattr(ctx, 'clang_compilation_database_tasks', []):
try:
cmd = task.last_cmd
except AttributeError:
continue
directory = getattr(task, 'cwd', ctx.variant_dir)
f_node = task.inputs[0]
filename = os.path.relpath(f_node.abspath(), directory)
cmd = " ".join(map(quote, cmd))
entry = {
"directory": directory,
"command": cmd,
"file": filename,
}
clang_db[filename] = entry
root = list(clang_db.values())
database_file.write(json.dumps(root, indent=2))
|
jiangzhuo/kbengine
|
refs/heads/master
|
kbe/res/scripts/common/Lib/site-packages/pip/_vendor/requests/packages/urllib3/packages/ordered_dict.py
|
1093
|
# Backport of OrderedDict() class that runs on Python 2.4, 2.5, 2.6, 2.7 and pypy.
# Passes Python2.7's test suite and incorporates all the latest updates.
# Copyright 2009 Raymond Hettinger, released under the MIT License.
# http://code.activestate.com/recipes/576693/
try:
from thread import get_ident as _get_ident
except ImportError:
from dummy_thread import get_ident as _get_ident
try:
from _abcoll import KeysView, ValuesView, ItemsView
except ImportError:
pass
class OrderedDict(dict):
'Dictionary that remembers insertion order'
# An inherited dict maps keys to values.
# The inherited dict provides __getitem__, __len__, __contains__, and get.
# The remaining methods are order-aware.
# Big-O running times for all methods are the same as for regular dictionaries.
# The internal self.__map dictionary maps keys to links in a doubly linked list.
# The circular doubly linked list starts and ends with a sentinel element.
# The sentinel element never gets deleted (this simplifies the algorithm).
# Each link is stored as a list of length three: [PREV, NEXT, KEY].
def __init__(self, *args, **kwds):
'''Initialize an ordered dictionary. Signature is the same as for
regular dictionaries, but keyword arguments are not recommended
because their insertion order is arbitrary.
'''
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
try:
self.__root
except AttributeError:
self.__root = root = [] # sentinel node
root[:] = [root, root, None]
self.__map = {}
self.__update(*args, **kwds)
def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
'od.__setitem__(i, y) <==> od[i]=y'
# Setting a new item creates a new link which goes at the end of the linked
# list, and the inherited dictionary is updated with the new key/value pair.
if key not in self:
root = self.__root
last = root[0]
last[1] = root[0] = self.__map[key] = [last, root, key]
dict_setitem(self, key, value)
def __delitem__(self, key, dict_delitem=dict.__delitem__):
'od.__delitem__(y) <==> del od[y]'
# Deleting an existing item uses self.__map to find the link which is
# then removed by updating the links in the predecessor and successor nodes.
dict_delitem(self, key)
link_prev, link_next, key = self.__map.pop(key)
link_prev[1] = link_next
link_next[0] = link_prev
def __iter__(self):
'od.__iter__() <==> iter(od)'
root = self.__root
curr = root[1]
while curr is not root:
yield curr[2]
curr = curr[1]
def __reversed__(self):
'od.__reversed__() <==> reversed(od)'
root = self.__root
curr = root[0]
while curr is not root:
yield curr[2]
curr = curr[0]
def clear(self):
'od.clear() -> None. Remove all items from od.'
try:
for node in self.__map.itervalues():
del node[:]
root = self.__root
root[:] = [root, root, None]
self.__map.clear()
except AttributeError:
pass
dict.clear(self)
def popitem(self, last=True):
'''od.popitem() -> (k, v), return and remove a (key, value) pair.
Pairs are returned in LIFO order if last is true or FIFO order if false.
'''
if not self:
raise KeyError('dictionary is empty')
root = self.__root
if last:
link = root[0]
link_prev = link[0]
link_prev[1] = root
root[0] = link_prev
else:
link = root[1]
link_next = link[1]
root[1] = link_next
link_next[0] = root
key = link[2]
del self.__map[key]
value = dict.pop(self, key)
return key, value
# -- the following methods do not depend on the internal structure --
def keys(self):
'od.keys() -> list of keys in od'
return list(self)
def values(self):
'od.values() -> list of values in od'
return [self[key] for key in self]
def items(self):
'od.items() -> list of (key, value) pairs in od'
return [(key, self[key]) for key in self]
def iterkeys(self):
'od.iterkeys() -> an iterator over the keys in od'
return iter(self)
def itervalues(self):
'od.itervalues -> an iterator over the values in od'
for k in self:
yield self[k]
def iteritems(self):
'od.iteritems -> an iterator over the (key, value) items in od'
for k in self:
yield (k, self[k])
def update(*args, **kwds):
'''od.update(E, **F) -> None. Update od from dict/iterable E and F.
If E is a dict instance, does: for k in E: od[k] = E[k]
If E has a .keys() method, does: for k in E.keys(): od[k] = E[k]
Or if E is an iterable of items, does: for k, v in E: od[k] = v
In either case, this is followed by: for k, v in F.items(): od[k] = v
'''
if len(args) > 2:
raise TypeError('update() takes at most 2 positional '
'arguments (%d given)' % (len(args),))
elif not args:
raise TypeError('update() takes at least 1 argument (0 given)')
self = args[0]
# Make progressively weaker assumptions about "other"
other = ()
if len(args) == 2:
other = args[1]
if isinstance(other, dict):
for key in other:
self[key] = other[key]
elif hasattr(other, 'keys'):
for key in other.keys():
self[key] = other[key]
else:
for key, value in other:
self[key] = value
for key, value in kwds.items():
self[key] = value
__update = update # let subclasses override update without breaking __init__
__marker = object()
def pop(self, key, default=__marker):
'''od.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised.
'''
if key in self:
result = self[key]
del self[key]
return result
if default is self.__marker:
raise KeyError(key)
return default
def setdefault(self, key, default=None):
'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
if key in self:
return self[key]
self[key] = default
return default
def __repr__(self, _repr_running={}):
'od.__repr__() <==> repr(od)'
call_key = id(self), _get_ident()
if call_key in _repr_running:
return '...'
_repr_running[call_key] = 1
try:
if not self:
return '%s()' % (self.__class__.__name__,)
return '%s(%r)' % (self.__class__.__name__, self.items())
finally:
del _repr_running[call_key]
def __reduce__(self):
'Return state information for pickling'
items = [[k, self[k]] for k in self]
inst_dict = vars(self).copy()
for k in vars(OrderedDict()):
inst_dict.pop(k, None)
if inst_dict:
return (self.__class__, (items,), inst_dict)
return self.__class__, (items,)
def copy(self):
'od.copy() -> a shallow copy of od'
return self.__class__(self)
@classmethod
def fromkeys(cls, iterable, value=None):
'''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S
and values equal to v (which defaults to None).
'''
d = cls()
for key in iterable:
d[key] = value
return d
def __eq__(self, other):
'''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive
while comparison to a regular mapping is order-insensitive.
'''
if isinstance(other, OrderedDict):
return len(self)==len(other) and self.items() == other.items()
return dict.__eq__(self, other)
def __ne__(self, other):
return not self == other
# -- the following methods are only used in Python 2.7 --
def viewkeys(self):
"od.viewkeys() -> a set-like object providing a view on od's keys"
return KeysView(self)
def viewvalues(self):
"od.viewvalues() -> an object providing a view on od's values"
return ValuesView(self)
def viewitems(self):
"od.viewitems() -> a set-like object providing a view on od's items"
return ItemsView(self)
|
pawelmhm/AutobahnPython
|
refs/heads/master
|
examples/twisted/websocket/echo/client_coroutines.py
|
18
|
###############################################################################
##
## Copyright (C) 2011-2014 Tavendo GmbH
##
## 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 autobahn.twisted.websocket import WebSocketClientProtocol, \
WebSocketClientFactory
from twisted.internet.defer import Deferred, inlineCallbacks
def sleep(delay):
d = Deferred()
reactor.callLater(delay, d.callback, None)
return d
class MyClientProtocol(WebSocketClientProtocol):
def onConnect(self, response):
print("Server connected: {0}".format(response.peer))
@inlineCallbacks
def onOpen(self):
print("WebSocket connection open.")
## start sending messages every second ..
while True:
self.sendMessage(u"Hello, world!".encode('utf8'))
self.sendMessage(b"\x00\x01\x03\x04", isBinary = True)
yield sleep(1)
def onMessage(self, payload, isBinary):
if isBinary:
print("Binary message received: {0} bytes".format(len(payload)))
else:
print("Text message received: {0}".format(payload.decode('utf8')))
def onClose(self, wasClean, code, reason):
print("WebSocket connection closed: {0}".format(reason))
if __name__ == '__main__':
import sys
from twisted.python import log
from twisted.internet import reactor
log.startLogging(sys.stdout)
factory = WebSocketClientFactory("ws://localhost:9000", debug = False)
factory.protocol = MyClientProtocol
reactor.connectTCP("127.0.0.1", 9000, factory)
reactor.run()
|
sharma1nitish/phantomjs
|
refs/heads/master
|
src/qt/qtwebkit/Tools/Scripts/webkitpy/common/watchlist/changedlinepattern.py
|
134
|
# Copyright (C) 2011 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
class ChangedLinePattern:
def __init__(self, compile_regex, index_for_zero_value):
self._regex = compile_regex
self._index_for_zero_value = index_for_zero_value
def match(self, path, diff_file):
for diff_line in diff_file:
if diff_line[self._index_for_zero_value]:
continue
if self._regex.search(diff_line[2]):
return True
return False
|
yunfeilu/scikit-learn
|
refs/heads/master
|
examples/decomposition/plot_pca_vs_lda.py
|
68
|
"""
=======================================================
Comparison of LDA and PCA 2D projection of Iris dataset
=======================================================
The Iris dataset represents 3 kind of Iris flowers (Setosa, Versicolour
and Virginica) with 4 attributes: sepal length, sepal width, petal length
and petal width.
Principal Component Analysis (PCA) applied to this data identifies the
combination of attributes (principal components, or directions in the
feature space) that account for the most variance in the data. Here we
plot the different samples on the 2 first principal components.
Linear Discriminant Analysis (LDA) tries to identify attributes that
account for the most variance *between classes*. In particular,
LDA, in contrast to PCA, is a supervised method, using known class labels.
"""
print(__doc__)
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.decomposition import PCA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
iris = datasets.load_iris()
X = iris.data
y = iris.target
target_names = iris.target_names
pca = PCA(n_components=2)
X_r = pca.fit(X).transform(X)
lda = LinearDiscriminantAnalysis(n_components=2)
X_r2 = lda.fit(X, y).transform(X)
# Percentage of variance explained for each components
print('explained variance ratio (first two components): %s'
% str(pca.explained_variance_ratio_))
plt.figure()
for c, i, target_name in zip("rgb", [0, 1, 2], target_names):
plt.scatter(X_r[y == i, 0], X_r[y == i, 1], c=c, label=target_name)
plt.legend()
plt.title('PCA of IRIS dataset')
plt.figure()
for c, i, target_name in zip("rgb", [0, 1, 2], target_names):
plt.scatter(X_r2[y == i, 0], X_r2[y == i, 1], c=c, label=target_name)
plt.legend()
plt.title('LDA of IRIS dataset')
plt.show()
|
ekiourk/ansible-modules-core
|
refs/heads/devel
|
cloud/rackspace/rax_cbs_attachments.py
|
157
|
#!/usr/bin/python
# 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/>.
# This is a DOCUMENTATION stub specific to this module, it extends
# a documentation fragment located in ansible.utils.module_docs_fragments
DOCUMENTATION = '''
---
module: rax_cbs_attachments
short_description: Manipulate Rackspace Cloud Block Storage Volume Attachments
description:
- Manipulate Rackspace Cloud Block Storage Volume Attachments
version_added: 1.6
options:
device:
description:
- The device path to attach the volume to, e.g. /dev/xvde
default: null
required: true
volume:
description:
- Name or id of the volume to attach/detach
default: null
required: true
server:
description:
- Name or id of the server to attach/detach
default: null
required: true
state:
description:
- Indicate desired state of the resource
choices:
- present
- absent
default: present
required: true
wait:
description:
- wait for the volume to be in 'in-use'/'available' state before returning
default: "no"
choices:
- "yes"
- "no"
wait_timeout:
description:
- how long before wait gives up, in seconds
default: 300
author:
- "Christopher H. Laco (@claco)"
- "Matt Martz (@sivel)"
extends_documentation_fragment: rackspace.openstack
'''
EXAMPLES = '''
- name: Attach a Block Storage Volume
gather_facts: False
hosts: local
connection: local
tasks:
- name: Storage volume attach request
local_action:
module: rax_cbs_attachments
credentials: ~/.raxpub
volume: my-volume
server: my-server
device: /dev/xvdd
region: DFW
wait: yes
state: present
register: my_volume
'''
try:
import pyrax
HAS_PYRAX = True
except ImportError:
HAS_PYRAX = False
def cloud_block_storage_attachments(module, state, volume, server, device,
wait, wait_timeout):
cbs = pyrax.cloud_blockstorage
cs = pyrax.cloudservers
if cbs is None or cs is None:
module.fail_json(msg='Failed to instantiate client. This '
'typically indicates an invalid region or an '
'incorrectly capitalized region name.')
changed = False
instance = {}
volume = rax_find_volume(module, pyrax, volume)
if not volume:
module.fail_json(msg='No matching storage volumes were found')
if state == 'present':
server = rax_find_server(module, pyrax, server)
if (volume.attachments and
volume.attachments[0]['server_id'] == server.id):
changed = False
elif volume.attachments:
module.fail_json(msg='Volume is attached to another server')
else:
try:
volume.attach_to_instance(server, mountpoint=device)
changed = True
except Exception, e:
module.fail_json(msg='%s' % e.message)
volume.get()
for key, value in vars(volume).iteritems():
if (isinstance(value, NON_CALLABLES) and
not key.startswith('_')):
instance[key] = value
result = dict(changed=changed)
if volume.status == 'error':
result['msg'] = '%s failed to build' % volume.id
elif wait:
attempts = wait_timeout / 5
pyrax.utils.wait_until(volume, 'status', 'in-use',
interval=5, attempts=attempts)
volume.get()
result['volume'] = rax_to_dict(volume)
if 'msg' in result:
module.fail_json(**result)
else:
module.exit_json(**result)
elif state == 'absent':
server = rax_find_server(module, pyrax, server)
if (volume.attachments and
volume.attachments[0]['server_id'] == server.id):
try:
volume.detach()
if wait:
pyrax.utils.wait_until(volume, 'status', 'available',
interval=3, attempts=0,
verbose=False)
changed = True
except Exception, e:
module.fail_json(msg='%s' % e.message)
volume.get()
changed = True
elif volume.attachments:
module.fail_json(msg='Volume is attached to another server')
result = dict(changed=changed, volume=rax_to_dict(volume))
if volume.status == 'error':
result['msg'] = '%s failed to build' % volume.id
if 'msg' in result:
module.fail_json(**result)
else:
module.exit_json(**result)
module.exit_json(changed=changed, volume=instance)
def main():
argument_spec = rax_argument_spec()
argument_spec.update(
dict(
device=dict(required=True),
volume=dict(required=True),
server=dict(required=True),
state=dict(default='present', choices=['present', 'absent']),
wait=dict(type='bool', default=False),
wait_timeout=dict(type='int', default=300)
)
)
module = AnsibleModule(
argument_spec=argument_spec,
required_together=rax_required_together()
)
if not HAS_PYRAX:
module.fail_json(msg='pyrax is required for this module')
device = module.params.get('device')
volume = module.params.get('volume')
server = module.params.get('server')
state = module.params.get('state')
wait = module.params.get('wait')
wait_timeout = module.params.get('wait_timeout')
setup_rax_module(module, pyrax)
cloud_block_storage_attachments(module, state, volume, server, device,
wait, wait_timeout)
# import module snippets
from ansible.module_utils.basic import *
from ansible.module_utils.rax import *
### invoke the module
main()
|
2014c2g19/2014c2g19
|
refs/heads/master
|
wsgi/programs/c2g5/__init__.py
|
2
|
import cherrypy
# 這是 C2G1 類別的定義
class C2G5(object):
# 各組利用 index 引導隨後的程式執行
@cherrypy.expose
def index(self, *args, **kwargs):
outstring = '''
這是 2014C2 協同專案下的 c2g5 分組程式開發網頁<br />
<!-- 這裡採用相對連結, 而非網址的絕對連結 (這一段為 html 註解) -->
老師示範<br />
<a href="fillpoly">c2g5 fillpoly 繪圖</a><br />
<a href="drawline">c2g5 drawline 繪圖</a><br />
<a href="animate1">c2g5 animate1 繪圖</a><br />
<a href="flag">c2g5 flag 繪圖</a><br />
<a href="square">c2g5 squared 繪圖</a><br />
<br />
第十二週任務<br />
<a href="triangle1">c2g5 triangle1 繪圖</a><br />
<a href="triangle2">c2g5 triangle2 繪圖</a><br />
<br />
第十三週任務<br />
<a href="JPflag">c2g5 JPflag 繪圖</a><br />
<br />
第十四週任務<br />
<a href="USAflag">c2g5 USAflag 繪圖</a><br />
<a href="http://2014c2-mdenfu.rhcloud.com/static/reeborg/world.html?proglang=python-en&world=%7B%22blank_canvas%22%3Atrue%7D&editor=%20%20%20%20%23%20%E5%B0%8E%E5%85%A5%20doc%0A%20%20%20%20from%20browser%20import%20doc%0A%20%20%20%20import%20math%0A%0A%20%20%20%20%23%20%E6%BA%96%E5%82%99%E7%B9%AA%E5%9C%96%E7%95%AB%E5%B8%83%0A%20%20%20%20canvas%20%3D%20doc%5B%22background_canvas%22%5D%0A%20%20%20%20ctx%20%3D%20canvas.getContext(%222d%22)%0A%20%20%20%20%23%20%E9%80%B2%E8%A1%8C%E5%BA%A7%E6%A8%99%E8%BD%89%E6%8F%9B%2C%20x%20%E8%BB%B8%E4%B8%8D%E8%AE%8A%2C%20y%20%E8%BB%B8%E5%8F%8D%E5%90%91%E4%B8%94%E7%A7%BB%E5%8B%95%20canvas.height%20%E5%96%AE%E4%BD%8D%E5%85%89%E9%BB%9E%0A%20%20%20%20%23%20ctx.setTransform(1%2C%200%2C%200%2C%20-1%2C%200%2C%20canvas.height)%0A%20%20%20%20%23%20%E4%BB%A5%E4%B8%8B%E6%8E%A1%E7%94%A8%20canvas%20%E5%8E%9F%E5%A7%8B%E5%BA%A7%E6%A8%99%E7%B9%AA%E5%9C%96%0A%20%20%20%20flag_w%20%3D%20180%0A%20%20%20%20flag_h%20%3D%20100%0A%20%20%20%20circle_x%20%3D%20flag_w%2F4%0A%20%20%20%20circle_y%20%3D%20flag_h%2F4%0A%20%20%20%20%23%20%E5%85%88%E7%95%AB%E6%BB%BF%E5%9C%B0%E7%B4%85%0A%20%20%20%20ctx.fillStyle%3D%20'%23fff'%0A%20%20%20%20ctx.fillRect(0%2C0%2Cflag_w%2Cflag_h)%0A%20%20%20%20%23%E9%95%B7%E6%A2%9D%E7%B4%85%E7%B7%9A%0A%20%20%20%20ctx.fillRect(0%2C0%2Cflag_w%2Cflag_h%2F13)%0A%20%20%20%20ctx.fillStyle%3D%20'rgb(255%2C%200%2C%200)'%0A%20%20%20%20for%20i%20in%20range(0%2Cflag_h%2C2*flag_h%2F13)%3A%0A%20%20%20%20%20%20%20%20b%3Di%0A%20%20%20%20%20%20%20%20ctx.fillRect(0%2Cb%2Cflag_w%2Cflag_h%2F13)%0A%20%20%20%20%20%20%20%20ctx.fillStyle%3D%20'rgb(255%2C%200%2C%200)'%0A%20%20%20%20%20%20%20%20ctx.fill()%0A%20%20%20%20%23%20%E5%85%88%E7%95%AB%E6%BB%BF%E9%9D%92%E5%A4%A9%0A%20%20%20%20ctx.fillStyle%3D'rgb(0%2C%200%2C%20150)'%0A%20%20%20%20ctx.fillRect(0%2C0%2C2*flag_w%2F5%2C7*flag_h%2F13)%0A%20%20%20%20%23%E6%98%9F%E6%98%9F%E7%99%BD%E8%89%B2%0A%20%20%20%20def%20draw_line(x1%2C%20y1%2C%20x2%2C%20y2%2C%20linethick%20%3D%203%2C%20color%20%3D%20%22black%22)%3A%0A%20%20%20%20%20%20%20%20ctx.beginPath()%0A%20%20%20%20%20%20%20%20ctx.lineWidth%20%3D%20linethick%0A%20%20%20%20%20%20%20%20ctx.moveTo(x1%2C%20y1)%0A%20%20%20%20%20%20%20%20ctx.lineTo(x2%2C%20y2)%0A%20%20%20%20%20%20%20%20ctx.strokeStyle%20%3D%20color%0A%20%20%20%20%20%20%20%20ctx.stroke()%0A%20%20%20%20%0A%20%20%20%20%23%20x%2C%20y%20%E7%82%BA%E4%B8%AD%E5%BF%83%2C%20%20r%20%E7%82%BA%E5%8D%8A%E5%BE%91%2C%20angle%20%E6%97%8B%E8%BD%89%E8%A7%92%2C%20%20solid%20%E7%A9%BA%E5%BF%83%E6%88%96%E5%AF%A6%E5%BF%83%2C%20%20color%20%E9%A1%8F%E8%89%B2%0A%20%20%20%20def%20star(x%2C%20y%2C%20r%2C%20angle%3D0%2C%20solid%3DFalse%2C%20color%3D%22%23f00%22)%3A%0A%20%20%20%20%20%20%20%20%23%20%E4%BB%A5%20x%2C%20y%20%E7%82%BA%E5%9C%93%E5%BF%83%2C%20%E8%A8%88%E7%AE%97%E4%BA%94%E5%80%8B%E5%A4%96%E9%BB%9E%0A%20%20%20%20%20%20%20%20deg%20%3D%20math.pi%2F180%0A%20%20%20%20%20%20%20%20%23%20%E5%9C%93%E5%BF%83%E5%88%B0%E6%B0%B4%E5%B9%B3%E7%B7%9A%E8%B7%9D%E9%9B%A2%0A%20%20%20%20%20%20%20%20a%20%3D%20r*math.cos(72*deg)%0A%20%20%20%20%20%20%20%20%23%20a%20%E9%A0%82%E9%BB%9E%E5%90%91%E5%8F%B3%E5%88%B0%E5%85%A7%E9%BB%9E%E8%B7%9D%E9%9B%A2%0A%20%20%20%20%20%20%20%20b%20%3D%20(r*math.cos(72*deg)%2Fmath.cos(36*deg))*math.sin(36*deg)%0A%20%20%20%20%20%20%20%20%23%20%E5%88%A9%E7%94%A8%E7%95%A2%E6%B0%8F%E5%AE%9A%E7%90%86%E6%B1%82%E5%85%A7%E9%BB%9E%E5%8D%8A%E5%BE%91%0A%20%20%20%20%20%20%20%20rin%20%3D%20math.sqrt(a**2%20%2B%20b**2)%0A%20%20%20%20%20%20%20%20%23%20%E6%9F%A5%E9%A9%97%20a%2C%20b%20%E8%88%87%20rin%0A%20%20%20%20%20%20%20%20%23print(a%2C%20b%2C%20rin)%0A%20%20%20%20%20%20%20%20if(solid)%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20ctx.beginPath()%0A%20%20%20%20%20%20%20%20for%20i%20in%20range(5)%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20xout%20%3D%20(x%20%2B%20r*math.sin((360%2F5)*deg*i%2Bangle*deg))%0A%20%20%20%20%20%20%20%20%20%20%20%20yout%20%3D%20(y%20%2B%20r*math.cos((360%2F5)*deg*i%2Bangle*deg))%0A%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E5%A4%96%E9%BB%9E%E5%A2%9E%E9%87%8F%20%2B%201%0A%20%20%20%20%20%20%20%20%20%20%20%20xout2%20%3D%20x%20%2B%20r*math.sin((360%2F5)*deg*(i%2B1)%2Bangle*deg)%0A%20%20%20%20%20%20%20%20%20%20%20%20yout2%20%3D%20y%20%2B%20r*math.cos((360%2F5)*deg*(i%2B1)%2Bangle*deg)%0A%20%20%20%20%20%20%20%20%20%20%20%20xin%20%3D%20x%20%2B%20rin*math.sin((360%2F5)*deg*i%2B36*deg%2Bangle*deg)%0A%20%20%20%20%20%20%20%20%20%20%20%20yin%20%3D%20y%20%2B%20rin*math.cos((360%2F5)*deg*i%2B36*deg%2Bangle*deg)%0A%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E6%9F%A5%E9%A9%97%E5%A4%96%E9%BB%9E%E8%88%87%E5%85%A7%E9%BB%9E%E5%BA%A7%E6%A8%99%0A%20%20%20%20%20%20%20%20%20%20%20%20%23print(xout%2C%20yout%2C%20xin%2C%20yin)%0A%20%20%20%20%20%20%20%20%20%20%20%20if(solid)%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E5%A1%AB%E8%89%B2%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20if(i%3D%3D0)%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20ctx.moveTo(xout%2C%20yout)%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20ctx.lineTo(xin%2C%20yin)%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20ctx.lineTo(xout2%2C%20yout2)%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20ctx.lineTo(xin%2C%20yin)%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20ctx.lineTo(xout2%2C%20yout2)%0A%20%20%20%20%20%20%20%20%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E7%A9%BA%E5%BF%83%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20draw_line(xout%2C%20yout%2C%20xin%2C%20yin%2C%20color)%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E7%95%AB%E7%A9%BA%E5%BF%83%E4%BA%94%E8%8A%92%E6%98%9F%2C%20%E7%84%A1%E9%97%9C%E7%95%AB%E7%B7%9A%E6%AC%A1%E5%BA%8F%2C%20%E8%8B%A5%E5%AF%A6%E5%BF%83%E5%89%87%E8%88%87%E7%95%AB%E7%B7%9A%E6%AC%A1%E5%BA%8F%E6%9C%89%E9%97%9C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20draw_line(xout2%2C%20yout2%2C%20xin%2C%20yin%2C%20color)%0A%20%20%20%20%20%20%20%20if(solid)%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20ctx.fillStyle%20%3D%20color%0A%20%20%20%20%20%20%20%20%20%20%20%20ctx.fill()%0A%20%20%20%20%23star(100%2C%20100%2C%2050%2C%200%2C%20False%2C%20%22%23000%22)%0A%20%20%20%20for%20i%20in%20range(5)%3A%0A%20%20%20%20%20%20%20%20for%20j%20in%20range(4)%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20star(12%2B12*i%2C%2012%2B10*j%2C%203%2C%200%2C%20true%2C%20%22%23fff%22)%0A%20%20%20%20for%20i%20in%20range(6)%3A%0A%20%20%20%20%20%20%20%20for%20j%20in%20range(5)%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20star(6%2B12*i%2C%206%2B10*j%2C%203%2C%200%2C%20true%2C%20%22%23fff%22)&library=%23%20'import%20my_lib'%20in%20Python%20Code%20is%20required%20to%20use%0A%23%20the%20code%20in%20this%20library.%20%0Adef%20turn_right()%3A%0A%20%20%20%20repeat(turn_left%2C%203)">c2g5 機器人-USA 繪圖</a><br />
<a href="http://2014c2-mdenfu.rhcloud.com/static/reeborg/world.html?proglang=python-en&world=%7B%22blank_canvas%22%3Atrue%7D&editor=%20%20%20%20%23%20%E5%B0%8E%E5%85%A5%20doc%0A%20%20%20%20from%20browser%20import%20doc%0A%20%20%20%20import%20math%0A%0A%20%20%20%20%23%20%E6%BA%96%E5%82%99%E7%B9%AA%E5%9C%96%E7%95%AB%E5%B8%83%0A%20%20%20%20canvas%20%3D%20doc%5B%22background_canvas%22%5D%0A%20%20%20%20ctx%20%3D%20canvas.getContext(%222d%22)%0A%20%20%20%20ctx.setTransform(1%2C%201%2C%20-1%2C%201%2C%20150%2C%20100)%0A%20%20%20%20%23%20%E9%80%B2%E8%A1%8C%E5%BA%A7%E6%A8%99%E8%BD%89%E6%8F%9B%2C%20x%20%E8%BB%B8%E4%B8%8D%E8%AE%8A%2C%20y%20%E8%BB%B8%E5%8F%8D%E5%90%91%E4%B8%94%E7%A7%BB%E5%8B%95%20canvas.height%20%E5%96%AE%E4%BD%8D%E5%85%89%E9%BB%9E%0A%20%20%20%20%23%20ctx.setTransform(1%2C%200%2C%200%2C%20-1%2C%200%2C%20canvas.height)%0A%20%20%20%20%23%20%E4%BB%A5%E4%B8%8B%E6%8E%A1%E7%94%A8%20canvas%20%E5%8E%9F%E5%A7%8B%E5%BA%A7%E6%A8%99%E7%B9%AA%E5%9C%96%0A%20%20%20%20flag_w%20%3D%20180%0A%20%20%20%20flag_h%20%3D%20100%0A%20%20%20%20circle_x%20%3D%20flag_w%2F4%0A%20%20%20%20circle_y%20%3D%20flag_h%2F4%0A%20%20%20%20%23%20%E5%85%88%E7%95%AB%E6%BB%BF%E5%9C%B0%E7%B4%85%0A%20%20%20%20ctx.fillStyle%3D%20'%23fff'%0A%20%20%20%20ctx.fillRect(0%2C0%2Cflag_w%2Cflag_h)%0A%20%20%20%20%23%E9%95%B7%E6%A2%9D%E7%B4%85%E7%B7%9A%0A%20%20%20%20ctx.fillRect(0%2C0%2Cflag_w%2Cflag_h%2F13)%0A%20%20%20%20ctx.fillStyle%3D%20'rgb(255%2C%200%2C%200)'%0A%20%20%20%20for%20i%20in%20range(0%2Cflag_h%2C2*flag_h%2F13)%3A%0A%20%20%20%20%20%20%20%20b%3Di%0A%20%20%20%20%20%20%20%20ctx.fillRect(0%2Cb%2Cflag_w%2Cflag_h%2F13)%0A%20%20%20%20%20%20%20%20ctx.fillStyle%3D%20'rgb(255%2C%200%2C%200)'%0A%20%20%20%20%20%20%20%20ctx.fill()%0A%20%20%20%20%23%20%E5%85%88%E7%95%AB%E6%BB%BF%E9%9D%92%E5%A4%A9%0A%20%20%20%20ctx.fillStyle%3D'rgb(0%2C%200%2C%20150)'%0A%20%20%20%20ctx.fillRect(0%2C0%2C2*flag_w%2F5%2C7*flag_h%2F13)%0A%20%20%20%20%23%E6%98%9F%E6%98%9F%E7%99%BD%E8%89%B2%0A%20%20%20%20def%20draw_line(x1%2C%20y1%2C%20x2%2C%20y2%2C%20linethick%20%3D%203%2C%20color%20%3D%20%22black%22)%3A%0A%20%20%20%20%20%20%20%20ctx.beginPath()%0A%20%20%20%20%20%20%20%20ctx.lineWidth%20%3D%20linethick%0A%20%20%20%20%20%20%20%20ctx.moveTo(x1%2C%20y1)%0A%20%20%20%20%20%20%20%20ctx.lineTo(x2%2C%20y2)%0A%20%20%20%20%20%20%20%20ctx.strokeStyle%20%3D%20color%0A%20%20%20%20%20%20%20%20ctx.stroke()%0A%20%20%20%20%0A%20%20%20%20%23%20x%2C%20y%20%E7%82%BA%E4%B8%AD%E5%BF%83%2C%20%20r%20%E7%82%BA%E5%8D%8A%E5%BE%91%2C%20angle%20%E6%97%8B%E8%BD%89%E8%A7%92%2C%20%20solid%20%E7%A9%BA%E5%BF%83%E6%88%96%E5%AF%A6%E5%BF%83%2C%20%20color%20%E9%A1%8F%E8%89%B2%0A%20%20%20%20def%20star(x%2C%20y%2C%20r%2C%20angle%3D0%2C%20solid%3DFalse%2C%20color%3D%22%23f00%22)%3A%0A%20%20%20%20%20%20%20%20%23%20%E4%BB%A5%20x%2C%20y%20%E7%82%BA%E5%9C%93%E5%BF%83%2C%20%E8%A8%88%E7%AE%97%E4%BA%94%E5%80%8B%E5%A4%96%E9%BB%9E%0A%20%20%20%20%20%20%20%20deg%20%3D%20math.pi%2F180%0A%20%20%20%20%20%20%20%20%23%20%E5%9C%93%E5%BF%83%E5%88%B0%E6%B0%B4%E5%B9%B3%E7%B7%9A%E8%B7%9D%E9%9B%A2%0A%20%20%20%20%20%20%20%20a%20%3D%20r*math.cos(72*deg)%0A%20%20%20%20%20%20%20%20%23%20a%20%E9%A0%82%E9%BB%9E%E5%90%91%E5%8F%B3%E5%88%B0%E5%85%A7%E9%BB%9E%E8%B7%9D%E9%9B%A2%0A%20%20%20%20%20%20%20%20b%20%3D%20(r*math.cos(72*deg)%2Fmath.cos(36*deg))*math.sin(36*deg)%0A%20%20%20%20%20%20%20%20%23%20%E5%88%A9%E7%94%A8%E7%95%A2%E6%B0%8F%E5%AE%9A%E7%90%86%E6%B1%82%E5%85%A7%E9%BB%9E%E5%8D%8A%E5%BE%91%0A%20%20%20%20%20%20%20%20rin%20%3D%20math.sqrt(a**2%20%2B%20b**2)%0A%20%20%20%20%20%20%20%20%23%20%E6%9F%A5%E9%A9%97%20a%2C%20b%20%E8%88%87%20rin%0A%20%20%20%20%20%20%20%20%23print(a%2C%20b%2C%20rin)%0A%20%20%20%20%20%20%20%20if(solid)%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20ctx.beginPath()%0A%20%20%20%20%20%20%20%20for%20i%20in%20range(5)%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20xout%20%3D%20(x%20%2B%20r*math.sin((360%2F5)*deg*i%2Bangle*deg))%0A%20%20%20%20%20%20%20%20%20%20%20%20yout%20%3D%20(y%20%2B%20r*math.cos((360%2F5)*deg*i%2Bangle*deg))%0A%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E5%A4%96%E9%BB%9E%E5%A2%9E%E9%87%8F%20%2B%201%0A%20%20%20%20%20%20%20%20%20%20%20%20xout2%20%3D%20x%20%2B%20r*math.sin((360%2F5)*deg*(i%2B1)%2Bangle*deg)%0A%20%20%20%20%20%20%20%20%20%20%20%20yout2%20%3D%20y%20%2B%20r*math.cos((360%2F5)*deg*(i%2B1)%2Bangle*deg)%0A%20%20%20%20%20%20%20%20%20%20%20%20xin%20%3D%20x%20%2B%20rin*math.sin((360%2F5)*deg*i%2B36*deg%2Bangle*deg)%0A%20%20%20%20%20%20%20%20%20%20%20%20yin%20%3D%20y%20%2B%20rin*math.cos((360%2F5)*deg*i%2B36*deg%2Bangle*deg)%0A%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E6%9F%A5%E9%A9%97%E5%A4%96%E9%BB%9E%E8%88%87%E5%85%A7%E9%BB%9E%E5%BA%A7%E6%A8%99%0A%20%20%20%20%20%20%20%20%20%20%20%20%23print(xout%2C%20yout%2C%20xin%2C%20yin)%0A%20%20%20%20%20%20%20%20%20%20%20%20if(solid)%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E5%A1%AB%E8%89%B2%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20if(i%3D%3D0)%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20ctx.moveTo(xout%2C%20yout)%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20ctx.lineTo(xin%2C%20yin)%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20ctx.lineTo(xout2%2C%20yout2)%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20ctx.lineTo(xin%2C%20yin)%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20ctx.lineTo(xout2%2C%20yout2)%0A%20%20%20%20%20%20%20%20%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E7%A9%BA%E5%BF%83%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20draw_line(xout%2C%20yout%2C%20xin%2C%20yin%2C%20color)%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E7%95%AB%E7%A9%BA%E5%BF%83%E4%BA%94%E8%8A%92%E6%98%9F%2C%20%E7%84%A1%E9%97%9C%E7%95%AB%E7%B7%9A%E6%AC%A1%E5%BA%8F%2C%20%E8%8B%A5%E5%AF%A6%E5%BF%83%E5%89%87%E8%88%87%E7%95%AB%E7%B7%9A%E6%AC%A1%E5%BA%8F%E6%9C%89%E9%97%9C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20draw_line(xout2%2C%20yout2%2C%20xin%2C%20yin%2C%20color)%0A%20%20%20%20%20%20%20%20if(solid)%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20ctx.fillStyle%20%3D%20color%0A%20%20%20%20%20%20%20%20%20%20%20%20ctx.fill()%0A%20%20%20%20%23star(100%2C%20100%2C%2050%2C%200%2C%20False%2C%20%22%23000%22)%0A%20%20%20%20for%20i%20in%20range(5)%3A%0A%20%20%20%20%20%20%20%20for%20j%20in%20range(4)%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20star(12%2B12*i%2C%2012%2B10*j%2C%203%2C%200%2C%20true%2C%20%22%23fff%22)%0A%20%20%20%20for%20i%20in%20range(6)%3A%0A%20%20%20%20%20%20%20%20for%20j%20in%20range(5)%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20star(6%2B12*i%2C%206%2B10*j%2C%203%2C%200%2C%20true%2C%20%22%23fff%22)&library=%23%20'import%20my_lib'%20in%20Python%20Code%20is%20required%20to%20use%0A%23%20the%20code%20in%20this%20library.%20%0Adef%20turn_right()%3A%0A%20%20%20%20repeat(turn_left%2C%203)">c2g5 機器人-USA-轉 繪圖</a><br />
<br />
第十五週任務<br />
<a href="http://2014c2-mdenfu.rhcloud.com/static/reeborg/world.html?proglang=python-en&world=%7B%22robots%22%3A%5B%7B%22x%22%3A1%2C%22y%22%3A1%2C%22tokens%22%3A%22infinite%22%2C%22orientation%22%3A0%2C%22_prev_x%22%3A1%2C%22_prev_y%22%3A1%2C%22_prev_orientation%22%3A0%7D%5D%2C%22walls%22%3A%7B%222%2C1%22%3A%5B%22east%22%5D%2C%224%2C1%22%3A%5B%22east%22%5D%2C%226%2C1%22%3A%5B%22east%22%5D%2C%228%2C1%22%3A%5B%22east%22%5D%2C%2210%2C1%22%3A%5B%22east%22%5D%2C%2212%2C1%22%3A%5B%22east%22%5D%7D%2C%22goal%22%3A%7B%22position%22%3A%7B%22x%22%3A12%2C%22y%22%3A1%7D%7D%7D&editor=def%20turn_right()%3A%0A%20%20%20%20repeat(turn_left%2C%203)%0Adef%20jump_over_hurdle()%3A%0A%20%20%20%20turn_left()%0A%20%20%20%20move()%0A%20%20%20%20turn_right()%0A%20%20%20%20move()%0A%20%20%20%20turn_right()%0A%20%20%20%20move()%0A%20%20%20%20turn_left()%0A%0Amove()%0Ajump_over_hurdle()%0Amove()%0Ajump_over_hurdle()%0Amove()%0Ajump_over_hurdle()%0Amove()%0Ajump_over_hurdle()%0Amove()%0Ajump_over_hurdle()%0Amove()&library=%23%20'import%20my_lib'%20in%20Python%20Code%20is%20required%20to%20use%0A%23%20the%20code%20in%20this%20library.%20%0Adef%20turn_right()%3A%0A%20%20%20%20repeat(turn_left%2C%203)">c2g5 Robot跨越Hurdles1</a><br />
<a href="http://2014c2-mdenfu.rhcloud.com/static/reeborg/world.html?proglang=python-en&world=%7B%22robots%22%3A%5B%7B%22x%22%3A12%2C%22y%22%3A1%2C%22tokens%22%3A%22infinite%22%2C%22orientation%22%3A0%2C%22_prev_x%22%3A11%2C%22_prev_y%22%3A1%2C%22_prev_orientation%22%3A3%7D%5D%2C%22walls%22%3A%7B%222%2C1%22%3A%5B%22east%22%5D%2C%224%2C1%22%3A%5B%22east%22%5D%2C%226%2C1%22%3A%5B%22east%22%5D%2C%228%2C1%22%3A%5B%22east%22%5D%2C%2210%2C1%22%3A%5B%22east%22%5D%2C%2212%2C1%22%3A%5B%22east%22%5D%2C%223%2C1%22%3A%5B%22east%22%5D%2C%227%2C1%22%3A%5B%22east%22%5D%7D%2C%22goal%22%3A%7B%22position%22%3A%7B%22x%22%3A12%2C%22y%22%3A1%7D%7D%7D&editor=def%20turn_right()%3A%0A%20%20%20%20repeat(turn_left%2C%203)%0Adef%20jump_over_hurdle()%3A%0A%20%20%20%20turn_left()%0A%20%20%20%20move()%0A%20%20%20%20turn_right()%0A%20%20%20%20move()%0A%20%20%20%20turn_right()%0A%20%20%20%20move()%0A%20%20%20%20turn_left()%0A%0Amove()%0Ajump_over_hurdle()%0Ajump_over_hurdle()%0Ajump_over_hurdle()%0Amove()%0Ajump_over_hurdle()%0Ajump_over_hurdle()%0Ajump_over_hurdle()%0Amove()%0Ajump_over_hurdle()%0Amove()%0A&library=%23%20'import%20my_lib'%20in%20Python%20Code%20is%20required%20to%20use%0A%23%20the%20code%20in%20this%20library.%20%0Adef%20turn_right()%3A%0A%20%20%20%20repeat(turn_left%2C%203)">c2g5 Robot跨越Hurdles3</a><br />
<a href="http://www.facebook.com/l.php?u=http%3A%2F%2F2014c2-mdenfu.rhcloud.com%2Fstatic%2Freeborg%2Fworld.html%3Fproglang%3Dpython-en%26world%3D%257B%2522robots%2522%253A%255B%257B%2522x%2522%253A1%252C%2522y%2522%253A1%252C%2522tokens%2522%253A%2522infinite%2522%252C%2522orientation%2522%253A0%252C%2522_prev_x%2522%253A1%252C%2522_prev_y%2522%253A1%252C%2522_prev_orientation%2522%253A0%257D%255D%252C%2522walls%2522%253A%257B%25222%252C1%2522%253A%255B%2522east%2522%255D%252C%25224%252C1%2522%253A%255B%2522east%2522%255D%252C%25226%252C1%2522%253A%255B%2522east%2522%255D%252C%25228%252C1%2522%253A%255B%2522east%2522%255D%252C%252210%252C1%2522%253A%255B%2522east%2522%255D%252C%252212%252C1%2522%253A%255B%2522east%2522%255D%252C%25223%252C1%2522%253A%255B%2522east%2522%255D%252C%25227%252C1%2522%253A%255B%2522east%2522%255D%257D%252C%2522goal%2522%253A%257B%2522position%2522%253A%257B%2522x%2522%253A12%252C%2522y%2522%253A1%257D%257D%257D%26editor%3Ddef%2520turn_right()%253A%250A%2520%2520%2520%2520repeat(turn_left%252C%25203)%250A%250Adef%2520jump_over_hurdle()%253A%250A%2520%2520%2520%2520turn_left()%250A%2520%2520%2520%2520move()%250A%2520%2520%2520%2520turn_right()%250A%2520%2520%2520%2520move()%250A%2520%2520%2520%2520turn_right()%250A%2520%2520%2520%2520move()%250A%2520%2520%2520%2520turn_left()%250A%2520%2520%2520%2520%250A%2520%250Amove()%250Ajump_over_hurdle()%250Ajump_over_hurdle()%250Ajump_over_hurdle()%250Amove()%250Ajump_over_hurdle()%250Ajump_over_hurdle()%250Ajump_over_hurdle()%250Amove()%250Ajump_over_hurdle()%250Amove()%26library%3D%2523%2520%2527import%2520my_lib%2527%2520in%2520Python%2520Code%2520is%2520required%2520to%2520use%250A%2523%2520the%2520code%2520in%2520this%2520library.%2520%250A%250A&h=iAQHcqml0">c2g5 Robot同時跨越Hurdles1.Hurdles3</a><br />
'''
return outstring
# 以下為 c2g1 組所建立的 CherryPy 程式方法, 這裡的 fillpoly 利用 Brython 執行網際繪圖
'''
假如採用下列規畫
import programs.c2g1 as c2g1
root.c2g1 = c2g1.C2G1()
則程式啟動後, 可以利用 /c2g1/fillpoly 呼叫函式執行
'''
@cherrypy.expose
def fillpoly(self, *args, **kwargs):
outstring = '''
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<script type="text/javascript" src="/static/Brython2.1.0-20140419-113919/brython.js"></script>
</head>
<body onload="brython({debug:1, cache:'version'})">
<canvas id="plotarea" width="800" height="800"></canvas>
<script type="text/python">
# 導入數學模組的所有方法
from math import *
# 導入時間模組
import time
# 導入 doc
from browser import doc
# 準備繪圖畫布
canvas = doc["plotarea"]
ctx = canvas.getContext("2d")
# 定義座標轉換(0, 0) 到 (75, 20)
def change_ref_system(x, y):
return (20 + x * 8, 420 - y * 20)
# 定義畫線函式
def draw_line(x1, y1, x2, y2, linethick = 3, color = "black"):
ctx.beginPath()
ctx.lineWidth = linethick
ctx.moveTo(x1, y1)
ctx.lineTo(x2, y2)
ctx.strokeStyle = color
ctx.stroke()
def fill():
ctx.beginPath()
ctx.moveTo(75,50)
ctx.lineTo(100,75)
ctx.lineTo(100,25)
ctx.fill()
def star():
ctx.beginPath()
ctx.moveTo(0,50)
ctx.lineTo(11,16)
ctx.lineTo(48,16)
ctx.fill()
ctx.fillStyle = "blue"
fill()
star()
x1, y1 = change_ref_system(0, 0)
for 索引 in range(0, 70, 4):
x2, y2 = change_ref_system(索引, 20)
draw_line(x1, y1, x2, y2, linethick=3, color="blue")
x1, y1 = change_ref_system(70, 0)
for 索引 in range(0, 70, 4):
x2, y2 = change_ref_system(索引, 20)
draw_line(x1, y1, x2, y2, linethick=3, color="red")
</script>
</body>
</html>
'''
return outstring
'''
假如採用下列規畫
import programs.c2g1 as c2g1
root.c2g1 = c2g1.C2G1()
則程式啟動後, 可以利用 /c2g1/drawline 呼叫函式執行
context.setTransform(a,b,c,d,e,f)
a To Scale the object across along the X axis
b To skew the object horizontally(i.e horizontal shear)
c To skew the object vertically(i.e vertical shear)
d To scale the object across Y axis
e To translate the object along the X axis
f To translate the object along the Y axis
a c e
b d f
0 0 1
'''
@cherrypy.expose
def drawline(self, *args, **kwargs):
outstring = '''
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<script type="text/javascript" src="/static/Brython2.1.0-20140419-113919/brython.js"></script>
</head>
<body onload="brython({debug:1, cache:'version'})">
<canvas id="plotarea" width="800" height="800"></canvas>
<script type="text/python">
# 導入 doc
from browser import doc
# 準備繪圖畫布
canvas = doc["plotarea"]
ctx = canvas.getContext("2d")
# 進行座標轉換, x 軸不變, y 軸反向且移動 800 光點
ctx.setTransform(1, 0, 0, -1, 0, 800)
# 定義畫線函式
def draw_line(x1, y1, x2, y2, linethick = 3, color = "black"):
ctx.beginPath()
ctx.lineWidth = linethick
ctx.moveTo(x1, y1)
ctx.lineTo(x2, y2)
ctx.strokeStyle = color
ctx.stroke()
draw_line(0, 0, 100, 100)
</script>
</body>
</html>
'''
return outstring
@cherrypy.expose
def animate1(self, *args, **kwargs):
outstring = '''
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<script type="text/javascript" src="/static/Brython2.1.0-20140419-113919/brython.js"></script>
</head>
<body onload="brython({debug:1, cache:'version'})">
<canvas id="plotarea" width="800" height="800"></canvas>
<script type="text/python">
# 導入 doc
from browser import doc
import browser.timer
# 準備繪圖畫布
canvas = doc["plotarea"]
ctx = canvas.getContext("2d")
# 進行座標轉換, x 軸不變, y 軸反向且移動 800 光點
ctx.setTransform(1, 0, 0, -1, 0, 800)
# 設定 y 的起始值
y = 0
# 設定增量變數 inc 為 1
inc = 1
# 將畫筆設為紅色
ctx.strokeStyle = "rgb(255, 0, 0)"
# 定義畫水平線函式
def draw():
# 將 y 與 inc 設為全域變數
global y, inc
# 畫新圖之前, 先清除畫面
ctx.clearRect(0, 0, 800, 800)
# 開始畫水平線
ctx.beginPath()
ctx.moveTo(0, y)
ctx.lineTo(800-1, y)
ctx.stroke()
# y 的值增量
y = y + inc
# 若 y 碰到兩個極端值, 則改變增量方向
if y == 0 or y == 800-1:
inc = inc*-1
# ev 為事件輸入, 與隨後的 bind 方法配合
def start(ev):
# interval 為全域變數, 因為 stop 函式需要
global interval
# 每 10 個 micro second 呼叫一次 draw
interval = browser.timer.set_interval(draw,10)
def stop(ev):
global interval
browser.timer.clear_interval(interval)
# 將 id 為 start 的按鈕與 start 函式利用 click 事件加以連結
doc['start'].bind('click', start)
# 將 id 為 stop 的按鈕與 stop 函式利用 click 事件加以連結
doc['stop'].bind('click', stop)
</script>
<!-- 這裡建立 start 與 stop 按鈕-->
<button id="start">start</button>
<button id="stop">stop</button>
</body>
</html>
'''
return outstring
@cherrypy.expose
def flag(self, *args, **kwargs):
'''
原始程式來源: http://blog.roodo.com/esabear/archives/19215194.html
改寫為 Brython 程式
'''
outstring = '''
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<script type="text/javascript" src="/static/Brython2.1.0-20140419-113919/brython.js"></script>
</head>
<body onload="brython({debug:1, cache:'version'})">
<canvas id="plotarea" width="300" height="200"></canvas>
<script type="text/python">
# 導入 doc
from browser import doc
import math
# 準備繪圖畫布
canvas = doc["plotarea"]
ctx = canvas.getContext("2d")
# 進行座標轉換, x 軸不變, y 軸反向且移動 canvas.height 單位光點
# ctx.setTransform(1, 0, 0, -1, 0, canvas.height)
# 以下採用 canvas 原始座標繪圖
flag_w = canvas.width
flag_h = canvas.height
circle_x = flag_w/4
circle_y = flag_h/4
# 先畫滿地紅
ctx.fillStyle='rgb(255, 0, 0)'
ctx.fillRect(0,0,flag_w,flag_h)
# 再畫青天
ctx.fillStyle='rgb(0, 0, 150)'
ctx.fillRect(0,0,flag_w/2,flag_h/2)
# 畫十二到光芒白日
ctx.beginPath()
star_radius = flag_w/8
angle = 0
for i in range(24):
angle += 5*math.pi*2/12
toX = circle_x + math.cos(angle)*star_radius
toY = circle_y + math.sin(angle)*star_radius
# 只有 i 為 0 時移動到 toX, toY, 其餘都進行 lineTo
if (i):
ctx.lineTo(toX, toY)
else:
ctx.moveTo(toX, toY)
# 將填色設為白色
ctx.fillStyle = '#fff'
ctx.fill()
# 白日:藍圈
ctx.beginPath()
# 查詢 canvas arc 如何定義
ctx.arc(circle_x, circle_y, flag_w*17/240, 0, math.pi*2, true)
ctx.closePath()
# 填色設為藍色
ctx.fillStyle = 'rgb(0, 0, 149)'
ctx.fill()
# 白日:白心
ctx.beginPath()
ctx.arc(circle_x, circle_y, flag_w/16, 0, math.pi*2, true)
ctx.closePath()
# 填色設為白色
ctx.fillStyle = '#fff'
ctx.fill()
</script>
</body>
</html>
'''
return outstring
@cherrypy.expose
def square(self, *args, **kwargs):
outstring = '''
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<script type="text/javascript" src="/static/Brython2.1.0-20140419-113919/brython.js"></script>
</head>
<body onload="brython({debug:1, cache:'version'})">
<canvas id="plotarea" width="800" height="800"></canvas>
<script type="text/python">
# 導入數學模組的所有方法
from math import *
# 導入時間模組
import time
# 導入 doc
from browser import doc
# 準備繪圖畫布
canvas = doc["plotarea"]
ctx = canvas.getContext("2d")
# 進行座標轉換, x 軸不變, y 軸反向且移動 800 光點
ctx.setTransform(1, 0, 0, -1, 0, 800)
# 定義畫線函式
def draw_line(x1, y1, x2, y2, linethick = 3, color = "black"):
ctx.beginPath()
ctx.lineWidth = linethick
ctx.moveTo(x1, y1)
ctx.lineTo(x2, y2)
ctx.strokeStyle = color
ctx.stroke()
def square(x, y ,width):
draw_line(300, 300, 500, 300)
draw_line(500, 300, 500, 500)
draw_line(500, 500, 300, 500)
draw_line(300, 500, 300, 300)
square(400,400,200)
</script>
</body>
</html>
'''
return outstring
@cherrypy.expose
def triangle1(self, *args, **kwargs):
outstring = '''
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<script type="text/javascript" src="/static/Brython2.1.0-20140419-113919/brython.js"></script>
</head>
<body onload="brython({debug:1, cache:'version'})">
<canvas id="plotarea" width="800" height="800"></canvas>
<script type="text/python">
# 導入數學模組的所有方法
from math import *
# 導入時間模組
import time
# 導入 doc
from browser import doc
# 準備繪圖畫布
canvas = doc["plotarea"]
ctx = canvas.getContext("2d")
# 進行座標轉換, x 軸不變, y 軸反向且移動 800 光點
ctx.setTransform(1, 0, 0, -1, 0, 800)
# 定義畫線函式
def draw_line(x1, y1, x2, y2, linethick = 3, color = "blue"):
ctx.beginPath()
ctx.lineWidth = linethick
ctx.moveTo(x1, y1)
ctx.lineTo(x2, y2)
ctx.strokeStyle = color
ctx.stroke()
draw_line(100, 100, 150, 250)
draw_line(150, 250, 400, 400)
draw_line(400, 400, 100, 100)
</script>
</body>
</html>
'''
return outstring
@cherrypy.expose
def triangle2(self, *args, **kwargs):
outstring = '''
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<script type="text/javascript" src="/static/Brython2.1.0-20140419-113919/brython.js"></script>
</head>
<body onload="brython({debug:1, cache:'version'})">
<canvas id="plotarea" width="800" height="800"></canvas>
<script type="text/python">
# 導入數學模組的所有方法
from math import *
# 導入時間模組
import time
# 導入 doc
from browser import doc
# 準備繪圖畫布
canvas = doc["plotarea"]
ctx = canvas.getContext("2d")
# 進行座標轉換, x 軸不變, y 軸反向且移動 800 光點
ctx.setTransform(1, 0, 0, -1, 0, 800)
# 定義畫線函式
def draw_line(x1, y1, x2, y2, linethick = 3, color = "blue"):
ctx.beginPath()
ctx.lineWidth = linethick
ctx.moveTo(x1, y1)
ctx.lineTo(x2, y2)
ctx.strokeStyle = color
ctx.stroke()
def fill():
ctx.beginPath()
ctx.moveTo(100,100)
ctx.lineTo(150,250)
ctx.lineTo(400,400)
ctx.fill()
ctx.fillStyle = "red"
fill()
draw_line(100, 100, 150, 250)
draw_line(150, 250, 400, 400)
draw_line(400, 400, 100, 100)
</script>
</body>
</html>
'''
return outstring
@cherrypy.expose
def JPflag(self, *args, **kwargs):
outstring = '''
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<script type="text/javascript" src="/static/Brython2.1.0-20140419-113919/brython.js"></script>
</head>
<body onload="brython({debug:1, cache:'version'})">
<canvas id="plotarea" width="300" height="200"></canvas>
<script type="text/python">
# 導入數學模組的所有方法
from math import *
# 導入時間模組
import time
# 導入 doc
from browser import doc
# 準備繪圖畫布
canvas = doc["plotarea"]
ctx = canvas.getContext("2d")
# 進行座標轉換, x 軸不變, y 軸反向且移動 800 光點
ctx.setTransform(1, 0, 0, -1, 0, canvas.height)
flag_w = canvas.width
flag_h = canvas.height
circle_x = flag_w/2
circle_y = flag_h/2
# 定義畫線函式
def draw_line(x1, y1, x2, y2, linethick = 3, color = "blue"):
ctx.beginPath()
ctx.lineWidth = linethick
ctx.moveTo(x1, y1)
ctx.lineTo(x2, y2)
ctx.strokeStyle = color
ctx.stroke()
draw_line(0, 0, 300, 0)
draw_line(300, 0, 300, 200)
draw_line(300, 200, 0, 200)
draw_line(0, 200, 0, 0)
ctx.beginPath()
#ctx.arc(circle_x, circle_y, flag_h*0.6, 0, pi*2, true)
ctx.arc(circle_x, circle_y, 60, 0, pi*2)
ctx.closePath()
# 填色設為紅色
ctx.fillStyle = 'rgb(255, 0, 0)'
ctx.fill()
def draw_line(x1, y1, x2, y2, linethick = 3, color = "blue"):
ctx.beginPath()
ctx.lineWidth = linethick
ctx.moveTo(x1, y1)
ctx.lineTo(x2, y2)
ctx.strokeStyle = color
ctx.stroke()
draw_line(0, 0, 300, 0)
draw_line(300, 0, 300, 200)
draw_line(300, 200, 0, 200)
draw_line(0, 200, 0, 0)
ctx.beginPath()
#ctx.arc(circle_x, circle_y, flag_h*0.6, 0, pi*2, true)
ctx.arc(circle_x, circle_y, 60, 0, pi*2)
ctx.closePath()
# 填色設為紅色
ctx.fillStyle = 'rgb(255, 0, 0)'
ctx.fill()
</script>
</body>
</html>
'''
return outstring
@cherrypy.expose
def USAflag (self, *args, **kwargs):
'''
原始程式來源: http://blog.roodo.com/esabear/archives/19215194.html
改寫為 Brython 程式
'''
outstring = '''
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<script type="text/javascript" src="/static/Brython2.1.0-20140419-113919/brython.js"></script>
</head>
<body onload="brython({debug:1, cache:'version'})">
<canvas id="plotarea" width="190" height="100"></canvas>
<script type="text/python">
# 導入 doc
from browser import doc
import math
# 準備繪圖畫布
canvas = doc["plotarea"]
ctx = canvas.getContext("2d")
# 進行座標轉換, x 軸不變, y 軸反向且移動 canvas.height 單位光點
# ctx.setTransform(1, 0, 0, -1, 0, canvas.height)
# 以下採用 canvas 原始座標繪圖
flag_w = canvas.width
flag_h = canvas.height
circle_x = flag_w/4
circle_y = flag_h/4
# 先畫滿地紅
ctx.fillStyle= '#fff'
ctx.fillRect(0,0,flag_w,flag_h)
#長條紅線
ctx.fillRect(0,0,flag_w,flag_h/13)
ctx.fillStyle= 'rgb(255, 0, 0)'
for i in range(0,flag_h,2*flag_h/13):
b=i
ctx.fillRect(0,b,flag_w,flag_h/13)
ctx.fillStyle= 'rgb(255, 0, 0)'
ctx.fill()
# 先畫滿青天
ctx.fillStyle='rgb(0, 0, 150)'
ctx.fillRect(0,0,2*flag_w/5,7*flag_h/13)
#星星白色
def draw_line(x1, y1, x2, y2, linethick = 3, color = "black"):
ctx.beginPath()
ctx.lineWidth = linethick
ctx.moveTo(x1, y1)
ctx.lineTo(x2, y2)
ctx.strokeStyle = color
ctx.stroke()
# x, y 為中心, r 為半徑, angle 旋轉角, solid 空心或實心, color 顏色
def star(x, y, r, angle=0, solid=False, color="#f00"):
# 以 x, y 為圓心, 計算五個外點
deg = math.pi/180
# 圓心到水平線距離
a = r*math.cos(72*deg)
# a 頂點向右到內點距離
b = (r*math.cos(72*deg)/math.cos(36*deg))*math.sin(36*deg)
# 利用畢氏定理求內點半徑
rin = math.sqrt(a**2 + b**2)
# 查驗 a, b 與 rin
#print(a, b, rin)
if(solid):
ctx.beginPath()
for i in range(5):
xout = (x + r*math.sin((360/5)*deg*i+angle*deg))
yout = (y + r*math.cos((360/5)*deg*i+angle*deg))
# 外點增量 + 1
xout2 = x + r*math.sin((360/5)*deg*(i+1)+angle*deg)
yout2 = y + r*math.cos((360/5)*deg*(i+1)+angle*deg)
xin = x + rin*math.sin((360/5)*deg*i+36*deg+angle*deg)
yin = y + rin*math.cos((360/5)*deg*i+36*deg+angle*deg)
# 查驗外點與內點座標
#print(xout, yout, xin, yin)
if(solid):
# 填色
if(i==0):
ctx.moveTo(xout, yout)
ctx.lineTo(xin, yin)
ctx.lineTo(xout2, yout2)
else:
ctx.lineTo(xin, yin)
ctx.lineTo(xout2, yout2)
else:
# 空心
draw_line(xout, yout, xin, yin, color)
# 畫空心五芒星, 無關畫線次序, 若實心則與畫線次序有關
draw_line(xout2, yout2, xin, yin, color)
if(solid):
ctx.fillStyle = color
ctx.fill()
#star(100, 100, 50, 0, False, "#000")
for i in range(5):
for j in range(4):
star(12+12*i, 12+10*j, 3, 0, true, "#fff")
for i in range(6):
for j in range(5):
star(6+12*i, 6+10*j, 3, 0, true, "#fff")
</script>
</body>
</html>
'''
return outstring
|
rimbalinux/MSISDNArea
|
refs/heads/master
|
django/contrib/gis/gdal/geomtype.py
|
12
|
from django.contrib.gis.gdal.error import OGRException
#### OGRGeomType ####
class OGRGeomType(object):
"Encapulates OGR Geometry Types."
wkb25bit = -2147483648
# Dictionary of acceptable OGRwkbGeometryType s and their string names.
_types = {0 : 'Unknown',
1 : 'Point',
2 : 'LineString',
3 : 'Polygon',
4 : 'MultiPoint',
5 : 'MultiLineString',
6 : 'MultiPolygon',
7 : 'GeometryCollection',
100 : 'None',
101 : 'LinearRing',
1 + wkb25bit: 'Point25D',
2 + wkb25bit: 'LineString25D',
3 + wkb25bit: 'Polygon25D',
4 + wkb25bit: 'MultiPoint25D',
5 + wkb25bit : 'MultiLineString25D',
6 + wkb25bit : 'MultiPolygon25D',
7 + wkb25bit : 'GeometryCollection25D',
}
# Reverse type dictionary, keyed by lower-case of the name.
_str_types = dict([(v.lower(), k) for k, v in _types.items()])
def __init__(self, type_input):
"Figures out the correct OGR Type based upon the input."
if isinstance(type_input, OGRGeomType):
num = type_input.num
elif isinstance(type_input, basestring):
type_input = type_input.lower()
if type_input == 'geometry': type_input='unknown'
num = self._str_types.get(type_input, None)
if num is None:
raise OGRException('Invalid OGR String Type "%s"' % type_input)
elif isinstance(type_input, int):
if not type_input in self._types:
raise OGRException('Invalid OGR Integer Type: %d' % type_input)
num = type_input
else:
raise TypeError('Invalid OGR input type given.')
# Setting the OGR geometry type number.
self.num = num
def __str__(self):
"Returns the value of the name property."
return self.name
def __eq__(self, other):
"""
Does an equivalence test on the OGR type with the given
other OGRGeomType, the short-hand string, or the integer.
"""
if isinstance(other, OGRGeomType):
return self.num == other.num
elif isinstance(other, basestring):
return self.name.lower() == other.lower()
elif isinstance(other, int):
return self.num == other
else:
return False
def __ne__(self, other):
return not (self == other)
@property
def name(self):
"Returns a short-hand string form of the OGR Geometry type."
return self._types[self.num]
@property
def django(self):
"Returns the Django GeometryField for this OGR Type."
s = self.name.replace('25D', '')
if s in ('LinearRing', 'None'):
return None
elif s == 'Unknown':
s = 'Geometry'
return s + 'Field'
|
ArneBab/pypyjs
|
refs/heads/master
|
website/demo/home/rfk/repos/pypy/lib-python/2.7/encodings/latin_1.py
|
853
|
""" Python 'latin-1' Codec
Written by Marc-Andre Lemburg (mal@lemburg.com).
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
"""
import codecs
### Codec APIs
class Codec(codecs.Codec):
# Note: Binding these as C functions will result in the class not
# converting them to methods. This is intended.
encode = codecs.latin_1_encode
decode = codecs.latin_1_decode
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input, final=False):
return codecs.latin_1_encode(input,self.errors)[0]
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
return codecs.latin_1_decode(input,self.errors)[0]
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
class StreamConverter(StreamWriter,StreamReader):
encode = codecs.latin_1_decode
decode = codecs.latin_1_encode
### encodings module API
def getregentry():
return codecs.CodecInfo(
name='iso8859-1',
encode=Codec.encode,
decode=Codec.decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamreader=StreamReader,
streamwriter=StreamWriter,
)
|
sradl1981/LIGGGHTS-PUBLIC-ParScale
|
refs/heads/master
|
regress/benchmark.py
|
15
|
#!/usr/bin/env python
"""
function: numerical comparisions of logs and corresponding benchmarks
usage: benchmark.py <nprocs> <njobs> <dirs>
"""
import sys
import os
import math
import re
from operator import itemgetter
from glob import glob
import time
import multiprocessing as mp
try:
import Queue as queue # 2.6
except ImportError:
import queue # 3.0
#====================================================
### constants
#====================================================
thermo_pattern = re.compile("^Step "); # fragile
data_pattern = re.compile("\s*\d"); # fragile
fail_pattern = re.compile("FAIL");
tol = 1.e-6 # 1.e-10
arch = "openmpi"
src_path = "../src/" #relative to home
exe_path = "../"+src_path
#====================================================
### date
#====================================================
def date():
return time.asctime()
#====================================================
### timer
#====================================================
## NOTE these don't seem to work how I expect them to
def start():
global dt
dt = -(time.clock())
def stop():
global dt
dt += (time.clock())
return dt
#====================================================
### run a benchmark
#====================================================
def run_test(test):
input = "in."+test;
log = "log."+test
stdout = "stdout."+test
ref = (glob(log+"*."+str(np)))[0];
msg = "==== comparing "+log+" with "+ref+" ====\n"
if (os.path.isfile(log)): os.remove(log)
if (os.path.isfile(stdout)): os.remove(stdout)
os.system(lmps+input+" >& "+stdout);
if (not os.path.isfile(log)) :
msg += "!!! no "+log+"\n";
msg += "!!! test "+test+" FAILED\n"
return msg
[cdict,cdata] = extract_data(log);
[bdict,bdata] = extract_data(ref);
cols = range(len(bdict))
if (len(cdata) != len(bdata)):
msg += "!!! data size "+str(len(cdata))+" does not match data "+str(len(bdata))+" in "+ref+"\n";
msg += "!!! test "+test+" FAILED\n"
return msg
fail = False
i = 0
for name in bdict:
[passing,cmsg] = compare(name,cdata[cols[i]],bdata[cols[i]]);
i += 1
msg += cmsg
if (not passing) : fail = True
if (fail) :
msg += "!!! test "+test+" FAILED\n"
else :
msg += "*** test "+test+" passed\n"
return msg
#====================================================
### extract data from log file
#====================================================
def extract_data(file):
dictionary = [];
data = []
read = False
for line in open(file):
if (read and data_pattern.match(line)) :
cols = line.split();
data.append(cols)
else :
read = False
if (thermo_pattern.match(line)):
dictionary = line.split();
read = True
return [dictionary,data]
#====================================================
### compare columns of current and benchmark
#====================================================
def compare(name,col1,col2):
err = 0.
norm1 = 0.
norm2 = 0.
n = len(col2)
for i in range(n):
v1 = float(col1[i])
v2 = float(col2[i])
norm1 += v1*v1
norm2 += v2*v2
dv = v1-v2
err += dv*dv
norm1 /= n
norm2 /= n
err /= n
if (norm2 > tol) :
msg = "{0:7s} relative error {1:4} wrt norm {2:7}\n".format(name,err,norm2)
else :
msg = "{0:7s} error {1:4}\n" .format(name,err)
return [(err < tol),msg];
#################################################################
class Worker(mp.Process):
def __init__(self, work_queue, result_queue):
mp.Process.__init__(self)
self.work_queue = work_queue
self.result_queue = result_queue
def run(self):
while True:
try:
job = self.work_queue.get_nowait()
except queue.Empty:
break
#print(">>> starting " + str(job[1]) + " ...")
os.chdir(job[0])
start()
msg = run_test(job[1])
elapsed_time = stop()
msg += "elapsed time "+str(elapsed_time)+"\n"
os.chdir(home)
self.result_queue.put([job[1],msg])
#====================================================
### parse
#====================================================
def init() :
global np, njobs, ntests, lmps, arch, home
home = os.getcwd()
if (len(sys.argv) < 4) :
print "usage: benchmark.py <nprocs> <njobs> <test_dirs>"
sys.exit(1)
np = int(sys.argv[1])
njobs = int(sys.argv[2])
lmps = "../"+src_path+"lmp_"+arch+" -in "
if (np > 1):
lmps = "mpirun -np "+str(np)+" "+lmps
else:
arch = "serial"
lmps = exe_path+"lmp_"+arch+" -in "
pool = mp.Pool(njobs)
dirs = sys.argv[3:]
tests = []
for dir in dirs:
os.chdir(dir);
for path in glob("./in.*"):
test = path[5:];
tests.append([dir,test])
os.chdir(home)
ntests = len(tests)
print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
print "start: ",date()
print "arch:",arch,
print "nprocs:",np
print "ntests:",ntests,
print "njobs:",njobs
print "relative tolerance:",tol
print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
print
return tests
#====================================================
### build executable
#====================================================
def build(arch):
os.system("cd ..; svn update >& svn_update.log")
os.system("cd ../src; make no-atc >& /dev/null")
os.system("cd ../src; make clean-all >& /dev/null")
#os.system("cd ../src; make yes-all >& /dev/null")
os.system("cd ../src; make yes-dipole >& /dev/null")
sys.stdout.flush()
print "** building ",arch,"...",
os.system("cd "+src_path+"; make -j "+str(np)+" "+arch+" >& build_"+arch+".log")
if (not os.path.isfile(src_path+"lmp_"+arch)) :
print "!!! build ",arch," FAILED"
sys.exit()
else:
print "done"
print
#====================================================
### main
#====================================================
if __name__ == '__main__':
tests = init()
build(arch)
work_queue = mp.Queue()
for test in tests:
work_queue.put(test)
result_queue = mp.Queue()
nfails = 0
fail_list = []
for i in range(njobs):
w = Worker(work_queue, result_queue)
w.start()
for i in range(ntests):
[test,msg] = result_queue.get()
if (fail_pattern.search(msg)) :
nfails += 1
fail_list.append(test)
#print msg # can print only if failed
print msg # can print only if failed
#print test, " passed"
print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
print "end:",date()
if (nfails == 0):
print "*** no failures ***"
else :
print "!!!",nfails,"of",ntests,"tests failed"
for test in fail_list:
print test
print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
|
r0e/servo
|
refs/heads/master
|
tests/wpt/css-tests/tools/pywebsocket/src/mod_pywebsocket/_stream_hixie75.py
|
681
|
# Copyright 2011, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""This file provides a class for parsing/building frames of the WebSocket
protocol version HyBi 00 and Hixie 75.
Specification:
- HyBi 00 http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-00
- Hixie 75 http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-75
"""
from mod_pywebsocket import common
from mod_pywebsocket._stream_base import BadOperationException
from mod_pywebsocket._stream_base import ConnectionTerminatedException
from mod_pywebsocket._stream_base import InvalidFrameException
from mod_pywebsocket._stream_base import StreamBase
from mod_pywebsocket._stream_base import UnsupportedFrameException
from mod_pywebsocket import util
class StreamHixie75(StreamBase):
"""A class for parsing/building frames of the WebSocket protocol version
HyBi 00 and Hixie 75.
"""
def __init__(self, request, enable_closing_handshake=False):
"""Construct an instance.
Args:
request: mod_python request.
enable_closing_handshake: to let StreamHixie75 perform closing
handshake as specified in HyBi 00, set
this option to True.
"""
StreamBase.__init__(self, request)
self._logger = util.get_class_logger(self)
self._enable_closing_handshake = enable_closing_handshake
self._request.client_terminated = False
self._request.server_terminated = False
def send_message(self, message, end=True, binary=False):
"""Send message.
Args:
message: unicode string to send.
binary: not used in hixie75.
Raises:
BadOperationException: when called on a server-terminated
connection.
"""
if not end:
raise BadOperationException(
'StreamHixie75 doesn\'t support send_message with end=False')
if binary:
raise BadOperationException(
'StreamHixie75 doesn\'t support send_message with binary=True')
if self._request.server_terminated:
raise BadOperationException(
'Requested send_message after sending out a closing handshake')
self._write(''.join(['\x00', message.encode('utf-8'), '\xff']))
def _read_payload_length_hixie75(self):
"""Reads a length header in a Hixie75 version frame with length.
Raises:
ConnectionTerminatedException: when read returns empty string.
"""
length = 0
while True:
b_str = self._read(1)
b = ord(b_str)
length = length * 128 + (b & 0x7f)
if (b & 0x80) == 0:
break
return length
def receive_message(self):
"""Receive a WebSocket frame and return its payload an unicode string.
Returns:
payload unicode string in a WebSocket frame.
Raises:
ConnectionTerminatedException: when read returns empty
string.
BadOperationException: when called on a client-terminated
connection.
"""
if self._request.client_terminated:
raise BadOperationException(
'Requested receive_message after receiving a closing '
'handshake')
while True:
# Read 1 byte.
# mp_conn.read will block if no bytes are available.
# Timeout is controlled by TimeOut directive of Apache.
frame_type_str = self.receive_bytes(1)
frame_type = ord(frame_type_str)
if (frame_type & 0x80) == 0x80:
# The payload length is specified in the frame.
# Read and discard.
length = self._read_payload_length_hixie75()
if length > 0:
_ = self.receive_bytes(length)
# 5.3 3. 12. if /type/ is 0xFF and /length/ is 0, then set the
# /client terminated/ flag and abort these steps.
if not self._enable_closing_handshake:
continue
if frame_type == 0xFF and length == 0:
self._request.client_terminated = True
if self._request.server_terminated:
self._logger.debug(
'Received ack for server-initiated closing '
'handshake')
return None
self._logger.debug(
'Received client-initiated closing handshake')
self._send_closing_handshake()
self._logger.debug(
'Sent ack for client-initiated closing handshake')
return None
else:
# The payload is delimited with \xff.
bytes = self._read_until('\xff')
# The WebSocket protocol section 4.4 specifies that invalid
# characters must be replaced with U+fffd REPLACEMENT
# CHARACTER.
message = bytes.decode('utf-8', 'replace')
if frame_type == 0x00:
return message
# Discard data of other types.
def _send_closing_handshake(self):
if not self._enable_closing_handshake:
raise BadOperationException(
'Closing handshake is not supported in Hixie 75 protocol')
self._request.server_terminated = True
# 5.3 the server may decide to terminate the WebSocket connection by
# running through the following steps:
# 1. send a 0xFF byte and a 0x00 byte to the client to indicate the
# start of the closing handshake.
self._write('\xff\x00')
def close_connection(self, unused_code='', unused_reason=''):
"""Closes a WebSocket connection.
Raises:
ConnectionTerminatedException: when closing handshake was
not successfull.
"""
if self._request.server_terminated:
self._logger.debug(
'Requested close_connection but server is already terminated')
return
if not self._enable_closing_handshake:
self._request.server_terminated = True
self._logger.debug('Connection closed')
return
self._send_closing_handshake()
self._logger.debug('Sent server-initiated closing handshake')
# TODO(ukai): 2. wait until the /client terminated/ flag has been set,
# or until a server-defined timeout expires.
#
# For now, we expect receiving closing handshake right after sending
# out closing handshake, and if we couldn't receive non-handshake
# frame, we take it as ConnectionTerminatedException.
message = self.receive_message()
if message is not None:
raise ConnectionTerminatedException(
'Didn\'t receive valid ack for closing handshake')
# TODO: 3. close the WebSocket connection.
# note: mod_python Connection (mp_conn) doesn't have close method.
def send_ping(self, body):
raise BadOperationException(
'StreamHixie75 doesn\'t support send_ping')
# vi:sts=4 sw=4 et
|
TNT-Samuel/Coding-Projects
|
refs/heads/master
|
DNS Server/Source - Copy/Lib/site-packages/dask/dataframe/multi.py
|
2
|
"""
Algorithms that Involve Multiple DataFrames
===========================================
The pandas operations ``concat``, ``join``, and ``merge`` combine multiple
DataFrames. This module contains analogous algorithms in the parallel case.
There are two important cases:
1. We combine along a partitioned index
2. We combine along an unpartitioned index or other column
In the first case we know which partitions of each dataframe interact with
which others. This lets uss be significantly more clever and efficient.
In the second case each partition from one dataset interacts with all
partitions from the other. We handle this through a shuffle operation.
Partitioned Joins
-----------------
In the first case where we join along a partitioned index we proceed in the
following stages.
1. Align the partitions of all inputs to be the same. This involves a call
to ``dd.repartition`` which will split up and concat existing partitions as
necessary. After this step all inputs have partitions that align with
each other. This step is relatively cheap.
See the function ``align_partitions``.
2. Remove unnecessary partitions based on the type of join we perform (left,
right, inner, outer). We can do this at the partition level before any
computation happens. We'll do it again on each partition when we call the
in-memory function. See the function ``require``.
3. Embarrassingly parallel calls to ``pd.concat``, ``pd.join``, or
``pd.merge``. Now that the data is aligned and unnecessary blocks have
been removed we can rely on the fast in-memory Pandas join machinery to
execute joins per-partition. We know that all intersecting records exist
within the same partition
Hash Joins via Shuffle
----------------------
When we join along an unpartitioned index or along an arbitrary column any
partition from one input might interact with any partition in another. In
this case we perform a hash-join by shuffling data in each input by that
column. This results in new inputs with the same partition structure cleanly
separated along that column.
We proceed with hash joins in the following stages:
1. Shuffle each input on the specified column. See the function
``dask.dataframe.shuffle.shuffle``.
2. Perform embarrassingly parallel join across shuffled inputs.
"""
from __future__ import absolute_import, division, print_function
from functools import wraps, partial
from warnings import warn
from toolz import merge_sorted, unique, first
import toolz
import pandas as pd
from ..base import tokenize
from ..compatibility import apply
from .core import (_Frame, DataFrame, Series, map_partitions, Index,
_maybe_from_pandas, new_dd_object, is_broadcastable)
from .io import from_pandas
from . import methods
from .shuffle import shuffle, rearrange_by_divisions
from .utils import strip_unknown_categories
def align_partitions(*dfs):
""" Mutually partition and align DataFrame blocks
This serves as precursor to multi-dataframe operations like join, concat,
or merge.
Parameters
----------
dfs: sequence of dd.DataFrame, dd.Series and dd.base.Scalar
Sequence of dataframes to be aligned on their index
Returns
-------
dfs: sequence of dd.DataFrame, dd.Series and dd.base.Scalar
These must have consistent divisions with each other
divisions: tuple
Full divisions sequence of the entire result
result: list
A list of lists of keys that show which data exist on which
divisions
"""
_is_broadcastable = partial(is_broadcastable, dfs)
dfs1 = [df for df in dfs
if isinstance(df, _Frame) and
not _is_broadcastable(df)]
if len(dfs) == 0:
raise ValueError("dfs contains no DataFrame and Series")
if not all(df.known_divisions for df in dfs1):
raise ValueError("Not all divisions are known, can't align "
"partitions. Please use `set_index` "
"to set the index.")
divisions = list(unique(merge_sorted(*[df.divisions for df in dfs1])))
if len(divisions) == 1: # single value for index
divisions = (divisions[0], divisions[0])
dfs2 = [df.repartition(divisions, force=True)
if isinstance(df, _Frame) else df for df in dfs]
result = list()
inds = [0 for df in dfs]
for d in divisions[:-1]:
L = list()
for i, df in enumerate(dfs2):
if isinstance(df, _Frame):
j = inds[i]
divs = df.divisions
if j < len(divs) - 1 and divs[j] == d:
L.append((df._name, inds[i]))
inds[i] += 1
else:
L.append(None)
else: # Scalar has no divisions
L.append(None)
result.append(L)
return dfs2, tuple(divisions), result
def _maybe_align_partitions(args):
"""Align DataFrame blocks if divisions are different.
Note that if all divisions are unknown, but have equal npartitions, then
they will be passed through unchanged. This is different than
`align_partitions`, which will fail if divisions aren't all known"""
_is_broadcastable = partial(is_broadcastable, args)
dfs = [df for df in args
if isinstance(df, _Frame) and
not _is_broadcastable(df)]
if not dfs:
return args
divisions = dfs[0].divisions
if not all(df.divisions == divisions for df in dfs):
dfs2 = iter(align_partitions(*dfs)[0])
return [a if not isinstance(a, _Frame) else next(dfs2) for a in args]
return args
def require(divisions, parts, required=None):
""" Clear out divisions where required components are not present
In left, right, or inner joins we exclude portions of the dataset if one
side or the other is not present. We can achieve this at the partition
level as well
>>> divisions = [1, 3, 5, 7, 9]
>>> parts = [(('a', 0), None),
... (('a', 1), ('b', 0)),
... (('a', 2), ('b', 1)),
... (None, ('b', 2))]
>>> divisions2, parts2 = require(divisions, parts, required=[0])
>>> divisions2
(1, 3, 5, 7)
>>> parts2 # doctest: +NORMALIZE_WHITESPACE
((('a', 0), None),
(('a', 1), ('b', 0)),
(('a', 2), ('b', 1)))
>>> divisions2, parts2 = require(divisions, parts, required=[1])
>>> divisions2
(3, 5, 7, 9)
>>> parts2 # doctest: +NORMALIZE_WHITESPACE
((('a', 1), ('b', 0)),
(('a', 2), ('b', 1)),
(None, ('b', 2)))
>>> divisions2, parts2 = require(divisions, parts, required=[0, 1])
>>> divisions2
(3, 5, 7)
>>> parts2 # doctest: +NORMALIZE_WHITESPACE
((('a', 1), ('b', 0)),
(('a', 2), ('b', 1)))
"""
if not required:
return divisions, parts
for i in required:
present = [j for j, p in enumerate(parts) if p[i] is not None]
divisions = tuple(divisions[min(present): max(present) + 2])
parts = tuple(parts[min(present): max(present) + 1])
return divisions, parts
###############################################################
# Join / Merge
###############################################################
required = {'left': [0], 'right': [1], 'inner': [0, 1], 'outer': []}
def merge_indexed_dataframes(lhs, rhs, how='left', lsuffix='', rsuffix='',
indicator=False, left_on=None, right_on=None,
left_index=True, right_index=True):
""" Join two partitioned dataframes along their index """
(lhs, rhs), divisions, parts = align_partitions(lhs, rhs)
divisions, parts = require(divisions, parts, required[how])
left_empty = lhs._meta
right_empty = rhs._meta
name = 'join-indexed-' + tokenize(lhs, rhs, how, lsuffix, rsuffix,
indicator, left_on, right_on,
left_index, right_index)
dsk = dict()
for i, (a, b) in enumerate(parts):
if a is None and how in ('right', 'outer'):
a = left_empty
if b is None and how in ('left', 'outer'):
b = right_empty
dsk[(name, i)] = (methods.merge, a, b, how, left_on, right_on,
left_index, right_index,
indicator, (lsuffix, rsuffix), left_empty,
right_empty)
meta = pd.merge(lhs._meta_nonempty, rhs._meta_nonempty, how=how,
left_index=left_index, right_index=right_index,
left_on=left_on, right_on=right_on,
suffixes=(lsuffix, rsuffix), indicator=indicator)
return new_dd_object(toolz.merge(lhs.dask, rhs.dask, dsk),
name, meta, divisions)
shuffle_func = shuffle # name sometimes conflicts with keyword argument
def hash_join(lhs, left_on, rhs, right_on, how='inner',
npartitions=None, suffixes=('_x', '_y'), shuffle=None,
indicator=False):
""" Join two DataFrames on particular columns with hash join
This shuffles both datasets on the joined column and then performs an
embarrassingly parallel join partition-by-partition
>>> hash_join(a, 'id', rhs, 'id', how='left', npartitions=10) # doctest: +SKIP
"""
if npartitions is None:
npartitions = max(lhs.npartitions, rhs.npartitions)
lhs2 = shuffle_func(lhs, left_on, npartitions=npartitions, shuffle=shuffle)
rhs2 = shuffle_func(rhs, right_on, npartitions=npartitions, shuffle=shuffle)
if isinstance(left_on, Index):
left_on = None
left_index = True
else:
left_index = False
if isinstance(right_on, Index):
right_on = None
right_index = True
else:
right_index = False
# dummy result
meta = pd.merge(lhs._meta_nonempty, rhs._meta_nonempty, how=how,
left_on=left_on, right_on=right_on,
left_index=left_index, right_index=right_index,
suffixes=suffixes, indicator=indicator)
if isinstance(left_on, list):
left_on = (list, tuple(left_on))
if isinstance(right_on, list):
right_on = (list, tuple(right_on))
token = tokenize(lhs2, left_on, rhs2, right_on, left_index, right_index,
how, npartitions, suffixes, shuffle, indicator)
name = 'hash-join-' + token
dsk = {(name, i): (methods.merge,
(lhs2._name, i), (rhs2._name, i),
how, left_on, right_on,
left_index, right_index, indicator,
suffixes, lhs._meta, rhs._meta)
for i in range(npartitions)}
divisions = [None] * (npartitions + 1)
return new_dd_object(toolz.merge(lhs2.dask, rhs2.dask, dsk),
name, meta, divisions)
def single_partition_join(left, right, **kwargs):
# if the merge is perfomed on_index, divisions can be kept, otherwise the
# new index will not necessarily correspond the current divisions
meta = pd.merge(left._meta_nonempty, right._meta_nonempty, **kwargs)
name = 'merge-' + tokenize(left, right, **kwargs)
if left.npartitions == 1:
left_key = first(left.__dask_keys__())
dsk = {(name, i): (apply, pd.merge, [left_key, right_key], kwargs)
for i, right_key in enumerate(right.__dask_keys__())}
if kwargs.get('right_index') or right._contains_index_name(
kwargs.get('right_on')):
divisions = right.divisions
else:
divisions = [None for _ in right.divisions]
elif right.npartitions == 1:
right_key = first(right.__dask_keys__())
dsk = {(name, i): (apply, pd.merge, [left_key, right_key], kwargs)
for i, left_key in enumerate(left.__dask_keys__())}
if kwargs.get('left_index') or left._contains_index_name(
kwargs.get('left_on')):
divisions = left.divisions
else:
divisions = [None for _ in left.divisions]
return new_dd_object(toolz.merge(dsk, left.dask, right.dask), name,
meta, divisions)
@wraps(pd.merge)
def merge(left, right, how='inner', on=None, left_on=None, right_on=None,
left_index=False, right_index=False, suffixes=('_x', '_y'),
indicator=False, npartitions=None, shuffle=None, max_branch=None):
for o in [on, left_on, right_on]:
if isinstance(o, _Frame):
raise NotImplementedError(
"Dask collections not currently allowed in merge columns")
if not on and not left_on and not right_on and not left_index and not right_index:
on = [c for c in left.columns if c in right.columns]
if not on:
left_index = right_index = True
if on and not left_on and not right_on:
left_on = right_on = on
on = None
if (isinstance(left, (pd.Series, pd.DataFrame)) and
isinstance(right, (pd.Series, pd.DataFrame))):
return pd.merge(left, right, how=how, on=on, left_on=left_on,
right_on=right_on, left_index=left_index,
right_index=right_index, suffixes=suffixes,
indicator=indicator)
# Transform pandas objects into dask.dataframe objects
if isinstance(left, (pd.Series, pd.DataFrame)):
if right_index and left_on: # change to join on index
left = left.set_index(left[left_on])
left_on = False
left_index = True
left = from_pandas(left, npartitions=1) # turn into DataFrame
if isinstance(right, (pd.Series, pd.DataFrame)):
if left_index and right_on: # change to join on index
right = right.set_index(right[right_on])
right_on = False
right_index = True
right = from_pandas(right, npartitions=1) # turn into DataFrame
# Both sides are now dd.DataFrame or dd.Series objects
merge_indexed_left = (left_index or left._contains_index_name(
left_on)) and left.known_divisions
merge_indexed_right = (right_index or right._contains_index_name(
right_on)) and right.known_divisions
# Both sides indexed
if merge_indexed_left and merge_indexed_right: # Do indexed join
return merge_indexed_dataframes(left, right, how=how,
lsuffix=suffixes[0],
rsuffix=suffixes[1],
indicator=indicator,
left_on=left_on,
right_on=right_on,
left_index=left_index,
right_index=right_index)
# Single partition on one side
elif (left.npartitions == 1 and how in ('inner', 'right') or
right.npartitions == 1 and how in ('inner', 'left')):
return single_partition_join(left, right, how=how, right_on=right_on,
left_on=left_on, left_index=left_index,
right_index=right_index,
suffixes=suffixes, indicator=indicator)
# One side is indexed, the other not
elif (left_index and left.known_divisions and not right_index or
right_index and right.known_divisions and not left_index):
left_empty = left._meta_nonempty
right_empty = right._meta_nonempty
meta = pd.merge(left_empty, right_empty, how=how, on=on,
left_on=left_on, right_on=right_on,
left_index=left_index, right_index=right_index,
suffixes=suffixes, indicator=indicator)
if merge_indexed_left and left.known_divisions:
right = rearrange_by_divisions(right, right_on, left.divisions,
max_branch, shuffle=shuffle)
left = left.clear_divisions()
elif merge_indexed_right and right.known_divisions:
left = rearrange_by_divisions(left, left_on, right.divisions,
max_branch, shuffle=shuffle)
right = right.clear_divisions()
return map_partitions(pd.merge, left, right, meta=meta, how=how, on=on,
left_on=left_on, right_on=right_on,
left_index=left_index, right_index=right_index,
suffixes=suffixes, indicator=indicator)
# Catch all hash join
else:
return hash_join(left, left.index if left_index else left_on,
right, right.index if right_index else right_on,
how, npartitions, suffixes, shuffle=shuffle,
indicator=indicator)
###############################################################
# Concat
###############################################################
def concat_and_check(dfs):
if len(set(map(len, dfs))) != 1:
raise ValueError("Concatenated DataFrames of different lengths")
return pd.concat(dfs, axis=1)
def concat_unindexed_dataframes(dfs):
name = 'concat-' + tokenize(*dfs)
dsk = {(name, i): (concat_and_check, [(df._name, i) for df in dfs])
for i in range(dfs[0].npartitions)}
meta = pd.concat([df._meta for df in dfs], axis=1)
return new_dd_object(toolz.merge(dsk, *[df.dask for df in dfs]),
name, meta, dfs[0].divisions)
def concat_indexed_dataframes(dfs, axis=0, join='outer'):
""" Concatenate indexed dataframes together along the index """
meta = methods.concat([df._meta for df in dfs], axis=axis, join=join)
empties = [strip_unknown_categories(df._meta) for df in dfs]
dfs2, divisions, parts = align_partitions(*dfs)
name = 'concat-indexed-' + tokenize(join, *dfs)
parts2 = [[df if df is not None else empty
for df, empty in zip(part, empties)]
for part in parts]
dsk = dict(((name, i), (methods.concat, part, axis, join))
for i, part in enumerate(parts2))
for df in dfs2:
dsk.update(df.dask)
return new_dd_object(dsk, name, meta, divisions)
def stack_partitions(dfs, divisions, join='outer'):
"""Concatenate partitions on axis=0 by doing a simple stack"""
meta = methods.concat([df._meta for df in dfs], join=join)
empty = strip_unknown_categories(meta)
name = 'concat-{0}'.format(tokenize(*dfs))
dsk = {}
i = 0
for df in dfs:
dsk.update(df.dask)
# An error will be raised if the schemas or categories don't match. In
# this case we need to pass along the meta object to transform each
# partition, so they're all equivalent.
try:
df._meta == meta
match = True
except (ValueError, TypeError):
match = False
for key in df.__dask_keys__():
if match:
dsk[(name, i)] = key
else:
dsk[(name, i)] = (methods.concat, [empty, key], 0, join)
i += 1
return new_dd_object(dsk, name, meta, divisions)
def concat(dfs, axis=0, join='outer', interleave_partitions=False):
""" Concatenate DataFrames along rows.
- When axis=0 (default), concatenate DataFrames row-wise:
- If all divisions are known and ordered, concatenate DataFrames keeping
divisions. When divisions are not ordered, specifying
interleave_partition=True allows concatenate divisions each by each.
- If any of division is unknown, concatenate DataFrames resetting its
division to unknown (None)
- When axis=1, concatenate DataFrames column-wise:
- Allowed if all divisions are known.
- If any of division is unknown, it raises ValueError.
Parameters
----------
dfs : list
List of dask.DataFrames to be concatenated
axis : {0, 1, 'index', 'columns'}, default 0
The axis to concatenate along
join : {'inner', 'outer'}, default 'outer'
How to handle indexes on other axis
interleave_partitions : bool, default False
Whether to concatenate DataFrames ignoring its order. If True, every
divisions are concatenated each by each.
Notes
-----
This differs in from ``pd.concat`` in the when concatenating Categoricals
with different categories. Pandas currently coerces those to objects
before concatenating. Coercing to objects is very expensive for large
arrays, so dask preserves the Categoricals by taking the union of
the categories.
Examples
--------
If all divisions are known and ordered, divisions are kept.
>>> a # doctest: +SKIP
dd.DataFrame<x, divisions=(1, 3, 5)>
>>> b # doctest: +SKIP
dd.DataFrame<y, divisions=(6, 8, 10)>
>>> dd.concat([a, b]) # doctest: +SKIP
dd.DataFrame<concat-..., divisions=(1, 3, 6, 8, 10)>
Unable to concatenate if divisions are not ordered.
>>> a # doctest: +SKIP
dd.DataFrame<x, divisions=(1, 3, 5)>
>>> b # doctest: +SKIP
dd.DataFrame<y, divisions=(2, 3, 6)>
>>> dd.concat([a, b]) # doctest: +SKIP
ValueError: All inputs have known divisions which cannot be concatenated
in order. Specify interleave_partitions=True to ignore order
Specify interleave_partitions=True to ignore the division order.
>>> dd.concat([a, b], interleave_partitions=True) # doctest: +SKIP
dd.DataFrame<concat-..., divisions=(1, 2, 3, 5, 6)>
If any of division is unknown, the result division will be unknown
>>> a # doctest: +SKIP
dd.DataFrame<x, divisions=(None, None)>
>>> b # doctest: +SKIP
dd.DataFrame<y, divisions=(1, 4, 10)>
>>> dd.concat([a, b]) # doctest: +SKIP
dd.DataFrame<concat-..., divisions=(None, None, None, None)>
Different categoricals are unioned
>> dd.concat([ # doctest: +SKIP
... dd.from_pandas(pd.Series(['a', 'b'], dtype='category'), 1),
... dd.from_pandas(pd.Series(['a', 'c'], dtype='category'), 1),
... ], interleave_partitions=True).dtype
CategoricalDtype(categories=['a', 'b', 'c'], ordered=False)
"""
if not isinstance(dfs, list):
raise TypeError("dfs must be a list of DataFrames/Series objects")
if len(dfs) == 0:
raise ValueError('No objects to concatenate')
if len(dfs) == 1:
if axis == 1 and isinstance(dfs[0], Series):
return dfs[0].to_frame()
else:
return dfs[0]
if join not in ('inner', 'outer'):
raise ValueError("'join' must be 'inner' or 'outer'")
axis = DataFrame._validate_axis(axis)
dasks = [df for df in dfs if isinstance(df, _Frame)]
dfs = _maybe_from_pandas(dfs)
if axis == 1:
if all(df.known_divisions for df in dasks):
return concat_indexed_dataframes(dfs, axis=axis, join=join)
elif (len(dasks) == len(dfs) and
all(not df.known_divisions for df in dfs) and
len({df.npartitions for df in dasks}) == 1):
warn("Concatenating dataframes with unknown divisions.\n"
"We're assuming that the indexes of each dataframes are \n"
"aligned. This assumption is not generally safe.")
return concat_unindexed_dataframes(dfs)
else:
raise ValueError('Unable to concatenate DataFrame with unknown '
'division specifying axis=1')
else:
if all(df.known_divisions for df in dasks):
# each DataFrame's division must be greater than previous one
if all(dfs[i].divisions[-1] < dfs[i + 1].divisions[0]
for i in range(len(dfs) - 1)):
divisions = []
for df in dfs[:-1]:
# remove last to concatenate with next
divisions += df.divisions[:-1]
divisions += dfs[-1].divisions
return stack_partitions(dfs, divisions, join=join)
elif interleave_partitions:
return concat_indexed_dataframes(dfs, join=join)
else:
raise ValueError('All inputs have known divisions which '
'cannot be concatenated in order. Specify '
'interleave_partitions=True to ignore order')
else:
divisions = [None] * (sum([df.npartitions for df in dfs]) + 1)
return stack_partitions(dfs, divisions, join=join)
|
billiob/papyon
|
refs/heads/master
|
papyon/media/message.py
|
7
|
# -*- coding: utf-8 -*-
#
# papyon - a python client library for Msn
#
# Copyright (C) 2009 Collabora Ltd.
#
# 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 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, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from papyon.util.decorator import rw_property
__all__ = ['MediaSessionMessage', 'MediaStreamDescription']
class MediaSessionMessage(object):
"""Class representing messages sent between call participants. It contains
the different media descriptions. Different implementations need to
override _create_stream_description, _parse and __str__ functions."""
def __init__(self, session=None, body=None):
self._descriptions = []
if session is not None:
self._build(session)
elif body is not None:
self._parse(body)
@property
def descriptions(self):
"""Media stream descriptions"""
return self._descriptions
def _create_stream_description(self, stream):
raise NotImplementedError
def _build(self, session):
for stream in session.streams:
desc = self._create_stream_description(stream)
self._descriptions.append(desc)
def _parse(self, body):
raise NotImplementedError
def __str__(self):
raise NotImplementedError
class MediaStreamDescription(object):
"""Class representing a media stream description : name, direction and
codecs. Implementations of this class might also contain informations
about transport candidates. Such implementation should also override
the property "candidate_encoder" to return a subclass of
L{papyon.media.candidate.MediaCandidateEncoder} to encode and decode
these informations.
If the stream only accept a specific set of codecs, the function
is_valid_codec must be overriden as well."""
def __init__(self, stream=None, name=None, direction=None):
self._name = name
self._direction = direction
self._session_type = None
self._codecs = []
self.ip = ""
self.port = 0
self.rtcp = 0
if stream is not None:
self._build(stream)
@property
def name(self):
return self._name
@property
def direction(self):
return self._direction
@property
def candidate_encoder(self):
return None
@property
def session_type(self):
return self._session_type
@rw_property
def codecs():
def fget(self):
return self._codecs
def fset(self, value):
self._codecs = value
return locals()
@property
def valid_codecs(self):
return filter(lambda c: self.is_valid_codec(c), self.codecs)
def is_valid_codec(self, codec):
return True
def set_codecs(self, codecs):
codecs = filter(lambda c: self.is_valid_codec(c), codecs)
self.codecs = codecs
def get_codec(self, payload):
for codec in self._codecs:
if codec.payload == payload:
return codec
raise KeyError("No codec with payload %i in media", payload)
def set_candidates(self, local_candidates=None, remote_candidates=None):
if self.candidate_encoder is not None:
encoder = self.candidate_encoder
encoder.encode_candidates(self, local_candidates, remote_candidates)
def get_candidates(self):
if self.candidate_encoder is not None:
candidates = list(self.candidate_encoder.decode_candidates(self))
if not candidates[0]:
candidates[0] = self.candidate_encoder.get_default_candidates(self)
return candidates
return [], []
def _build(self, stream):
local_candidates = stream.get_active_local_candidates()
remote_candidates = stream.get_active_remote_candidates()
self._name = stream.name
self._direction = stream.direction
self._session_type = stream.session.type
self.ip, self.port, self.rtcp = stream.get_default_address()
self.set_codecs(stream.get_local_codecs())
self.set_candidates(local_candidates, remote_candidates)
def __repr__(self):
return "<Media Description: %s>" % self.name
|
dbjohnson/advent-of-code
|
refs/heads/master
|
solutions/day21/solution.py
|
1
|
import itertools
weapons = [{'Name': 'Dagger', 'Cost': 8, 'Damage': 4, 'Armor': 0},
{'Name': 'Shortsword', 'Cost': 10, 'Damage': 5, 'Armor': 0},
{'Name': 'Warhammer', 'Cost': 25, 'Damage': 6, 'Armor': 0},
{'Name': 'Longsword', 'Cost': 40, 'Damage': 7, 'Armor': 0},
{'Name': 'Greataxe', 'Cost': 74, 'Damage': 8, 'Armor': 0}]
armor = [{'Name': 'Leather', 'Cost': 13, 'Damage': 0, 'Armor': 1},
{'Name': 'Chainmail', 'Cost': 31, 'Damage': 0, 'Armor': 2},
{'Name': 'Splintmail', 'Cost': 53, 'Damage': 0, 'Armor': 3},
{'Name': 'Bandedmail', 'Cost': 75, 'Damage': 0, 'Armor': 4},
{'Name': 'Platemail', 'Cost': 102, 'Damage': 0, 'Armor': 5},
{'Name': 'None', 'Cost': 0, 'Damage': 0, 'Armor': 0}]
rings = [{'Name': 'Damage +1', 'Cost': 25, 'Damage': 1, 'Armor': 0},
{'Name': 'Damage +2', 'Cost': 50, 'Damage': 2, 'Armor': 0},
{'Name': 'Damage +3', 'Cost': 100, 'Damage': 3, 'Armor': 0},
{'Name': 'Defense +1', 'Cost': 20, 'Damage': 0, 'Armor': 1},
{'Name': 'Defense +2', 'Cost': 40, 'Damage': 0, 'Armor': 2},
{'Name': 'Defense +3', 'Cost': 80, 'Damage': 0, 'Armor': 3},
{'Name': 'None', 'Cost': 0, 'Damage': 0, 'Armor': 0}]
class Fighter(object):
def __init__(self, hitpoints=100, damage=0, armor=0, equipment=[]):
self.hitpoints = hitpoints
self.damage = damage
self.armor = armor
self.equipment_cost = 0
for item in equipment:
self.damage += item['Damage']
self.armor += item['Armor']
self.equipment_cost += item['Cost']
def deal_blow(self, other):
other.hitpoints -= max(1, self.damage - other.armor)
return other.hitpoints <= 0
losing_outfit_costs = []
winning_outfit_costs = []
for w in weapons:
for a in armor:
for nr in (1, 2):
for rrs in itertools.combinations(rings, nr):
fighter = Fighter(equipment=(w, a) + rrs)
boss = Fighter(100, 8, 2)
while True:
if fighter.deal_blow(boss):
winning_outfit_costs.append(fighter.equipment_cost)
break
if boss.deal_blow(fighter):
losing_outfit_costs.append(fighter.equipment_cost)
break
print 'part 1:', min(winning_outfit_costs)
print 'part 2:', max(losing_outfit_costs)
|
rayners/offlineimap
|
refs/heads/master
|
offlineimap/folder/Base.py
|
2
|
# Base folder support
# Copyright (C) 2002-2011 John Goerzen & contributors
#
# 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 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, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
from offlineimap import threadutil
from offlineimap.ui import getglobalui
from offlineimap.error import OfflineImapError
import os.path
import re
from sys import exc_info
import traceback
try: # python 2.6 has set() built in
set
except NameError:
from sets import Set as set
class BaseFolder(object):
def __init__(self):
self.ui = getglobalui()
def getname(self):
"""Returns name"""
return self.name
def __str__(self):
return self.name
def suggeststhreads(self):
"""Returns true if this folder suggests using threads for actions;
false otherwise. Probably only IMAP will return true."""
return 0
def getcopyinstancelimit(self):
"""For threading folders, returns the instancelimitname for
InstanceLimitedThreads."""
raise NotImplementedException
def storesmessages(self):
"""Should be true for any backend that actually saves message bodies.
(Almost all of them). False for the LocalStatus backend. Saves
us from having to slurp up messages just for localstatus purposes."""
return 1
def getvisiblename(self):
return self.name
def getrepository(self):
"""Returns the repository object that this folder is within."""
return self.repository
def getroot(self):
"""Returns the root of the folder, in a folder-specific fashion."""
return self.root
def getsep(self):
"""Returns the separator for this folder type."""
return self.sep
def getfullname(self):
if self.getroot():
return self.getroot() + self.getsep() + self.getname()
else:
return self.getname()
def getfolderbasename(self):
"""Return base file name of file to store Status/UID info in"""
if not self.name:
basename = '.'
else: #avoid directory hierarchies and file names such as '/'
basename = self.name.replace('/', '.')
# replace with literal 'dot' if final path name is '.' as '.' is
# an invalid file name.
basename = re.sub('(^|\/)\.$','\\1dot', basename)
return basename
def isuidvalidityok(self):
"""Does the cached UID match the real UID
If required it caches the UID. In this case the function is not
threadsafe. So don't attempt to call it from concurrent threads."""
if self.getsaveduidvalidity() != None:
return self.getsaveduidvalidity() == self.getuidvalidity()
else:
self.saveuidvalidity()
return 1
def _getuidfilename(self):
return os.path.join(self.repository.getuiddir(),
self.getfolderbasename())
def getsaveduidvalidity(self):
if hasattr(self, '_base_saved_uidvalidity'):
return self._base_saved_uidvalidity
uidfilename = self._getuidfilename()
if not os.path.exists(uidfilename):
self._base_saved_uidvalidity = None
else:
file = open(uidfilename, "rt")
self._base_saved_uidvalidity = long(file.readline().strip())
file.close()
return self._base_saved_uidvalidity
def saveuidvalidity(self):
"""Save the UID value of the folder to the status
This function is not threadsafe, so don't attempt to call it
from concurrent threads."""
newval = self.getuidvalidity()
uidfilename = self._getuidfilename()
file = open(uidfilename + ".tmp", "wt")
file.write("%d\n" % newval)
file.close()
os.rename(uidfilename + ".tmp", uidfilename)
self._base_saved_uidvalidity = newval
def getuidvalidity(self):
raise NotImplementedException
def cachemessagelist(self):
"""Reads the message list from disk or network and stores it in
memory for later use. This list will not be re-read from disk or
memory unless this function is called again."""
raise NotImplementedException
def getmessagelist(self):
"""Gets the current message list.
You must call cachemessagelist() before calling this function!"""
raise NotImplementedException
def uidexists(self, uid):
"""Returns True if uid exists"""
return uid in self.getmessagelist()
def getmessageuidlist(self):
"""Gets a list of UIDs.
You may have to call cachemessagelist() before calling this function!"""
return self.getmessagelist().keys()
def getmessagecount(self):
"""Gets the number of messages."""
return len(self.getmessagelist())
def getmessage(self, uid):
"""Returns the content of the specified message."""
raise NotImplementedException
def savemessage(self, uid, content, flags, rtime):
"""Writes a new message, with the specified uid.
If the uid is < 0: The backend should assign a new uid and
return it. In case it cannot assign a new uid, it returns
the negative uid passed in WITHOUT saving the message.
If the backend CAN assign a new uid, but cannot find out what
this UID is (as is the case with some IMAP servers), it
returns 0 but DOES save the message.
IMAP backend should be the only one that can assign a new
uid.
If the uid is > 0, the backend should set the uid to this, if it can.
If it cannot set the uid to that, it will save it anyway.
It will return the uid assigned in any case.
"""
raise NotImplementedException
def getmessagetime(self, uid):
"""Return the received time for the specified message."""
raise NotImplementedException
def getmessageflags(self, uid):
"""Returns the flags for the specified message."""
raise NotImplementedException
def savemessageflags(self, uid, flags):
"""Sets the specified message's flags to the given set."""
raise NotImplementedException
def addmessageflags(self, uid, flags):
"""Adds the specified flags to the message's flag set. If a given
flag is already present, it will not be duplicated.
:param flags: A set() of flags"""
newflags = self.getmessageflags(uid) | flags
self.savemessageflags(uid, newflags)
def addmessagesflags(self, uidlist, flags):
for uid in uidlist:
self.addmessageflags(uid, flags)
def deletemessageflags(self, uid, flags):
"""Removes each flag given from the message's flag set. If a given
flag is already removed, no action will be taken for that flag."""
newflags = self.getmessageflags(uid) - flags
self.savemessageflags(uid, newflags)
def deletemessagesflags(self, uidlist, flags):
for uid in uidlist:
self.deletemessageflags(uid, flags)
def deletemessage(self, uid):
raise NotImplementedException
def deletemessages(self, uidlist):
for uid in uidlist:
self.deletemessage(uid)
def copymessageto(self, uid, dstfolder, statusfolder, register = 1):
"""Copies a message from self to dst if needed, updating the status
:param uid: uid of the message to be copied.
:param dstfolder: A BaseFolder-derived instance
:param statusfolder: A LocalStatusFolder instance
:param register: whether we should register a new thread."
:returns: Nothing on success, or raises an Exception."""
# Sometimes, it could be the case that if a sync takes awhile,
# a message might be deleted from the maildir before it can be
# synced to the status cache. This is only a problem with
# self.getmessage(). So, don't call self.getmessage unless
# really needed.
if register: # output that we start a new thread
self.ui.registerthread(self.getaccountname())
try:
message = None
flags = self.getmessageflags(uid)
rtime = self.getmessagetime(uid)
if uid > 0 and dstfolder.uidexists(uid):
# dst has message with that UID already, only update status
statusfolder.savemessage(uid, None, flags, rtime)
return
self.ui.copyingmessage(uid, self, dstfolder)
# If any of the destinations actually stores the message body,
# load it up.
if dstfolder.storesmessages():
message = self.getmessage(uid)
#Succeeded? -> IMAP actually assigned a UID. If newid
#remained negative, no server was willing to assign us an
#UID. If newid is 0, saving succeeded, but we could not
#retrieve the new UID. Ignore message in this case.
newuid = dstfolder.savemessage(uid, message, flags, rtime)
if newuid > 0:
if newuid != uid:
# Got new UID, change the local uid.
#TODO: Maildir could do this with a rename rather than
#load/save/del operation, IMPLEMENT a changeuid()
#function or so.
self.savemessage(newuid, message, flags, rtime)
self.deletemessage(uid)
uid = newuid
# Save uploaded status in the statusfolder
statusfolder.savemessage(uid, message, flags, rtime)
elif newuid == 0:
# Message was stored to dstfolder, but we can't find it's UID
# This means we can't link current message to the one created
# in IMAP. So we just delete local message and on next run
# we'll sync it back
# XXX This could cause infinite loop on syncing between two
# IMAP servers ...
self.deletemessage(uid)
else:
raise OfflineImapError("Trying to save msg (uid %d) on folder "
"%s returned invalid uid %d" % \
(uid,
dstfolder.getvisiblename(),
newuid),
OfflineImapError.ERROR.MESSAGE)
except OfflineImapError, e:
if e.severity > OfflineImapError.ERROR.MESSAGE:
raise # buble severe errors up
self.ui.error(e, exc_info()[2])
except Exception, e:
self.ui.error(e, "Copying message %s [acc: %s]:\n %s" %\
(uid, self.getaccountname(),
traceback.format_exc()))
raise #raise on unknown errors, so we can fix those
def syncmessagesto_copy(self, dstfolder, statusfolder):
"""Pass1: Copy locally existing messages not on the other side
This will copy messages to dstfolder that exist locally but are
not in the statusfolder yet. The strategy is:
1) Look for messages present in self but not in statusfolder.
2) invoke copymessageto() on those which:
- If dstfolder doesn't have it yet, add them to dstfolder.
- Update statusfolder
"""
threads = []
copylist = filter(lambda uid: not \
statusfolder.uidexists(uid),
self.getmessageuidlist())
for uid in copylist:
# exceptions are caught in copymessageto()
if self.suggeststhreads():
self.waitforthread()
thread = threadutil.InstanceLimitedThread(\
self.getcopyinstancelimit(),
target = self.copymessageto,
name = "Copy message %d from %s" % (uid,
self.getvisiblename()),
args = (uid, dstfolder, statusfolder))
thread.setDaemon(1)
thread.start()
threads.append(thread)
else:
self.copymessageto(uid, dstfolder, statusfolder,
register = 0)
for thread in threads:
thread.join()
def syncmessagesto_delete(self, dstfolder, statusfolder):
"""Pass 2: Remove locally deleted messages on dst
Get all UIDS in statusfolder but not self. These are messages
that were deleted in 'self'. Delete those from dstfolder and
statusfolder."""
deletelist = filter(lambda uid: uid>=0 \
and not self.uidexists(uid),
statusfolder.getmessageuidlist())
if len(deletelist):
self.ui.deletingmessages(deletelist, [dstfolder])
# delete in statusfolder first to play safe. In case of abort, we
# won't lose message, we will just retransmit some unneccessary.
for folder in [statusfolder, dstfolder]:
folder.deletemessages(deletelist)
def syncmessagesto_flags(self, dstfolder, statusfolder):
"""Pass 3: Flag synchronization
Compare flag mismatches in self with those in statusfolder. If
msg has a valid UID and exists on dstfolder (has not e.g. been
deleted there), sync the flag change to both dstfolder and
statusfolder.
"""
# For each flag, we store a list of uids to which it should be
# added. Then, we can call addmessagesflags() to apply them in
# bulk, rather than one call per message.
addflaglist = {}
delflaglist = {}
for uid in self.getmessageuidlist():
# Ignore messages with negative UIDs missed by pass 1 and
# don't do anything if the message has been deleted remotely
if uid < 0 or not dstfolder.uidexists(uid):
continue
selfflags = self.getmessageflags(uid)
statusflags = statusfolder.getmessageflags(uid)
#if we could not get message flags from LocalStatus, assume empty.
if statusflags is None:
statusflags = set()
addflags = selfflags - statusflags
delflags = statusflags - selfflags
for flag in addflags:
if not flag in addflaglist:
addflaglist[flag] = []
addflaglist[flag].append(uid)
for flag in delflags:
if not flag in delflaglist:
delflaglist[flag] = []
delflaglist[flag].append(uid)
for flag, uids in addflaglist.items():
self.ui.addingflags(uids, flag, dstfolder)
dstfolder.addmessagesflags(uids, set(flag))
statusfolder.addmessagesflags(uids, set(flag))
for flag,uids in delflaglist.items():
self.ui.deletingflags(uids, flag, dstfolder)
dstfolder.deletemessagesflags(uids, set(flag))
statusfolder.deletemessagesflags(uids, set(flag))
def syncmessagesto(self, dstfolder, statusfolder):
"""Syncs messages in this folder to the destination dstfolder.
This is the high level entry for syncing messages in one direction.
Syncsteps are:
Pass1: Copy locally existing messages
Copy messages in self, but not statusfolder to dstfolder if not
already in dstfolder. dstfolder might assign a new UID (e.g. if
uploading to IMAP). Update statusfolder.
Pass2: Remove locally deleted messages
Get all UIDS in statusfolder but not self. These are messages
that were deleted in 'self'. Delete those from dstfolder and
statusfolder.
After this pass, the message lists should be identical wrt the
uids present (except for potential negative uids that couldn't
be placed anywhere).
Pass3: Synchronize flag changes
Compare flag mismatches in self with those in statusfolder. If
msg has a valid UID and exists on dstfolder (has not e.g. been
deleted there), sync the flag change to both dstfolder and
statusfolder.
:param dstfolder: Folderinstance to sync the msgs to.
:param statusfolder: LocalStatus instance to sync against.
"""
passes = [('copying messages' , self.syncmessagesto_copy),
('deleting messages' , self.syncmessagesto_delete),
('syncing flags' , self.syncmessagesto_flags)]
for (passdesc, action) in passes:
try:
action(dstfolder, statusfolder)
except (KeyboardInterrupt):
raise
except OfflineImapError, e:
if e.severity > OfflineImapError.ERROR.FOLDER:
raise
self.ui.error(e, exc_info()[2])
except Exception, e:
self.ui.error(e, exc_info()[2], "Syncing folder %s [acc: %s]" %\
(self, self.getaccountname()))
raise # raise unknown Exceptions so we can fix them
|
pulinagrawal/nupic
|
refs/heads/master
|
tests/unit/nupic/frameworks/opf/previous_value_model_test.py
|
5
|
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# 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 Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
"""
## @file
This file tests the operation of the Previous Value Model.
"""
import unittest2 as unittest
from nupic.data import dictutils
from nupic.frameworks.opf import opfutils, previousvaluemodel
SEQUENCE_LENGTH = 100
def _generateIncreasing():
return [i for i in range(SEQUENCE_LENGTH)]
def _generateDecreasing():
return [SEQUENCE_LENGTH - i for i in range(SEQUENCE_LENGTH)]
def _generateSaw():
return [i % 3 for i in range(SEQUENCE_LENGTH)]
class PreviousValueModelTest(unittest.TestCase):
"""Unit test for the Previous Value Model."""
def _runNextStep(self, data):
model = previousvaluemodel.PreviousValueModel(
opfutils.InferenceType.TemporalNextStep, predictedField = 'a')
inputRecords = (dictutils.DictObj({'a' : d}) for d in data)
for i, (inputRecord, expectedInference) in enumerate(zip(inputRecords,
data)):
results = model.run(inputRecord)
self.assertEqual(results.predictionNumber, i)
self.assertEqual(results.inferences[
opfutils.InferenceElement.prediction], expectedInference)
self.assertEqual(results.inferences[
opfutils.InferenceElement.multiStepBestPredictions][1],
expectedInference)
def _runMultiStep(self, data):
model = previousvaluemodel.PreviousValueModel(
opfutils.InferenceType.TemporalMultiStep, predictedField = 'a',
predictionSteps = [1, 3, 5])
inputRecords = (dictutils.DictObj({'a' : d}) for d in data)
for i, (inputRecord, expectedInference) in enumerate(zip(inputRecords,
data)):
results = model.run(inputRecord)
self.assertEqual(results.predictionNumber, i)
self.assertEqual(results.inferences[
opfutils.InferenceElement.prediction], expectedInference)
self.assertEqual(results.inferences[
opfutils.InferenceElement.multiStepBestPredictions][1],
expectedInference)
self.assertEqual(results.inferences[
opfutils.InferenceElement.multiStepBestPredictions][3],
expectedInference)
self.assertEqual(results.inferences[
opfutils.InferenceElement.multiStepBestPredictions][5],
expectedInference)
def testNextStepIncreasing(self):
self._runNextStep(_generateIncreasing())
def testNextStepDecreasing(self):
self._runNextStep(_generateDecreasing())
def testNextStepSaw(self):
self._runNextStep(_generateSaw())
def testMultiStepIncreasing(self):
self._runMultiStep(_generateIncreasing())
def testMultiStepDecreasing(self):
self._runMultiStep(_generateDecreasing())
def testMultiStepSaw(self):
self._runMultiStep(_generateSaw())
if __name__ == '__main__':
unittest.main()
|
StackPointCloud/ansible-modules-extras
|
refs/heads/devel
|
system/selinux_permissive.py
|
88
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2015, Michael Scherer <misc@zarb.org>
# inspired by code of github.com/dandiker/
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
DOCUMENTATION = '''
---
module: selinux_permissive
short_description: Change permissive domain in SELinux policy
description:
- Add and remove domain from the list of permissive domain.
version_added: "2.0"
options:
domain:
description:
- "the domain that will be added or removed from the list of permissive domains"
required: true
permissive:
description:
- "indicate if the domain should or should not be set as permissive"
required: true
choices: [ 'True', 'False' ]
no_reload:
description:
- "automatically reload the policy after a change"
- "default is set to 'false' as that's what most people would want after changing one domain"
- "Note that this doesn't work on older version of the library (example EL 6), the module will silently ignore it in this case"
required: false
default: False
choices: [ 'True', 'False' ]
store:
description:
- "name of the SELinux policy store to use"
required: false
default: null
notes:
- Requires a version of SELinux recent enough ( ie EL 6 or newer )
requirements: [ policycoreutils-python ]
author: Michael Scherer <misc@zarb.org>
'''
EXAMPLES = '''
- selinux_permissive: name=httpd_t permissive=true
'''
HAVE_SEOBJECT = False
try:
import seobject
HAVE_SEOBJECT = True
except ImportError:
pass
def main():
module = AnsibleModule(
argument_spec=dict(
domain=dict(aliases=['name'], required=True),
store=dict(required=False, default=''),
permissive=dict(type='bool', required=True),
no_reload=dict(type='bool', required=False, default=False),
),
supports_check_mode=True
)
# global vars
changed = False
store = module.params['store']
permissive = module.params['permissive']
domain = module.params['domain']
no_reload = module.params['no_reload']
if not HAVE_SEOBJECT:
module.fail_json(changed=False, msg="policycoreutils-python required for this module")
try:
permissive_domains = seobject.permissiveRecords(store)
except ValueError, e:
module.fail_json(domain=domain, msg=str(e))
# not supported on EL 6
if 'set_reload' in dir(permissive_domains):
permissive_domains.set_reload(not no_reload)
try:
all_domains = permissive_domains.get_all()
except ValueError, e:
module.fail_json(domain=domain, msg=str(e))
if permissive:
if domain not in all_domains:
if not module.check_mode:
try:
permissive_domains.add(domain)
except ValueError, e:
module.fail_json(domain=domain, msg=str(e))
changed = True
else:
if domain in all_domains:
if not module.check_mode:
try:
permissive_domains.delete(domain)
except ValueError, e:
module.fail_json(domain=domain, msg=str(e))
changed = True
module.exit_json(changed=changed, store=store,
permissive=permissive, domain=domain)
#################################################
# import module snippets
from ansible.module_utils.basic import *
main()
|
ellio167/lammps
|
refs/heads/master
|
examples/ELASTIC/compliance.py
|
29
|
#!/usr/bin/env python
# This file reads in the file log.lammps generated by the script ELASTIC/in.elastic
# It prints out the 6x6 tensor of elastic constants Cij
# followed by the 6x6 tensor of compliance constants Sij
# It uses the same conventions as described in:
# Sprik, Impey and Klein PRB (1984).
# The units of Cij are whatever was used in log.lammps (usually GPa)
# The units of Sij are the inverse of that (usually 1/GPa)
from numpy import zeros
from numpy.linalg import inv
# define logfile layout
nvals = 21
valpos = 4
valstr = '\nElastic Constant C'
# define order of Cij in logfile
cindices = [0]*nvals
cindices[0] = (0,0)
cindices[1] = (1,1)
cindices[2] = (2,2)
cindices[3] = (0,1)
cindices[4] = (0,2)
cindices[5] = (1,2)
cindices[6] = (3,3)
cindices[7] = (4,4)
cindices[8] = (5,5)
cindices[9] = (0,3)
cindices[10] = (0,4)
cindices[11] = (0,5)
cindices[12] = (1,3)
cindices[13] = (1,4)
cindices[14] = (1,5)
cindices[15] = (2,3)
cindices[16] = (2,4)
cindices[17] = (2,5)
cindices[18] = (3,4)
cindices[19] = (3,5)
cindices[20] = (4,5)
# open logfile
logfile = open("log.lammps",'r')
txt = logfile.read()
# search for 21 elastic constants
c = zeros((6,6))
s2 = 0
for ival in range(nvals):
s1 = txt.find(valstr,s2)
if (s1 == -1):
print "Failed to find elastic constants in log file"
exit(1)
s1 += 1
s2 = txt.find("\n",s1)
line = txt[s1:s2]
# print line
words = line.split()
(i1,i2) = cindices[ival]
c[i1,i2] = float(words[valpos])
c[i2,i1] = c[i1,i2]
print "C tensor [GPa]"
for i in range(6):
for j in range(6):
print "%10.8g " % c[i][j],
print
# apply factor of 2 to columns of off-diagonal elements
for i in range(6):
for j in range(3,6):
c[i][j] *= 2.0
s = inv(c)
# apply factor of 1/2 to columns of off-diagonal elements
for i in range(6):
for j in range(3,6):
s[i][j] *= 0.5
print "S tensor [1/GPa]"
for i in range(6):
for j in range(6):
print "%10.8g " % s[i][j],
print
|
jehutting/kivy
|
refs/heads/master
|
kivy/uix/popup.py
|
19
|
'''
Popup
=====
.. versionadded:: 1.0.7
.. image:: images/popup.jpg
:align: right
The :class:`Popup` widget is used to create modal popups. By default, the popup
will cover the whole "parent" window. When you are creating a popup, you
must at least set a :attr:`Popup.title` and :attr:`Popup.content`.
Remember that the default size of a Widget is size_hint=(1, 1). If you don't
want your popup to be fullscreen, either use size hints with values less than 1
(for instance size_hint=(.8, .8)) or deactivate the size_hint and use
fixed size attributes.
.. versionchanged:: 1.4.0
The :class:`Popup` class now inherits from
:class:`~kivy.uix.modalview.ModalView`. The :class:`Popup` offers a default
layout with a title and a separation bar.
Examples
--------
Example of a simple 400x400 Hello world popup::
popup = Popup(title='Test popup',
content=Label(text='Hello world'),
size_hint=(None, None), size=(400, 400))
By default, any click outside the popup will dismiss/close it. If you don't
want that, you can set
:attr:`~kivy.uix.modalview.ModalView.auto_dismiss` to False::
popup = Popup(title='Test popup', content=Label(text='Hello world'),
auto_dismiss=False)
popup.open()
To manually dismiss/close the popup, use
:attr:`~kivy.uix.modalview.ModalView.dismiss`::
popup.dismiss()
Both :meth:`~kivy.uix.modalview.ModalView.open` and
:meth:`~kivy.uix.modalview.ModalView.dismiss` are bindable. That means you
can directly bind the function to an action, e.g. to a button's on_press::
# create content and add to the popup
content = Button(text='Close me!')
popup = Popup(content=content, auto_dismiss=False)
# bind the on_press event of the button to the dismiss function
content.bind(on_press=popup.dismiss)
# open the popup
popup.open()
Popup Events
------------
There are two events available: `on_open` which is raised when the popup is
opening, and `on_dismiss` which is raised when the popup is closed.
For `on_dismiss`, you can prevent the
popup from closing by explictly returning True from your callback::
def my_callback(instance):
print('Popup', instance, 'is being dismissed but is prevented!')
return True
popup = Popup(content=Label(text='Hello world'))
popup.bind(on_dismiss=my_callback)
popup.open()
'''
__all__ = ('Popup', 'PopupException')
from kivy.uix.modalview import ModalView
from kivy.properties import (StringProperty, ObjectProperty, OptionProperty,
NumericProperty, ListProperty)
class PopupException(Exception):
'''Popup exception, fired when multiple content widgets are added to the
popup.
.. versionadded:: 1.4.0
'''
class Popup(ModalView):
'''Popup class. See module documentation for more information.
:Events:
`on_open`:
Fired when the Popup is opened.
`on_dismiss`:
Fired when the Popup is closed. If the callback returns True, the
dismiss will be canceled.
'''
title = StringProperty('No title')
'''String that represents the title of the popup.
:attr:`title` is a :class:`~kivy.properties.StringProperty` and defaults to
'No title'.
'''
title_size = NumericProperty('14sp')
'''Represents the font size of the popup title.
.. versionadded:: 1.6.0
:attr:`title_size` is a :class:`~kivy.properties.NumericProperty` and
defaults to '14sp'.
'''
title_align = OptionProperty('left',
options=['left', 'center', 'right', 'justify'])
'''Horizontal alignment of the title.
.. versionadded:: 1.9.0
:attr:`title_align` is a :class:`~kivy.properties.OptionProperty` and
defaults to 'left'. Available options are left, middle, right and justify.
'''
title_font = StringProperty('Roboto')
'''Font used to render the title text.
.. versionadded:: 1.9.0
:attr:`title_font` is a :class:`~kivy.properties.StringProperty` and
defaults to 'Roboto'.
'''
content = ObjectProperty(None)
'''Content of the popup that is displayed just under the title.
:attr:`content` is an :class:`~kivy.properties.ObjectProperty` and defaults
to None.
'''
title_color = ListProperty([1, 1, 1, 1])
'''Color used by the Title.
.. versionadded:: 1.8.0
:attr:`title_color` is a :class:`~kivy.properties.ListProperty` and
defaults to [1, 1, 1, 1].
'''
separator_color = ListProperty([47 / 255., 167 / 255., 212 / 255., 1.])
'''Color used by the separator between title and content.
.. versionadded:: 1.1.0
:attr:`separator_color` is a :class:`~kivy.properties.ListProperty` and
defaults to [47 / 255., 167 / 255., 212 / 255., 1.]
'''
separator_height = NumericProperty('2dp')
'''Height of the separator.
.. versionadded:: 1.1.0
:attr:`separator_height` is a :class:`~kivy.properties.NumericProperty` and
defaults to 2dp.
'''
# Internal properties used for graphical representation.
_container = ObjectProperty(None)
def add_widget(self, widget):
if self._container:
if self.content:
raise PopupException(
'Popup can have only one widget as content')
self.content = widget
else:
super(Popup, self).add_widget(widget)
def on_content(self, instance, value):
if self._container:
self._container.clear_widgets()
self._container.add_widget(value)
def on__container(self, instance, value):
if value is None or self.content is None:
return
self._container.clear_widgets()
self._container.add_widget(self.content)
def on_touch_down(self, touch):
if self.disabled and self.collide_point(*touch.pos):
return True
return super(Popup, self).on_touch_down(touch)
if __name__ == '__main__':
from kivy.base import runTouchApp
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.core.window import Window
# add popup
content = GridLayout(cols=1)
content_cancel = Button(text='Cancel', size_hint_y=None, height=40)
content.add_widget(Label(text='This is a hello world'))
content.add_widget(content_cancel)
popup = Popup(title='Test popup',
size_hint=(None, None), size=(256, 256),
content=content, disabled=True)
content_cancel.bind(on_release=popup.dismiss)
layout = GridLayout(cols=3)
for x in range(9):
btn = Button(text=str(x))
btn.bind(on_release=popup.open)
layout.add_widget(btn)
Window.add_widget(layout)
popup.open()
runTouchApp()
|
cliffe/SecGen
|
refs/heads/master
|
modules/utilities/unix/ctf/metactf/files/repository/src_angr/solutions/13_angr_static_binary/solve13.py
|
3
|
# This challenge is the exact same as the first challenge, except that it was
# compiled as a static binary. Normally, Angr automatically replaces standard
# library functions with SimProcedures that work much more quickly.
#
# To solve the challenge, manually hook any standard library c functions that
# are used. Then, ensure that you begin the execution at the beginning of the
# main function. Do not use entry_state.
#
# Here are a few SimProcedures Angr has already written for you. They implement
# standard library functions. You will not need all of them:
# angr.SIM_PROCEDURES['libc']['malloc']
# angr.SIM_PROCEDURES['libc']['fopen']
# angr.SIM_PROCEDURES['libc']['fclose']
# angr.SIM_PROCEDURES['libc']['fwrite']
# angr.SIM_PROCEDURES['libc']['getchar']
# angr.SIM_PROCEDURES['libc']['strncmp']
# angr.SIM_PROCEDURES['libc']['strcmp']
# angr.SIM_PROCEDURES['libc']['scanf']
# angr.SIM_PROCEDURES['libc']['printf']
# angr.SIM_PROCEDURES['libc']['puts']
# angr.SIM_PROCEDURES['libc']['exit']
#
# As a reminder, you can hook functions with something similar to:
# project.hook(malloc_address, angr.SIM_PROCEDURES['libc']['malloc']())
#
# There are many more, see:
# https://github.com/angr/angr/tree/master/angr/procedures/libc
import angr
import sys
def main(argv):
path_to_binary = argv[1]
project = angr.Project(path_to_binary)
initial_state = project.factory.entry_state()
project.hook(0x804ed40, angr.SIM_PROCEDURES['libc']['printf']())
project.hook(0x804ed80, angr.SIM_PROCEDURES['libc']['scanf']())
project.hook(0x804f350, angr.SIM_PROCEDURES['libc']['puts']())
project.hook(0x8048d10, angr.SIM_PROCEDURES['glibc']['__libc_start_main']())
simulation = project.factory.simgr(initial_state)
# Define a function that checks if you have found the state you are looking
# for.
def is_successful(state):
# Dump whatever has been printed out by the binary so far into a string.
stdout_output = state.posix.dumps(sys.stdout.fileno())
# Return whether 'Good Job.' has been printed yet.
# (!)
return 'Good Job.' in stdout_output # :boolean
# Same as above, but this time check if the state should abort. If you return
# False, Angr will continue to step the state. In this specific challenge, the
# only time at which you will know you should abort is when the program prints
# "Try again."
def should_abort(state):
stdout_output = state.posix.dumps(sys.stdout.fileno())
return 'Try again.' in stdout_output # :boolean
# Tell Angr to explore the binary and find any state that is_successful identfies
# as a successful state by returning True.
simulation.explore(find=is_successful, avoid=should_abort)
if simulation.found:
solution_state = simulation.found[0]
print solution_state.posix.dumps(sys.stdin.fileno())
else:
raise Exception('Could not find the solution')
if __name__ == '__main__':
main(sys.argv)
|
evansd/django
|
refs/heads/master
|
tests/proxy_model_inheritance/app1/models.py
|
515
|
# TODO: why can't I make this ..app2
from app2.models import NiceModel
class ProxyModel(NiceModel):
class Meta:
proxy = True
|
alexlo03/ansible
|
refs/heads/devel
|
lib/ansible/parsing/quoting.py
|
241
|
# (c) 2014 James Cammarata, <jcammarata@ansible.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
def is_quoted(data):
return len(data) > 1 and data[0] == data[-1] and data[0] in ('"', "'") and data[-2] != '\\'
def unquote(data):
''' removes first and last quotes from a string, if the string starts and ends with the same quotes '''
if is_quoted(data):
return data[1:-1]
return data
|
TomBurnett/Blender-Game-Engine-Javabot-AI
|
refs/heads/master
|
google/protobuf/internal/containers.py
|
3
|
# Protocol Buffers - Google's data interchange format
# Copyright 2008 Google Inc. All rights reserved.
# http://code.google.com/p/protobuf/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Contains container classes to represent different protocol buffer types.
This file defines container classes which represent categories of protocol
buffer field types which need extra maintenance. Currently these categories
are:
- Repeated scalar fields - These are all repeated fields which aren't
composite (e.g. they are of simple types like int32, string, etc).
- Repeated composite fields - Repeated fields which are composite. This
includes groups and nested messages.
"""
__author__ = 'petar@google.com (Petar Petrov)'
from google.protobuf.internal.utils import cmp
class BaseContainer(object):
"""Base container class."""
# Minimizes memory usage and disallows assignment to other attributes.
__slots__ = ['_message_listener', '_values']
def __init__(self, message_listener):
"""
Args:
message_listener: A MessageListener implementation.
The RepeatedScalarFieldContainer will call this object's
Modified() method when it is modified.
"""
self._message_listener = message_listener
self._values = []
def __getitem__(self, key):
"""Retrieves item by the specified key."""
return self._values[key]
def __len__(self):
"""Returns the number of elements in the container."""
return len(self._values)
def __ne__(self, other):
"""Checks if another instance isn't equal to this one."""
# The concrete classes should define __eq__.
return not self == other
def __hash__(self):
raise TypeError('unhashable object')
def __repr__(self):
return repr(self._values)
def sort(self, sort_function=cmp):
self._values.sort(sort_function)
class RepeatedScalarFieldContainer(BaseContainer):
"""Simple, type-checked, list-like container for holding repeated scalars."""
# Disallows assignment to other attributes.
__slots__ = ['_type_checker']
def __init__(self, message_listener, type_checker):
"""
Args:
message_listener: A MessageListener implementation.
The RepeatedScalarFieldContainer will call this object's
Modified() method when it is modified.
type_checker: A type_checkers.ValueChecker instance to run on elements
inserted into this container.
"""
super(RepeatedScalarFieldContainer, self).__init__(message_listener)
self._type_checker = type_checker
def append(self, value):
"""Appends an item to the list. Similar to list.append()."""
self._type_checker.CheckValue(value)
self._values.append(value)
if not self._message_listener.dirty:
self._message_listener.Modified()
def insert(self, key, value):
"""Inserts the item at the specified position. Similar to list.insert()."""
self._type_checker.CheckValue(value)
self._values.insert(key, value)
if not self._message_listener.dirty:
self._message_listener.Modified()
def extend(self, elem_seq):
"""Extends by appending the given sequence. Similar to list.extend()."""
if not elem_seq:
return
new_values = []
for elem in elem_seq:
self._type_checker.CheckValue(elem)
new_values.append(elem)
self._values.extend(new_values)
self._message_listener.Modified()
def MergeFrom(self, other):
"""Appends the contents of another repeated field of the same type to this
one. We do not check the types of the individual fields.
"""
self._values.extend(other._values)
self._message_listener.Modified()
def remove(self, elem):
"""Removes an item from the list. Similar to list.remove()."""
self._values.remove(elem)
self._message_listener.Modified()
def __setitem__(self, key, value):
"""Sets the item on the specified position."""
if isinstance(key, slice):
new_values = []
for val in value:
self._type_checker.CheckValue(val)
new_values.append(val)
self._values[key.start:key.stop] = new_values
self._message_listener.Modified()
else:
self._type_checker.CheckValue(value)
self._values[key] = value
self._message_listener.Modified()
def __getitem__(self, key):
"""Retrieves the subset of items from between the specified indices."""
if isinstance(key, slice):
return self._values[key.start:key.stop]
else:
return super(RepeatedScalarFieldContainer, self).__getitem__(key)
def __delslice__(self, start, stop):
del self._values[start:stop]
self._message_listener.Modified()
def __getslice__(self, start, stop):
return self._values[start:stop]
def __setslice__(self, start, stop, values):
"""Sets the subset of items from between the specified indices."""
new_values = []
for value in values:
self._type_checker.CheckValue(value)
new_values.append(value)
self._values[start:stop] = new_values
self._message_listener.Modified()
def __delitem__(self, key):
"""Deletes the subset of items from between the specified indices."""
if isinstance(key, slice):
del self._values[key.start:key.stop]
else:
del self._values[key]
self._message_listener.Modified()
def __eq__(self, other):
"""Compares the current instance with another one."""
if self is other:
return True
# Special case for the same type which should be common and fast.
if isinstance(other, self.__class__):
return other._values == self._values
# We are presumably comparing against some other sequence type.
return other == self._values
class RepeatedCompositeFieldContainer(BaseContainer):
"""Simple, list-like container for holding repeated composite fields."""
# Disallows assignment to other attributes.
__slots__ = ['_message_descriptor']
def __init__(self, message_listener, message_descriptor):
"""
Note that we pass in a descriptor instead of the generated directly,
since at the time we construct a _RepeatedCompositeFieldContainer we
haven't yet necessarily initialized the type that will be contained in the
container.
Args:
message_listener: A MessageListener implementation.
The RepeatedCompositeFieldContainer will call this object's
Modified() method when it is modified.
message_descriptor: A Descriptor instance describing the protocol type
that should be present in this container. We'll use the
_concrete_class field of this descriptor when the client calls add().
"""
super(RepeatedCompositeFieldContainer, self).__init__(message_listener)
self._message_descriptor = message_descriptor
def add(self, **kwargs):
"""Adds a new element at the end of the list and returns it. Keyword
arguments may be used to initialize the element.
"""
new_element = self._message_descriptor._concrete_class(**kwargs)
new_element._SetListener(self._message_listener)
self._values.append(new_element)
if not self._message_listener.dirty:
self._message_listener.Modified()
return new_element
def extend(self, elem_seq):
"""Extends by appending the given sequence of elements of the same type
as this one, copying each individual message.
"""
message_class = self._message_descriptor._concrete_class
listener = self._message_listener
values = self._values
for message in elem_seq:
new_element = message_class()
new_element._SetListener(listener)
new_element.MergeFrom(message)
values.append(new_element)
listener.Modified()
def MergeFrom(self, other):
"""Appends the contents of another repeated field of the same type to this
one, copying each individual message.
"""
self.extend(other._values)
def remove(self, elem):
"""Removes an item from the list. Similar to list.remove()."""
self._values.remove(elem)
self._message_listener.Modified()
def __getitem__(self, key):
"""Retrieves the subset of items from between the specified indices."""
if isinstance(key, slice):
return self._values[key.start:key.stop]
else:
return super(RepeatedCompositeFieldContainer, self).__getitem__(key)
def __delitem__(self, key):
"""Deletes the subset of items from between the specified indices."""
if isinstance(key, slice):
del self._values[key.start:key.stop]
else:
del self._values[key]
self._message_listener.Modified()
def __eq__(self, other):
"""Compares the current instance with another one."""
if self is other:
return True
if not isinstance(other, self.__class__):
raise TypeError('Can only compare repeated composite fields against '
'other repeated composite fields.')
return self._values == other._values
|
cantora/pyc
|
refs/heads/master
|
p2tests/grader_tests/fun4.py
|
1
|
# L = {y,x,f}
x = 1
y = 2
def f(y): # H = {x,y}, L={z,g}, P={y}, F = {y}
z = x + y
def g(w): # H = {x,y}, L={}, P={}
v = w + y
return v
return g
print (f(3))(4)
|
gsehub/edx-platform
|
refs/heads/gsehub-release
|
lms/djangoapps/shoppingcart/processors/__init__.py
|
215
|
"""
Public API for payment processor implementations.
The specific implementation is determined at runtime using Django settings:
CC_PROCESSOR_NAME: The name of the Python module (in `shoppingcart.processors`) to use.
CC_PROCESSOR: Dictionary of configuration options for specific processor implementations,
keyed to processor names.
"""
from django.conf import settings
# Import the processor implementation, using `CC_PROCESSOR_NAME`
# as the name of the Python module in `shoppingcart.processors`
PROCESSOR_MODULE = __import__(
'shoppingcart.processors.' + settings.CC_PROCESSOR_NAME,
fromlist=[
'render_purchase_form_html',
'process_postpay_callback',
'get_purchase_endpoint',
'get_signed_purchase_params',
]
)
def render_purchase_form_html(cart, **kwargs):
"""
Render an HTML form with POSTs to the hosted payment processor.
Args:
cart (Order): The order model representing items in the user's cart.
Returns:
unicode: the rendered HTML form
"""
return PROCESSOR_MODULE.render_purchase_form_html(cart, **kwargs)
def process_postpay_callback(params, **kwargs):
"""
Handle a response from the payment processor.
Concrete implementations should:
1) Verify the parameters and determine if the payment was successful.
2) If successful, mark the order as purchased and call `purchased_callbacks` of the cart items.
3) If unsuccessful, try to figure out why and generate a helpful error message.
4) Return a dictionary of the form:
{'success': bool, 'order': Order, 'error_html': str}
Args:
params (dict): Dictionary of parameters received from the payment processor.
Keyword Args:
Can be used to provide additional information to concrete implementations.
Returns:
dict
"""
return PROCESSOR_MODULE.process_postpay_callback(params, **kwargs)
def get_purchase_endpoint():
"""
Return the URL of the current payment processor's endpoint.
Returns:
unicode
"""
return PROCESSOR_MODULE.get_purchase_endpoint()
def get_signed_purchase_params(cart, **kwargs):
"""
Return the parameters to send to the current payment processor.
Args:
cart (Order): The order model representing items in the user's cart.
Keyword Args:
Can be used to provide additional information to concrete implementations.
Returns:
dict
"""
return PROCESSOR_MODULE.get_signed_purchase_params(cart, **kwargs)
|
eranimo/historia
|
refs/heads/master
|
historia/pops/__init__.py
|
1
|
from historia.pops.enums import PopJob, PopClass
from historia.pops.models import Inventory, Pop
from historia.pops.pop_service import *
|
tkettu/rokego
|
refs/heads/master
|
distances/views.py
|
1
|
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect, Http404
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django_tables2 import RequestConfig
from django.db.models import Sum
from .models import Exercise
from .forms import (
ExerciseForm,
ExerciseFilterFormHelper, RecordFilterFormHelper,
EditExerciseForm, GraphFilterFormHelper
)
from .tables import ExerciseTable
from distances.filters import ExerciseFilter, RecordFilter, GraphFilter
from distances.helpers.stats import Stats
import distances.helpers.records as rec
import distances.json.sports as spo
import distances.graphs as gra
from datetime import datetime, date
import logging
# Debugging
# import pdb; pdb.set_trace()
logger = logging.getLogger(__name__)
exercise_name = 'all'
end_date = ''
start_date = ''
def index(request):
"""The home page for Distance Tracker."""
if request.user.is_authenticated:
today = date.today()
cur_week = today.isocalendar()[1]
cur_month = today.month
cur_year = today.year
exercises_week = Exercise.objects.filter(owner=request.user,
date__week=cur_week, date__year=cur_year).all().order_by('-date')
exercises_month = Exercise.objects.filter(owner=request.user,
date__month=cur_month, date__year=cur_year).all().order_by('-date')
exes10 = Exercise.objects.filter(owner=request.user).all().order_by('-date')[:10]
distance_week = Stats.totals(exercises_week)
time_week = Stats.totaltime(exercises_week)
distance_month = Stats.totals(exercises_month)
time_month = Stats.totaltime(exercises_month)
ret_url = 'distances:index'
if request.method != 'POST':
form = ExerciseForm()
else:
modaln = new_exercise_modal(request, ret_url)
if modaln[1]:
return HttpResponseRedirect(reverse(modaln[2]))
form = modaln[0]
context = {'dist': distance_week, 'time': time_week, 'distm': distance_month,
'timem': time_month, 'exercises': exes10, 'form': form,
'subsports': spo.get_sports_json()}
else:
context = {'link': 'https://www.youtube.com/watch?v=tENiCpaIk9A'}
return render(request, 'distances/index.html', context)
@login_required
def exercises(request):
context = {}
exercises = Exercise.objects.filter(owner=request.user).all().order_by('-date')
filter = ExerciseFilter(request.GET, queryset=exercises)
filter.form.helper = ExerciseFilterFormHelper()
filtered_exercises = filter.qs
# Add new exercise with modal
ret_url = 'distances:exercises'
if request.method != 'POST':
form = ExerciseForm()
else:
if request.POST.get('delete'):
# TODO, implement working multi delete
items = request.POST.getlist('checks')
modaln = new_exercise_modal(request, ret_url)
if modaln[1]:
return HttpResponseRedirect(reverse(modaln[2]))
form = modaln[0]
table = ExerciseTable(filtered_exercises)
# set totals, averages etc. table.set...(Stats.get...)
RequestConfig(request).configure(table)
context['filter'] = filter
context['table'] = table
# context['form'] = modalForm
context['form'] = form
context['subsports'] = spo.get_sports_json()
response = render(request, 'distances/exercises.html', context)
return response
def new_exercise_modal(request, ret_url):
form = ExerciseForm(data=request.POST)
isForm = False
if form.is_valid():
new_exercise = form.save(commit=False)
new_exercise.owner = request.user
check_numberfields(new_exercise)
new_exercise.save()
if request.POST.get("submit"):
isForm = True
# return HttpResponseRedirect(reverse(ret_url))
elif request.POST.get("submitother"):
msg = 'Added ' + str(new_exercise.sport) + ' ' + str(new_exercise.distance) + ' km.'
ret_url = 'distances:new_exercise'
isForm = True
# return HttpResponseRedirect(reverse('distances:new_exercise'))
return [form, isForm, ret_url]
def check_numberfields(ex):
if ex.hours is None:
ex.hours = 0
if ex.minutes is None:
ex.minutes = 0
if ex.distance is None:
ex.distance = 0
@login_required
def new_exercise(request):
"""Add a new exercise."""
if request.method != 'POST':
form = ExerciseForm()
else:
form = ExerciseForm(data=request.POST)
if form.is_valid():
new_exercise = form.save(commit=False)
new_exercise.owner = request.user
check_numberfields(new_exercise)
new_exercise.save()
logger.warning(request.POST)
# if request.POST.get("addone", "submit"):
if request.POST.get("submit"):
logger.warning('Going back to exercises?')
return HttpResponseRedirect(reverse('distances:exercises'))
elif request.POST.get("submitother"):
# Inform somehow that new was added
logger.warning('Going to new_exercises?')
msg = 'Added ' + str(new_exercise.sport) + ' ' + str(new_exercise.distance) + ' km.'
messages.info(request, msg)
return HttpResponseRedirect(reverse('distances:new_exercise'))
context = {'form': form, 'subsports': spo.get_sports_json()}
return render(request, 'distances/new_exercise.html', context)
@login_required
def stats(request):
""" Display different records"""
context = {}
data = request.GET.copy()
if len(data) == 0:
default_year = datetime.now().year
elif data['year'] == '':
default_year = datetime.now().year
else:
default_year = request.GET.get('year')
exercises = Exercise.objects.filter(owner=request.user, date__year=default_year).all().order_by('-date')
record_filter = RecordFilter(request.GET, queryset=exercises)
record_filter.form.helper = RecordFilterFormHelper()
ddays = [7, 30, 365] # , filter.get_days()]
recs = []
# Todo optimize longest period, now this is like O(n^2)
# for d in ddays:
# re0 = rec.longest_period(filter.qs, days=d)
# recs.append(re0)
context['yearnro'] = default_year
context['year'] = record_filter.qs.aggregate(Sum('distance'))['distance__sum']
context['yeartime'] = Stats.totaltime(record_filter.qs) # filter.qs.aggregate(Sum('time_as_hours'))['time_as_hours__sum']
weeks = rec.week_results(record_filter.qs)
# recs = rec.longest_period(request.user, days=7, sport='Running')
context['filter'] = record_filter
# context['recs'] = recs
context['weeks'] = weeks
context['months'] = rec.month_results(record_filter.qs)
# context['month'] = months
# context = {'form': form, 'recs': recs, 'weeks': weeks, 'ename': sport}
return render(request, 'distances/stats.html', context)
@login_required
def edit_exercise(request, exercise_id):
"""Edit en existing entry"""
#entry = Exercise.objects.get(id=exercise_id)
entry = get_object_or_404(Exercise, id=exercise_id)
cur_user = request.user
check_exercise_owner(entry, cur_user)
if request.method != 'POST':
# Initial request; pre-fill form from the current entry.
form = EditExerciseForm(instance=entry, sport=entry.sport, sub_sport=entry.sub_sport)
else:
# POST data submitted; process data
if request.POST.get('delete'):
entry.delete()
return HttpResponseRedirect(reverse('distances:exercises'))
form = EditExerciseForm(instance=entry, data=request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('distances:exercises'))
context = {'exercise': entry, 'form': form}
return render(request, 'distances/edit_exercise.html', context)
def get_exercises(names, cur_user):
exercises = Exercise.objects.filter(owner=cur_user, sport='NOSPORT').all().order_by('-date')
for s in names:
ex = Exercise.objects.filter(owner=cur_user, sport=s).all().order_by('-date')
exercises = exercises | ex
return exercises
@login_required
def exercise(request, exercisename):
"""Show single sport and its totals."""
e = exercisename
cur_user = request.user
exercises = Exercise.objects.filter(owner=cur_user, sport=e).order_by('-date')
context = {'exercises': exercises, 'total': Stats.total(cur_user, sport=e),
'totaltime': Stats.totaltime(cur_user, sport=e)}
return render(request, 'distances/exercises.html', context)
######## GRAPHS #########
# pattern for splitting multiple sports and dates from graphs to image
ptr = 'AND'
sptr = 'SDATE'
eptr = 'EDATE'
gptr = 'GTYPE'
default_graph = ''
def set_default_graph(graph_type):
global default_graph
default_graph = graph_type
@login_required
def graphs(request):
""" Display graphs"""
context = {}
exercises = Exercise.objects.filter(owner=request.user).all().order_by('-date')
graph_filter = GraphFilter(request.GET, queryset=exercises)
graph_filter.form.helper = GraphFilterFormHelper()
context['filter'] = graph_filter
#TODO exercises without repeat
#filtered_exercises = graph_filter.qs
#graph_type = request.POST.get('...') -> Front-endiin POST
sport_request = request.GET.getlist('sport')
start_date_req = request.GET.get('startDate')
end_date_req = request.GET.get('endDate')
graph_type = request.GET.get('graphType')
if (graph_type != 'e'):
set_default_graph(graph_type)
context['image'] = set_image_filter(sport_request, start_date_req, end_date_req, graph_type)
#Todo distance and time images side by side for boxplot, histogram etc.
#if graph_type == 'b':
# context['image2'] = set_image_filter(sport_request, start_date_req, end_date_req, 'bt')
return render(request, 'distances/graphs.html', context)
def set_image_filter(sport="", start_date="", end_date="", graph_type="s"):
start_date = str(start_date)
end_date = str(end_date)
if (sport == "") & (start_date == "") & (end_date == ""):
ret_str = 'None'
else:
if len(sport) != 0:
req = ''
for i in sport:
req = req + i + ptr
ret_str = req + sptr + start_date + eptr + end_date
else:
ret_str = sptr + start_date + eptr + end_date
if not isinstance(default_graph, str):
if isinstance(graph_type,str):
return ret_str + gptr + graph_type
else:
return ret_str + gptr + "s"
else:
return ret_str + gptr + default_graph
@login_required
def image(request, filters):
"""Build image by filters
Format of '<Sport1>ptr<Sport2>ptr...<SportN>ptr+sptr<start_date>sptr<end_date>gptr<t>'
We split filters for sports, dates and graphtype and call corresponding graph with filters"""
if (filters != 'None'): # & (filters != ''):
sports = filters.split(ptr) # [<sport1>,<sport2>,...,<sportN>,sptr<start_date>eptr<end_date>gptr<t>]
dates = sports[-1] # sptr<start_date>eptr<end_date>gptr<t>
sports = sports[:-1] # [<sport1>,<sport2>,...,<sportN>]
dates = dates.replace(sptr, eptr) # eptr<start_date>eptr<end_date>gptr<t>
dates = dates.split(eptr) # ['', <start_date>,<end_date>gptr<t>]
# dates[0] is (hopefully) always ''
sd = dates[1]
ed = dates[2] # <end_date>gptr<t>
gtype = ed.split(gptr) # [<end_date>,<t>]
ed = gtype[0]
gtype = gtype[1]
if (ed == 'None') | (ed == ''):
ed = date.today()
if (sd == 'None') | (sd == ''):
# if type(sd) != date:
if isinstance(ed, str):
ed = datetime.strptime(ed, '%Y-%m-%d').date()
sd = date(ed.year, 1, 1)
# sd = date(date.today().year, 1, 1)
if len(sports) != 0:
exercises = Exercise.objects.filter(owner=request.user, sport__in=sports,
date__range=[sd, ed]).all().order_by('-date')
else:
exercises = Exercise.objects.filter(owner=request.user,
date__range=[sd, ed]).all().order_by('-date')
else:
exercises = Exercise.objects.filter(owner=request.user).all().order_by('-date')
if gtype == 's':
response = gra.graphs2(exercises)
elif gtype == 'c':
response = gra.graph_dist_sum(exercises)
elif gtype == 'b':
response = gra.box_plot(exercises, quant='distance')
elif gtype == 'bt':
response = gra.box_plot(exercises, quant='time_as_hours')
elif gtype == 'h':
response = gra.graph_histogram(exercises)
else:
response = gra.graphs2(exercises)
return response
def check_exercise_owner(exercise, user):
if exercise.owner != user:
raise Http404
return True
def get_stats(cur_user, sport='all'):
""" method for averages total ..."""
|
ininex/geofire-python
|
refs/heads/master
|
resource/lib/python2.7/site-packages/gcloud/bigtable/client.py
|
2
|
# 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.
"""Parent client for calling the Google Cloud Bigtable API.
This is the base from which all interactions with the API occur.
In the hierarchy of API concepts
* a :class:`Client` owns a :class:`.Instance`
* a :class:`.Instance` owns a :class:`Table <gcloud.bigtable.table.Table>`
* a :class:`Table <gcloud.bigtable.table.Table>` owns a
:class:`ColumnFamily <.column_family.ColumnFamily>`
* a :class:`Table <gcloud.bigtable.table.Table>` owns a :class:`Row <.row.Row>`
(and all the cells in the row)
"""
from pkg_resources import get_distribution
from grpc.beta import implementations
from gcloud.bigtable._generated_v2 import (
bigtable_instance_admin_pb2 as instance_admin_v2_pb2)
# V1 table admin service
from gcloud.bigtable._generated_v2 import (
bigtable_table_admin_pb2 as table_admin_v2_pb2)
# V1 data service
from gcloud.bigtable._generated_v2 import (
bigtable_pb2 as data_v2_pb2)
from gcloud.bigtable._generated_v2 import (
operations_grpc_pb2 as operations_grpc_v2_pb2)
from gcloud.bigtable.cluster import DEFAULT_SERVE_NODES
from gcloud.bigtable.instance import Instance
from gcloud.bigtable.instance import _EXISTING_INSTANCE_LOCATION_ID
from gcloud.client import _ClientFactoryMixin
from gcloud.client import _ClientProjectMixin
from gcloud.credentials import get_credentials
TABLE_STUB_FACTORY_V2 = (
table_admin_v2_pb2.beta_create_BigtableTableAdmin_stub)
TABLE_ADMIN_HOST_V2 = 'bigtableadmin.googleapis.com'
"""Table Admin API request host."""
TABLE_ADMIN_PORT_V2 = 443
"""Table Admin API request port."""
INSTANCE_STUB_FACTORY_V2 = (
instance_admin_v2_pb2.beta_create_BigtableInstanceAdmin_stub)
INSTANCE_ADMIN_HOST_V2 = 'bigtableadmin.googleapis.com'
"""Cluster Admin API request host."""
INSTANCE_ADMIN_PORT_V2 = 443
"""Cluster Admin API request port."""
DATA_STUB_FACTORY_V2 = data_v2_pb2.beta_create_Bigtable_stub
DATA_API_HOST_V2 = 'bigtable.googleapis.com'
"""Data API request host."""
DATA_API_PORT_V2 = 443
"""Data API request port."""
OPERATIONS_STUB_FACTORY_V2 = operations_grpc_v2_pb2.beta_create_Operations_stub
OPERATIONS_API_HOST_V2 = INSTANCE_ADMIN_HOST_V2
OPERATIONS_API_PORT_V2 = INSTANCE_ADMIN_PORT_V2
ADMIN_SCOPE = 'https://www.googleapis.com/auth/bigtable.admin'
"""Scope for interacting with the Cluster Admin and Table Admin APIs."""
DATA_SCOPE = 'https://www.googleapis.com/auth/bigtable.data'
"""Scope for reading and writing table data."""
READ_ONLY_SCOPE = 'https://www.googleapis.com/auth/bigtable.data.readonly'
"""Scope for reading table data."""
DEFAULT_TIMEOUT_SECONDS = 10
"""The default timeout to use for API requests."""
DEFAULT_USER_AGENT = 'gcloud-python/{0}'.format(
get_distribution('gcloud').version)
"""The default user agent for API requests."""
class Client(_ClientFactoryMixin, _ClientProjectMixin):
"""Client for interacting with Google Cloud Bigtable API.
.. note::
Since the Cloud Bigtable API requires the gRPC transport, no
``http`` argument is accepted by this class.
:type project: :class:`str` or :func:`unicode <unicode>`
:param project: (Optional) The ID of the project which owns the
instances, tables and data. If not provided, will
attempt to determine from the environment.
:type credentials:
:class:`OAuth2Credentials <oauth2client.client.OAuth2Credentials>` or
:data:`NoneType <types.NoneType>`
:param credentials: (Optional) The OAuth2 Credentials to use for this
client. If not provided, defaults to the Google
Application Default Credentials.
:type read_only: bool
:param read_only: (Optional) Boolean indicating if the data scope should be
for reading only (or for writing as well). Defaults to
:data:`False`.
:type admin: bool
:param admin: (Optional) Boolean indicating if the client will be used to
interact with the Instance Admin or Table Admin APIs. This
requires the :const:`ADMIN_SCOPE`. Defaults to :data:`False`.
:type user_agent: str
:param user_agent: (Optional) The user agent to be used with API request.
Defaults to :const:`DEFAULT_USER_AGENT`.
:type timeout_seconds: int
:param timeout_seconds: Number of seconds for request time-out. If not
passed, defaults to
:const:`DEFAULT_TIMEOUT_SECONDS`.
:raises: :class:`ValueError <exceptions.ValueError>` if both ``read_only``
and ``admin`` are :data:`True`
"""
def __init__(self, project=None, credentials=None,
read_only=False, admin=False, user_agent=DEFAULT_USER_AGENT,
timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
_ClientProjectMixin.__init__(self, project=project)
if credentials is None:
credentials = get_credentials()
if read_only and admin:
raise ValueError('A read-only client cannot also perform'
'administrative actions.')
scopes = []
if read_only:
scopes.append(READ_ONLY_SCOPE)
else:
scopes.append(DATA_SCOPE)
if admin:
scopes.append(ADMIN_SCOPE)
self._admin = bool(admin)
try:
credentials = credentials.create_scoped(scopes)
except AttributeError:
pass
self._credentials = credentials
self.user_agent = user_agent
self.timeout_seconds = timeout_seconds
# These will be set in start().
self._data_stub_internal = None
self._instance_stub_internal = None
self._operations_stub_internal = None
self._table_stub_internal = None
def copy(self):
"""Make a copy of this client.
Copies the local data stored as simple types but does not copy the
current state of any open connections with the Cloud Bigtable API.
:rtype: :class:`.Client`
:returns: A copy of the current client.
"""
credentials = self._credentials
copied_creds = credentials.create_scoped(credentials.scopes)
return self.__class__(
self.project,
copied_creds,
READ_ONLY_SCOPE in copied_creds.scopes,
self._admin,
self.user_agent,
self.timeout_seconds,
)
@property
def credentials(self):
"""Getter for client's credentials.
:rtype:
:class:`OAuth2Credentials <oauth2client.client.OAuth2Credentials>`
:returns: The credentials stored on the client.
"""
return self._credentials
@property
def project_name(self):
"""Project name to be used with Instance Admin API.
.. note::
This property will not change if ``project`` does not, but the
return value is not cached.
The project name is of the form
``"projects/{project}"``
:rtype: str
:returns: The project name to be used with the Cloud Bigtable Admin
API RPC service.
"""
return 'projects/' + self.project
@property
def _data_stub(self):
"""Getter for the gRPC stub used for the Data API.
:rtype: :class:`grpc.beta._stub._AutoIntermediary`
:returns: A gRPC stub object.
:raises: :class:`ValueError <exceptions.ValueError>` if the current
client has not been :meth:`start`-ed.
"""
if self._data_stub_internal is None:
raise ValueError('Client has not been started.')
return self._data_stub_internal
@property
def _instance_stub(self):
"""Getter for the gRPC stub used for the Instance Admin API.
:rtype: :class:`grpc.beta._stub._AutoIntermediary`
:returns: A gRPC stub object.
:raises: :class:`ValueError <exceptions.ValueError>` if the current
client is not an admin client or if it has not been
:meth:`start`-ed.
"""
if not self._admin:
raise ValueError('Client is not an admin client.')
if self._instance_stub_internal is None:
raise ValueError('Client has not been started.')
return self._instance_stub_internal
@property
def _operations_stub(self):
"""Getter for the gRPC stub used for the Operations API.
:rtype: :class:`grpc.beta._stub._AutoIntermediary`
:returns: A gRPC stub object.
:raises: :class:`ValueError <exceptions.ValueError>` if the current
client is not an admin client or if it has not been
:meth:`start`-ed.
"""
if not self._admin:
raise ValueError('Client is not an admin client.')
if self._operations_stub_internal is None:
raise ValueError('Client has not been started.')
return self._operations_stub_internal
@property
def _table_stub(self):
"""Getter for the gRPC stub used for the Table Admin API.
:rtype: :class:`grpc.beta._stub._AutoIntermediary`
:returns: A gRPC stub object.
:raises: :class:`ValueError <exceptions.ValueError>` if the current
client is not an admin client or if it has not been
:meth:`start`-ed.
"""
if not self._admin:
raise ValueError('Client is not an admin client.')
if self._table_stub_internal is None:
raise ValueError('Client has not been started.')
return self._table_stub_internal
def _make_data_stub(self):
"""Creates gRPC stub to make requests to the Data API.
:rtype: :class:`grpc.beta._stub._AutoIntermediary`
:returns: A gRPC stub object.
"""
return _make_stub(self, DATA_STUB_FACTORY_V2,
DATA_API_HOST_V2, DATA_API_PORT_V2)
def _make_instance_stub(self):
"""Creates gRPC stub to make requests to the Instance Admin API.
:rtype: :class:`grpc.beta._stub._AutoIntermediary`
:returns: A gRPC stub object.
"""
return _make_stub(self, INSTANCE_STUB_FACTORY_V2,
INSTANCE_ADMIN_HOST_V2, INSTANCE_ADMIN_PORT_V2)
def _make_operations_stub(self):
"""Creates gRPC stub to make requests to the Operations API.
These are for long-running operations of the Instance Admin API,
hence the host and port matching.
:rtype: :class:`grpc.beta._stub._AutoIntermediary`
:returns: A gRPC stub object.
"""
return _make_stub(self, OPERATIONS_STUB_FACTORY_V2,
OPERATIONS_API_HOST_V2, OPERATIONS_API_PORT_V2)
def _make_table_stub(self):
"""Creates gRPC stub to make requests to the Table Admin API.
:rtype: :class:`grpc.beta._stub._AutoIntermediary`
:returns: A gRPC stub object.
"""
return _make_stub(self, TABLE_STUB_FACTORY_V2,
TABLE_ADMIN_HOST_V2, TABLE_ADMIN_PORT_V2)
def is_started(self):
"""Check if the client has been started.
:rtype: bool
:returns: Boolean indicating if the client has been started.
"""
return self._data_stub_internal is not None
def start(self):
"""Prepare the client to make requests.
Activates gRPC contexts for making requests to the Bigtable
Service(s).
"""
if self.is_started():
return
# NOTE: We __enter__ the stubs more-or-less permanently. This is
# because only after entering the context managers is the
# connection created. We don't want to immediately close
# those connections since the client will make many
# requests with it over HTTP/2.
self._data_stub_internal = self._make_data_stub()
self._data_stub_internal.__enter__()
if self._admin:
self._instance_stub_internal = self._make_instance_stub()
self._operations_stub_internal = self._make_operations_stub()
self._table_stub_internal = self._make_table_stub()
self._instance_stub_internal.__enter__()
self._operations_stub_internal.__enter__()
self._table_stub_internal.__enter__()
def __enter__(self):
"""Starts the client as a context manager."""
self.start()
return self
def stop(self):
"""Closes all the open gRPC clients."""
if not self.is_started():
return
# When exit-ing, we pass None as the exception type, value and
# traceback to __exit__.
self._data_stub_internal.__exit__(None, None, None)
if self._admin:
self._instance_stub_internal.__exit__(None, None, None)
self._operations_stub_internal.__exit__(None, None, None)
self._table_stub_internal.__exit__(None, None, None)
self._data_stub_internal = None
self._instance_stub_internal = None
self._operations_stub_internal = None
self._table_stub_internal = None
def __exit__(self, exc_type, exc_val, exc_t):
"""Stops the client as a context manager."""
self.stop()
def instance(self, instance_id, location=_EXISTING_INSTANCE_LOCATION_ID,
display_name=None, serve_nodes=DEFAULT_SERVE_NODES):
"""Factory to create a instance associated with this client.
:type instance_id: str
:param instance_id: The ID of the instance.
:type location: string
:param location: location name, in form
``projects/<project>/locations/<location>``; used to
set up the instance's cluster.
:type display_name: str
:param display_name: (Optional) The display name for the instance in
the Cloud Console UI. (Must be between 4 and 30
characters.) If this value is not set in the
constructor, will fall back to the instance ID.
:type serve_nodes: int
:param serve_nodes: (Optional) The number of nodes in the instance's
cluster; used to set up the instance's cluster.
:rtype: :class:`.Instance`
:returns: an instance owned by this client.
"""
return Instance(instance_id, self, location,
display_name=display_name, serve_nodes=serve_nodes)
def list_instances(self):
"""List instances owned by the project.
:rtype: tuple
:returns: A pair of results, the first is a list of
:class:`.Instance` objects returned and the second is a
list of strings (the failed locations in the request).
"""
request_pb = instance_admin_v2_pb2.ListInstancesRequest(
parent=self.project_name)
response = self._instance_stub.ListInstances(
request_pb, self.timeout_seconds)
instances = [Instance.from_pb(instance_pb, self)
for instance_pb in response.instances]
return instances, response.failed_locations
class _MetadataPlugin(object):
"""Callable class to transform metadata for gRPC requests.
:type client: :class:`.client.Client`
:param client: The client that owns the instance.
Provides authorization and user agent.
"""
def __init__(self, client):
self._credentials = client.credentials
self._user_agent = client.user_agent
def __call__(self, unused_context, callback):
"""Adds authorization header to request metadata."""
access_token = self._credentials.get_access_token().access_token
headers = [
('Authorization', 'Bearer ' + access_token),
('User-agent', self._user_agent),
]
callback(headers, None)
def _make_stub(client, stub_factory, host, port):
"""Makes a stub for an RPC service.
Uses / depends on the beta implementation of gRPC.
:type client: :class:`.client.Client`
:param client: The client that owns the instance.
Provides authorization and user agent.
:type stub_factory: callable
:param stub_factory: A factory which will create a gRPC stub for
a given service.
:type host: str
:param host: The host for the service.
:type port: int
:param port: The port for the service.
:rtype: :class:`grpc.beta._stub._AutoIntermediary`
:returns: The stub object used to make gRPC requests to a given API.
"""
# Leaving the first argument to ssl_channel_credentials() as None
# loads root certificates from `grpc/_adapter/credentials/roots.pem`.
transport_creds = implementations.ssl_channel_credentials(None, None, None)
custom_metadata_plugin = _MetadataPlugin(client)
auth_creds = implementations.metadata_call_credentials(
custom_metadata_plugin, name='google_creds')
channel_creds = implementations.composite_channel_credentials(
transport_creds, auth_creds)
channel = implementations.secure_channel(host, port, channel_creds)
return stub_factory(channel)
|
antb/TPT----My-old-mod
|
refs/heads/master
|
src/python/stdlib/distutils/command/install_data.py
|
4
|
"""distutils.command.install_data
Implements the Distutils 'install_data' command, for installing
platform-independent data files."""
# contributed by Bastian Kleineidam
__revision__ = "$Id: install_data.py 76849 2009-12-15 06:29:19Z tarek.ziade $"
import os
from distutils.core import Command
from distutils.util import change_root, convert_path
class install_data(Command):
description = "install data files"
user_options = [
('install-dir=', 'd',
"base directory for installing data files "
"(default: installation base dir)"),
('root=', None,
"install everything relative to this alternate root directory"),
('force', 'f', "force installation (overwrite existing files)"),
]
boolean_options = ['force']
def initialize_options(self):
self.install_dir = None
self.outfiles = []
self.root = None
self.force = 0
self.data_files = self.distribution.data_files
self.warn_dir = 1
def finalize_options(self):
self.set_undefined_options('install',
('install_data', 'install_dir'),
('root', 'root'),
('force', 'force'),
)
def run(self):
self.mkpath(self.install_dir)
for f in self.data_files:
if isinstance(f, str):
# it's a simple file, so copy it
f = convert_path(f)
if self.warn_dir:
self.warn("setup script did not provide a directory for "
"'%s' -- installing right in '%s'" %
(f, self.install_dir))
(out, _) = self.copy_file(f, self.install_dir)
self.outfiles.append(out)
else:
# it's a tuple with path to install to and a list of files
dir = convert_path(f[0])
if not os.path.isabs(dir):
dir = os.path.join(self.install_dir, dir)
elif self.root:
dir = change_root(self.root, dir)
self.mkpath(dir)
if f[1] == []:
# If there are no files listed, the user must be
# trying to create an empty directory, so add the
# directory to the list of output files.
self.outfiles.append(dir)
else:
# Copy files, adding them to the list of output files.
for data in f[1]:
data = convert_path(data)
(out, _) = self.copy_file(data, dir)
self.outfiles.append(out)
def get_inputs(self):
return self.data_files or []
def get_outputs(self):
return self.outfiles
|
mcauser/micropython
|
refs/heads/master
|
tests/basics/int_big_zeroone.py
|
113
|
# test [0,-0,1,-1] edge cases of bignum
long_zero = (2**64) >> 65
long_neg_zero = -long_zero
long_one = long_zero + 1
long_neg_one = -long_one
cases = [long_zero, long_neg_zero, long_one, long_neg_one]
print(cases)
print([-c for c in cases])
print([~c for c in cases])
print([c >> 1 for c in cases])
print([c << 1 for c in cases])
# comparison of 0/-0/+0
print(long_zero == 0)
print(long_neg_zero == 0)
print(long_one - 1 == 0)
print(long_neg_one + 1 == 0)
print(long_zero < 1)
print(long_zero < -1)
print(long_zero > 1)
print(long_zero > -1)
print(long_neg_zero < 1)
print(long_neg_zero < -1)
print(long_neg_zero > 1)
print(long_neg_zero > -1)
|
nwjs/chromium.src
|
refs/heads/nw45-log
|
third_party/blink/tools/blinkpy/third_party/wpt/wpt/tools/webdriver/webdriver/error.py
|
7
|
import collections
import json
from six import itervalues
class WebDriverException(Exception):
http_status = None
status_code = None
def __init__(self, http_status=None, status_code=None, message=None, stacktrace=None):
super(WebDriverException, self)
self.http_status = http_status
self.status_code = status_code
self.message = message
self.stacktrace = stacktrace
def __repr__(self):
return "<%s http_status=%s>" % (self.__class__.__name__, self.http_status)
def __str__(self):
message = "%s (%s)" % (self.status_code, self.http_status)
if self.message is not None:
message += ": %s" % self.message
message += "\n"
if self.stacktrace:
message += ("\nRemote-end stacktrace:\n\n%s" % self.stacktrace)
return message
class ElementClickInterceptedException(WebDriverException):
http_status = 400
status_code = "element click intercepted"
class ElementNotSelectableException(WebDriverException):
http_status = 400
status_code = "element not selectable"
class ElementNotVisibleException(WebDriverException):
http_status = 400
status_code = "element not visible"
class InsecureCertificateException(WebDriverException):
http_status = 400
status_code = "insecure certificate"
class InvalidArgumentException(WebDriverException):
http_status = 400
status_code = "invalid argument"
class InvalidCookieDomainException(WebDriverException):
http_status = 400
status_code = "invalid cookie domain"
class InvalidElementCoordinatesException(WebDriverException):
http_status = 400
status_code = "invalid element coordinates"
class InvalidElementStateException(WebDriverException):
http_status = 400
status_code = "invalid element state"
class InvalidSelectorException(WebDriverException):
http_status = 400
status_code = "invalid selector"
class InvalidSessionIdException(WebDriverException):
http_status = 404
status_code = "invalid session id"
class JavascriptErrorException(WebDriverException):
http_status = 500
status_code = "javascript error"
class MoveTargetOutOfBoundsException(WebDriverException):
http_status = 500
status_code = "move target out of bounds"
class NoSuchAlertException(WebDriverException):
http_status = 404
status_code = "no such alert"
class NoSuchCookieException(WebDriverException):
http_status = 404
status_code = "no such cookie"
class NoSuchElementException(WebDriverException):
http_status = 404
status_code = "no such element"
class NoSuchFrameException(WebDriverException):
http_status = 404
status_code = "no such frame"
class NoSuchWindowException(WebDriverException):
http_status = 404
status_code = "no such window"
class ScriptTimeoutException(WebDriverException):
http_status = 500
status_code = "script timeout"
class SessionNotCreatedException(WebDriverException):
http_status = 500
status_code = "session not created"
class StaleElementReferenceException(WebDriverException):
http_status = 404
status_code = "stale element reference"
class TimeoutException(WebDriverException):
http_status = 500
status_code = "timeout"
class UnableToSetCookieException(WebDriverException):
http_status = 500
status_code = "unable to set cookie"
class UnexpectedAlertOpenException(WebDriverException):
http_status = 500
status_code = "unexpected alert open"
class UnknownErrorException(WebDriverException):
http_status = 500
status_code = "unknown error"
class UnknownCommandException(WebDriverException):
http_status = 404
status_code = "unknown command"
class UnknownMethodException(WebDriverException):
http_status = 405
status_code = "unknown method"
class UnsupportedOperationException(WebDriverException):
http_status = 500
status_code = "unsupported operation"
def from_response(response):
"""
Unmarshals an error from a ``Response``'s `body`, failing
if not all three required `error`, `message`, and `stacktrace`
fields are given. Defaults to ``WebDriverException`` if `error`
is unknown.
"""
if response.status == 200:
raise UnknownErrorException(
response.status,
None,
"Response is not an error:\n"
"%s" % json.dumps(response.body))
if "value" in response.body:
value = response.body["value"]
else:
raise UnknownErrorException(
response.status,
None,
"Expected 'value' key in response body:\n"
"%s" % json.dumps(response.body))
# all fields must exist, but stacktrace can be an empty string
code = value["error"]
message = value["message"]
stack = value["stacktrace"] or None
cls = get(code)
return cls(response.status, code, message, stacktrace=stack)
def get(error_code):
"""
Gets exception from `error_code`, falling back to
``WebDriverException`` if it is not found.
"""
return _errors.get(error_code, WebDriverException)
_errors = collections.defaultdict()
for item in list(itervalues(locals())):
if type(item) == type and issubclass(item, WebDriverException):
_errors[item.status_code] = item
|
dianna-project/dianna
|
refs/heads/master
|
scripts/qt/extract_strings_qt.py
|
31
|
#!/usr/bin/python
'''
Extract _("...") strings for translation and convert to Qt4 stringdefs so that
they can be picked up by Qt linguist.
'''
from subprocess import Popen, PIPE
OUT_CPP="src/qt/bitcoinstrings.cpp"
EMPTY=['""']
def parse_po(text):
"""
Parse 'po' format produced by xgettext.
Return a list of (msgid,msgstr) tuples.
"""
messages = []
msgid = []
msgstr = []
in_msgid = False
in_msgstr = False
for line in text.split('\n'):
line = line.rstrip('\r')
if line.startswith('msgid '):
if in_msgstr:
messages.append((msgid, msgstr))
in_msgstr = False
# message start
in_msgid = True
msgid = [line[6:]]
elif line.startswith('msgstr '):
in_msgid = False
in_msgstr = True
msgstr = [line[7:]]
elif line.startswith('"'):
if in_msgid:
msgid.append(line)
if in_msgstr:
msgstr.append(line)
if in_msgstr:
messages.append((msgid, msgstr))
return messages
files = ['src/base58.h', 'src/bignum.h', 'src/db.cpp', 'src/db.h', 'src/headers.h', 'src/init.cpp', 'src/init.h', 'src/irc.cpp', 'src/irc.h', 'src/key.h', 'src/main.cpp', 'src/main.h', 'src/net.cpp', 'src/net.h', 'src/noui.h', 'src/script.cpp', 'src/script.h', 'src/serialize.h', 'src/strlcpy.h', 'src/uint256.h', 'src/util.cpp', 'src/util.h']
# xgettext -n --keyword=_ $FILES
child = Popen(['xgettext','--output=-','-n','--keyword=_'] + files, stdout=PIPE)
(out, err) = child.communicate()
messages = parse_po(out)
f = open(OUT_CPP, 'w')
f.write('#include <QtGlobal>\n')
f.write('// Automatically generated by extract_strings.py\n')
f.write('static const char *bitcoin_strings[] = {')
for (msgid, msgstr) in messages:
if msgid != EMPTY:
f.write('QT_TRANSLATE_NOOP("bitcoin-core", %s),\n' % ('\n'.join(msgid)))
f.write('};')
f.close()
|
Dino0631/RedRain-Bot
|
refs/heads/develop
|
lib/nacl/bindings/sodium_core.py
|
17
|
# Copyright 2013 Donald Stufft and individual contributors
#
# 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
from nacl._sodium import lib
from nacl.exceptions import CryptoError
def sodium_init():
"""
Initializes sodium, picking the best implementations available for this
machine.
"""
if lib.sodium_init() != 0:
raise CryptoError("Could not initialize sodium")
|
Cinntax/home-assistant
|
refs/heads/dev
|
homeassistant/components/xs1/switch.py
|
14
|
"""Support for XS1 switches."""
import logging
from xs1_api_client.api_constants import ActuatorType
from homeassistant.helpers.entity import ToggleEntity
from . import ACTUATORS, DOMAIN as COMPONENT_DOMAIN, XS1DeviceEntity
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the XS1 switch platform."""
actuators = hass.data[COMPONENT_DOMAIN][ACTUATORS]
switch_entities = []
for actuator in actuators:
if (actuator.type() == ActuatorType.SWITCH) or (
actuator.type() == ActuatorType.DIMMER
):
switch_entities.append(XS1SwitchEntity(actuator))
add_entities(switch_entities)
class XS1SwitchEntity(XS1DeviceEntity, ToggleEntity):
"""Representation of a XS1 switch actuator."""
@property
def name(self):
"""Return the name of the device if any."""
return self.device.name()
@property
def is_on(self):
"""Return true if switch is on."""
return self.device.value() == 100
def turn_on(self, **kwargs):
"""Turn the device on."""
self.device.turn_on()
def turn_off(self, **kwargs):
"""Turn the device off."""
self.device.turn_off()
|
fengbaicanhe/intellij-community
|
refs/heads/master
|
python/testData/inspections/AddCallSuperKeywordOnlyParamInInit.py
|
79
|
class A:
def __init__(self, a):
pass
class B(A):
def <warning descr="Call to __init__ of super class is missed">__i<caret>nit__</warning>(self, b, c=1, *args, kw_only):
pass
|
dkodnik/Ant
|
refs/heads/master
|
openerp/tests/addons/test_translation_import/tests/test_term_count.py
|
323
|
# -*- coding: utf-8 -*-
import openerp
from openerp.tests import common
class TestTermCount(common.TransactionCase):
def test_count_term(self):
"""
Just make sure we have as many translation entries as we wanted.
"""
openerp.tools.trans_load(self.cr, 'test_translation_import/i18n/fr.po', 'fr_FR', verbose=False)
ids = self.registry('ir.translation').search(self.cr, self.uid,
[('src', '=', '1XBUO5PUYH2RYZSA1FTLRYS8SPCNU1UYXMEYMM25ASV7JC2KTJZQESZYRV9L8CGB')])
self.assertEqual(len(ids), 2)
|
TravisCG/SI_scripts
|
refs/heads/master
|
getcomm.py
|
1
|
#!/usr/bin/python
import sys
keep = set()
for i in open(sys.argv[1]):
keep.add(i.rstrip())
for i in open(sys.argv[2]):
fields = i.rstrip().split("\t")
if fields[0] in keep:
print i.rstrip()
|
shakamunyi/solum
|
refs/heads/master
|
solum/config.py
|
8
|
# Copyright 2013 - Red Hat, 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.
"""Solum specific config handling."""
from oslo.config import cfg
from solum import version
def parse_args(argv, default_config_files=None):
cfg.CONF(argv[1:],
project='solum',
version=version.version_string(),
default_config_files=default_config_files)
|
hkawasaki/kawasaki-aio8-1
|
refs/heads/gacco2/master
|
cms/envs/aws.py
|
8
|
"""
This is the default template for our main set of AWS servers.
"""
# We intentionally define lots of variables that aren't used, and
# want to import all variables from base settings files
# pylint: disable=W0401, W0614
import json
from .common import *
from logsettings import get_logger_config
import os
from path import path
from dealer.git import git
# SERVICE_VARIANT specifies name of the variant used, which decides what JSON
# configuration files are read during startup.
SERVICE_VARIANT = os.environ.get('SERVICE_VARIANT', None)
# CONFIG_ROOT specifies the directory where the JSON configuration
# files are expected to be found. If not specified, use the project
# directory.
CONFIG_ROOT = path(os.environ.get('CONFIG_ROOT', ENV_ROOT))
# CONFIG_PREFIX specifies the prefix of the JSON configuration files,
# based on the service variant. If no variant is use, don't use a
# prefix.
CONFIG_PREFIX = SERVICE_VARIANT + "." if SERVICE_VARIANT else ""
############### ALWAYS THE SAME ################################
DEBUG = False
TEMPLATE_DEBUG = False
EMAIL_BACKEND = 'django_ses.SESBackend'
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
###################################### CELERY ################################
# Don't use a connection pool, since connections are dropped by ELB.
BROKER_POOL_LIMIT = 0
BROKER_CONNECTION_TIMEOUT = 1
# For the Result Store, use the django cache named 'celery'
CELERY_RESULT_BACKEND = 'cache'
CELERY_CACHE_BACKEND = 'celery'
# When the broker is behind an ELB, use a heartbeat to refresh the
# connection and to detect if it has been dropped.
BROKER_HEARTBEAT = 10.0
BROKER_HEARTBEAT_CHECKRATE = 2
# Each worker should only fetch one message at a time
CELERYD_PREFETCH_MULTIPLIER = 1
# Skip djcelery migrations, since we don't use the database as the broker
SOUTH_MIGRATION_MODULES = {
'djcelery': 'ignore',
}
# Rename the exchange and queues for each variant
QUEUE_VARIANT = CONFIG_PREFIX.lower()
CELERY_DEFAULT_EXCHANGE = 'edx.{0}core'.format(QUEUE_VARIANT)
HIGH_PRIORITY_QUEUE = 'edx.{0}core.high'.format(QUEUE_VARIANT)
DEFAULT_PRIORITY_QUEUE = 'edx.{0}core.default'.format(QUEUE_VARIANT)
LOW_PRIORITY_QUEUE = 'edx.{0}core.low'.format(QUEUE_VARIANT)
CELERY_DEFAULT_QUEUE = DEFAULT_PRIORITY_QUEUE
CELERY_DEFAULT_ROUTING_KEY = DEFAULT_PRIORITY_QUEUE
CELERY_QUEUES = {
HIGH_PRIORITY_QUEUE: {},
LOW_PRIORITY_QUEUE: {},
DEFAULT_PRIORITY_QUEUE: {}
}
############# NON-SECURE ENV CONFIG ##############################
# Things like server locations, ports, etc.
with open(CONFIG_ROOT / CONFIG_PREFIX + "env.json") as env_file:
ENV_TOKENS = json.load(env_file)
# STATIC_URL_BASE specifies the base url to use for static files
STATIC_URL_BASE = ENV_TOKENS.get('STATIC_URL_BASE', None)
if STATIC_URL_BASE:
# collectstatic will fail if STATIC_URL is a unicode string
STATIC_URL = STATIC_URL_BASE.encode('ascii')
if not STATIC_URL.endswith("/"):
STATIC_URL += "/"
STATIC_URL += git.revision + "/"
# GITHUB_REPO_ROOT is the base directory
# for course data
GITHUB_REPO_ROOT = ENV_TOKENS.get('GITHUB_REPO_ROOT', GITHUB_REPO_ROOT)
# STATIC_ROOT specifies the directory where static files are
# collected
STATIC_ROOT_BASE = ENV_TOKENS.get('STATIC_ROOT_BASE', None)
if STATIC_ROOT_BASE:
STATIC_ROOT = path(STATIC_ROOT_BASE) / git.revision
EMAIL_BACKEND = ENV_TOKENS.get('EMAIL_BACKEND', EMAIL_BACKEND)
EMAIL_FILE_PATH = ENV_TOKENS.get('EMAIL_FILE_PATH', None)
EMAIL_HOST = ENV_TOKENS.get('EMAIL_HOST', EMAIL_HOST)
EMAIL_PORT = ENV_TOKENS.get('EMAIL_PORT', EMAIL_PORT)
EMAIL_USE_TLS = ENV_TOKENS.get('EMAIL_USE_TLS', EMAIL_USE_TLS)
LMS_BASE = ENV_TOKENS.get('LMS_BASE')
# Note that FEATURES['PREVIEW_LMS_BASE'] gets read in from the environment file.
SITE_NAME = ENV_TOKENS['SITE_NAME']
LOG_DIR = ENV_TOKENS['LOG_DIR']
CACHES = ENV_TOKENS['CACHES']
# Cache used for location mapping -- called many times with the same key/value
# in a given request.
if 'loc_cache' not in CACHES:
CACHES['loc_cache'] = {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'edx_location_mem_cache',
}
SESSION_COOKIE_DOMAIN = ENV_TOKENS.get('SESSION_COOKIE_DOMAIN')
SESSION_ENGINE = ENV_TOKENS.get('SESSION_ENGINE', SESSION_ENGINE)
# allow for environments to specify what cookie name our login subsystem should use
# this is to fix a bug regarding simultaneous logins between edx.org and edge.edx.org which can
# happen with some browsers (e.g. Firefox)
if ENV_TOKENS.get('SESSION_COOKIE_NAME', None):
# NOTE, there's a bug in Django (http://bugs.python.org/issue18012) which necessitates this being a str()
SESSION_COOKIE_NAME = str(ENV_TOKENS.get('SESSION_COOKIE_NAME'))
#Email overrides
DEFAULT_FROM_EMAIL = ENV_TOKENS.get('DEFAULT_FROM_EMAIL', DEFAULT_FROM_EMAIL)
DEFAULT_FEEDBACK_EMAIL = ENV_TOKENS.get('DEFAULT_FEEDBACK_EMAIL', DEFAULT_FEEDBACK_EMAIL)
ADMINS = ENV_TOKENS.get('ADMINS', ADMINS)
SERVER_EMAIL = ENV_TOKENS.get('SERVER_EMAIL', SERVER_EMAIL)
MKTG_URLS = ENV_TOKENS.get('MKTG_URLS', MKTG_URLS)
TECH_SUPPORT_EMAIL = ENV_TOKENS.get('TECH_SUPPORT_EMAIL', TECH_SUPPORT_EMAIL)
COURSES_WITH_UNSAFE_CODE = ENV_TOKENS.get("COURSES_WITH_UNSAFE_CODE", [])
# Theme overrides
THEME_NAME = ENV_TOKENS.get('THEME_NAME', None)
#Timezone overrides
TIME_ZONE = ENV_TOKENS.get('TIME_ZONE', TIME_ZONE)
# Push to LMS overrides
GIT_REPO_EXPORT_DIR = ENV_TOKENS.get('GIT_REPO_EXPORT_DIR', '/edx/var/edxapp/export_course_repos')
# Translation overrides
LANGUAGES = ENV_TOKENS.get('LANGUAGES', LANGUAGES)
LANGUAGE_CODE = ENV_TOKENS.get('LANGUAGE_CODE', LANGUAGE_CODE)
USE_I18N = ENV_TOKENS.get('USE_I18N', USE_I18N)
ENV_FEATURES = ENV_TOKENS.get('FEATURES', ENV_TOKENS.get('MITX_FEATURES', {}))
for feature, value in ENV_FEATURES.items():
FEATURES[feature] = value
WIKI_ENABLED = ENV_TOKENS.get('WIKI_ENABLED', WIKI_ENABLED)
LOGGING = get_logger_config(LOG_DIR,
logging_env=ENV_TOKENS['LOGGING_ENV'],
syslog_addr=(ENV_TOKENS['SYSLOG_SERVER'], 514),
debug=False,
service_variant=SERVICE_VARIANT)
#theming start:
PLATFORM_NAME = ENV_TOKENS.get('PLATFORM_NAME', 'edX')
# Event Tracking
if "TRACKING_IGNORE_URL_PATTERNS" in ENV_TOKENS:
TRACKING_IGNORE_URL_PATTERNS = ENV_TOKENS.get("TRACKING_IGNORE_URL_PATTERNS")
# Django CAS external authentication settings
CAS_EXTRA_LOGIN_PARAMS = ENV_TOKENS.get("CAS_EXTRA_LOGIN_PARAMS", None)
if FEATURES.get('AUTH_USE_CAS'):
CAS_SERVER_URL = ENV_TOKENS.get("CAS_SERVER_URL", None)
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'django_cas.backends.CASBackend',
)
INSTALLED_APPS += ('django_cas',)
MIDDLEWARE_CLASSES += ('django_cas.middleware.CASMiddleware',)
CAS_ATTRIBUTE_CALLBACK = ENV_TOKENS.get('CAS_ATTRIBUTE_CALLBACK', None)
if CAS_ATTRIBUTE_CALLBACK:
import importlib
CAS_USER_DETAILS_RESOLVER = getattr(
importlib.import_module(CAS_ATTRIBUTE_CALLBACK['module']),
CAS_ATTRIBUTE_CALLBACK['function']
)
################ SECURE AUTH ITEMS ###############################
# Secret things: passwords, access keys, etc.
with open(CONFIG_ROOT / CONFIG_PREFIX + "auth.json") as auth_file:
AUTH_TOKENS = json.load(auth_file)
EMAIL_HOST_USER = AUTH_TOKENS.get('EMAIL_HOST_USER', EMAIL_HOST_USER)
EMAIL_HOST_PASSWORD = AUTH_TOKENS.get('EMAIL_HOST_PASSWORD', EMAIL_HOST_PASSWORD)
# If Segment.io key specified, load it and turn on Segment.io if the feature flag is set
# Note that this is the Studio key. There is a separate key for the LMS.
SEGMENT_IO_KEY = AUTH_TOKENS.get('SEGMENT_IO_KEY')
if SEGMENT_IO_KEY:
FEATURES['SEGMENT_IO'] = ENV_TOKENS.get('SEGMENT_IO', False)
AWS_ACCESS_KEY_ID = AUTH_TOKENS["AWS_ACCESS_KEY_ID"]
if AWS_ACCESS_KEY_ID == "":
AWS_ACCESS_KEY_ID = None
AWS_SECRET_ACCESS_KEY = AUTH_TOKENS["AWS_SECRET_ACCESS_KEY"]
if AWS_SECRET_ACCESS_KEY == "":
AWS_SECRET_ACCESS_KEY = None
DATABASES = AUTH_TOKENS['DATABASES']
MODULESTORE = AUTH_TOKENS['MODULESTORE']
CONTENTSTORE = AUTH_TOKENS['CONTENTSTORE']
DOC_STORE_CONFIG = AUTH_TOKENS['DOC_STORE_CONFIG']
# Datadog for events!
DATADOG = AUTH_TOKENS.get("DATADOG", {})
DATADOG.update(ENV_TOKENS.get("DATADOG", {}))
# TODO: deprecated (compatibility with previous settings)
if 'DATADOG_API' in AUTH_TOKENS:
DATADOG['api_key'] = AUTH_TOKENS['DATADOG_API']
# Celery Broker
CELERY_BROKER_TRANSPORT = ENV_TOKENS.get("CELERY_BROKER_TRANSPORT", "")
CELERY_BROKER_HOSTNAME = ENV_TOKENS.get("CELERY_BROKER_HOSTNAME", "")
CELERY_BROKER_VHOST = ENV_TOKENS.get("CELERY_BROKER_VHOST", "")
CELERY_BROKER_USER = AUTH_TOKENS.get("CELERY_BROKER_USER", "")
CELERY_BROKER_PASSWORD = AUTH_TOKENS.get("CELERY_BROKER_PASSWORD", "")
BROKER_URL = "{0}://{1}:{2}@{3}/{4}".format(CELERY_BROKER_TRANSPORT,
CELERY_BROKER_USER,
CELERY_BROKER_PASSWORD,
CELERY_BROKER_HOSTNAME,
CELERY_BROKER_VHOST)
# Event tracking
TRACKING_BACKENDS.update(AUTH_TOKENS.get("TRACKING_BACKENDS", {}))
EVENT_TRACKING_BACKENDS.update(AUTH_TOKENS.get("EVENT_TRACKING_BACKENDS", {}))
SUBDOMAIN_BRANDING = ENV_TOKENS.get('SUBDOMAIN_BRANDING', {})
VIRTUAL_UNIVERSITIES = ENV_TOKENS.get('VIRTUAL_UNIVERSITIES', [])
##### ACCOUNT LOCKOUT DEFAULT PARAMETERS #####
MAX_FAILED_LOGIN_ATTEMPTS_ALLOWED = ENV_TOKENS.get("MAX_FAILED_LOGIN_ATTEMPTS_ALLOWED", 5)
MAX_FAILED_LOGIN_ATTEMPTS_LOCKOUT_PERIOD_SECS = ENV_TOKENS.get("MAX_FAILED_LOGIN_ATTEMPTS_LOCKOUT_PERIOD_SECS", 15 * 60)
MICROSITE_CONFIGURATION = ENV_TOKENS.get('MICROSITE_CONFIGURATION', {})
MICROSITE_ROOT_DIR = path(ENV_TOKENS.get('MICROSITE_ROOT_DIR', ''))
#### PASSWORD POLICY SETTINGS #####
PASSWORD_MIN_LENGTH = ENV_TOKENS.get("PASSWORD_MIN_LENGTH")
PASSWORD_MAX_LENGTH = ENV_TOKENS.get("PASSWORD_MAX_LENGTH")
PASSWORD_COMPLEXITY = ENV_TOKENS.get("PASSWORD_COMPLEXITY", {})
PASSWORD_DICTIONARY_EDIT_DISTANCE_THRESHOLD = ENV_TOKENS.get("PASSWORD_DICTIONARY_EDIT_DISTANCE_THRESHOLD")
PASSWORD_DICTIONARY = ENV_TOKENS.get("PASSWORD_DICTIONARY", [])
### INACTIVITY SETTINGS ####
SESSION_INACTIVITY_TIMEOUT_IN_SECONDS = AUTH_TOKENS.get("SESSION_INACTIVITY_TIMEOUT_IN_SECONDS")
##### X-Frame-Options response header settings #####
X_FRAME_OPTIONS = ENV_TOKENS.get('X_FRAME_OPTIONS', X_FRAME_OPTIONS)
##### ADVANCED_SECURITY_CONFIG #####
ADVANCED_SECURITY_CONFIG = ENV_TOKENS.get('ADVANCED_SECURITY_CONFIG', {})
|
datapythonista/pandas
|
refs/heads/master
|
pandas/tests/frame/methods/test_describe.py
|
2
|
import numpy as np
import pytest
import pandas as pd
from pandas import (
Categorical,
DataFrame,
Series,
Timestamp,
date_range,
)
import pandas._testing as tm
class TestDataFrameDescribe:
def test_describe_bool_in_mixed_frame(self):
df = DataFrame(
{
"string_data": ["a", "b", "c", "d", "e"],
"bool_data": [True, True, False, False, False],
"int_data": [10, 20, 30, 40, 50],
}
)
# Integer data are included in .describe() output,
# Boolean and string data are not.
result = df.describe()
expected = DataFrame(
{"int_data": [5, 30, df.int_data.std(), 10, 20, 30, 40, 50]},
index=["count", "mean", "std", "min", "25%", "50%", "75%", "max"],
)
tm.assert_frame_equal(result, expected)
# Top value is a boolean value that is False
result = df.describe(include=["bool"])
expected = DataFrame(
{"bool_data": [5, 2, False, 3]}, index=["count", "unique", "top", "freq"]
)
tm.assert_frame_equal(result, expected)
def test_describe_empty_object(self):
# GH#27183
df = DataFrame({"A": [None, None]}, dtype=object)
result = df.describe()
expected = DataFrame(
{"A": [0, 0, np.nan, np.nan]},
dtype=object,
index=["count", "unique", "top", "freq"],
)
tm.assert_frame_equal(result, expected)
result = df.iloc[:0].describe()
tm.assert_frame_equal(result, expected)
def test_describe_bool_frame(self):
# GH#13891
df = DataFrame(
{
"bool_data_1": [False, False, True, True],
"bool_data_2": [False, True, True, True],
}
)
result = df.describe()
expected = DataFrame(
{"bool_data_1": [4, 2, False, 2], "bool_data_2": [4, 2, True, 3]},
index=["count", "unique", "top", "freq"],
)
tm.assert_frame_equal(result, expected)
df = DataFrame(
{
"bool_data": [False, False, True, True, False],
"int_data": [0, 1, 2, 3, 4],
}
)
result = df.describe()
expected = DataFrame(
{"int_data": [5, 2, df.int_data.std(), 0, 1, 2, 3, 4]},
index=["count", "mean", "std", "min", "25%", "50%", "75%", "max"],
)
tm.assert_frame_equal(result, expected)
df = DataFrame(
{"bool_data": [False, False, True, True], "str_data": ["a", "b", "c", "a"]}
)
result = df.describe()
expected = DataFrame(
{"bool_data": [4, 2, False, 2], "str_data": [4, 3, "a", 2]},
index=["count", "unique", "top", "freq"],
)
tm.assert_frame_equal(result, expected)
def test_describe_categorical(self):
df = DataFrame({"value": np.random.randint(0, 10000, 100)})
labels = [f"{i} - {i + 499}" for i in range(0, 10000, 500)]
cat_labels = Categorical(labels, labels)
df = df.sort_values(by=["value"], ascending=True)
df["value_group"] = pd.cut(
df.value, range(0, 10500, 500), right=False, labels=cat_labels
)
cat = df
# Categoricals should not show up together with numerical columns
result = cat.describe()
assert len(result.columns) == 1
# In a frame, describe() for the cat should be the same as for string
# arrays (count, unique, top, freq)
cat = Categorical(
["a", "b", "b", "b"], categories=["a", "b", "c"], ordered=True
)
s = Series(cat)
result = s.describe()
expected = Series([4, 2, "b", 3], index=["count", "unique", "top", "freq"])
tm.assert_series_equal(result, expected)
cat = Series(Categorical(["a", "b", "c", "c"]))
df3 = DataFrame({"cat": cat, "s": ["a", "b", "c", "c"]})
result = df3.describe()
tm.assert_numpy_array_equal(result["cat"].values, result["s"].values)
def test_describe_empty_categorical_column(self):
# GH#26397
# Ensure the index of an empty categorical DataFrame column
# also contains (count, unique, top, freq)
df = DataFrame({"empty_col": Categorical([])})
result = df.describe()
expected = DataFrame(
{"empty_col": [0, 0, np.nan, np.nan]},
index=["count", "unique", "top", "freq"],
dtype="object",
)
tm.assert_frame_equal(result, expected)
# ensure NaN, not None
assert np.isnan(result.iloc[2, 0])
assert np.isnan(result.iloc[3, 0])
def test_describe_categorical_columns(self):
# GH#11558
columns = pd.CategoricalIndex(["int1", "int2", "obj"], ordered=True, name="XXX")
df = DataFrame(
{
"int1": [10, 20, 30, 40, 50],
"int2": [10, 20, 30, 40, 50],
"obj": ["A", 0, None, "X", 1],
},
columns=columns,
)
result = df.describe()
exp_columns = pd.CategoricalIndex(
["int1", "int2"],
categories=["int1", "int2", "obj"],
ordered=True,
name="XXX",
)
expected = DataFrame(
{
"int1": [5, 30, df.int1.std(), 10, 20, 30, 40, 50],
"int2": [5, 30, df.int2.std(), 10, 20, 30, 40, 50],
},
index=["count", "mean", "std", "min", "25%", "50%", "75%", "max"],
columns=exp_columns,
)
tm.assert_frame_equal(result, expected)
tm.assert_categorical_equal(result.columns.values, expected.columns.values)
def test_describe_datetime_columns(self):
columns = pd.DatetimeIndex(
["2011-01-01", "2011-02-01", "2011-03-01"],
freq="MS",
tz="US/Eastern",
name="XXX",
)
df = DataFrame(
{
0: [10, 20, 30, 40, 50],
1: [10, 20, 30, 40, 50],
2: ["A", 0, None, "X", 1],
}
)
df.columns = columns
result = df.describe()
exp_columns = pd.DatetimeIndex(
["2011-01-01", "2011-02-01"], freq="MS", tz="US/Eastern", name="XXX"
)
expected = DataFrame(
{
0: [5, 30, df.iloc[:, 0].std(), 10, 20, 30, 40, 50],
1: [5, 30, df.iloc[:, 1].std(), 10, 20, 30, 40, 50],
},
index=["count", "mean", "std", "min", "25%", "50%", "75%", "max"],
)
expected.columns = exp_columns
tm.assert_frame_equal(result, expected)
assert result.columns.freq == "MS"
assert result.columns.tz == expected.columns.tz
def test_describe_timedelta_values(self):
# GH#6145
t1 = pd.timedelta_range("1 days", freq="D", periods=5)
t2 = pd.timedelta_range("1 hours", freq="H", periods=5)
df = DataFrame({"t1": t1, "t2": t2})
expected = DataFrame(
{
"t1": [
5,
pd.Timedelta("3 days"),
df.iloc[:, 0].std(),
pd.Timedelta("1 days"),
pd.Timedelta("2 days"),
pd.Timedelta("3 days"),
pd.Timedelta("4 days"),
pd.Timedelta("5 days"),
],
"t2": [
5,
pd.Timedelta("3 hours"),
df.iloc[:, 1].std(),
pd.Timedelta("1 hours"),
pd.Timedelta("2 hours"),
pd.Timedelta("3 hours"),
pd.Timedelta("4 hours"),
pd.Timedelta("5 hours"),
],
},
index=["count", "mean", "std", "min", "25%", "50%", "75%", "max"],
)
result = df.describe()
tm.assert_frame_equal(result, expected)
exp_repr = (
" t1 t2\n"
"count 5 5\n"
"mean 3 days 00:00:00 0 days 03:00:00\n"
"std 1 days 13:56:50.394919273 0 days 01:34:52.099788303\n"
"min 1 days 00:00:00 0 days 01:00:00\n"
"25% 2 days 00:00:00 0 days 02:00:00\n"
"50% 3 days 00:00:00 0 days 03:00:00\n"
"75% 4 days 00:00:00 0 days 04:00:00\n"
"max 5 days 00:00:00 0 days 05:00:00"
)
assert repr(result) == exp_repr
def test_describe_tz_values(self, tz_naive_fixture):
# GH#21332
tz = tz_naive_fixture
s1 = Series(range(5))
start = Timestamp(2018, 1, 1)
end = Timestamp(2018, 1, 5)
s2 = Series(date_range(start, end, tz=tz))
df = DataFrame({"s1": s1, "s2": s2})
expected = DataFrame(
{
"s1": [5, 2, 0, 1, 2, 3, 4, 1.581139],
"s2": [
5,
Timestamp(2018, 1, 3).tz_localize(tz),
start.tz_localize(tz),
s2[1],
s2[2],
s2[3],
end.tz_localize(tz),
np.nan,
],
},
index=["count", "mean", "min", "25%", "50%", "75%", "max", "std"],
)
result = df.describe(include="all", datetime_is_numeric=True)
tm.assert_frame_equal(result, expected)
def test_datetime_is_numeric_includes_datetime(self):
df = DataFrame({"a": date_range("2012", periods=3), "b": [1, 2, 3]})
result = df.describe(datetime_is_numeric=True)
expected = DataFrame(
{
"a": [
3,
Timestamp("2012-01-02"),
Timestamp("2012-01-01"),
Timestamp("2012-01-01T12:00:00"),
Timestamp("2012-01-02"),
Timestamp("2012-01-02T12:00:00"),
Timestamp("2012-01-03"),
np.nan,
],
"b": [3, 2, 1, 1.5, 2, 2.5, 3, 1],
},
index=["count", "mean", "min", "25%", "50%", "75%", "max", "std"],
)
tm.assert_frame_equal(result, expected)
def test_describe_tz_values2(self):
tz = "CET"
s1 = Series(range(5))
start = Timestamp(2018, 1, 1)
end = Timestamp(2018, 1, 5)
s2 = Series(date_range(start, end, tz=tz))
df = DataFrame({"s1": s1, "s2": s2})
s1_ = s1.describe()
s2_ = Series(
[
5,
5,
s2.value_counts().index[0],
1,
start.tz_localize(tz),
end.tz_localize(tz),
],
index=["count", "unique", "top", "freq", "first", "last"],
)
idx = [
"count",
"unique",
"top",
"freq",
"first",
"last",
"mean",
"std",
"min",
"25%",
"50%",
"75%",
"max",
]
expected = pd.concat([s1_, s2_], axis=1, keys=["s1", "s2"]).loc[idx]
with tm.assert_produces_warning(FutureWarning):
result = df.describe(include="all")
tm.assert_frame_equal(result, expected)
def test_describe_percentiles_integer_idx(self):
# GH#26660
df = DataFrame({"x": [1]})
pct = np.linspace(0, 1, 10 + 1)
result = df.describe(percentiles=pct)
expected = DataFrame(
{"x": [1.0, 1.0, np.NaN, 1.0, *[1.0 for _ in pct], 1.0]},
index=[
"count",
"mean",
"std",
"min",
"0%",
"10%",
"20%",
"30%",
"40%",
"50%",
"60%",
"70%",
"80%",
"90%",
"100%",
"max",
],
)
tm.assert_frame_equal(result, expected)
def test_describe_does_not_raise_error_for_dictlike_elements(self):
# GH#32409
df = DataFrame([{"test": {"a": "1"}}, {"test": {"a": "2"}}])
expected = DataFrame(
{"test": [2, 2, {"a": "1"}, 1]}, index=["count", "unique", "top", "freq"]
)
result = df.describe()
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("exclude", ["x", "y", ["x", "y"], ["x", "z"]])
def test_describe_when_include_all_exclude_not_allowed(self, exclude):
"""
When include is 'all', then setting exclude != None is not allowed.
"""
df = DataFrame({"x": [1], "y": [2], "z": [3]})
msg = "exclude must be None when include is 'all'"
with pytest.raises(ValueError, match=msg):
df.describe(include="all", exclude=exclude)
def test_describe_with_duplicate_columns(self):
df = DataFrame(
[[1, 1, 1], [2, 2, 2], [3, 3, 3]],
columns=["bar", "a", "a"],
dtype="float64",
)
result = df.describe()
ser = df.iloc[:, 0].describe()
expected = pd.concat([ser, ser, ser], keys=df.columns, axis=1)
tm.assert_frame_equal(result, expected)
|
ruslanloman/nova
|
refs/heads/master
|
nova/db/sqlalchemy/api_migrations/migrate_repo/versions/001_cell_mapping.py
|
48
|
# 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 migrate import UniqueConstraint
from sqlalchemy import Column
from sqlalchemy import DateTime
from sqlalchemy import Index
from sqlalchemy import Integer
from sqlalchemy import MetaData
from sqlalchemy import String
from sqlalchemy import Table
from sqlalchemy import Text
def upgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
cell_mappings = Table('cell_mappings', meta,
Column('created_at', DateTime),
Column('updated_at', DateTime),
Column('id', Integer, primary_key=True, nullable=False),
Column('uuid', String(length=36), nullable=False),
Column('name', String(length=255)),
Column('transport_url', Text()),
Column('database_connection', Text()),
UniqueConstraint('uuid', name='uniq_cell_mappings0uuid'),
mysql_engine='InnoDB',
mysql_charset='utf8'
)
# NOTE(mriedem): DB2 creates an index when a unique constraint is created
# so trying to add a second index on the uuid column will fail with
# error SQL0605W, so omit the index in the case of DB2.
if migrate_engine.name != 'ibm_db_sa':
Index('uuid_idx', cell_mappings.c.uuid)
cell_mappings.create(checkfirst=True)
|
vivekn/redis-simple-cache
|
refs/heads/master
|
redis_cache/__init__.py
|
3
|
from rediscache import *
|
repotvsupertuga/tvsupertuga.repository
|
refs/heads/master
|
plugin.video.loganaddon/resources/lib/libraries/cache.py
|
19
|
# -*- coding: utf-8 -*-
'''
Specto Add-on
Copyright (C) 2015 lambda
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
import re,hashlib,time, json
try:
from sqlite3 import dbapi2 as database
except:
from pysqlite2 import dbapi2 as database
from resources.lib.libraries import control
def get(function, timeout, *args, **table):
try:
response = None
f = repr(function)
f = re.sub('.+\smethod\s|.+function\s|\sat\s.+|\sof\s.+', '', f)
a = hashlib.md5()
for i in args: a.update(str(i))
a = str(a.hexdigest())
except:
pass
try:
table = table['table']
except:
table = 'rel_list'
try:
control.makeFile(control.dataPath)
dbcon = database.connect(control.cacheFile)
dbcur = dbcon.cursor()
dbcur.execute("SELECT * FROM %s WHERE func = '%s' AND args = '%s'" % (table, f, a))
match = dbcur.fetchone()
response = eval(match[2].encode('utf-8'))
t1 = int(match[3])
t2 = int(time.time())
update = (abs(t2 - t1) / 3600) >= int(timeout)
if update == False:
return response
except:
pass
try:
r = function(*args)
if (r == None or r == []) and not response == None:
return response
elif (r == None or r == []):
return r
except:
return
try:
r = repr(r)
t = int(time.time())
dbcur.execute("CREATE TABLE IF NOT EXISTS %s (""func TEXT, ""args TEXT, ""response TEXT, ""added TEXT, ""UNIQUE(func, args)"");" % table)
dbcur.execute("DELETE FROM %s WHERE func = '%s' AND args = '%s'" % (table, f, a))
dbcur.execute("INSERT INTO %s Values (?, ?, ?, ?)" % table, (f, a, r, t))
dbcon.commit()
except:
pass
try:
return eval(r.encode('utf-8'))
except:
pass
def timeout(function, *args, **table):
try:
response = None
f = repr(function)
f = re.sub('.+\smethod\s|.+function\s|\sat\s.+|\sof\s.+', '', f)
a = hashlib.md5()
for i in args: a.update(str(i))
a = str(a.hexdigest())
except:
pass
try:
table = table['table']
except:
table = 'rel_list'
try:
control.makeFile(control.dataPath)
dbcon = database.connect(control.cacheFile)
dbcur = dbcon.cursor()
dbcur.execute("SELECT * FROM %s WHERE func = '%s' AND args = '%s'" % (table, f, a))
match = dbcur.fetchone()
return int(match[3])
except:
return
def clear(table=None):
try:
control.idle()
if table == None: table = ['rel_list', 'rel_lib']
elif not type(table) == list: table = [table]
yes = control.yesnoDialog(control.lang(30401).encode('utf-8'), '', '')
if not yes: return
dbcon = database.connect(control.cacheFile)
dbcur = dbcon.cursor()
for t in table:
try:
dbcur.execute("DROP TABLE IF EXISTS %s" % t)
dbcur.execute("VACUUM")
dbcon.commit()
except:
pass
control.infoDialog(control.lang(30402).encode('utf-8'))
except:
pass
#def getMovieSource(self, title, year, imdb, source, call):
def get_cached_url(self, url, data='', cache_limit=8):
try:
dbcon = database.connect(control.sourcescachedUrl)
dbcur = dbcon.cursor()
#dbcur.execute(
# "CREATE TABLE IF NOT EXISTS rel_url (""source TEXT, ""imdb_id TEXT, ""season TEXT, ""episode TEXT, ""rel_url TEXT, ""UNIQUE(source, imdb_id, season, episode)"");")
dbcur.execute(
"CREATE TABLE IF NOT EXISTS url_cache (url VARCHAR(255) NOT NULL, data VARCHAR(255), response, res_header, timestamp, PRIMARY KEY(url, data))")
except:
pass
try:
if data is None: data = ''
html = ''
res_header = []
created = 0
now = time.time()
age = now - created
limit = 60 * 60 * cache_limit
dbcur.execute('SELECT timestamp, response, res_header FROM url_cache WHERE url = %s and data=%s' % (url,data))
rows = dbcur.fetchall()
control.log('DB ROWS: Url: %s, ' % (rows))
if rows:
created = float(rows[0][0])
res_header = json.loads(rows[0][2])
age = now - created
if age < limit:
html = rows[0][1]
control.log('DB Cache: Url: %s, Data: %s, Cache Hit: %s, created: %s, age: %.2fs (%.2fh), limit: %ss' % (
url, data, bool(html), created, age, age / (60 * 60), limit))
return created, res_header, html
except:
return
def cache_url(self, url, body, data=None, res_header=None):
try:
dbcon = database.connect(control.sourcescachedUrl)
dbcur = dbcon.cursor()
dbcur.execute(
"CREATE TABLE IF NOT EXISTS url_cache (url VARCHAR(255) NOT NULL, data VARCHAR(255), response, res_header, timestamp, PRIMARY KEY(url, data))")
except:
pass
try:
now = time.time()
if data is None: data = ''
if res_header is None: res_header = []
res_header = json.dumps(res_header)
# truncate data if running mysql and greater than col size
sql = "REPLACE INTO url_cache (url, data, response, res_header, timestamp) VALUES(?, ?, ?, ?, ?)" % (url, data, body, res_header, now)
#dbcur.execute("DELETE FROM url_cache WHERE func = '%s' AND args = '%s'" % (table, f, a))
#dbcur.execute("INSERT INTO %s Values (?, ?, ?, ?)" % table, (f, a, r, t))
dbcur.execute(sql)
dbcon.commit()
except:
pass
|
gkoelln/youtube-dl
|
refs/heads/master
|
youtube_dl/extractor/everyonesmixtape.py
|
88
|
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
ExtractorError,
sanitized_Request,
)
class EveryonesMixtapeIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?everyonesmixtape\.com/#/mix/(?P<id>[0-9a-zA-Z]+)(?:/(?P<songnr>[0-9]))?$'
_TESTS = [{
'url': 'http://everyonesmixtape.com/#/mix/m7m0jJAbMQi/5',
'info_dict': {
'id': '5bfseWNmlds',
'ext': 'mp4',
'title': "Passion Pit - \"Sleepyhead\" (Official Music Video)",
'uploader': 'FKR.TV',
'uploader_id': 'frenchkissrecords',
'description': "Music video for \"Sleepyhead\" from Passion Pit's debut EP Chunk Of Change.\nBuy on iTunes: https://itunes.apple.com/us/album/chunk-of-change-ep/id300087641\n\nDirected by The Wilderness.\n\nhttp://www.passionpitmusic.com\nhttp://www.frenchkissrecords.com",
'upload_date': '20081015'
},
'params': {
'skip_download': True, # This is simply YouTube
}
}, {
'url': 'http://everyonesmixtape.com/#/mix/m7m0jJAbMQi',
'info_dict': {
'id': 'm7m0jJAbMQi',
'title': 'Driving',
},
'playlist_count': 24
}]
def _real_extract(self, url):
mobj = re.match(self._VALID_URL, url)
playlist_id = mobj.group('id')
pllist_url = 'http://everyonesmixtape.com/mixtape.php?a=getMixes&u=-1&linked=%s&explore=' % playlist_id
pllist_req = sanitized_Request(pllist_url)
pllist_req.add_header('X-Requested-With', 'XMLHttpRequest')
playlist_list = self._download_json(
pllist_req, playlist_id, note='Downloading playlist metadata')
try:
playlist_no = next(playlist['id']
for playlist in playlist_list
if playlist['code'] == playlist_id)
except StopIteration:
raise ExtractorError('Playlist id not found')
pl_url = 'http://everyonesmixtape.com/mixtape.php?a=getMix&id=%s&userId=null&code=' % playlist_no
pl_req = sanitized_Request(pl_url)
pl_req.add_header('X-Requested-With', 'XMLHttpRequest')
playlist = self._download_json(
pl_req, playlist_id, note='Downloading playlist info')
entries = [{
'_type': 'url',
'url': t['url'],
'title': t['title'],
} for t in playlist['tracks']]
if mobj.group('songnr'):
songnr = int(mobj.group('songnr')) - 1
return entries[songnr]
playlist_title = playlist['mixData']['name']
return {
'_type': 'playlist',
'id': playlist_id,
'title': playlist_title,
'entries': entries,
}
|
madebydaniz/django1-11
|
refs/heads/master
|
src/muypicky/settings/base.py
|
1
|
"""
Django settings for muypicky project.
Generated by 'django-admin startproject' using Django 1.11.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '6&z)*vjgvw3_yr!2%10a(v(y1thw3e-0g=jpb)9%jowpyqx1(n'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'menus',
'restaurants'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'muypicky.urls'
LOGIN_URL = '/login/'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'muypicky.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
|
hynnet/hiwifi-openwrt-HC5661-HC5761
|
refs/heads/master
|
staging_dir/target-mipsel_r2_uClibc-0.9.33.2/usr/lib/python2.7/shelve.py
|
225
|
"""Manage shelves of pickled objects.
A "shelf" is a persistent, dictionary-like object. The difference
with dbm databases is that the values (not the keys!) in a shelf can
be essentially arbitrary Python objects -- anything that the "pickle"
module can handle. This includes most class instances, recursive data
types, and objects containing lots of shared sub-objects. The keys
are ordinary strings.
To summarize the interface (key is a string, data is an arbitrary
object):
import shelve
d = shelve.open(filename) # open, with (g)dbm filename -- no suffix
d[key] = data # store data at key (overwrites old data if
# using an existing key)
data = d[key] # retrieve a COPY of the data at key (raise
# KeyError if no such key) -- NOTE that this
# access returns a *copy* of the entry!
del d[key] # delete data stored at key (raises KeyError
# if no such key)
flag = d.has_key(key) # true if the key exists; same as "key in d"
list = d.keys() # a list of all existing keys (slow!)
d.close() # close it
Dependent on the implementation, closing a persistent dictionary may
or may not be necessary to flush changes to disk.
Normally, d[key] returns a COPY of the entry. This needs care when
mutable entries are mutated: for example, if d[key] is a list,
d[key].append(anitem)
does NOT modify the entry d[key] itself, as stored in the persistent
mapping -- it only modifies the copy, which is then immediately
discarded, so that the append has NO effect whatsoever. To append an
item to d[key] in a way that will affect the persistent mapping, use:
data = d[key]
data.append(anitem)
d[key] = data
To avoid the problem with mutable entries, you may pass the keyword
argument writeback=True in the call to shelve.open. When you use:
d = shelve.open(filename, writeback=True)
then d keeps a cache of all entries you access, and writes them all back
to the persistent mapping when you call d.close(). This ensures that
such usage as d[key].append(anitem) works as intended.
However, using keyword argument writeback=True may consume vast amount
of memory for the cache, and it may make d.close() very slow, if you
access many of d's entries after opening it in this way: d has no way to
check which of the entries you access are mutable and/or which ones you
actually mutate, so it must cache, and write back at close, all of the
entries that you access. You can call d.sync() to write back all the
entries in the cache, and empty the cache (d.sync() also synchronizes
the persistent dictionary on disk, if feasible).
"""
# Try using cPickle and cStringIO if available.
try:
from cPickle import Pickler, Unpickler
except ImportError:
from pickle import Pickler, Unpickler
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
import UserDict
__all__ = ["Shelf","BsdDbShelf","DbfilenameShelf","open"]
class _ClosedDict(UserDict.DictMixin):
'Marker for a closed dict. Access attempts raise a ValueError.'
def closed(self, *args):
raise ValueError('invalid operation on closed shelf')
__getitem__ = __setitem__ = __delitem__ = keys = closed
def __repr__(self):
return '<Closed Dictionary>'
class Shelf(UserDict.DictMixin):
"""Base class for shelf implementations.
This is initialized with a dictionary-like object.
See the module's __doc__ string for an overview of the interface.
"""
def __init__(self, dict, protocol=None, writeback=False):
self.dict = dict
if protocol is None:
protocol = 0
self._protocol = protocol
self.writeback = writeback
self.cache = {}
def keys(self):
return self.dict.keys()
def __len__(self):
return len(self.dict)
def has_key(self, key):
return key in self.dict
def __contains__(self, key):
return key in self.dict
def get(self, key, default=None):
if key in self.dict:
return self[key]
return default
def __getitem__(self, key):
try:
value = self.cache[key]
except KeyError:
f = StringIO(self.dict[key])
value = Unpickler(f).load()
if self.writeback:
self.cache[key] = value
return value
def __setitem__(self, key, value):
if self.writeback:
self.cache[key] = value
f = StringIO()
p = Pickler(f, self._protocol)
p.dump(value)
self.dict[key] = f.getvalue()
def __delitem__(self, key):
del self.dict[key]
try:
del self.cache[key]
except KeyError:
pass
def close(self):
self.sync()
try:
self.dict.close()
except AttributeError:
pass
# Catch errors that may happen when close is called from __del__
# because CPython is in interpreter shutdown.
try:
self.dict = _ClosedDict()
except (NameError, TypeError):
self.dict = None
def __del__(self):
if not hasattr(self, 'writeback'):
# __init__ didn't succeed, so don't bother closing
return
self.close()
def sync(self):
if self.writeback and self.cache:
self.writeback = False
for key, entry in self.cache.iteritems():
self[key] = entry
self.writeback = True
self.cache = {}
if hasattr(self.dict, 'sync'):
self.dict.sync()
class BsdDbShelf(Shelf):
"""Shelf implementation using the "BSD" db interface.
This adds methods first(), next(), previous(), last() and
set_location() that have no counterpart in [g]dbm databases.
The actual database must be opened using one of the "bsddb"
modules "open" routines (i.e. bsddb.hashopen, bsddb.btopen or
bsddb.rnopen) and passed to the constructor.
See the module's __doc__ string for an overview of the interface.
"""
def __init__(self, dict, protocol=None, writeback=False):
Shelf.__init__(self, dict, protocol, writeback)
def set_location(self, key):
(key, value) = self.dict.set_location(key)
f = StringIO(value)
return (key, Unpickler(f).load())
def next(self):
(key, value) = self.dict.next()
f = StringIO(value)
return (key, Unpickler(f).load())
def previous(self):
(key, value) = self.dict.previous()
f = StringIO(value)
return (key, Unpickler(f).load())
def first(self):
(key, value) = self.dict.first()
f = StringIO(value)
return (key, Unpickler(f).load())
def last(self):
(key, value) = self.dict.last()
f = StringIO(value)
return (key, Unpickler(f).load())
class DbfilenameShelf(Shelf):
"""Shelf implementation using the "anydbm" generic dbm interface.
This is initialized with the filename for the dbm database.
See the module's __doc__ string for an overview of the interface.
"""
def __init__(self, filename, flag='c', protocol=None, writeback=False):
import anydbm
Shelf.__init__(self, anydbm.open(filename, flag), protocol, writeback)
def open(filename, flag='c', protocol=None, writeback=False):
"""Open a persistent dictionary for reading and writing.
The filename parameter is the base filename for the underlying
database. As a side-effect, an extension may be added to the
filename and more than one file may be created. The optional flag
parameter has the same interpretation as the flag parameter of
anydbm.open(). The optional protocol parameter specifies the
version of the pickle protocol (0, 1, or 2).
See the module's __doc__ string for an overview of the interface.
"""
return DbfilenameShelf(filename, flag, protocol, writeback)
|
kingvuplus/italysat-enigma2
|
refs/heads/master
|
lib/python/Components/Converter/EGAnalogic.py
|
44
|
# shamelessly copied from BP Project
from Components.Converter.Converter import Converter
from Components.Element import cached
from time import localtime, strftime
class EGAnalogic(Converter, object):
def __init__(self, type):
Converter.__init__(self, type)
if type == "Seconds":
self.type = 1
elif type == "Minutes":
self.type = 2
elif type == "Hours":
self.type = 3
else:
self.type = -1
@cached
def getValue(self):
time = self.source.time
if time is None:
return 0
t = localtime(time)
if self.type == 1:
return int((t.tm_sec *100) /60)
elif self.type == 2:
return int((t.tm_min *100) /60)
elif self.type == 3:
return int(((t.tm_hour *100) /12) + (t.tm_min /8))
value = property(getValue)
|
matehall/Python-koan
|
refs/heads/master
|
python 3/koans/about_inheritance.py
|
14
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutInheritance(Koan):
class Dog:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
def bark(self):
return "WOOF"
class Chihuahua(Dog):
def wag(self):
return "happy"
def bark(self):
return "yip"
def test_subclasses_have_the_parent_as_an_ancestor(self):
self.assertEqual(__, issubclass(self.Chihuahua, self.Dog))
def test_this_all_classes_in_python_3_ultimately_inherit_from_object_class(self):
self.assertEqual(__, issubclass(self.Chihuahua, object))
# Note: This isn't the case in Python 2. In that version you have
# to inherit from a built in class or object explicitly
def test_instances_inherit_behavior_from_parent_class(self):
chico = self.Chihuahua("Chico")
self.assertEqual(__, chico.name)
def test_subclasses_add_new_behavior(self):
chico = self.Chihuahua("Chico")
self.assertEqual(__, chico.wag())
fido = self.Dog("Fido")
with self.assertRaises(___): fido.wag()
def test_subclasses_can_modify_existing_behavior(self):
chico = self.Chihuahua("Chico")
self.assertEqual(__, chico.bark())
fido = self.Dog("Fido")
self.assertEqual(__, fido.bark())
# ------------------------------------------------------------------
class BullDog(Dog):
def bark(self):
return super().bark() + ", GRR"
# Note, super() is much simpler to use in Python 3!
def test_subclasses_can_invoke_parent_behavior_via_super(self):
ralph = self.BullDog("Ralph")
self.assertEqual(__, ralph.bark())
# ------------------------------------------------------------------
class GreatDane(Dog):
def growl(self):
return super().bark() + ", GROWL"
def test_super_works_across_methods(self):
george = self.GreatDane("George")
self.assertEqual(__, george.growl())
# ---------------------------------------------------------
class Pug(Dog):
def __init__(self, name):
pass
class Greyhound(Dog):
def __init__(self, name):
super().__init__(name)
def test_base_init_does_not_get_called_automatically(self):
snoopy = self.Pug("Snoopy")
with self.assertRaises(___): name = snoopy.name
def test_base_init_has_to_be_called_explicitly(self):
boxer = self.Greyhound("Boxer")
self.assertEqual(__, boxer.name)
|
AlphaX2/FotoShareN9
|
refs/heads/master
|
1.6.1/fotoshare/opt/FotoShareN9/plugins/sftp/libs/paramiko/agent.py
|
16
|
# Copyright (C) 2003-2007 John Rochester <john@jrochester.org>
#
# This file is part of paramiko.
#
# Paramiko 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.
#
# Paramiko is distrubuted 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 Paramiko; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
"""
SSH Agent interface for Unix clients.
"""
import os
import socket
import struct
import sys
from paramiko.ssh_exception import SSHException
from paramiko.message import Message
from paramiko.pkey import PKey
SSH2_AGENTC_REQUEST_IDENTITIES, SSH2_AGENT_IDENTITIES_ANSWER, \
SSH2_AGENTC_SIGN_REQUEST, SSH2_AGENT_SIGN_RESPONSE = range(11, 15)
class Agent:
"""
Client interface for using private keys from an SSH agent running on the
local machine. If an SSH agent is running, this class can be used to
connect to it and retreive L{PKey} objects which can be used when
attempting to authenticate to remote SSH servers.
Because the SSH agent protocol uses environment variables and unix-domain
sockets, this probably doesn't work on Windows. It does work on most
posix platforms though (Linux and MacOS X, for example).
"""
def __init__(self):
"""
Open a session with the local machine's SSH agent, if one is running.
If no agent is running, initialization will succeed, but L{get_keys}
will return an empty tuple.
@raise SSHException: if an SSH agent is found, but speaks an
incompatible protocol
"""
self.conn = None
self.keys = ()
if ('SSH_AUTH_SOCK' in os.environ) and (sys.platform != 'win32'):
conn = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
conn.connect(os.environ['SSH_AUTH_SOCK'])
except:
# probably a dangling env var: the ssh agent is gone
return
self.conn = conn
elif sys.platform == 'win32':
import win_pageant
if win_pageant.can_talk_to_agent():
self.conn = win_pageant.PageantConnection()
else:
return
else:
# no agent support
return
ptype, result = self._send_message(chr(SSH2_AGENTC_REQUEST_IDENTITIES))
if ptype != SSH2_AGENT_IDENTITIES_ANSWER:
raise SSHException('could not get keys from ssh-agent')
keys = []
for i in range(result.get_int()):
keys.append(AgentKey(self, result.get_string()))
result.get_string()
self.keys = tuple(keys)
def close(self):
"""
Close the SSH agent connection.
"""
if self.conn is not None:
self.conn.close()
self.conn = None
self.keys = ()
def get_keys(self):
"""
Return the list of keys available through the SSH agent, if any. If
no SSH agent was running (or it couldn't be contacted), an empty list
will be returned.
@return: a list of keys available on the SSH agent
@rtype: tuple of L{AgentKey}
"""
return self.keys
def _send_message(self, msg):
msg = str(msg)
self.conn.send(struct.pack('>I', len(msg)) + msg)
l = self._read_all(4)
msg = Message(self._read_all(struct.unpack('>I', l)[0]))
return ord(msg.get_byte()), msg
def _read_all(self, wanted):
result = self.conn.recv(wanted)
while len(result) < wanted:
if len(result) == 0:
raise SSHException('lost ssh-agent')
extra = self.conn.recv(wanted - len(result))
if len(extra) == 0:
raise SSHException('lost ssh-agent')
result += extra
return result
class AgentKey(PKey):
"""
Private key held in a local SSH agent. This type of key can be used for
authenticating to a remote server (signing). Most other key operations
work as expected.
"""
def __init__(self, agent, blob):
self.agent = agent
self.blob = blob
self.name = Message(blob).get_string()
def __str__(self):
return self.blob
def get_name(self):
return self.name
def sign_ssh_data(self, rng, data):
msg = Message()
msg.add_byte(chr(SSH2_AGENTC_SIGN_REQUEST))
msg.add_string(self.blob)
msg.add_string(data)
msg.add_int(0)
ptype, result = self.agent._send_message(msg)
if ptype != SSH2_AGENT_SIGN_RESPONSE:
raise SSHException('key cannot be used for signing')
return result.get_string()
|
madgik/exareme
|
refs/heads/master
|
Exareme-Docker/src/exareme/exareme-tools/madis/src/lib/pymysql/converters.py
|
1
|
import datetime
import re
import sys
import time
from charset import charset_by_id
from constants import FIELD_TYPE, FLAG
PYTHON3 = sys.version_info[0] > 2
try:
set
except NameError:
try:
from sets import BaseSet as set
except ImportError:
from sets import Set as set
ESCAPE_REGEX = re.compile(r"[\0\n\r\032\'\"\\]")
ESCAPE_MAP = {'\0': '\\0', '\n': '\\n', '\r': '\\r', '\032': '\\Z',
'\'': '\\\'', '"': '\\"', '\\': '\\\\'}
def escape_item(val, charset):
if type(val) in [tuple, list, set]:
return escape_sequence(val, charset)
if type(val) is dict:
return escape_dict(val, charset)
if PYTHON3 and hasattr(val, "decode") and not isinstance(val, unicode):
# deal with py3k bytes
val = val.decode(charset)
encoder = encoders[type(val)]
val = encoder(val)
if type(val) in [str, int, unicode]:
return val
val = val.encode(charset)
return val
def escape_dict(val, charset):
n = {}
for k, v in val.items():
quoted = escape_item(v, charset)
n[k] = quoted
return n
def escape_sequence(val, charset):
n = []
for item in val:
quoted = escape_item(item, charset)
n.append(quoted)
return "(" + ",".join(n) + ")"
def escape_set(val, charset):
val = map(lambda x: escape_item(x, charset), val)
return ','.join(val)
def escape_bool(value):
return str(int(value))
def escape_object(value):
return str(value)
def escape_int(value):
return value
escape_long = escape_object
def escape_float(value):
return ('%.15g' % value)
def escape_string(value):
return ("'%s'" % ESCAPE_REGEX.sub(
lambda match: ESCAPE_MAP.get(match.group(0)), value))
def escape_unicode(value):
return escape_string(value)
def escape_None(value):
return 'NULL'
def escape_timedelta(obj):
seconds = int(obj.seconds) % 60
minutes = int(obj.seconds // 60) % 60
hours = int(obj.seconds // 3600) % 24 + int(obj.days) * 24
return escape_string('%02d:%02d:%02d' % (hours, minutes, seconds))
def escape_time(obj):
s = "%02d:%02d:%02d" % (int(obj.hour), int(obj.minute),
int(obj.second))
if obj.microsecond:
s += ".%f" % obj.microsecond
return escape_string(s)
def escape_datetime(obj):
return escape_string(obj.strftime("%Y-%m-%d %H:%M:%S"))
def escape_date(obj):
return escape_string(obj.strftime("%Y-%m-%d"))
def escape_struct_time(obj):
return escape_datetime(datetime.datetime(*obj[:6]))
def convert_datetime(connection, field, obj):
"""Returns a DATETIME or TIMESTAMP column value as a datetime object:
>>> datetime_or_None('2007-02-25 23:06:20')
datetime.datetime(2007, 2, 25, 23, 6, 20)
>>> datetime_or_None('2007-02-25T23:06:20')
datetime.datetime(2007, 2, 25, 23, 6, 20)
Illegal values are returned as None:
>>> datetime_or_None('2007-02-31T23:06:20') is None
True
>>> datetime_or_None('0000-00-00 00:00:00') is None
True
"""
if not isinstance(obj, unicode):
obj = obj.decode(connection.charset)
if ' ' in obj:
sep = ' '
elif 'T' in obj:
sep = 'T'
else:
return convert_date(connection, field, obj)
try:
ymd, hms = obj.split(sep, 1)
return datetime.datetime(*[int(x) for x in ymd.split('-') + hms.split(':')])
except ValueError:
return convert_date(connection, field, obj)
def convert_timedelta(connection, field, obj):
"""Returns a TIME column as a timedelta object:
>>> timedelta_or_None('25:06:17')
datetime.timedelta(1, 3977)
>>> timedelta_or_None('-25:06:17')
datetime.timedelta(-2, 83177)
Illegal values are returned as None:
>>> timedelta_or_None('random crap') is None
True
Note that MySQL always returns TIME columns as (+|-)HH:MM:SS, but
can accept values as (+|-)DD HH:MM:SS. The latter format will not
be parsed correctly by this function.
"""
try:
microseconds = 0
if not isinstance(obj, unicode):
obj = obj.decode(connection.charset)
if "." in obj:
(obj, tail) = obj.split('.')
microseconds = int(tail)
hours, minutes, seconds = obj.split(':')
tdelta = datetime.timedelta(
hours=int(hours),
minutes=int(minutes),
seconds=int(seconds),
microseconds=microseconds
)
return tdelta
except ValueError:
return None
def convert_time(connection, field, obj):
"""Returns a TIME column as a time object:
>>> time_or_None('15:06:17')
datetime.time(15, 6, 17)
Illegal values are returned as None:
>>> time_or_None('-25:06:17') is None
True
>>> time_or_None('random crap') is None
True
Note that MySQL always returns TIME columns as (+|-)HH:MM:SS, but
can accept values as (+|-)DD HH:MM:SS. The latter format will not
be parsed correctly by this function.
Also note that MySQL's TIME column corresponds more closely to
Python's timedelta and not time. However if you want TIME columns
to be treated as time-of-day and not a time offset, then you can
use set this function as the converter for FIELD_TYPE.TIME.
"""
try:
microseconds = 0
if "." in obj:
(obj, tail) = obj.split('.')
microseconds = int(tail)
hours, minutes, seconds = obj.split(':')
return datetime.time(hour=int(hours), minute=int(minutes),
second=int(seconds), microsecond=microseconds)
except ValueError:
return None
def convert_date(connection, field, obj):
"""Returns a DATE column as a date object:
>>> date_or_None('2007-02-26')
datetime.date(2007, 2, 26)
Illegal values are returned as None:
>>> date_or_None('2007-02-31') is None
True
>>> date_or_None('0000-00-00') is None
True
"""
try:
if not isinstance(obj, unicode):
obj = obj.decode(connection.charset)
return datetime.date(*[int(x) for x in obj.split('-', 2)])
except ValueError:
return None
def convert_mysql_timestamp(connection, field, timestamp):
"""Convert a MySQL TIMESTAMP to a Timestamp object.
MySQL >= 4.1 returns TIMESTAMP in the same format as DATETIME:
>>> mysql_timestamp_converter('2007-02-25 22:32:17')
datetime.datetime(2007, 2, 25, 22, 32, 17)
MySQL < 4.1 uses a big string of numbers:
>>> mysql_timestamp_converter('20070225223217')
datetime.datetime(2007, 2, 25, 22, 32, 17)
Illegal values are returned as None:
>>> mysql_timestamp_converter('2007-02-31 22:32:17') is None
True
>>> mysql_timestamp_converter('00000000000000') is None
True
"""
if not isinstance(timestamp, unicode):
timestamp = timestamp.decode(connection.charset)
if timestamp[4] == '-':
return convert_datetime(connection, field, timestamp)
timestamp += "0" * (14 - len(timestamp)) # padding
year, month, day, hour, minute, second = \
int(timestamp[:4]), int(timestamp[4:6]), int(timestamp[6:8]), \
int(timestamp[8:10]), int(timestamp[10:12]), int(timestamp[12:14])
try:
return datetime.datetime(year, month, day, hour, minute, second)
except ValueError:
return None
def convert_set(s):
return set(s.split(","))
def convert_bit(connection, field, b):
# b = "\x00" * (8 - len(b)) + b # pad w/ zeroes
# return struct.unpack(">Q", b)[0]
#
# the snippet above is right, but MySQLdb doesn't process bits,
# so we shouldn't either
return b
def convert_characters(connection, field, data):
field_charset = charset_by_id(field.charsetnr).name
if field.flags & FLAG.SET:
return convert_set(data.decode(field_charset))
if field.flags & FLAG.BINARY:
return data
if connection.use_unicode:
data = data.decode(field_charset)
elif connection.charset != field_charset:
data = data.decode(field_charset)
data = data.encode(connection.charset)
return data
def convert_int(connection, field, data):
return int(data)
def convert_long(connection, field, data):
return long(data)
def convert_float(connection, field, data):
return float(data)
encoders = {
bool: escape_bool,
int: escape_int,
long: escape_long,
float: escape_float,
str: escape_string,
unicode: escape_unicode,
tuple: escape_sequence,
list: escape_sequence,
set: escape_sequence,
dict: escape_dict,
type(None): escape_None,
datetime.date: escape_date,
datetime.datetime: escape_datetime,
datetime.timedelta: escape_timedelta,
datetime.time: escape_time,
time.struct_time: escape_struct_time,
}
decoders = {
FIELD_TYPE.BIT: convert_bit,
FIELD_TYPE.TINY: convert_int,
FIELD_TYPE.SHORT: convert_int,
FIELD_TYPE.LONG: convert_long,
FIELD_TYPE.FLOAT: convert_float,
FIELD_TYPE.DOUBLE: convert_float,
FIELD_TYPE.DECIMAL: convert_float,
FIELD_TYPE.NEWDECIMAL: convert_float,
FIELD_TYPE.LONGLONG: convert_long,
FIELD_TYPE.INT24: convert_int,
FIELD_TYPE.YEAR: convert_int,
FIELD_TYPE.TIMESTAMP: convert_mysql_timestamp,
FIELD_TYPE.DATETIME: convert_datetime,
FIELD_TYPE.TIME: convert_timedelta,
FIELD_TYPE.DATE: convert_date,
FIELD_TYPE.SET: convert_set,
FIELD_TYPE.BLOB: convert_characters,
FIELD_TYPE.TINY_BLOB: convert_characters,
FIELD_TYPE.MEDIUM_BLOB: convert_characters,
FIELD_TYPE.LONG_BLOB: convert_characters,
FIELD_TYPE.STRING: convert_characters,
FIELD_TYPE.VAR_STRING: convert_characters,
FIELD_TYPE.VARCHAR: convert_characters,
# FIELD_TYPE.BLOB: str,
# FIELD_TYPE.STRING: str,
# FIELD_TYPE.VAR_STRING: str,
# FIELD_TYPE.VARCHAR: str
}
conversions = decoders # for MySQLdb compatibility
try:
# python version > 2.3
from decimal import Decimal
def convert_decimal(connection, field, data):
data = data.decode(connection.charset)
return Decimal(data)
decoders[FIELD_TYPE.DECIMAL] = convert_decimal
decoders[FIELD_TYPE.NEWDECIMAL] = convert_decimal
def escape_decimal(obj):
return unicode(obj)
encoders[Decimal] = escape_decimal
except ImportError:
pass
|
rsteca/python-social-auth
|
refs/heads/master
|
social/backends/stackoverflow.py
|
77
|
"""
Stackoverflow OAuth2 backend, docs at:
http://psa.matiasaguirre.net/docs/backends/stackoverflow.html
"""
from social.backends.oauth import BaseOAuth2
class StackoverflowOAuth2(BaseOAuth2):
"""Stackoverflow OAuth2 authentication backend"""
name = 'stackoverflow'
ID_KEY = 'user_id'
AUTHORIZATION_URL = 'https://stackexchange.com/oauth'
ACCESS_TOKEN_URL = 'https://stackexchange.com/oauth/access_token'
ACCESS_TOKEN_METHOD = 'POST'
SCOPE_SEPARATOR = ','
EXTRA_DATA = [
('id', 'id'),
('expires', 'expires')
]
def get_user_details(self, response):
"""Return user details from Stackoverflow account"""
fullname, first_name, last_name = self.get_user_names(
response.get('display_name')
)
return {'username': response.get('link').rsplit('/', 1)[-1],
'full_name': fullname,
'first_name': first_name,
'last_name': last_name}
def user_data(self, access_token, *args, **kwargs):
"""Loads user data from service"""
return self.get_json(
'https://api.stackexchange.com/2.1/me',
params={
'site': 'stackoverflow',
'access_token': access_token,
'key': self.setting('API_KEY')
}
)['items'][0]
def request_access_token(self, *args, **kwargs):
return self.get_querystring(*args, **kwargs)
|
windyuuy/opera
|
refs/heads/master
|
chromium/src/tools/gyp/test/win/gyptest-cl-buffer-security-check.py
|
344
|
#!/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.
"""
Make sure buffer security check setting is extracted properly.
"""
import TestGyp
import sys
if sys.platform == 'win32':
test = TestGyp.TestGyp(formats=['msvs', 'ninja'])
CHDIR = 'compiler-flags'
test.run_gyp('buffer-security-check.gyp', chdir=CHDIR)
test.build('buffer-security-check.gyp', chdir=CHDIR)
def GetDisassemblyOfMain(exe):
# The standard library uses buffer security checks independent of our
# buffer security settings, so we extract just our code (i.e. main()) to
# check against.
full_path = test.built_file_path(exe, chdir=CHDIR)
output = test.run_dumpbin('/disasm', full_path)
result = []
in_main = False
for line in output.splitlines():
if line == '_main:':
in_main = True
elif in_main:
# Disassembly of next function starts.
if line.startswith('_'):
break
result.append(line)
return '\n'.join(result)
# Buffer security checks are on by default, make sure security_cookie
# appears in the disassembly of our code.
if 'security_cookie' not in GetDisassemblyOfMain('test_bsc_unset.exe'):
test.fail_test()
# Explicitly on.
if 'security_cookie' not in GetDisassemblyOfMain('test_bsc_on.exe'):
test.fail_test()
# Explicitly off, shouldn't be a reference to the security cookie.
if 'security_cookie' in GetDisassemblyOfMain('test_bsc_off.exe'):
test.fail_test()
test.pass_test()
|
mail-apps/pootle
|
refs/heads/master
|
tests/forms/unit.py
|
7
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.contrib.auth import get_user_model
from pootle_app.models.permissions import get_matching_permissions
from pootle_store.util import FUZZY, TRANSLATED, UNTRANSLATED
from pootle_store.forms import unit_form_factory, UnitStateField
def _create_post_request(rf, directory, user, url='/', data=None):
"""Convenience function to create and setup fake POST requests."""
if data is None:
data = {}
User = get_user_model()
request = rf.post(url, data=data)
request.user = user
request.profile = User.get(user)
request.permissions = get_matching_permissions(request.profile,
directory)
return request
def _create_unit_form(request, language, unit):
"""Convenience function to create unit forms."""
form_class = unit_form_factory(language, request=request)
return form_class(request.POST, instance=unit, request=request)
def test_submit_no_source(rf, default, default_ps, af_tutorial_po):
"""Tests that the source string cannot be modified."""
language = af_tutorial_po.translation_project.language
unit = af_tutorial_po.getitem(0)
source_string = unit.source_f
directory = unit.store.parent
post_dict = {
'id': unit.id,
'index': unit.index,
'source_f_0': 'altered source string',
'target_f_0': 'dummy',
}
request = _create_post_request(rf, directory, data=post_dict, user=default)
form = _create_unit_form(request, language, unit)
assert form.is_valid()
form.save()
unit = af_tutorial_po.getitem(0)
assert unit.source_f == source_string
assert unit.target_f == 'dummy'
def test_submit_fuzzy(rf, admin, default, default_ps,
afrikaans, af_tutorial_po):
"""Tests that non-admin users can't set the fuzzy flag."""
language = afrikaans
unit = af_tutorial_po.getitem(0)
directory = unit.store.parent
post_dict = {
'id': unit.id,
'index': unit.index,
'target_f_0': unit.target_f,
'state': FUZZY,
}
request = _create_post_request(rf, directory, data=post_dict, user=admin)
admin_form = _create_unit_form(request, language, unit)
assert admin_form.is_valid()
request = _create_post_request(rf, directory, data=post_dict, user=default)
user_form = _create_unit_form(request, language, unit)
assert not user_form.is_valid()
assert 'state' in user_form.errors
def test_submit_similarity(rf, default, default_ps, afrikaans, af_tutorial_po):
"""Tests that similarities are within a particular range."""
language = afrikaans
unit = af_tutorial_po.getitem(0)
directory = unit.store.parent
post_dict = {
'id': unit.id,
'index': unit.index,
'target_f_0': unit.target_f,
}
# Similarity should be optional
request = _create_post_request(rf, directory, data=post_dict, user=default)
form = _create_unit_form(request, language, unit)
assert form.is_valid()
# Similarities, if passed, should be in the [0..1] range
post_dict.update({
'similarity': 9999,
'mt_similarity': 'foo bar',
})
request = _create_post_request(rf, directory, data=post_dict, user=default)
form = _create_unit_form(request, language, unit)
assert not form.is_valid()
post_dict.update({
'similarity': 1,
})
request = _create_post_request(rf, directory, data=post_dict, user=default)
form = _create_unit_form(request, language, unit)
assert not form.is_valid()
post_dict.update({
'mt_similarity': 2,
})
request = _create_post_request(rf, directory, data=post_dict, user=default)
form = _create_unit_form(request, language, unit)
assert not form.is_valid()
post_dict.update({
'mt_similarity': 0.69,
})
request = _create_post_request(rf, directory, data=post_dict, user=default)
form = _create_unit_form(request, language, unit)
assert form.is_valid()
def test_unit_state():
"""Tests how checkbox states (as strings) map to booleans."""
field = UnitStateField(required=False)
assert field.clean(str(FUZZY))
assert field.clean(str(TRANSLATED))
assert field.clean(str(UNTRANSLATED))
assert field.clean(True)
assert not field.clean('True') # Unknown state value evaluates to False
assert not field.clean(False)
assert not field.clean('False')
|
gwpy/gwpy.github.io
|
refs/heads/master
|
docs/0.9.0/examples/timeseries/statevector-2.py
|
11
|
bits = [
'Summary state',
'State 1 damped',
'Stage 1 isolated',
'Stage 2 damped',
'Stage 2 isolated',
'Master switch ON',
'Stage 1 WatchDog OK',
'Stage 2 WatchDog OK',
]
data = StateVector.get('L1:ISI-ETMX_ODC_CHANNEL_OUT_DQ', 'May 22 2014 14:00', 'May 22 2014 15:00', bits=bits)
|
lalanza808/lalanza808.github.io
|
refs/heads/master
|
vendor/bundle/ruby/2.3.0/gems/pygments.rb-0.6.3/vendor/pygments-main/tests/test_rtf_formatter.py
|
34
|
# -*- coding: utf-8 -*-
"""
Pygments RTF formatter tests
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import unittest
from string_asserts import StringTests
from pygments.util import StringIO
from pygments.formatters import RtfFormatter
from pygments.lexers.special import TextLexer
class RtfFormatterTest(StringTests, unittest.TestCase):
foot = (r'\par' '\n' r'}')
def _escape(self, string):
return(string.replace("\n", r"\n"))
def _build_message(self, *args, **kwargs):
string = kwargs.get('string', None)
t = self._escape(kwargs.get('t', ''))
expected = self._escape(kwargs.get('expected', ''))
result = self._escape(kwargs.get('result', ''))
if string is None:
string = (u"The expected output of '{t}'\n"
u"\t\tShould be '{expected}'\n"
u"\t\tActually outputs '{result}'\n"
u"\t(WARNING: Partial Output of Result!)")
end = -(len(self._escape(self.foot)))
start = end-len(expected)
return string.format(t=t,
result = result[start:end],
expected = expected)
def format_rtf(self, t):
tokensource = list(TextLexer().get_tokens(t))
fmt = RtfFormatter()
buf = StringIO()
fmt.format(tokensource, buf)
result = buf.getvalue()
buf.close()
return result
def test_rtf_header(self):
t = u''
result = self.format_rtf(t)
expected = r'{\rtf1\ansi\uc0'
msg = (u"RTF documents are expected to start with '{expected}'\n"
u"\t\tStarts intead with '{result}'\n"
u"\t(WARNING: Partial Output of Result!)".format(
expected = expected,
result = result[:len(expected)]))
self.assertStartsWith(result, expected, msg)
def test_rtf_footer(self):
t = u''
result = self.format_rtf(t)
expected = self.foot
msg = (u"RTF documents are expected to end with '{expected}'\n"
u"\t\tEnds intead with '{result}'\n"
u"\t(WARNING: Partial Output of Result!)".format(
expected = self._escape(expected),
result = self._escape(result[-len(expected):])))
self.assertEndsWith(result, expected, msg)
def test_ascii_characters(self):
t = u'a b c d ~'
result = self.format_rtf(t)
expected = (r'a b c d ~')
if not result.endswith(self.foot):
return(unittest.skip('RTF Footer incorrect'))
msg = self._build_message(t=t, result=result, expected=expected)
self.assertEndsWith(result, expected+self.foot, msg)
def test_escape_characters(self):
t = u'\ {{'
result = self.format_rtf(t)
expected = (r'\\ \{\{')
if not result.endswith(self.foot):
return(unittest.skip('RTF Footer incorrect'))
msg = self._build_message(t=t, result=result, expected=expected)
self.assertEndsWith(result, expected+self.foot, msg)
def test_single_characters(self):
t = u'â € ¤ каждой'
result = self.format_rtf(t)
expected = (r'{\u226} {\u8364} {\u164} '
r'{\u1082}{\u1072}{\u1078}{\u1076}{\u1086}{\u1081}')
if not result.endswith(self.foot):
return(unittest.skip('RTF Footer incorrect'))
msg = self._build_message(t=t, result=result, expected=expected)
self.assertEndsWith(result, expected+self.foot, msg)
def test_double_characters(self):
t = u'က 힣 ↕ ↕︎ 鼖'
result = self.format_rtf(t)
expected = (r'{\u4096} {\u55203} {\u8597} '
r'{\u8597}{\u65038} {\u55422}{\u56859}')
if not result.endswith(self.foot):
return(unittest.skip('RTF Footer incorrect'))
msg = self._build_message(t=t, result=result, expected=expected)
self.assertEndsWith(result, expected+self.foot, msg)
|
daler/trackhub
|
refs/heads/master
|
setup.py
|
1
|
import os
import sys
from setuptools import setup
version_py = os.path.join(os.path.dirname(__file__), 'trackhub', 'version.py')
version = open(version_py).read().strip().split('=')[-1].replace('"','')
long_description = """
Create and manage UCSC track hubs from Python
"""
setup(
name="trackhub",
version=version,
install_requires=[i.strip() for i in open('requirements.txt') if not i.startswith('#')],
packages=['trackhub',
'trackhub.test',
'trackhub.test.data',
],
author="Ryan Dale",
description=long_description,
long_description=long_description,
url="http://github.com/daler/trackhub",
package_data = {'trackhub':["test/data/*"]},
package_dir = {"trackhub": "trackhub"},
license = 'MIT',
author_email="dalerr@niddk.nih.gov",
classifiers=[
'Intended Audience :: Science/Research',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Topic :: Scientific/Engineering :: Bio-Informatics',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
crystalspace/CS
|
refs/heads/master
|
scripts/python/frozen/cspace/ivaria.py
|
1
|
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 1.3.36
#
# Don't modify this file, modify the SWIG interface instead.
import _ivaria
import new
new_instancemethod = new.instancemethod
try:
_swig_property = property
except NameError:
pass # Python < 2.2 doesn't have 'property'.
def _swig_setattr_nondynamic(self,class_type,name,value,static=1):
if (name == "thisown"): return self.this.own(value)
if (name == "this"):
if type(value).__name__ == 'PySwigObject':
self.__dict__[name] = value
return
method = class_type.__swig_setmethods__.get(name,None)
if method: return method(self,value)
if (not static) or hasattr(self,name):
self.__dict__[name] = value
else:
raise AttributeError("You cannot add attributes to %s" % self)
def _swig_setattr(self,class_type,name,value):
return _swig_setattr_nondynamic(self,class_type,name,value,0)
def _swig_getattr(self,class_type,name):
if (name == "thisown"): return self.this.own()
method = class_type.__swig_getmethods__.get(name,None)
if method: return method(self)
raise AttributeError,name
def _swig_repr(self):
try: strthis = "proxy of " + self.this.__repr__()
except: strthis = ""
return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
import types
try:
_object = types.ObjectType
_newclass = 1
except AttributeError:
class _object : pass
_newclass = 0
del types
def _swig_setattr_nondynamic_method(set):
def set_attr(self,name,value):
if (name == "thisown"): return self.this.own(value)
if hasattr(self,name) or (name == "this"):
set(self,name,value)
else:
raise AttributeError("You cannot add attributes to %s" % self)
return set_attr
import core
_SetSCFPointer = _ivaria._SetSCFPointer
_GetSCFPointer = _ivaria._GetSCFPointer
if not "core" in dir():
core = __import__("cspace").__dict__["core"]
core.AddSCFLink(_SetSCFPointer)
CSMutableArrayHelper = core.CSMutableArrayHelper
class iDecal(object):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
this = _ivaria.new_iDecal(*args)
try: self.this.append(this)
except: self.this = this
__swig_destroy__ = _ivaria.delete_iDecal
__del__ = lambda self : None;
iDecal_swigregister = _ivaria.iDecal_swigregister
iDecal_swigregister(iDecal)
class iDecalTemplate(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def GetTimeToLive(*args): return _ivaria.iDecalTemplate_GetTimeToLive(*args)
def GetMaterialWrapper(*args): return _ivaria.iDecalTemplate_GetMaterialWrapper(*args)
def GetRenderPriority(*args): return _ivaria.iDecalTemplate_GetRenderPriority(*args)
def GetZBufMode(*args): return _ivaria.iDecalTemplate_GetZBufMode(*args)
def GetPolygonNormalThreshold(*args): return _ivaria.iDecalTemplate_GetPolygonNormalThreshold(*args)
def GetDecalOffset(*args): return _ivaria.iDecalTemplate_GetDecalOffset(*args)
def HasTopClipping(*args): return _ivaria.iDecalTemplate_HasTopClipping(*args)
def GetTopClippingScale(*args): return _ivaria.iDecalTemplate_GetTopClippingScale(*args)
def HasBottomClipping(*args): return _ivaria.iDecalTemplate_HasBottomClipping(*args)
def GetBottomClippingScale(*args): return _ivaria.iDecalTemplate_GetBottomClippingScale(*args)
def GetMinTexCoord(*args): return _ivaria.iDecalTemplate_GetMinTexCoord(*args)
def GetMainColor(*args): return _ivaria.iDecalTemplate_GetMainColor(*args)
def GetTopColor(*args): return _ivaria.iDecalTemplate_GetTopColor(*args)
def GetBottomColor(*args): return _ivaria.iDecalTemplate_GetBottomColor(*args)
def GetMaxTexCoord(*args): return _ivaria.iDecalTemplate_GetMaxTexCoord(*args)
def GetMixMode(*args): return _ivaria.iDecalTemplate_GetMixMode(*args)
def GetPerpendicularFaceThreshold(*args): return _ivaria.iDecalTemplate_GetPerpendicularFaceThreshold(*args)
def GetPerpendicularFaceOffset(*args): return _ivaria.iDecalTemplate_GetPerpendicularFaceOffset(*args)
def SetTimeToLive(*args): return _ivaria.iDecalTemplate_SetTimeToLive(*args)
def SetMaterialWrapper(*args): return _ivaria.iDecalTemplate_SetMaterialWrapper(*args)
def SetRenderPriority(*args): return _ivaria.iDecalTemplate_SetRenderPriority(*args)
def SetZBufMode(*args): return _ivaria.iDecalTemplate_SetZBufMode(*args)
def SetPolygonNormalThreshold(*args): return _ivaria.iDecalTemplate_SetPolygonNormalThreshold(*args)
def SetDecalOffset(*args): return _ivaria.iDecalTemplate_SetDecalOffset(*args)
def SetTopClipping(*args): return _ivaria.iDecalTemplate_SetTopClipping(*args)
def SetBottomClipping(*args): return _ivaria.iDecalTemplate_SetBottomClipping(*args)
def SetTexCoords(*args): return _ivaria.iDecalTemplate_SetTexCoords(*args)
def SetMixMode(*args): return _ivaria.iDecalTemplate_SetMixMode(*args)
def SetPerpendicularFaceThreshold(*args): return _ivaria.iDecalTemplate_SetPerpendicularFaceThreshold(*args)
def SetPerpendicularFaceOffset(*args): return _ivaria.iDecalTemplate_SetPerpendicularFaceOffset(*args)
def SetMainColor(*args): return _ivaria.iDecalTemplate_SetMainColor(*args)
def SetTopColor(*args): return _ivaria.iDecalTemplate_SetTopColor(*args)
def SetBottomColor(*args): return _ivaria.iDecalTemplate_SetBottomColor(*args)
def SetClipping(*args): return _ivaria.iDecalTemplate_SetClipping(*args)
def HasClipping(*args): return _ivaria.iDecalTemplate_HasClipping(*args)
scfGetVersion = staticmethod(_ivaria.iDecalTemplate_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iDecalTemplate
__del__ = lambda self : None;
iDecalTemplate_swigregister = _ivaria.iDecalTemplate_swigregister
iDecalTemplate_swigregister(iDecalTemplate)
iDecalTemplate_scfGetVersion = _ivaria.iDecalTemplate_scfGetVersion
class iDecalAnimationControl(object):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
__swig_destroy__ = _ivaria.delete_iDecalAnimationControl
__del__ = lambda self : None;
def UpdateDecal(*args): return _ivaria.iDecalAnimationControl_UpdateDecal(*args)
iDecalAnimationControl_swigregister = _ivaria.iDecalAnimationControl_swigregister
iDecalAnimationControl_swigregister(iDecalAnimationControl)
class iDecalBuilder(object):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
__swig_destroy__ = _ivaria.delete_iDecalBuilder
__del__ = lambda self : None;
def AddStaticPoly(*args): return _ivaria.iDecalBuilder_AddStaticPoly(*args)
def SetDecalAnimationControl(*args): return _ivaria.iDecalBuilder_SetDecalAnimationControl(*args)
iDecalBuilder_swigregister = _ivaria.iDecalBuilder_swigregister
iDecalBuilder_swigregister(iDecalBuilder)
class iDecalManager(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def CreateDecalTemplate(*args): return _ivaria.iDecalManager_CreateDecalTemplate(*args)
def DeleteDecal(*args): return _ivaria.iDecalManager_DeleteDecal(*args)
def GetDecalCount(*args): return _ivaria.iDecalManager_GetDecalCount(*args)
def GetDecal(*args): return _ivaria.iDecalManager_GetDecal(*args)
def CreateDecal(*args): return _ivaria.iDecalManager_CreateDecal(*args)
scfGetVersion = staticmethod(_ivaria.iDecalManager_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iDecalManager
__del__ = lambda self : None;
iDecalManager_swigregister = _ivaria.iDecalManager_swigregister
iDecalManager_swigregister(iDecalManager)
iDecalManager_scfGetVersion = _ivaria.iDecalManager_scfGetVersion
csConPageUp = _ivaria.csConPageUp
csConPageDown = _ivaria.csConPageDown
csConVeryTop = _ivaria.csConVeryTop
csConVeryBottom = _ivaria.csConVeryBottom
csConNoCursor = _ivaria.csConNoCursor
csConNormalCursor = _ivaria.csConNormalCursor
csConInsertCursor = _ivaria.csConInsertCursor
class iConsoleWatcher(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def ConsoleVisibilityChanged(*args): return _ivaria.iConsoleWatcher_ConsoleVisibilityChanged(*args)
__swig_destroy__ = _ivaria.delete_iConsoleWatcher
__del__ = lambda self : None;
iConsoleWatcher_swigregister = _ivaria.iConsoleWatcher_swigregister
iConsoleWatcher_swigregister(iConsoleWatcher)
class iConsoleOutput(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def PutText(*args): return _ivaria.iConsoleOutput_PutText(*args)
def GetLine(*args): return _ivaria.iConsoleOutput_GetLine(*args)
def Draw2D(*args): return _ivaria.iConsoleOutput_Draw2D(*args)
def Draw3D(*args): return _ivaria.iConsoleOutput_Draw3D(*args)
def Clear(*args): return _ivaria.iConsoleOutput_Clear(*args)
def SetBufferSize(*args): return _ivaria.iConsoleOutput_SetBufferSize(*args)
def GetTransparency(*args): return _ivaria.iConsoleOutput_GetTransparency(*args)
def SetTransparency(*args): return _ivaria.iConsoleOutput_SetTransparency(*args)
def GetFont(*args): return _ivaria.iConsoleOutput_GetFont(*args)
def SetFont(*args): return _ivaria.iConsoleOutput_SetFont(*args)
def GetTopLine(*args): return _ivaria.iConsoleOutput_GetTopLine(*args)
def ScrollTo(*args): return _ivaria.iConsoleOutput_ScrollTo(*args)
def GetCursorStyle(*args): return _ivaria.iConsoleOutput_GetCursorStyle(*args)
def SetCursorStyle(*args): return _ivaria.iConsoleOutput_SetCursorStyle(*args)
def SetVisible(*args): return _ivaria.iConsoleOutput_SetVisible(*args)
def GetVisible(*args): return _ivaria.iConsoleOutput_GetVisible(*args)
def AutoUpdate(*args): return _ivaria.iConsoleOutput_AutoUpdate(*args)
def SetCursorPos(*args): return _ivaria.iConsoleOutput_SetCursorPos(*args)
def GetMaxLineWidth(*args): return _ivaria.iConsoleOutput_GetMaxLineWidth(*args)
def RegisterWatcher(*args): return _ivaria.iConsoleOutput_RegisterWatcher(*args)
def PerformExtension(*args): return _ivaria.iConsoleOutput_PerformExtension(*args)
scfGetVersion = staticmethod(_ivaria.iConsoleOutput_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iConsoleOutput
__del__ = lambda self : None;
iConsoleOutput_swigregister = _ivaria.iConsoleOutput_swigregister
iConsoleOutput_swigregister(iConsoleOutput)
iConsoleOutput_scfGetVersion = _ivaria.iConsoleOutput_scfGetVersion
class iConsoleExecCallback(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def Execute(*args): return _ivaria.iConsoleExecCallback_Execute(*args)
scfGetVersion = staticmethod(_ivaria.iConsoleExecCallback_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iConsoleExecCallback
__del__ = lambda self : None;
iConsoleExecCallback_swigregister = _ivaria.iConsoleExecCallback_swigregister
iConsoleExecCallback_swigregister(iConsoleExecCallback)
iConsoleExecCallback_scfGetVersion = _ivaria.iConsoleExecCallback_scfGetVersion
class iConsoleInput(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def Bind(*args): return _ivaria.iConsoleInput_Bind(*args)
def SetExecuteCallback(*args): return _ivaria.iConsoleInput_SetExecuteCallback(*args)
def GetExecuteCallback(*args): return _ivaria.iConsoleInput_GetExecuteCallback(*args)
def GetText(*args): return _ivaria.iConsoleInput_GetText(*args)
def GetCurLine(*args): return _ivaria.iConsoleInput_GetCurLine(*args)
def GetBufferSize(*args): return _ivaria.iConsoleInput_GetBufferSize(*args)
def SetBufferSize(*args): return _ivaria.iConsoleInput_SetBufferSize(*args)
def Clear(*args): return _ivaria.iConsoleInput_Clear(*args)
def SetPrompt(*args): return _ivaria.iConsoleInput_SetPrompt(*args)
def HandleEvent(*args): return _ivaria.iConsoleInput_HandleEvent(*args)
scfGetVersion = staticmethod(_ivaria.iConsoleInput_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iConsoleInput
__del__ = lambda self : None;
iConsoleInput_swigregister = _ivaria.iConsoleInput_swigregister
iConsoleInput_swigregister(iConsoleInput)
iConsoleInput_scfGetVersion = _ivaria.iConsoleInput_scfGetVersion
class iStandardReporterListener(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def SetOutputConsole(*args): return _ivaria.iStandardReporterListener_SetOutputConsole(*args)
def SetNativeWindowManager(*args): return _ivaria.iStandardReporterListener_SetNativeWindowManager(*args)
def SetReporter(*args): return _ivaria.iStandardReporterListener_SetReporter(*args)
def SetDebugFile(*args): return _ivaria.iStandardReporterListener_SetDebugFile(*args)
def SetDefaults(*args): return _ivaria.iStandardReporterListener_SetDefaults(*args)
def SetMessageDestination(*args): return _ivaria.iStandardReporterListener_SetMessageDestination(*args)
def SetStandardOutput(*args): return _ivaria.iStandardReporterListener_SetStandardOutput(*args)
def IsStandardOutput(*args): return _ivaria.iStandardReporterListener_IsStandardOutput(*args)
def SetStandardError(*args): return _ivaria.iStandardReporterListener_SetStandardError(*args)
def IsStandardError(*args): return _ivaria.iStandardReporterListener_IsStandardError(*args)
def SetConsoleOutput(*args): return _ivaria.iStandardReporterListener_SetConsoleOutput(*args)
def IsConsoleOutput(*args): return _ivaria.iStandardReporterListener_IsConsoleOutput(*args)
def SetAlertOutput(*args): return _ivaria.iStandardReporterListener_SetAlertOutput(*args)
def IsAlertOutput(*args): return _ivaria.iStandardReporterListener_IsAlertOutput(*args)
def SetDebugOutput(*args): return _ivaria.iStandardReporterListener_SetDebugOutput(*args)
def IsDebugOutput(*args): return _ivaria.iStandardReporterListener_IsDebugOutput(*args)
def SetPopupOutput(*args): return _ivaria.iStandardReporterListener_SetPopupOutput(*args)
def IsPopupOutput(*args): return _ivaria.iStandardReporterListener_IsPopupOutput(*args)
def RemoveMessages(*args): return _ivaria.iStandardReporterListener_RemoveMessages(*args)
def ShowMessageID(*args): return _ivaria.iStandardReporterListener_ShowMessageID(*args)
def GetDebugFile(*args): return _ivaria.iStandardReporterListener_GetDebugFile(*args)
scfGetVersion = staticmethod(_ivaria.iStandardReporterListener_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iStandardReporterListener
__del__ = lambda self : None;
iStandardReporterListener_swigregister = _ivaria.iStandardReporterListener_swigregister
iStandardReporterListener_swigregister(iStandardReporterListener)
iStandardReporterListener_scfGetVersion = _ivaria.iStandardReporterListener_scfGetVersion
class iView(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def GetEngine(*args): return _ivaria.iView_GetEngine(*args)
def SetEngine(*args): return _ivaria.iView_SetEngine(*args)
def GetCamera(*args): return _ivaria.iView_GetCamera(*args)
def SetCamera(*args): return _ivaria.iView_SetCamera(*args)
def GetPerspectiveCamera(*args): return _ivaria.iView_GetPerspectiveCamera(*args)
def SetPerspectiveCamera(*args): return _ivaria.iView_SetPerspectiveCamera(*args)
def GetContext(*args): return _ivaria.iView_GetContext(*args)
def SetContext(*args): return _ivaria.iView_SetContext(*args)
def SetRectangle(*args): return _ivaria.iView_SetRectangle(*args)
def ClearView(*args): return _ivaria.iView_ClearView(*args)
def AddViewVertex(*args): return _ivaria.iView_AddViewVertex(*args)
def RestrictClipperToScreen(*args): return _ivaria.iView_RestrictClipperToScreen(*args)
def UpdateClipper(*args): return _ivaria.iView_UpdateClipper(*args)
def GetClipper(*args): return _ivaria.iView_GetClipper(*args)
def Draw(*args): return _ivaria.iView_Draw(*args)
def SetAutoResize(*args): return _ivaria.iView_SetAutoResize(*args)
def GetMeshFilter(*args): return _ivaria.iView_GetMeshFilter(*args)
def GetCustomMatrixCamera(*args): return _ivaria.iView_GetCustomMatrixCamera(*args)
def SetCustomMatrixCamera(*args): return _ivaria.iView_SetCustomMatrixCamera(*args)
def GetWidth(*args): return _ivaria.iView_GetWidth(*args)
def GetHeight(*args): return _ivaria.iView_GetHeight(*args)
def SetWidth(*args): return _ivaria.iView_SetWidth(*args)
def SetHeight(*args): return _ivaria.iView_SetHeight(*args)
def NormalizedToScreen(*args): return _ivaria.iView_NormalizedToScreen(*args)
def ScreenToNormalized(*args): return _ivaria.iView_ScreenToNormalized(*args)
scfGetVersion = staticmethod(_ivaria.iView_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iView
__del__ = lambda self : None;
iView_swigregister = _ivaria.iView_swigregister
iView_swigregister(iView)
iView_scfGetVersion = _ivaria.iView_scfGetVersion
class iBugPlugRenderObject(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def Render(*args): return _ivaria.iBugPlugRenderObject_Render(*args)
__swig_destroy__ = _ivaria.delete_iBugPlugRenderObject
__del__ = lambda self : None;
iBugPlugRenderObject_swigregister = _ivaria.iBugPlugRenderObject_swigregister
iBugPlugRenderObject_swigregister(iBugPlugRenderObject)
class iBugPlug(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def SetupDebugSector(*args): return _ivaria.iBugPlug_SetupDebugSector(*args)
def DebugSectorBox(*args): return _ivaria.iBugPlug_DebugSectorBox(*args)
def DebugSectorTriangle(*args): return _ivaria.iBugPlug_DebugSectorTriangle(*args)
def SwitchDebugSector(*args): return _ivaria.iBugPlug_SwitchDebugSector(*args)
def CheckDebugSector(*args): return _ivaria.iBugPlug_CheckDebugSector(*args)
def SetupDebugView(*args): return _ivaria.iBugPlug_SetupDebugView(*args)
def DebugViewPoint(*args): return _ivaria.iBugPlug_DebugViewPoint(*args)
def DebugViewLine(*args): return _ivaria.iBugPlug_DebugViewLine(*args)
def DebugViewBox(*args): return _ivaria.iBugPlug_DebugViewBox(*args)
def DebugViewPointCount(*args): return _ivaria.iBugPlug_DebugViewPointCount(*args)
def DebugViewGetPoint(*args): return _ivaria.iBugPlug_DebugViewGetPoint(*args)
def DebugViewLineCount(*args): return _ivaria.iBugPlug_DebugViewLineCount(*args)
def DebugViewGetLine(*args): return _ivaria.iBugPlug_DebugViewGetLine(*args)
def DebugViewBoxCount(*args): return _ivaria.iBugPlug_DebugViewBoxCount(*args)
def DebugViewGetBox(*args): return _ivaria.iBugPlug_DebugViewGetBox(*args)
def DebugViewRenderObject(*args): return _ivaria.iBugPlug_DebugViewRenderObject(*args)
def DebugViewClearScreen(*args): return _ivaria.iBugPlug_DebugViewClearScreen(*args)
def SwitchDebugView(*args): return _ivaria.iBugPlug_SwitchDebugView(*args)
def CheckDebugView(*args): return _ivaria.iBugPlug_CheckDebugView(*args)
def AddCounter(*args): return _ivaria.iBugPlug_AddCounter(*args)
def AddCounterEnum(*args): return _ivaria.iBugPlug_AddCounterEnum(*args)
def ResetCounter(*args): return _ivaria.iBugPlug_ResetCounter(*args)
def RemoveCounter(*args): return _ivaria.iBugPlug_RemoveCounter(*args)
def ExecCommand(*args): return _ivaria.iBugPlug_ExecCommand(*args)
scfGetVersion = staticmethod(_ivaria.iBugPlug_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iBugPlug
__del__ = lambda self : None;
iBugPlug_swigregister = _ivaria.iBugPlug_swigregister
iBugPlug_swigregister(iBugPlug)
iBugPlug_scfGetVersion = _ivaria.iBugPlug_scfGetVersion
class csCollisionPair(object):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
a1 = _swig_property(_ivaria.csCollisionPair_a1_get, _ivaria.csCollisionPair_a1_set)
b1 = _swig_property(_ivaria.csCollisionPair_b1_get, _ivaria.csCollisionPair_b1_set)
c1 = _swig_property(_ivaria.csCollisionPair_c1_get, _ivaria.csCollisionPair_c1_set)
a2 = _swig_property(_ivaria.csCollisionPair_a2_get, _ivaria.csCollisionPair_a2_set)
b2 = _swig_property(_ivaria.csCollisionPair_b2_get, _ivaria.csCollisionPair_b2_set)
c2 = _swig_property(_ivaria.csCollisionPair_c2_get, _ivaria.csCollisionPair_c2_set)
def __eq__(*args): return _ivaria.csCollisionPair___eq__(*args)
def __init__(self, *args):
this = _ivaria.new_csCollisionPair(*args)
try: self.this.append(this)
except: self.this = this
__swig_destroy__ = _ivaria.delete_csCollisionPair
__del__ = lambda self : None;
csCollisionPair_swigregister = _ivaria.csCollisionPair_swigregister
csCollisionPair_swigregister(csCollisionPair)
class csIntersectingTriangle(object):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
a = _swig_property(_ivaria.csIntersectingTriangle_a_get, _ivaria.csIntersectingTriangle_a_set)
b = _swig_property(_ivaria.csIntersectingTriangle_b_get, _ivaria.csIntersectingTriangle_b_set)
c = _swig_property(_ivaria.csIntersectingTriangle_c_get, _ivaria.csIntersectingTriangle_c_set)
def __init__(self, *args):
this = _ivaria.new_csIntersectingTriangle(*args)
try: self.this.append(this)
except: self.this = this
__swig_destroy__ = _ivaria.delete_csIntersectingTriangle
__del__ = lambda self : None;
csIntersectingTriangle_swigregister = _ivaria.csIntersectingTriangle_swigregister
csIntersectingTriangle_swigregister(csIntersectingTriangle)
CS_MESH_COLLIDER = _ivaria.CS_MESH_COLLIDER
CS_TERRAFORMER_COLLIDER = _ivaria.CS_TERRAFORMER_COLLIDER
CS_TERRAIN_COLLIDER = _ivaria.CS_TERRAIN_COLLIDER
class iCollider(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def GetColliderType(*args): return _ivaria.iCollider_GetColliderType(*args)
scfGetVersion = staticmethod(_ivaria.iCollider_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iCollider
__del__ = lambda self : None;
iCollider_swigregister = _ivaria.iCollider_swigregister
iCollider_swigregister(iCollider)
iCollider_scfGetVersion = _ivaria.iCollider_scfGetVersion
class iCollideSystem(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def GetTriangleDataID(*args): return _ivaria.iCollideSystem_GetTriangleDataID(*args)
def GetBaseDataID(*args): return _ivaria.iCollideSystem_GetBaseDataID(*args)
def CreateCollider(*args): return _ivaria.iCollideSystem_CreateCollider(*args)
def Collide(*args): return _ivaria.iCollideSystem_Collide(*args)
def GetCollisionPairs(*args): return _ivaria.iCollideSystem_GetCollisionPairs(*args)
def GetCollisionPairCount(*args): return _ivaria.iCollideSystem_GetCollisionPairCount(*args)
def ResetCollisionPairs(*args): return _ivaria.iCollideSystem_ResetCollisionPairs(*args)
def CollideRay(*args): return _ivaria.iCollideSystem_CollideRay(*args)
def CollideSegment(*args): return _ivaria.iCollideSystem_CollideSegment(*args)
def GetIntersectingTriangles(*args): return _ivaria.iCollideSystem_GetIntersectingTriangles(*args)
def SetOneHitOnly(*args): return _ivaria.iCollideSystem_SetOneHitOnly(*args)
def GetOneHitOnly(*args): return _ivaria.iCollideSystem_GetOneHitOnly(*args)
def GetCollisionPairByIndex(*args): return _ivaria.iCollideSystem_GetCollisionPairByIndex(*args)
scfGetVersion = staticmethod(_ivaria.iCollideSystem_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iCollideSystem
__del__ = lambda self : None;
def GetCollisionPairs (self):
num = self.GetCollisionPairCount()
pairs = []
for i in range(num):
pairs.append(self.GetCollisionPairByIndex(i))
return pairs
iCollideSystem_swigregister = _ivaria.iCollideSystem_swigregister
iCollideSystem_swigregister(iCollideSystem)
iCollideSystem_scfGetVersion = _ivaria.iCollideSystem_scfGetVersion
class csCollisionPairArrayReadOnly(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def GetSize(*args): return _ivaria.csCollisionPairArrayReadOnly_GetSize(*args)
def Get(*args): return _ivaria.csCollisionPairArrayReadOnly_Get(*args)
def Top(*args): return _ivaria.csCollisionPairArrayReadOnly_Top(*args)
def Find(*args): return _ivaria.csCollisionPairArrayReadOnly_Find(*args)
def GetIndex(*args): return _ivaria.csCollisionPairArrayReadOnly_GetIndex(*args)
def IsEmpty(*args): return _ivaria.csCollisionPairArrayReadOnly_IsEmpty(*args)
def GetAll(*args): return _ivaria.csCollisionPairArrayReadOnly_GetAll(*args)
__swig_destroy__ = _ivaria.delete_csCollisionPairArrayReadOnly
__del__ = lambda self : None;
csCollisionPairArrayReadOnly_swigregister = _ivaria.csCollisionPairArrayReadOnly_swigregister
csCollisionPairArrayReadOnly_swigregister(csCollisionPairArrayReadOnly)
class csCollisionPairArrayChangeElements(csCollisionPairArrayReadOnly):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def Get(*args): return _ivaria.csCollisionPairArrayChangeElements_Get(*args)
def Top(*args): return _ivaria.csCollisionPairArrayChangeElements_Top(*args)
__swig_destroy__ = _ivaria.delete_csCollisionPairArrayChangeElements
__del__ = lambda self : None;
csCollisionPairArrayChangeElements_swigregister = _ivaria.csCollisionPairArrayChangeElements_swigregister
csCollisionPairArrayChangeElements_swigregister(csCollisionPairArrayChangeElements)
class csCollisionPairArrayChangeAll(csCollisionPairArrayChangeElements):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def SetSize(*args): return _ivaria.csCollisionPairArrayChangeAll_SetSize(*args)
def GetExtend(*args): return _ivaria.csCollisionPairArrayChangeAll_GetExtend(*args)
def Put(*args): return _ivaria.csCollisionPairArrayChangeAll_Put(*args)
def Push(*args): return _ivaria.csCollisionPairArrayChangeAll_Push(*args)
def PushSmart(*args): return _ivaria.csCollisionPairArrayChangeAll_PushSmart(*args)
def Pop(*args): return _ivaria.csCollisionPairArrayChangeAll_Pop(*args)
def Insert(*args): return _ivaria.csCollisionPairArrayChangeAll_Insert(*args)
def DeleteAll(*args): return _ivaria.csCollisionPairArrayChangeAll_DeleteAll(*args)
def Truncate(*args): return _ivaria.csCollisionPairArrayChangeAll_Truncate(*args)
def Empty(*args): return _ivaria.csCollisionPairArrayChangeAll_Empty(*args)
def DeleteIndex(*args): return _ivaria.csCollisionPairArrayChangeAll_DeleteIndex(*args)
def DeleteIndexFast(*args): return _ivaria.csCollisionPairArrayChangeAll_DeleteIndexFast(*args)
def Delete(*args): return _ivaria.csCollisionPairArrayChangeAll_Delete(*args)
__swig_destroy__ = _ivaria.delete_csCollisionPairArrayChangeAll
__del__ = lambda self : None;
csCollisionPairArrayChangeAll_swigregister = _ivaria.csCollisionPairArrayChangeAll_swigregister
csCollisionPairArrayChangeAll_swigregister(csCollisionPairArrayChangeAll)
class iDynamicsStepCallback(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def Step(*args): return _ivaria.iDynamicsStepCallback_Step(*args)
__swig_destroy__ = _ivaria.delete_iDynamicsStepCallback
__del__ = lambda self : None;
iDynamicsStepCallback_swigregister = _ivaria.iDynamicsStepCallback_swigregister
iDynamicsStepCallback_swigregister(iDynamicsStepCallback)
class iDynamics(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def CreateSystem(*args): return _ivaria.iDynamics_CreateSystem(*args)
def RemoveSystem(*args): return _ivaria.iDynamics_RemoveSystem(*args)
def RemoveSystems(*args): return _ivaria.iDynamics_RemoveSystems(*args)
def FindSystem(*args): return _ivaria.iDynamics_FindSystem(*args)
def Step(*args): return _ivaria.iDynamics_Step(*args)
def AddStepCallback(*args): return _ivaria.iDynamics_AddStepCallback(*args)
def RemoveStepCallback(*args): return _ivaria.iDynamics_RemoveStepCallback(*args)
scfGetVersion = staticmethod(_ivaria.iDynamics_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iDynamics
__del__ = lambda self : None;
iDynamics_swigregister = _ivaria.iDynamics_swigregister
iDynamics_swigregister(iDynamics)
iDynamics_scfGetVersion = _ivaria.iDynamics_scfGetVersion
class iDynamicSystem(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def QueryObject(*args): return _ivaria.iDynamicSystem_QueryObject(*args)
def SetGravity(*args): return _ivaria.iDynamicSystem_SetGravity(*args)
def GetGravity(*args): return _ivaria.iDynamicSystem_GetGravity(*args)
def SetLinearDampener(*args): return _ivaria.iDynamicSystem_SetLinearDampener(*args)
def GetLinearDampener(*args): return _ivaria.iDynamicSystem_GetLinearDampener(*args)
def SetRollingDampener(*args): return _ivaria.iDynamicSystem_SetRollingDampener(*args)
def GetRollingDampener(*args): return _ivaria.iDynamicSystem_GetRollingDampener(*args)
def EnableAutoDisable(*args): return _ivaria.iDynamicSystem_EnableAutoDisable(*args)
def AutoDisableEnabled(*args): return _ivaria.iDynamicSystem_AutoDisableEnabled(*args)
def SetAutoDisableParams(*args): return _ivaria.iDynamicSystem_SetAutoDisableParams(*args)
def Step(*args): return _ivaria.iDynamicSystem_Step(*args)
def CreateBody(*args): return _ivaria.iDynamicSystem_CreateBody(*args)
def RemoveBody(*args): return _ivaria.iDynamicSystem_RemoveBody(*args)
def FindBody(*args): return _ivaria.iDynamicSystem_FindBody(*args)
def GetBody(*args): return _ivaria.iDynamicSystem_GetBody(*args)
def GetBodysCount(*args): return _ivaria.iDynamicSystem_GetBodysCount(*args)
def CreateGroup(*args): return _ivaria.iDynamicSystem_CreateGroup(*args)
def RemoveGroup(*args): return _ivaria.iDynamicSystem_RemoveGroup(*args)
def CreateJoint(*args): return _ivaria.iDynamicSystem_CreateJoint(*args)
def RemoveJoint(*args): return _ivaria.iDynamicSystem_RemoveJoint(*args)
def GetDefaultMoveCallback(*args): return _ivaria.iDynamicSystem_GetDefaultMoveCallback(*args)
def AttachColliderConvexMesh(*args): return _ivaria.iDynamicSystem_AttachColliderConvexMesh(*args)
def AttachColliderMesh(*args): return _ivaria.iDynamicSystem_AttachColliderMesh(*args)
def AttachColliderCylinder(*args): return _ivaria.iDynamicSystem_AttachColliderCylinder(*args)
def AttachColliderBox(*args): return _ivaria.iDynamicSystem_AttachColliderBox(*args)
def AttachColliderSphere(*args): return _ivaria.iDynamicSystem_AttachColliderSphere(*args)
def AttachColliderPlane(*args): return _ivaria.iDynamicSystem_AttachColliderPlane(*args)
def DestroyColliders(*args): return _ivaria.iDynamicSystem_DestroyColliders(*args)
def DestroyCollider(*args): return _ivaria.iDynamicSystem_DestroyCollider(*args)
def AttachCollider(*args): return _ivaria.iDynamicSystem_AttachCollider(*args)
def CreateCollider(*args): return _ivaria.iDynamicSystem_CreateCollider(*args)
def GetCollider(*args): return _ivaria.iDynamicSystem_GetCollider(*args)
def GetColliderCount(*args): return _ivaria.iDynamicSystem_GetColliderCount(*args)
def AttachColliderCapsule(*args): return _ivaria.iDynamicSystem_AttachColliderCapsule(*args)
def AddBody(*args): return _ivaria.iDynamicSystem_AddBody(*args)
def AddJoint(*args): return _ivaria.iDynamicSystem_AddJoint(*args)
def SetPhysicsOrigin(*args): return _ivaria.iDynamicSystem_SetPhysicsOrigin(*args)
def GetPhysicsOrigin(*args): return _ivaria.iDynamicSystem_GetPhysicsOrigin(*args)
scfGetVersion = staticmethod(_ivaria.iDynamicSystem_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iDynamicSystem
__del__ = lambda self : None;
iDynamicSystem_swigregister = _ivaria.iDynamicSystem_swigregister
iDynamicSystem_swigregister(iDynamicSystem)
iDynamicSystem_scfGetVersion = _ivaria.iDynamicSystem_scfGetVersion
class iDynamicsMoveCallback(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def Execute(*args): return _ivaria.iDynamicsMoveCallback_Execute(*args)
__swig_destroy__ = _ivaria.delete_iDynamicsMoveCallback
__del__ = lambda self : None;
iDynamicsMoveCallback_swigregister = _ivaria.iDynamicsMoveCallback_swigregister
iDynamicsMoveCallback_swigregister(iDynamicsMoveCallback)
class iDynamicsCollisionCallback(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def Execute(*args): return _ivaria.iDynamicsCollisionCallback_Execute(*args)
__swig_destroy__ = _ivaria.delete_iDynamicsCollisionCallback
__del__ = lambda self : None;
iDynamicsCollisionCallback_swigregister = _ivaria.iDynamicsCollisionCallback_swigregister
iDynamicsCollisionCallback_swigregister(iDynamicsCollisionCallback)
class iBodyGroup(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def AddBody(*args): return _ivaria.iBodyGroup_AddBody(*args)
def RemoveBody(*args): return _ivaria.iBodyGroup_RemoveBody(*args)
def BodyInGroup(*args): return _ivaria.iBodyGroup_BodyInGroup(*args)
scfGetVersion = staticmethod(_ivaria.iBodyGroup_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iBodyGroup
__del__ = lambda self : None;
iBodyGroup_swigregister = _ivaria.iBodyGroup_swigregister
iBodyGroup_swigregister(iBodyGroup)
iBodyGroup_scfGetVersion = _ivaria.iBodyGroup_scfGetVersion
class iRigidBody(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def QueryObject(*args): return _ivaria.iRigidBody_QueryObject(*args)
def MakeStatic(*args): return _ivaria.iRigidBody_MakeStatic(*args)
def MakeDynamic(*args): return _ivaria.iRigidBody_MakeDynamic(*args)
def IsStatic(*args): return _ivaria.iRigidBody_IsStatic(*args)
def Disable(*args): return _ivaria.iRigidBody_Disable(*args)
def Enable(*args): return _ivaria.iRigidBody_Enable(*args)
def IsEnabled(*args): return _ivaria.iRigidBody_IsEnabled(*args)
def GetGroup(*args): return _ivaria.iRigidBody_GetGroup(*args)
def AttachColliderConvexMesh(*args): return _ivaria.iRigidBody_AttachColliderConvexMesh(*args)
def AttachColliderMesh(*args): return _ivaria.iRigidBody_AttachColliderMesh(*args)
def AttachColliderCylinder(*args): return _ivaria.iRigidBody_AttachColliderCylinder(*args)
def AttachColliderBox(*args): return _ivaria.iRigidBody_AttachColliderBox(*args)
def AttachColliderSphere(*args): return _ivaria.iRigidBody_AttachColliderSphere(*args)
def AttachColliderPlane(*args): return _ivaria.iRigidBody_AttachColliderPlane(*args)
def AttachCollider(*args): return _ivaria.iRigidBody_AttachCollider(*args)
def DestroyColliders(*args): return _ivaria.iRigidBody_DestroyColliders(*args)
def DestroyCollider(*args): return _ivaria.iRigidBody_DestroyCollider(*args)
def SetPosition(*args): return _ivaria.iRigidBody_SetPosition(*args)
def GetPosition(*args): return _ivaria.iRigidBody_GetPosition(*args)
def SetOrientation(*args): return _ivaria.iRigidBody_SetOrientation(*args)
def GetOrientation(*args): return _ivaria.iRigidBody_GetOrientation(*args)
def SetTransform(*args): return _ivaria.iRigidBody_SetTransform(*args)
def GetTransform(*args): return _ivaria.iRigidBody_GetTransform(*args)
def SetLinearVelocity(*args): return _ivaria.iRigidBody_SetLinearVelocity(*args)
def GetLinearVelocity(*args): return _ivaria.iRigidBody_GetLinearVelocity(*args)
def SetAngularVelocity(*args): return _ivaria.iRigidBody_SetAngularVelocity(*args)
def GetAngularVelocity(*args): return _ivaria.iRigidBody_GetAngularVelocity(*args)
def SetProperties(*args): return _ivaria.iRigidBody_SetProperties(*args)
def GetProperties(*args): return _ivaria.iRigidBody_GetProperties(*args)
def GetMass(*args): return _ivaria.iRigidBody_GetMass(*args)
def GetCenter(*args): return _ivaria.iRigidBody_GetCenter(*args)
def GetInertia(*args): return _ivaria.iRigidBody_GetInertia(*args)
def AdjustTotalMass(*args): return _ivaria.iRigidBody_AdjustTotalMass(*args)
def AddForce(*args): return _ivaria.iRigidBody_AddForce(*args)
def AddTorque(*args): return _ivaria.iRigidBody_AddTorque(*args)
def AddRelForce(*args): return _ivaria.iRigidBody_AddRelForce(*args)
def AddRelTorque(*args): return _ivaria.iRigidBody_AddRelTorque(*args)
def AddForceAtPos(*args): return _ivaria.iRigidBody_AddForceAtPos(*args)
def AddForceAtRelPos(*args): return _ivaria.iRigidBody_AddForceAtRelPos(*args)
def AddRelForceAtPos(*args): return _ivaria.iRigidBody_AddRelForceAtPos(*args)
def AddRelForceAtRelPos(*args): return _ivaria.iRigidBody_AddRelForceAtRelPos(*args)
def GetForce(*args): return _ivaria.iRigidBody_GetForce(*args)
def GetTorque(*args): return _ivaria.iRigidBody_GetTorque(*args)
def AttachMesh(*args): return _ivaria.iRigidBody_AttachMesh(*args)
def GetAttachedMesh(*args): return _ivaria.iRigidBody_GetAttachedMesh(*args)
def AttachLight(*args): return _ivaria.iRigidBody_AttachLight(*args)
def GetAttachedLight(*args): return _ivaria.iRigidBody_GetAttachedLight(*args)
def AttachCamera(*args): return _ivaria.iRigidBody_AttachCamera(*args)
def GetAttachedCamera(*args): return _ivaria.iRigidBody_GetAttachedCamera(*args)
def SetMoveCallback(*args): return _ivaria.iRigidBody_SetMoveCallback(*args)
def SetCollisionCallback(*args): return _ivaria.iRigidBody_SetCollisionCallback(*args)
def Collision(*args): return _ivaria.iRigidBody_Collision(*args)
def Update(*args): return _ivaria.iRigidBody_Update(*args)
def GetCollider(*args): return _ivaria.iRigidBody_GetCollider(*args)
def GetColliderCount(*args): return _ivaria.iRigidBody_GetColliderCount(*args)
def AttachColliderCapsule(*args): return _ivaria.iRigidBody_AttachColliderCapsule(*args)
__swig_destroy__ = _ivaria.delete_iRigidBody
__del__ = lambda self : None;
iRigidBody_swigregister = _ivaria.iRigidBody_swigregister
iRigidBody_swigregister(iRigidBody)
NO_GEOMETRY = _ivaria.NO_GEOMETRY
BOX_COLLIDER_GEOMETRY = _ivaria.BOX_COLLIDER_GEOMETRY
PLANE_COLLIDER_GEOMETRY = _ivaria.PLANE_COLLIDER_GEOMETRY
TRIMESH_COLLIDER_GEOMETRY = _ivaria.TRIMESH_COLLIDER_GEOMETRY
CONVEXMESH_COLLIDER_GEOMETRY = _ivaria.CONVEXMESH_COLLIDER_GEOMETRY
CYLINDER_COLLIDER_GEOMETRY = _ivaria.CYLINDER_COLLIDER_GEOMETRY
CAPSULE_COLLIDER_GEOMETRY = _ivaria.CAPSULE_COLLIDER_GEOMETRY
SPHERE_COLLIDER_GEOMETRY = _ivaria.SPHERE_COLLIDER_GEOMETRY
class iDynamicsColliderCollisionCallback(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def Execute(*args): return _ivaria.iDynamicsColliderCollisionCallback_Execute(*args)
__swig_destroy__ = _ivaria.delete_iDynamicsColliderCollisionCallback
__del__ = lambda self : None;
iDynamicsColliderCollisionCallback_swigregister = _ivaria.iDynamicsColliderCollisionCallback_swigregister
iDynamicsColliderCollisionCallback_swigregister(iDynamicsColliderCollisionCallback)
class iDynamicsSystemCollider(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def CreateSphereGeometry(*args): return _ivaria.iDynamicsSystemCollider_CreateSphereGeometry(*args)
def CreatePlaneGeometry(*args): return _ivaria.iDynamicsSystemCollider_CreatePlaneGeometry(*args)
def CreateConvexMeshGeometry(*args): return _ivaria.iDynamicsSystemCollider_CreateConvexMeshGeometry(*args)
def CreateMeshGeometry(*args): return _ivaria.iDynamicsSystemCollider_CreateMeshGeometry(*args)
def CreateBoxGeometry(*args): return _ivaria.iDynamicsSystemCollider_CreateBoxGeometry(*args)
def CreateCapsuleGeometry(*args): return _ivaria.iDynamicsSystemCollider_CreateCapsuleGeometry(*args)
def CreateCylinderGeometry(*args): return _ivaria.iDynamicsSystemCollider_CreateCylinderGeometry(*args)
def SetCollisionCallback(*args): return _ivaria.iDynamicsSystemCollider_SetCollisionCallback(*args)
def SetFriction(*args): return _ivaria.iDynamicsSystemCollider_SetFriction(*args)
def SetSoftness(*args): return _ivaria.iDynamicsSystemCollider_SetSoftness(*args)
def SetDensity(*args): return _ivaria.iDynamicsSystemCollider_SetDensity(*args)
def SetElasticity(*args): return _ivaria.iDynamicsSystemCollider_SetElasticity(*args)
def GetFriction(*args): return _ivaria.iDynamicsSystemCollider_GetFriction(*args)
def GetSoftness(*args): return _ivaria.iDynamicsSystemCollider_GetSoftness(*args)
def GetDensity(*args): return _ivaria.iDynamicsSystemCollider_GetDensity(*args)
def GetElasticity(*args): return _ivaria.iDynamicsSystemCollider_GetElasticity(*args)
def FillWithColliderGeometry(*args): return _ivaria.iDynamicsSystemCollider_FillWithColliderGeometry(*args)
def GetGeometryType(*args): return _ivaria.iDynamicsSystemCollider_GetGeometryType(*args)
def GetTransform(*args): return _ivaria.iDynamicsSystemCollider_GetTransform(*args)
def GetLocalTransform(*args): return _ivaria.iDynamicsSystemCollider_GetLocalTransform(*args)
def SetTransform(*args): return _ivaria.iDynamicsSystemCollider_SetTransform(*args)
def GetBoxGeometry(*args): return _ivaria.iDynamicsSystemCollider_GetBoxGeometry(*args)
def GetSphereGeometry(*args): return _ivaria.iDynamicsSystemCollider_GetSphereGeometry(*args)
def GetPlaneGeometry(*args): return _ivaria.iDynamicsSystemCollider_GetPlaneGeometry(*args)
def GetCylinderGeometry(*args): return _ivaria.iDynamicsSystemCollider_GetCylinderGeometry(*args)
def MakeStatic(*args): return _ivaria.iDynamicsSystemCollider_MakeStatic(*args)
def MakeDynamic(*args): return _ivaria.iDynamicsSystemCollider_MakeDynamic(*args)
def IsStatic(*args): return _ivaria.iDynamicsSystemCollider_IsStatic(*args)
def GetCapsuleGeometry(*args): return _ivaria.iDynamicsSystemCollider_GetCapsuleGeometry(*args)
def GetMeshGeometry(*args): return _ivaria.iDynamicsSystemCollider_GetMeshGeometry(*args)
def GetConvexMeshGeometry(*args): return _ivaria.iDynamicsSystemCollider_GetConvexMeshGeometry(*args)
__swig_destroy__ = _ivaria.delete_iDynamicsSystemCollider
__del__ = lambda self : None;
iDynamicsSystemCollider_swigregister = _ivaria.iDynamicsSystemCollider_swigregister
iDynamicsSystemCollider_swigregister(iDynamicsSystemCollider)
class iJoint(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def Attach(*args): return _ivaria.iJoint_Attach(*args)
def GetAttachedBody(*args): return _ivaria.iJoint_GetAttachedBody(*args)
def SetTransform(*args): return _ivaria.iJoint_SetTransform(*args)
def GetTransform(*args): return _ivaria.iJoint_GetTransform(*args)
def SetTransConstraints(*args): return _ivaria.iJoint_SetTransConstraints(*args)
def IsXTransConstrained(*args): return _ivaria.iJoint_IsXTransConstrained(*args)
def IsYTransConstrained(*args): return _ivaria.iJoint_IsYTransConstrained(*args)
def IsZTransConstrained(*args): return _ivaria.iJoint_IsZTransConstrained(*args)
def SetMinimumDistance(*args): return _ivaria.iJoint_SetMinimumDistance(*args)
def GetMinimumDistance(*args): return _ivaria.iJoint_GetMinimumDistance(*args)
def SetMaximumDistance(*args): return _ivaria.iJoint_SetMaximumDistance(*args)
def GetMaximumDistance(*args): return _ivaria.iJoint_GetMaximumDistance(*args)
def SetRotConstraints(*args): return _ivaria.iJoint_SetRotConstraints(*args)
def IsXRotConstrained(*args): return _ivaria.iJoint_IsXRotConstrained(*args)
def IsYRotConstrained(*args): return _ivaria.iJoint_IsYRotConstrained(*args)
def IsZRotConstrained(*args): return _ivaria.iJoint_IsZRotConstrained(*args)
def SetMinimumAngle(*args): return _ivaria.iJoint_SetMinimumAngle(*args)
def GetMinimumAngle(*args): return _ivaria.iJoint_GetMinimumAngle(*args)
def SetMaximumAngle(*args): return _ivaria.iJoint_SetMaximumAngle(*args)
def GetMaximumAngle(*args): return _ivaria.iJoint_GetMaximumAngle(*args)
def SetBounce(*args): return _ivaria.iJoint_SetBounce(*args)
def GetBounce(*args): return _ivaria.iJoint_GetBounce(*args)
def SetDesiredVelocity(*args): return _ivaria.iJoint_SetDesiredVelocity(*args)
def GetDesiredVelocity(*args): return _ivaria.iJoint_GetDesiredVelocity(*args)
def SetMaxForce(*args): return _ivaria.iJoint_SetMaxForce(*args)
def GetMaxForce(*args): return _ivaria.iJoint_GetMaxForce(*args)
def SetAngularConstraintAxis(*args): return _ivaria.iJoint_SetAngularConstraintAxis(*args)
def GetAngularConstraintAxis(*args): return _ivaria.iJoint_GetAngularConstraintAxis(*args)
def RebuildJoint(*args): return _ivaria.iJoint_RebuildJoint(*args)
scfGetVersion = staticmethod(_ivaria.iJoint_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iJoint
__del__ = lambda self : None;
iJoint_swigregister = _ivaria.iJoint_swigregister
iJoint_swigregister(iJoint)
iJoint_scfGetVersion = _ivaria.iJoint_scfGetVersion
class iODEFrameUpdateCallback(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def Execute(*args): return _ivaria.iODEFrameUpdateCallback_Execute(*args)
__swig_destroy__ = _ivaria.delete_iODEFrameUpdateCallback
__del__ = lambda self : None;
iODEFrameUpdateCallback_swigregister = _ivaria.iODEFrameUpdateCallback_swigregister
iODEFrameUpdateCallback_swigregister(iODEFrameUpdateCallback)
class iODEDynamicState(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def SetGlobalERP(*args): return _ivaria.iODEDynamicState_SetGlobalERP(*args)
def GlobalERP(*args): return _ivaria.iODEDynamicState_GlobalERP(*args)
def SetGlobalCFM(*args): return _ivaria.iODEDynamicState_SetGlobalCFM(*args)
def GlobalCFM(*args): return _ivaria.iODEDynamicState_GlobalCFM(*args)
def EnableStepFast(*args): return _ivaria.iODEDynamicState_EnableStepFast(*args)
def StepFastEnabled(*args): return _ivaria.iODEDynamicState_StepFastEnabled(*args)
def SetStepFastIterations(*args): return _ivaria.iODEDynamicState_SetStepFastIterations(*args)
def StepFastIterations(*args): return _ivaria.iODEDynamicState_StepFastIterations(*args)
def EnableQuickStep(*args): return _ivaria.iODEDynamicState_EnableQuickStep(*args)
def QuickStepEnabled(*args): return _ivaria.iODEDynamicState_QuickStepEnabled(*args)
def SetQuickStepIterations(*args): return _ivaria.iODEDynamicState_SetQuickStepIterations(*args)
def QuickStepIterations(*args): return _ivaria.iODEDynamicState_QuickStepIterations(*args)
def EnableFrameRate(*args): return _ivaria.iODEDynamicState_EnableFrameRate(*args)
def FrameRateEnabled(*args): return _ivaria.iODEDynamicState_FrameRateEnabled(*args)
def SetFrameRate(*args): return _ivaria.iODEDynamicState_SetFrameRate(*args)
def FrameRate(*args): return _ivaria.iODEDynamicState_FrameRate(*args)
def SetFrameLimit(*args): return _ivaria.iODEDynamicState_SetFrameLimit(*args)
def FrameLimit(*args): return _ivaria.iODEDynamicState_FrameLimit(*args)
def AddFrameUpdateCallback(*args): return _ivaria.iODEDynamicState_AddFrameUpdateCallback(*args)
def RemoveFrameUpdateCallback(*args): return _ivaria.iODEDynamicState_RemoveFrameUpdateCallback(*args)
def EnableEventProcessing(*args): return _ivaria.iODEDynamicState_EnableEventProcessing(*args)
def EventProcessingEnabled(*args): return _ivaria.iODEDynamicState_EventProcessingEnabled(*args)
def EnableFastObjects(*args): return _ivaria.iODEDynamicState_EnableFastObjects(*args)
def FastObjectsEnabled(*args): return _ivaria.iODEDynamicState_FastObjectsEnabled(*args)
scfGetVersion = staticmethod(_ivaria.iODEDynamicState_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iODEDynamicState
__del__ = lambda self : None;
iODEDynamicState_swigregister = _ivaria.iODEDynamicState_swigregister
iODEDynamicState_swigregister(iODEDynamicState)
iODEDynamicState_scfGetVersion = _ivaria.iODEDynamicState_scfGetVersion
class iODEDynamicSystemState(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def SetERP(*args): return _ivaria.iODEDynamicSystemState_SetERP(*args)
def ERP(*args): return _ivaria.iODEDynamicSystemState_ERP(*args)
def SetCFM(*args): return _ivaria.iODEDynamicSystemState_SetCFM(*args)
def CFM(*args): return _ivaria.iODEDynamicSystemState_CFM(*args)
def EnableStepFast(*args): return _ivaria.iODEDynamicSystemState_EnableStepFast(*args)
def StepFastEnabled(*args): return _ivaria.iODEDynamicSystemState_StepFastEnabled(*args)
def SetStepFastIterations(*args): return _ivaria.iODEDynamicSystemState_SetStepFastIterations(*args)
def StepFastIterations(*args): return _ivaria.iODEDynamicSystemState_StepFastIterations(*args)
def EnableQuickStep(*args): return _ivaria.iODEDynamicSystemState_EnableQuickStep(*args)
def QuickStepEnabled(*args): return _ivaria.iODEDynamicSystemState_QuickStepEnabled(*args)
def SetQuickStepIterations(*args): return _ivaria.iODEDynamicSystemState_SetQuickStepIterations(*args)
def QuickStepIterations(*args): return _ivaria.iODEDynamicSystemState_QuickStepIterations(*args)
def EnableAutoDisable(*args): return _ivaria.iODEDynamicSystemState_EnableAutoDisable(*args)
def AutoDisableEnabled(*args): return _ivaria.iODEDynamicSystemState_AutoDisableEnabled(*args)
def SetAutoDisableParams(*args): return _ivaria.iODEDynamicSystemState_SetAutoDisableParams(*args)
def EnableFrameRate(*args): return _ivaria.iODEDynamicSystemState_EnableFrameRate(*args)
def FrameRateEnabled(*args): return _ivaria.iODEDynamicSystemState_FrameRateEnabled(*args)
def SetFrameRate(*args): return _ivaria.iODEDynamicSystemState_SetFrameRate(*args)
def FrameRate(*args): return _ivaria.iODEDynamicSystemState_FrameRate(*args)
def SetFrameLimit(*args): return _ivaria.iODEDynamicSystemState_SetFrameLimit(*args)
def FrameLimit(*args): return _ivaria.iODEDynamicSystemState_FrameLimit(*args)
def AddFrameUpdateCallback(*args): return _ivaria.iODEDynamicSystemState_AddFrameUpdateCallback(*args)
def RemoveFrameUpdateCallback(*args): return _ivaria.iODEDynamicSystemState_RemoveFrameUpdateCallback(*args)
def EnableFastObjects(*args): return _ivaria.iODEDynamicSystemState_EnableFastObjects(*args)
def FastObjectsEnabled(*args): return _ivaria.iODEDynamicSystemState_FastObjectsEnabled(*args)
def CreateBallJoint(*args): return _ivaria.iODEDynamicSystemState_CreateBallJoint(*args)
def CreateHingeJoint(*args): return _ivaria.iODEDynamicSystemState_CreateHingeJoint(*args)
def CreateHinge2Joint(*args): return _ivaria.iODEDynamicSystemState_CreateHinge2Joint(*args)
def CreateAMotorJoint(*args): return _ivaria.iODEDynamicSystemState_CreateAMotorJoint(*args)
def CreateUniversalJoint(*args): return _ivaria.iODEDynamicSystemState_CreateUniversalJoint(*args)
def CreateSliderJoint(*args): return _ivaria.iODEDynamicSystemState_CreateSliderJoint(*args)
def RemoveJoint(*args): return _ivaria.iODEDynamicSystemState_RemoveJoint(*args)
def SetContactMaxCorrectingVel(*args): return _ivaria.iODEDynamicSystemState_SetContactMaxCorrectingVel(*args)
def GetContactMaxCorrectingVel(*args): return _ivaria.iODEDynamicSystemState_GetContactMaxCorrectingVel(*args)
def SetContactSurfaceLayer(*args): return _ivaria.iODEDynamicSystemState_SetContactSurfaceLayer(*args)
def GetContactSurfaceLayer(*args): return _ivaria.iODEDynamicSystemState_GetContactSurfaceLayer(*args)
def EnableOldInertia(*args): return _ivaria.iODEDynamicSystemState_EnableOldInertia(*args)
def IsOldInertiaEnabled(*args): return _ivaria.iODEDynamicSystemState_IsOldInertiaEnabled(*args)
scfGetVersion = staticmethod(_ivaria.iODEDynamicSystemState_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iODEDynamicSystemState
__del__ = lambda self : None;
iODEDynamicSystemState_swigregister = _ivaria.iODEDynamicSystemState_swigregister
iODEDynamicSystemState_swigregister(iODEDynamicSystemState)
iODEDynamicSystemState_scfGetVersion = _ivaria.iODEDynamicSystemState_scfGetVersion
CS_ODE_JOINT_TYPE_UNKNOWN = _ivaria.CS_ODE_JOINT_TYPE_UNKNOWN
CS_ODE_JOINT_TYPE_BALL = _ivaria.CS_ODE_JOINT_TYPE_BALL
CS_ODE_JOINT_TYPE_HINGE = _ivaria.CS_ODE_JOINT_TYPE_HINGE
CS_ODE_JOINT_TYPE_SLIDER = _ivaria.CS_ODE_JOINT_TYPE_SLIDER
CS_ODE_JOINT_TYPE_CONTACT = _ivaria.CS_ODE_JOINT_TYPE_CONTACT
CS_ODE_JOINT_TYPE_UNIVERSAL = _ivaria.CS_ODE_JOINT_TYPE_UNIVERSAL
CS_ODE_JOINT_TYPE_HINGE2 = _ivaria.CS_ODE_JOINT_TYPE_HINGE2
CS_ODE_JOINT_TYPE_FIXED = _ivaria.CS_ODE_JOINT_TYPE_FIXED
CS_ODE_JOINT_TYPE_AMOTOR = _ivaria.CS_ODE_JOINT_TYPE_AMOTOR
class iODEJointState(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def GetType(*args): return _ivaria.iODEJointState_GetType(*args)
def SetLoStop(*args): return _ivaria.iODEJointState_SetLoStop(*args)
def SetHiStop(*args): return _ivaria.iODEJointState_SetHiStop(*args)
def SetVel(*args): return _ivaria.iODEJointState_SetVel(*args)
def SetFMax(*args): return _ivaria.iODEJointState_SetFMax(*args)
def SetFudgeFactor(*args): return _ivaria.iODEJointState_SetFudgeFactor(*args)
def SetBounce(*args): return _ivaria.iODEJointState_SetBounce(*args)
def SetCFM(*args): return _ivaria.iODEJointState_SetCFM(*args)
def SetStopERP(*args): return _ivaria.iODEJointState_SetStopERP(*args)
def SetStopCFM(*args): return _ivaria.iODEJointState_SetStopCFM(*args)
def SetSuspensionERP(*args): return _ivaria.iODEJointState_SetSuspensionERP(*args)
def SetSuspensionCFM(*args): return _ivaria.iODEJointState_SetSuspensionCFM(*args)
def GetLoStop(*args): return _ivaria.iODEJointState_GetLoStop(*args)
def GetHiStop(*args): return _ivaria.iODEJointState_GetHiStop(*args)
def GetVel(*args): return _ivaria.iODEJointState_GetVel(*args)
def GetMaxForce(*args): return _ivaria.iODEJointState_GetMaxForce(*args)
def GetFudgeFactor(*args): return _ivaria.iODEJointState_GetFudgeFactor(*args)
def GetBounce(*args): return _ivaria.iODEJointState_GetBounce(*args)
def GetCFM(*args): return _ivaria.iODEJointState_GetCFM(*args)
def GetStopERP(*args): return _ivaria.iODEJointState_GetStopERP(*args)
def GetStopCFM(*args): return _ivaria.iODEJointState_GetStopCFM(*args)
def GetSuspensionERP(*args): return _ivaria.iODEJointState_GetSuspensionERP(*args)
def GetSuspensionCFM(*args): return _ivaria.iODEJointState_GetSuspensionCFM(*args)
scfGetVersion = staticmethod(_ivaria.iODEJointState_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iODEJointState
__del__ = lambda self : None;
iODEJointState_swigregister = _ivaria.iODEJointState_swigregister
iODEJointState_swigregister(iODEJointState)
iODEJointState_scfGetVersion = _ivaria.iODEJointState_scfGetVersion
class iODEGeneralJointState(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def SetLoStop(*args): return _ivaria.iODEGeneralJointState_SetLoStop(*args)
def SetHiStop(*args): return _ivaria.iODEGeneralJointState_SetHiStop(*args)
def SetVel(*args): return _ivaria.iODEGeneralJointState_SetVel(*args)
def SetFMax(*args): return _ivaria.iODEGeneralJointState_SetFMax(*args)
def SetFudgeFactor(*args): return _ivaria.iODEGeneralJointState_SetFudgeFactor(*args)
def SetBounce(*args): return _ivaria.iODEGeneralJointState_SetBounce(*args)
def SetCFM(*args): return _ivaria.iODEGeneralJointState_SetCFM(*args)
def SetStopERP(*args): return _ivaria.iODEGeneralJointState_SetStopERP(*args)
def SetStopCFM(*args): return _ivaria.iODEGeneralJointState_SetStopCFM(*args)
def SetSuspensionERP(*args): return _ivaria.iODEGeneralJointState_SetSuspensionERP(*args)
def SetSuspensionCFM(*args): return _ivaria.iODEGeneralJointState_SetSuspensionCFM(*args)
def GetLoStop(*args): return _ivaria.iODEGeneralJointState_GetLoStop(*args)
def GetHiStop(*args): return _ivaria.iODEGeneralJointState_GetHiStop(*args)
def GetVel(*args): return _ivaria.iODEGeneralJointState_GetVel(*args)
def GetFMax(*args): return _ivaria.iODEGeneralJointState_GetFMax(*args)
def GetFudgeFactor(*args): return _ivaria.iODEGeneralJointState_GetFudgeFactor(*args)
def GetBounce(*args): return _ivaria.iODEGeneralJointState_GetBounce(*args)
def GetCFM(*args): return _ivaria.iODEGeneralJointState_GetCFM(*args)
def GetStopERP(*args): return _ivaria.iODEGeneralJointState_GetStopERP(*args)
def GetStopCFM(*args): return _ivaria.iODEGeneralJointState_GetStopCFM(*args)
def GetSuspensionERP(*args): return _ivaria.iODEGeneralJointState_GetSuspensionERP(*args)
def GetSuspensionCFM(*args): return _ivaria.iODEGeneralJointState_GetSuspensionCFM(*args)
def Attach(*args): return _ivaria.iODEGeneralJointState_Attach(*args)
def GetAttachedBody(*args): return _ivaria.iODEGeneralJointState_GetAttachedBody(*args)
def GetFeedbackForce1(*args): return _ivaria.iODEGeneralJointState_GetFeedbackForce1(*args)
def GetFeedbackTorque1(*args): return _ivaria.iODEGeneralJointState_GetFeedbackTorque1(*args)
def GetFeedbackForce2(*args): return _ivaria.iODEGeneralJointState_GetFeedbackForce2(*args)
def GetFeedbackTorque2(*args): return _ivaria.iODEGeneralJointState_GetFeedbackTorque2(*args)
__swig_destroy__ = _ivaria.delete_iODEGeneralJointState
__del__ = lambda self : None;
iODEGeneralJointState_swigregister = _ivaria.iODEGeneralJointState_swigregister
iODEGeneralJointState_swigregister(iODEGeneralJointState)
class iODESliderJoint(iODEGeneralJointState):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def SetSliderAxis(*args): return _ivaria.iODESliderJoint_SetSliderAxis(*args)
def GetSliderAxis(*args): return _ivaria.iODESliderJoint_GetSliderAxis(*args)
def GetSliderPosition(*args): return _ivaria.iODESliderJoint_GetSliderPosition(*args)
def GetSliderPositionRate(*args): return _ivaria.iODESliderJoint_GetSliderPositionRate(*args)
scfGetVersion = staticmethod(_ivaria.iODESliderJoint_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iODESliderJoint
__del__ = lambda self : None;
iODESliderJoint_swigregister = _ivaria.iODESliderJoint_swigregister
iODESliderJoint_swigregister(iODESliderJoint)
iODESliderJoint_scfGetVersion = _ivaria.iODESliderJoint_scfGetVersion
class iODEUniversalJoint(iODEGeneralJointState):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def SetUniversalAnchor(*args): return _ivaria.iODEUniversalJoint_SetUniversalAnchor(*args)
def SetUniversalAxis1(*args): return _ivaria.iODEUniversalJoint_SetUniversalAxis1(*args)
def SetUniversalAxis2(*args): return _ivaria.iODEUniversalJoint_SetUniversalAxis2(*args)
def GetUniversalAnchor1(*args): return _ivaria.iODEUniversalJoint_GetUniversalAnchor1(*args)
def GetUniversalAnchor2(*args): return _ivaria.iODEUniversalJoint_GetUniversalAnchor2(*args)
def GetUniversalAxis1(*args): return _ivaria.iODEUniversalJoint_GetUniversalAxis1(*args)
def GetUniversalAxis2(*args): return _ivaria.iODEUniversalJoint_GetUniversalAxis2(*args)
scfGetVersion = staticmethod(_ivaria.iODEUniversalJoint_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iODEUniversalJoint
__del__ = lambda self : None;
iODEUniversalJoint_swigregister = _ivaria.iODEUniversalJoint_swigregister
iODEUniversalJoint_swigregister(iODEUniversalJoint)
iODEUniversalJoint_scfGetVersion = _ivaria.iODEUniversalJoint_scfGetVersion
CS_ODE_AMOTOR_MODE_UNKNOWN = _ivaria.CS_ODE_AMOTOR_MODE_UNKNOWN
CS_ODE_AMOTOR_MODE_USER = _ivaria.CS_ODE_AMOTOR_MODE_USER
CS_ODE_AMOTOR_MODE_EULER = _ivaria.CS_ODE_AMOTOR_MODE_EULER
CS_ODE_AMOTOR_MODE_LAST = _ivaria.CS_ODE_AMOTOR_MODE_LAST
class iODEAMotorJoint(iODEGeneralJointState):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def SetAMotorMode(*args): return _ivaria.iODEAMotorJoint_SetAMotorMode(*args)
def GetAMotorMode(*args): return _ivaria.iODEAMotorJoint_GetAMotorMode(*args)
def SetAMotorNumAxes(*args): return _ivaria.iODEAMotorJoint_SetAMotorNumAxes(*args)
def GetAMotorNumAxes(*args): return _ivaria.iODEAMotorJoint_GetAMotorNumAxes(*args)
def SetAMotorAxis(*args): return _ivaria.iODEAMotorJoint_SetAMotorAxis(*args)
def GetAMotorAxis(*args): return _ivaria.iODEAMotorJoint_GetAMotorAxis(*args)
def GetAMotorAxisRelOrientation(*args): return _ivaria.iODEAMotorJoint_GetAMotorAxisRelOrientation(*args)
def SetAMotorAngle(*args): return _ivaria.iODEAMotorJoint_SetAMotorAngle(*args)
def GetAMotorAngle(*args): return _ivaria.iODEAMotorJoint_GetAMotorAngle(*args)
def GetAMotorAngleRate(*args): return _ivaria.iODEAMotorJoint_GetAMotorAngleRate(*args)
scfGetVersion = staticmethod(_ivaria.iODEAMotorJoint_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iODEAMotorJoint
__del__ = lambda self : None;
iODEAMotorJoint_swigregister = _ivaria.iODEAMotorJoint_swigregister
iODEAMotorJoint_swigregister(iODEAMotorJoint)
iODEAMotorJoint_scfGetVersion = _ivaria.iODEAMotorJoint_scfGetVersion
class iODEHinge2Joint(iODEGeneralJointState):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def SetHingeAnchor(*args): return _ivaria.iODEHinge2Joint_SetHingeAnchor(*args)
def SetHingeAxis1(*args): return _ivaria.iODEHinge2Joint_SetHingeAxis1(*args)
def SetHingeAxis2(*args): return _ivaria.iODEHinge2Joint_SetHingeAxis2(*args)
def GetHingeAnchor1(*args): return _ivaria.iODEHinge2Joint_GetHingeAnchor1(*args)
def GetHingeAnchor2(*args): return _ivaria.iODEHinge2Joint_GetHingeAnchor2(*args)
def GetHingeAxis1(*args): return _ivaria.iODEHinge2Joint_GetHingeAxis1(*args)
def GetHingeAxis2(*args): return _ivaria.iODEHinge2Joint_GetHingeAxis2(*args)
def GetHingeAngle(*args): return _ivaria.iODEHinge2Joint_GetHingeAngle(*args)
def GetHingeAngleRate1(*args): return _ivaria.iODEHinge2Joint_GetHingeAngleRate1(*args)
def GetHingeAngleRate2(*args): return _ivaria.iODEHinge2Joint_GetHingeAngleRate2(*args)
def GetAnchorError(*args): return _ivaria.iODEHinge2Joint_GetAnchorError(*args)
scfGetVersion = staticmethod(_ivaria.iODEHinge2Joint_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iODEHinge2Joint
__del__ = lambda self : None;
iODEHinge2Joint_swigregister = _ivaria.iODEHinge2Joint_swigregister
iODEHinge2Joint_swigregister(iODEHinge2Joint)
iODEHinge2Joint_scfGetVersion = _ivaria.iODEHinge2Joint_scfGetVersion
class iODEHingeJoint(iODEGeneralJointState):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def SetHingeAnchor(*args): return _ivaria.iODEHingeJoint_SetHingeAnchor(*args)
def SetHingeAxis(*args): return _ivaria.iODEHingeJoint_SetHingeAxis(*args)
def GetHingeAnchor1(*args): return _ivaria.iODEHingeJoint_GetHingeAnchor1(*args)
def GetHingeAnchor2(*args): return _ivaria.iODEHingeJoint_GetHingeAnchor2(*args)
def GetHingeAxis(*args): return _ivaria.iODEHingeJoint_GetHingeAxis(*args)
def GetHingeAngle(*args): return _ivaria.iODEHingeJoint_GetHingeAngle(*args)
def GetHingeAngleRate(*args): return _ivaria.iODEHingeJoint_GetHingeAngleRate(*args)
def GetAnchorError(*args): return _ivaria.iODEHingeJoint_GetAnchorError(*args)
scfGetVersion = staticmethod(_ivaria.iODEHingeJoint_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iODEHingeJoint
__del__ = lambda self : None;
iODEHingeJoint_swigregister = _ivaria.iODEHingeJoint_swigregister
iODEHingeJoint_swigregister(iODEHingeJoint)
iODEHingeJoint_scfGetVersion = _ivaria.iODEHingeJoint_scfGetVersion
class iODEBallJoint(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def SetBallAnchor(*args): return _ivaria.iODEBallJoint_SetBallAnchor(*args)
def GetBallAnchor1(*args): return _ivaria.iODEBallJoint_GetBallAnchor1(*args)
def GetBallAnchor2(*args): return _ivaria.iODEBallJoint_GetBallAnchor2(*args)
def GetAnchorError(*args): return _ivaria.iODEBallJoint_GetAnchorError(*args)
def Attach(*args): return _ivaria.iODEBallJoint_Attach(*args)
def GetAttachedBody(*args): return _ivaria.iODEBallJoint_GetAttachedBody(*args)
def GetFeedbackForce1(*args): return _ivaria.iODEBallJoint_GetFeedbackForce1(*args)
def GetFeedbackTorque1(*args): return _ivaria.iODEBallJoint_GetFeedbackTorque1(*args)
def GetFeedbackForce2(*args): return _ivaria.iODEBallJoint_GetFeedbackForce2(*args)
def GetFeedbackTorque2(*args): return _ivaria.iODEBallJoint_GetFeedbackTorque2(*args)
scfGetVersion = staticmethod(_ivaria.iODEBallJoint_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iODEBallJoint
__del__ = lambda self : None;
iODEBallJoint_swigregister = _ivaria.iODEBallJoint_swigregister
iODEBallJoint_swigregister(iODEBallJoint)
iODEBallJoint_scfGetVersion = _ivaria.iODEBallJoint_scfGetVersion
CS_SEQUENCE_LIGHTCHANGE_NONE = _ivaria.CS_SEQUENCE_LIGHTCHANGE_NONE
CS_SEQUENCE_LIGHTCHANGE_LESS = _ivaria.CS_SEQUENCE_LIGHTCHANGE_LESS
CS_SEQUENCE_LIGHTCHANGE_GREATER = _ivaria.CS_SEQUENCE_LIGHTCHANGE_GREATER
class iParameterESM(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def GetValue(*args): return _ivaria.iParameterESM_GetValue(*args)
def IsConstant(*args): return _ivaria.iParameterESM_IsConstant(*args)
__swig_destroy__ = _ivaria.delete_iParameterESM
__del__ = lambda self : None;
iParameterESM_swigregister = _ivaria.iParameterESM_swigregister
iParameterESM_swigregister(iParameterESM)
class iEngineSequenceParameters(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def GetParameterCount(*args): return _ivaria.iEngineSequenceParameters_GetParameterCount(*args)
def GetParameter(*args): return _ivaria.iEngineSequenceParameters_GetParameter(*args)
def GetParameterIdx(*args): return _ivaria.iEngineSequenceParameters_GetParameterIdx(*args)
def GetParameterName(*args): return _ivaria.iEngineSequenceParameters_GetParameterName(*args)
def AddParameter(*args): return _ivaria.iEngineSequenceParameters_AddParameter(*args)
def SetParameter(*args): return _ivaria.iEngineSequenceParameters_SetParameter(*args)
def CreateParameterESM(*args): return _ivaria.iEngineSequenceParameters_CreateParameterESM(*args)
__swig_destroy__ = _ivaria.delete_iEngineSequenceParameters
__del__ = lambda self : None;
iEngineSequenceParameters_swigregister = _ivaria.iEngineSequenceParameters_swigregister
iEngineSequenceParameters_swigregister(iEngineSequenceParameters)
class iSequenceWrapper(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def QueryObject(*args): return _ivaria.iSequenceWrapper_QueryObject(*args)
def GetSequence(*args): return _ivaria.iSequenceWrapper_GetSequence(*args)
def CreateBaseParameterBlock(*args): return _ivaria.iSequenceWrapper_CreateBaseParameterBlock(*args)
def GetBaseParameterBlock(*args): return _ivaria.iSequenceWrapper_GetBaseParameterBlock(*args)
def CreateParameterBlock(*args): return _ivaria.iSequenceWrapper_CreateParameterBlock(*args)
def AddOperationSetVariable(*args): return _ivaria.iSequenceWrapper_AddOperationSetVariable(*args)
def AddOperationSetMaterial(*args): return _ivaria.iSequenceWrapper_AddOperationSetMaterial(*args)
def AddOperationSetLight(*args): return _ivaria.iSequenceWrapper_AddOperationSetLight(*args)
def AddOperationFadeLight(*args): return _ivaria.iSequenceWrapper_AddOperationFadeLight(*args)
def AddOperationSetAmbient(*args): return _ivaria.iSequenceWrapper_AddOperationSetAmbient(*args)
def AddOperationFadeAmbient(*args): return _ivaria.iSequenceWrapper_AddOperationFadeAmbient(*args)
def AddOperationRandomDelay(*args): return _ivaria.iSequenceWrapper_AddOperationRandomDelay(*args)
def AddOperationSetMeshColor(*args): return _ivaria.iSequenceWrapper_AddOperationSetMeshColor(*args)
def AddOperationFadeMeshColor(*args): return _ivaria.iSequenceWrapper_AddOperationFadeMeshColor(*args)
def AddOperationSetFog(*args): return _ivaria.iSequenceWrapper_AddOperationSetFog(*args)
def AddOperationFadeFog(*args): return _ivaria.iSequenceWrapper_AddOperationFadeFog(*args)
def AddOperationRotateDuration(*args): return _ivaria.iSequenceWrapper_AddOperationRotateDuration(*args)
def AddOperationMoveDuration(*args): return _ivaria.iSequenceWrapper_AddOperationMoveDuration(*args)
def AddOperationTriggerState(*args): return _ivaria.iSequenceWrapper_AddOperationTriggerState(*args)
def AddOperationCheckTrigger(*args): return _ivaria.iSequenceWrapper_AddOperationCheckTrigger(*args)
def AddOperationTestTrigger(*args): return _ivaria.iSequenceWrapper_AddOperationTestTrigger(*args)
__swig_destroy__ = _ivaria.delete_iSequenceWrapper
__del__ = lambda self : None;
iSequenceWrapper_swigregister = _ivaria.iSequenceWrapper_swigregister
iSequenceWrapper_swigregister(iSequenceWrapper)
class iSequenceTrigger(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def QueryObject(*args): return _ivaria.iSequenceTrigger_QueryObject(*args)
def AddConditionInSector(*args): return _ivaria.iSequenceTrigger_AddConditionInSector(*args)
def AddConditionSectorVisible(*args): return _ivaria.iSequenceTrigger_AddConditionSectorVisible(*args)
def AddConditionMeshClick(*args): return _ivaria.iSequenceTrigger_AddConditionMeshClick(*args)
def AddConditionLightChange(*args): return _ivaria.iSequenceTrigger_AddConditionLightChange(*args)
def AddConditionManual(*args): return _ivaria.iSequenceTrigger_AddConditionManual(*args)
def SetEnabled(*args): return _ivaria.iSequenceTrigger_SetEnabled(*args)
def IsEnabled(*args): return _ivaria.iSequenceTrigger_IsEnabled(*args)
def ClearConditions(*args): return _ivaria.iSequenceTrigger_ClearConditions(*args)
def Trigger(*args): return _ivaria.iSequenceTrigger_Trigger(*args)
def SetParameters(*args): return _ivaria.iSequenceTrigger_SetParameters(*args)
def GetParameters(*args): return _ivaria.iSequenceTrigger_GetParameters(*args)
def FireSequence(*args): return _ivaria.iSequenceTrigger_FireSequence(*args)
def GetFiredSequence(*args): return _ivaria.iSequenceTrigger_GetFiredSequence(*args)
def TestConditions(*args): return _ivaria.iSequenceTrigger_TestConditions(*args)
def CheckState(*args): return _ivaria.iSequenceTrigger_CheckState(*args)
def ForceFire(*args): return _ivaria.iSequenceTrigger_ForceFire(*args)
__swig_destroy__ = _ivaria.delete_iSequenceTrigger
__del__ = lambda self : None;
iSequenceTrigger_swigregister = _ivaria.iSequenceTrigger_swigregister
iSequenceTrigger_swigregister(iSequenceTrigger)
class iSequenceTimedOperation(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def Do(*args): return _ivaria.iSequenceTimedOperation_Do(*args)
__swig_destroy__ = _ivaria.delete_iSequenceTimedOperation
__del__ = lambda self : None;
iSequenceTimedOperation_swigregister = _ivaria.iSequenceTimedOperation_swigregister
iSequenceTimedOperation_swigregister(iSequenceTimedOperation)
class iEngineSequenceManager(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def GetSequenceManager(*args): return _ivaria.iEngineSequenceManager_GetSequenceManager(*args)
def CreateParameterESM(*args): return _ivaria.iEngineSequenceManager_CreateParameterESM(*args)
def CreateTrigger(*args): return _ivaria.iEngineSequenceManager_CreateTrigger(*args)
def RemoveTrigger(*args): return _ivaria.iEngineSequenceManager_RemoveTrigger(*args)
def RemoveTriggers(*args): return _ivaria.iEngineSequenceManager_RemoveTriggers(*args)
def GetTriggerCount(*args): return _ivaria.iEngineSequenceManager_GetTriggerCount(*args)
def GetTrigger(*args): return _ivaria.iEngineSequenceManager_GetTrigger(*args)
def FindTriggerByName(*args): return _ivaria.iEngineSequenceManager_FindTriggerByName(*args)
def FireTriggerByName(*args): return _ivaria.iEngineSequenceManager_FireTriggerByName(*args)
def CreateSequence(*args): return _ivaria.iEngineSequenceManager_CreateSequence(*args)
def RemoveSequence(*args): return _ivaria.iEngineSequenceManager_RemoveSequence(*args)
def RemoveSequences(*args): return _ivaria.iEngineSequenceManager_RemoveSequences(*args)
def GetSequenceCount(*args): return _ivaria.iEngineSequenceManager_GetSequenceCount(*args)
def GetSequence(*args): return _ivaria.iEngineSequenceManager_GetSequence(*args)
def FindSequenceByName(*args): return _ivaria.iEngineSequenceManager_FindSequenceByName(*args)
def RunSequenceByName(*args): return _ivaria.iEngineSequenceManager_RunSequenceByName(*args)
def FireTimedOperation(*args): return _ivaria.iEngineSequenceManager_FireTimedOperation(*args)
def DestroyTimedOperations(*args): return _ivaria.iEngineSequenceManager_DestroyTimedOperations(*args)
scfGetVersion = staticmethod(_ivaria.iEngineSequenceManager_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iEngineSequenceManager
__del__ = lambda self : None;
iEngineSequenceManager_swigregister = _ivaria.iEngineSequenceManager_swigregister
iEngineSequenceManager_swigregister(iEngineSequenceManager)
iEngineSequenceManager_scfGetVersion = _ivaria.iEngineSequenceManager_scfGetVersion
class iMovieRecorder(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def Start(*args): return _ivaria.iMovieRecorder_Start(*args)
def Stop(*args): return _ivaria.iMovieRecorder_Stop(*args)
def IsRecording(*args): return _ivaria.iMovieRecorder_IsRecording(*args)
def Pause(*args): return _ivaria.iMovieRecorder_Pause(*args)
def UnPause(*args): return _ivaria.iMovieRecorder_UnPause(*args)
def IsPaused(*args): return _ivaria.iMovieRecorder_IsPaused(*args)
def SetRecordingFile(*args): return _ivaria.iMovieRecorder_SetRecordingFile(*args)
def SetFilenameFormat(*args): return _ivaria.iMovieRecorder_SetFilenameFormat(*args)
scfGetVersion = staticmethod(_ivaria.iMovieRecorder_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iMovieRecorder
__del__ = lambda self : None;
iMovieRecorder_swigregister = _ivaria.iMovieRecorder_swigregister
iMovieRecorder_swigregister(iMovieRecorder)
iMovieRecorder_scfGetVersion = _ivaria.iMovieRecorder_scfGetVersion
class iMapNode(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def QueryObject(*args): return _ivaria.iMapNode_QueryObject(*args)
def SetPosition(*args): return _ivaria.iMapNode_SetPosition(*args)
def GetPosition(*args): return _ivaria.iMapNode_GetPosition(*args)
def SetXVector(*args): return _ivaria.iMapNode_SetXVector(*args)
def GetXVector(*args): return _ivaria.iMapNode_GetXVector(*args)
def SetYVector(*args): return _ivaria.iMapNode_SetYVector(*args)
def GetYVector(*args): return _ivaria.iMapNode_GetYVector(*args)
def SetZVector(*args): return _ivaria.iMapNode_SetZVector(*args)
def GetZVector(*args): return _ivaria.iMapNode_GetZVector(*args)
def SetSector(*args): return _ivaria.iMapNode_SetSector(*args)
def GetSector(*args): return _ivaria.iMapNode_GetSector(*args)
scfGetVersion = staticmethod(_ivaria.iMapNode_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iMapNode
__del__ = lambda self : None;
iMapNode_swigregister = _ivaria.iMapNode_swigregister
iMapNode_swigregister(iMapNode)
iMapNode_scfGetVersion = _ivaria.iMapNode_scfGetVersion
class iSequenceOperation(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def Do(*args): return _ivaria.iSequenceOperation_Do(*args)
def CleanupSequences(*args): return _ivaria.iSequenceOperation_CleanupSequences(*args)
scfGetVersion = staticmethod(_ivaria.iSequenceOperation_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iSequenceOperation
__del__ = lambda self : None;
iSequenceOperation_swigregister = _ivaria.iSequenceOperation_swigregister
iSequenceOperation_swigregister(iSequenceOperation)
iSequenceOperation_scfGetVersion = _ivaria.iSequenceOperation_scfGetVersion
class iSequenceCondition(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def Condition(*args): return _ivaria.iSequenceCondition_Condition(*args)
scfGetVersion = staticmethod(_ivaria.iSequenceCondition_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iSequenceCondition
__del__ = lambda self : None;
iSequenceCondition_swigregister = _ivaria.iSequenceCondition_swigregister
iSequenceCondition_swigregister(iSequenceCondition)
iSequenceCondition_scfGetVersion = _ivaria.iSequenceCondition_scfGetVersion
class csSequenceOp(object):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
next = _swig_property(_ivaria.csSequenceOp_next_get, _ivaria.csSequenceOp_next_set)
prev = _swig_property(_ivaria.csSequenceOp_prev_get, _ivaria.csSequenceOp_prev_set)
time = _swig_property(_ivaria.csSequenceOp_time_get, _ivaria.csSequenceOp_time_set)
params = _swig_property(_ivaria.csSequenceOp_params_get, _ivaria.csSequenceOp_params_set)
operation = _swig_property(_ivaria.csSequenceOp_operation_get, _ivaria.csSequenceOp_operation_set)
sequence_id = _swig_property(_ivaria.csSequenceOp_sequence_id_get, _ivaria.csSequenceOp_sequence_id_set)
def __init__(self, *args):
this = _ivaria.new_csSequenceOp(*args)
try: self.this.append(this)
except: self.this = this
__swig_destroy__ = _ivaria.delete_csSequenceOp
__del__ = lambda self : None;
csSequenceOp_swigregister = _ivaria.csSequenceOp_swigregister
csSequenceOp_swigregister(csSequenceOp)
class iSequence(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def GetFirstSequence(*args): return _ivaria.iSequence_GetFirstSequence(*args)
def AddOperation(*args): return _ivaria.iSequence_AddOperation(*args)
def AddRunSequence(*args): return _ivaria.iSequence_AddRunSequence(*args)
def AddCondition(*args): return _ivaria.iSequence_AddCondition(*args)
def AddLoop(*args): return _ivaria.iSequence_AddLoop(*args)
def Clear(*args): return _ivaria.iSequence_Clear(*args)
def IsEmpty(*args): return _ivaria.iSequence_IsEmpty(*args)
scfGetVersion = staticmethod(_ivaria.iSequence_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iSequence
__del__ = lambda self : None;
iSequence_swigregister = _ivaria.iSequence_swigregister
iSequence_swigregister(iSequence)
iSequence_scfGetVersion = _ivaria.iSequence_scfGetVersion
class iSequenceManager(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def Clear(*args): return _ivaria.iSequenceManager_Clear(*args)
def IsEmpty(*args): return _ivaria.iSequenceManager_IsEmpty(*args)
def Suspend(*args): return _ivaria.iSequenceManager_Suspend(*args)
def Resume(*args): return _ivaria.iSequenceManager_Resume(*args)
def IsSuspended(*args): return _ivaria.iSequenceManager_IsSuspended(*args)
def TimeWarp(*args): return _ivaria.iSequenceManager_TimeWarp(*args)
def GetMainTime(*args): return _ivaria.iSequenceManager_GetMainTime(*args)
def GetDeltaTime(*args): return _ivaria.iSequenceManager_GetDeltaTime(*args)
def NewSequence(*args): return _ivaria.iSequenceManager_NewSequence(*args)
def RunSequence(*args): return _ivaria.iSequenceManager_RunSequence(*args)
def DestroySequenceOperations(*args): return _ivaria.iSequenceManager_DestroySequenceOperations(*args)
def GetUniqueID(*args): return _ivaria.iSequenceManager_GetUniqueID(*args)
scfGetVersion = staticmethod(_ivaria.iSequenceManager_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iSequenceManager
__del__ = lambda self : None;
iSequenceManager_swigregister = _ivaria.iSequenceManager_swigregister
iSequenceManager_swigregister(iSequenceManager)
iSequenceManager_scfGetVersion = _ivaria.iSequenceManager_scfGetVersion
class iScriptValue(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
tInt = _ivaria.iScriptValue_tInt
tFloat = _ivaria.iScriptValue_tFloat
tDouble = _ivaria.iScriptValue_tDouble
tString = _ivaria.iScriptValue_tString
tBool = _ivaria.iScriptValue_tBool
tObject = _ivaria.iScriptValue_tObject
def GetScript(*args): return _ivaria.iScriptValue_GetScript(*args)
def GetTypes(*args): return _ivaria.iScriptValue_GetTypes(*args)
def GetInt(*args): return _ivaria.iScriptValue_GetInt(*args)
def GetFloat(*args): return _ivaria.iScriptValue_GetFloat(*args)
def GetDouble(*args): return _ivaria.iScriptValue_GetDouble(*args)
def GetString(*args): return _ivaria.iScriptValue_GetString(*args)
def GetBool(*args): return _ivaria.iScriptValue_GetBool(*args)
def GetObject(*args): return _ivaria.iScriptValue_GetObject(*args)
__swig_destroy__ = _ivaria.delete_iScriptValue
__del__ = lambda self : None;
iScriptValue_swigregister = _ivaria.iScriptValue_swigregister
iScriptValue_swigregister(iScriptValue)
class iScriptObject(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def GetScript(*args): return _ivaria.iScriptObject_GetScript(*args)
def GetClass(*args): return _ivaria.iScriptObject_GetClass(*args)
def IsA(*args): return _ivaria.iScriptObject_IsA(*args)
def IsType(*args): return _ivaria.iScriptObject_IsType(*args)
def GetPointer(*args): return _ivaria.iScriptObject_GetPointer(*args)
def SetPointer(*args): return _ivaria.iScriptObject_SetPointer(*args)
def Call(*args): return _ivaria.iScriptObject_Call(*args)
def SetFloat(*args): return _ivaria.iScriptObject_SetFloat(*args)
def Set(*args): return _ivaria.iScriptObject_Set(*args)
def SetTruth(*args): return _ivaria.iScriptObject_SetTruth(*args)
def GetFloat(*args): return _ivaria.iScriptObject_GetFloat(*args)
def Get(*args): return _ivaria.iScriptObject_Get(*args)
def GetTruth(*args): return _ivaria.iScriptObject_GetTruth(*args)
scfGetVersion = staticmethod(_ivaria.iScriptObject_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iScriptObject
__del__ = lambda self : None;
iScriptObject_swigregister = _ivaria.iScriptObject_swigregister
iScriptObject_swigregister(iScriptObject)
iScriptObject_scfGetVersion = _ivaria.iScriptObject_scfGetVersion
class iScript(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def RunText(*args): return _ivaria.iScript_RunText(*args)
def LoadModule(*args): return _ivaria.iScript_LoadModule(*args)
def LoadModuleNative(*args): return _ivaria.iScript_LoadModuleNative(*args)
def Call(*args): return _ivaria.iScript_Call(*args)
def RValue(*args): return _ivaria.iScript_RValue(*args)
def New(*args): return _ivaria.iScript_New(*args)
def Store(*args): return _ivaria.iScript_Store(*args)
def Remove(*args): return _ivaria.iScript_Remove(*args)
def NewObject(*args): return _ivaria.iScript_NewObject(*args)
def RetrieveFloat(*args): return _ivaria.iScript_RetrieveFloat(*args)
def Retrieve(*args): return _ivaria.iScript_Retrieve(*args)
def GetTruth(*args): return _ivaria.iScript_GetTruth(*args)
scfGetVersion = staticmethod(_ivaria.iScript_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iScript
__del__ = lambda self : None;
iScript_swigregister = _ivaria.iScript_swigregister
iScript_swigregister(iScript)
iScript_scfGetVersion = _ivaria.iScript_scfGetVersion
class iSimpleFormerState(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def SetHeightmap(*args): return _ivaria.iSimpleFormerState_SetHeightmap(*args)
def SetScale(*args): return _ivaria.iSimpleFormerState_SetScale(*args)
def SetOffset(*args): return _ivaria.iSimpleFormerState_SetOffset(*args)
def SetIntegerMap(*args): return _ivaria.iSimpleFormerState_SetIntegerMap(*args)
def SetFloatMap(*args): return _ivaria.iSimpleFormerState_SetFloatMap(*args)
def GetFloatMap(*args): return _ivaria.iSimpleFormerState_GetFloatMap(*args)
def SetMaterialScale(*args): return _ivaria.iSimpleFormerState_SetMaterialScale(*args)
scfGetVersion = staticmethod(_ivaria.iSimpleFormerState_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iSimpleFormerState
__del__ = lambda self : None;
iSimpleFormerState_swigregister = _ivaria.iSimpleFormerState_swigregister
iSimpleFormerState_swigregister(iSimpleFormerState)
iSimpleFormerState_scfGetVersion = _ivaria.iSimpleFormerState_scfGetVersion
class iTerraFormer(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def GetSampler(*args): return _ivaria.iTerraFormer_GetSampler(*args)
def GetIntegerMapSize(*args): return _ivaria.iTerraFormer_GetIntegerMapSize(*args)
def SampleFloat(*args): return _ivaria.iTerraFormer_SampleFloat(*args)
def SampleVector2(*args): return _ivaria.iTerraFormer_SampleVector2(*args)
def SampleVector3(*args): return _ivaria.iTerraFormer_SampleVector3(*args)
def SampleInteger(*args): return _ivaria.iTerraFormer_SampleInteger(*args)
def QueryObject(*args): return _ivaria.iTerraFormer_QueryObject(*args)
scfGetVersion = staticmethod(_ivaria.iTerraFormer_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iTerraFormer
__del__ = lambda self : None;
iTerraFormer_swigregister = _ivaria.iTerraFormer_swigregister
iTerraFormer_swigregister(iTerraFormer)
iTerraFormer_scfGetVersion = _ivaria.iTerraFormer_scfGetVersion
class iTerraSampler(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def SampleFloat(*args): return _ivaria.iTerraSampler_SampleFloat(*args)
def SampleVector2(*args): return _ivaria.iTerraSampler_SampleVector2(*args)
def SampleVector3(*args): return _ivaria.iTerraSampler_SampleVector3(*args)
def SampleInteger(*args): return _ivaria.iTerraSampler_SampleInteger(*args)
def GetMaterialPalette(*args): return _ivaria.iTerraSampler_GetMaterialPalette(*args)
def GetRegion(*args): return _ivaria.iTerraSampler_GetRegion(*args)
def GetResolution(*args): return _ivaria.iTerraSampler_GetResolution(*args)
def GetVersion(*args): return _ivaria.iTerraSampler_GetVersion(*args)
def Cleanup(*args): return _ivaria.iTerraSampler_Cleanup(*args)
scfGetVersion = staticmethod(_ivaria.iTerraSampler_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iTerraSampler
__del__ = lambda self : None;
iTerraSampler_swigregister = _ivaria.iTerraSampler_swigregister
iTerraSampler_swigregister(iTerraSampler)
iTerraSampler_scfGetVersion = _ivaria.iTerraSampler_scfGetVersion
class iTranslator(core.iBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError, "No constructor defined"
__repr__ = _swig_repr
def GetMsg(*args): return _ivaria.iTranslator_GetMsg(*args)
scfGetVersion = staticmethod(_ivaria.iTranslator_scfGetVersion)
__swig_destroy__ = _ivaria.delete_iTranslator
__del__ = lambda self : None;
iTranslator_swigregister = _ivaria.iTranslator_swigregister
iTranslator_swigregister(iTranslator)
iTranslator_scfGetVersion = _ivaria.iTranslator_scfGetVersion
def CS_REQUEST_REPORTERLISTENER ():
return core.CS_REQUEST_PLUGIN("crystalspace.utilities.stdrep",
iStandardReporterListener)
def CS_REQUEST_CONSOLEOUT ():
return core.CS_REQUEST_PLUGIN("crystalspace.console.output.standard",
iConsoleOutput)
|
dimagol/trex-core
|
refs/heads/master
|
scripts/automation/trex_control_plane/astf/trex_astf_lib/__init__.py
|
2
|
import sys
if sys.version_info < (2, 7):
print("\n**** TRex ASTF package requires Python version >= 2.7 ***\n")
exit(-1)
from . import trex_stl_ext
|
Deepakkothandan/ansible
|
refs/heads/devel
|
lib/ansible/modules/cloud/docker/docker_volume.py
|
26
|
#!/usr/bin/python
# coding: utf-8
#
# Copyright 2017 Red Hat | Ansible, Alex Grönholm <alex.gronholm@nextday.fi>
# 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 = u'''
module: docker_volume
version_added: "2.4"
short_description: Manage Docker volumes
description:
- Create/remove Docker volumes.
- Performs largely the same function as the "docker volume" CLI subcommand.
options:
name:
description:
- Name of the volume to operate on.
required: true
aliases:
- volume_name
driver:
description:
- Specify the type of volume. Docker provides the C(local) driver, but 3rd party drivers can also be used.
default: local
driver_options:
description:
- "Dictionary of volume settings. Consult docker docs for valid options and values:
U(https://docs.docker.com/engine/reference/commandline/volume_create/#driver-specific-options)"
labels:
description:
- List of labels to set for the volume
force:
description:
- With state C(present) causes the volume to be deleted and recreated if the volume already
exist and the driver, driver options or labels differ. This will cause any data in the existing
volume to be lost.
type: bool
default: 'no'
state:
description:
- C(absent) deletes the volume.
- C(present) creates the volume, if it does not already exist.
default: present
choices:
- absent
- present
extends_documentation_fragment:
- docker
author:
- Alex Grönholm (@agronholm)
requirements:
- "python >= 2.6"
- "docker-py >= 1.10.0"
- "The docker server >= 1.9.0"
'''
EXAMPLES = '''
- name: Create a volume
docker_volume:
name: volume_one
- name: Remove a volume
docker_volume:
name: volume_one
state: absent
- name: Create a volume with options
docker_volume:
name: volume_two
driver_options:
type: btrfs
device: /dev/sda2
'''
RETURN = '''
facts:
description: Volume inspection results for the affected volume.
returned: success
type: dict
sample: {}
'''
try:
from docker.errors import APIError
except ImportError:
# missing docker-py handled in ansible.module_utils.docker
pass
from ansible.module_utils.docker_common import DockerBaseClass, AnsibleDockerClient
from ansible.module_utils.six import iteritems, text_type
class TaskParameters(DockerBaseClass):
def __init__(self, client):
super(TaskParameters, self).__init__()
self.client = client
self.volume_name = None
self.driver = None
self.driver_options = None
self.labels = None
self.force = None
self.debug = None
for key, value in iteritems(client.module.params):
setattr(self, key, value)
class DockerVolumeManager(object):
def __init__(self, client):
self.client = client
self.parameters = TaskParameters(client)
self.check_mode = self.client.check_mode
self.results = {
u'changed': False,
u'actions': []
}
self.diff = self.client.module._diff
self.existing_volume = self.get_existing_volume()
state = self.parameters.state
if state == 'present':
self.present()
elif state == 'absent':
self.absent()
def get_existing_volume(self):
try:
volumes = self.client.volumes()
except APIError as e:
self.client.fail(text_type(e))
for volume in volumes[u'Volumes']:
if volume['Name'] == self.parameters.volume_name:
return volume
return None
def has_different_config(self):
"""
Return the list of differences between the current parameters and the existing volume.
:return: list of options that differ
"""
differences = []
if self.parameters.driver and self.parameters.driver != self.existing_volume['Driver']:
differences.append('driver')
if self.parameters.driver_options:
if not self.existing_volume.get('Options'):
differences.append('driver_options')
else:
for key, value in iteritems(self.parameters.driver_options):
if (not self.existing_volume['Options'].get(key) or
value != self.existing_volume['Options'][key]):
differences.append('driver_options.%s' % key)
if self.parameters.labels:
existing_labels = self.existing_volume.get('Labels', {})
all_labels = set(self.parameters.labels) | set(existing_labels)
for label in all_labels:
if existing_labels.get(label) != self.parameters.labels.get(label):
differences.append('labels.%s' % label)
return differences
def create_volume(self):
if not self.existing_volume:
if not self.check_mode:
try:
resp = self.client.create_volume(self.parameters.volume_name,
driver=self.parameters.driver,
driver_opts=self.parameters.driver_options,
labels=self.parameters.labels)
self.existing_volume = self.client.inspect_volume(resp['Name'])
except APIError as e:
self.client.fail(text_type(e))
self.results['actions'].append("Created volume %s with driver %s" % (self.parameters.volume_name, self.parameters.driver))
self.results['changed'] = True
def remove_volume(self):
if self.existing_volume:
if not self.check_mode:
try:
self.client.remove_volume(self.parameters.volume_name)
except APIError as e:
self.client.fail(text_type(e))
self.results['actions'].append("Removed volume %s" % self.parameters.volume_name)
self.results['changed'] = True
def present(self):
differences = []
if self.existing_volume:
differences = self.has_different_config()
if differences and self.parameters.force:
self.remove_volume()
self.existing_volume = None
self.create_volume()
if self.diff or self.check_mode or self.parameters.debug:
self.results['diff'] = differences
if not self.check_mode and not self.parameters.debug:
self.results.pop('actions')
self.results['ansible_facts'] = {u'docker_volume': self.get_existing_volume()}
def absent(self):
self.remove_volume()
def main():
argument_spec = dict(
volume_name=dict(type='str', required=True, aliases=['name']),
state=dict(type='str', default='present', choices=['present', 'absent']),
driver=dict(type='str', default='local'),
driver_options=dict(type='dict', default={}),
labels=dict(type='list'),
force=dict(type='bool', default=False),
debug=dict(type='bool', default=False)
)
client = AnsibleDockerClient(
argument_spec=argument_spec,
supports_check_mode=True
)
cm = DockerVolumeManager(client)
client.module.exit_json(**cm.results)
if __name__ == '__main__':
main()
|
fernandog/Sick-Beard
|
refs/heads/ThePirateBay
|
lib/unidecode/x0bd.py
|
253
|
data = (
'bols', # 0x00
'bolt', # 0x01
'bolp', # 0x02
'bolh', # 0x03
'bom', # 0x04
'bob', # 0x05
'bobs', # 0x06
'bos', # 0x07
'boss', # 0x08
'bong', # 0x09
'boj', # 0x0a
'boc', # 0x0b
'bok', # 0x0c
'bot', # 0x0d
'bop', # 0x0e
'boh', # 0x0f
'bwa', # 0x10
'bwag', # 0x11
'bwagg', # 0x12
'bwags', # 0x13
'bwan', # 0x14
'bwanj', # 0x15
'bwanh', # 0x16
'bwad', # 0x17
'bwal', # 0x18
'bwalg', # 0x19
'bwalm', # 0x1a
'bwalb', # 0x1b
'bwals', # 0x1c
'bwalt', # 0x1d
'bwalp', # 0x1e
'bwalh', # 0x1f
'bwam', # 0x20
'bwab', # 0x21
'bwabs', # 0x22
'bwas', # 0x23
'bwass', # 0x24
'bwang', # 0x25
'bwaj', # 0x26
'bwac', # 0x27
'bwak', # 0x28
'bwat', # 0x29
'bwap', # 0x2a
'bwah', # 0x2b
'bwae', # 0x2c
'bwaeg', # 0x2d
'bwaegg', # 0x2e
'bwaegs', # 0x2f
'bwaen', # 0x30
'bwaenj', # 0x31
'bwaenh', # 0x32
'bwaed', # 0x33
'bwael', # 0x34
'bwaelg', # 0x35
'bwaelm', # 0x36
'bwaelb', # 0x37
'bwaels', # 0x38
'bwaelt', # 0x39
'bwaelp', # 0x3a
'bwaelh', # 0x3b
'bwaem', # 0x3c
'bwaeb', # 0x3d
'bwaebs', # 0x3e
'bwaes', # 0x3f
'bwaess', # 0x40
'bwaeng', # 0x41
'bwaej', # 0x42
'bwaec', # 0x43
'bwaek', # 0x44
'bwaet', # 0x45
'bwaep', # 0x46
'bwaeh', # 0x47
'boe', # 0x48
'boeg', # 0x49
'boegg', # 0x4a
'boegs', # 0x4b
'boen', # 0x4c
'boenj', # 0x4d
'boenh', # 0x4e
'boed', # 0x4f
'boel', # 0x50
'boelg', # 0x51
'boelm', # 0x52
'boelb', # 0x53
'boels', # 0x54
'boelt', # 0x55
'boelp', # 0x56
'boelh', # 0x57
'boem', # 0x58
'boeb', # 0x59
'boebs', # 0x5a
'boes', # 0x5b
'boess', # 0x5c
'boeng', # 0x5d
'boej', # 0x5e
'boec', # 0x5f
'boek', # 0x60
'boet', # 0x61
'boep', # 0x62
'boeh', # 0x63
'byo', # 0x64
'byog', # 0x65
'byogg', # 0x66
'byogs', # 0x67
'byon', # 0x68
'byonj', # 0x69
'byonh', # 0x6a
'byod', # 0x6b
'byol', # 0x6c
'byolg', # 0x6d
'byolm', # 0x6e
'byolb', # 0x6f
'byols', # 0x70
'byolt', # 0x71
'byolp', # 0x72
'byolh', # 0x73
'byom', # 0x74
'byob', # 0x75
'byobs', # 0x76
'byos', # 0x77
'byoss', # 0x78
'byong', # 0x79
'byoj', # 0x7a
'byoc', # 0x7b
'byok', # 0x7c
'byot', # 0x7d
'byop', # 0x7e
'byoh', # 0x7f
'bu', # 0x80
'bug', # 0x81
'bugg', # 0x82
'bugs', # 0x83
'bun', # 0x84
'bunj', # 0x85
'bunh', # 0x86
'bud', # 0x87
'bul', # 0x88
'bulg', # 0x89
'bulm', # 0x8a
'bulb', # 0x8b
'buls', # 0x8c
'bult', # 0x8d
'bulp', # 0x8e
'bulh', # 0x8f
'bum', # 0x90
'bub', # 0x91
'bubs', # 0x92
'bus', # 0x93
'buss', # 0x94
'bung', # 0x95
'buj', # 0x96
'buc', # 0x97
'buk', # 0x98
'but', # 0x99
'bup', # 0x9a
'buh', # 0x9b
'bweo', # 0x9c
'bweog', # 0x9d
'bweogg', # 0x9e
'bweogs', # 0x9f
'bweon', # 0xa0
'bweonj', # 0xa1
'bweonh', # 0xa2
'bweod', # 0xa3
'bweol', # 0xa4
'bweolg', # 0xa5
'bweolm', # 0xa6
'bweolb', # 0xa7
'bweols', # 0xa8
'bweolt', # 0xa9
'bweolp', # 0xaa
'bweolh', # 0xab
'bweom', # 0xac
'bweob', # 0xad
'bweobs', # 0xae
'bweos', # 0xaf
'bweoss', # 0xb0
'bweong', # 0xb1
'bweoj', # 0xb2
'bweoc', # 0xb3
'bweok', # 0xb4
'bweot', # 0xb5
'bweop', # 0xb6
'bweoh', # 0xb7
'bwe', # 0xb8
'bweg', # 0xb9
'bwegg', # 0xba
'bwegs', # 0xbb
'bwen', # 0xbc
'bwenj', # 0xbd
'bwenh', # 0xbe
'bwed', # 0xbf
'bwel', # 0xc0
'bwelg', # 0xc1
'bwelm', # 0xc2
'bwelb', # 0xc3
'bwels', # 0xc4
'bwelt', # 0xc5
'bwelp', # 0xc6
'bwelh', # 0xc7
'bwem', # 0xc8
'bweb', # 0xc9
'bwebs', # 0xca
'bwes', # 0xcb
'bwess', # 0xcc
'bweng', # 0xcd
'bwej', # 0xce
'bwec', # 0xcf
'bwek', # 0xd0
'bwet', # 0xd1
'bwep', # 0xd2
'bweh', # 0xd3
'bwi', # 0xd4
'bwig', # 0xd5
'bwigg', # 0xd6
'bwigs', # 0xd7
'bwin', # 0xd8
'bwinj', # 0xd9
'bwinh', # 0xda
'bwid', # 0xdb
'bwil', # 0xdc
'bwilg', # 0xdd
'bwilm', # 0xde
'bwilb', # 0xdf
'bwils', # 0xe0
'bwilt', # 0xe1
'bwilp', # 0xe2
'bwilh', # 0xe3
'bwim', # 0xe4
'bwib', # 0xe5
'bwibs', # 0xe6
'bwis', # 0xe7
'bwiss', # 0xe8
'bwing', # 0xe9
'bwij', # 0xea
'bwic', # 0xeb
'bwik', # 0xec
'bwit', # 0xed
'bwip', # 0xee
'bwih', # 0xef
'byu', # 0xf0
'byug', # 0xf1
'byugg', # 0xf2
'byugs', # 0xf3
'byun', # 0xf4
'byunj', # 0xf5
'byunh', # 0xf6
'byud', # 0xf7
'byul', # 0xf8
'byulg', # 0xf9
'byulm', # 0xfa
'byulb', # 0xfb
'byuls', # 0xfc
'byult', # 0xfd
'byulp', # 0xfe
'byulh', # 0xff
)
|
sauloal/cnidaria
|
refs/heads/master
|
scripts/venv/lib/python2.7/site-packages/pandas/tseries/converter.py
|
13
|
from datetime import datetime, timedelta
import datetime as pydt
import numpy as np
from dateutil.relativedelta import relativedelta
import matplotlib.units as units
import matplotlib.dates as dates
from matplotlib.ticker import Formatter, AutoLocator, Locator
from matplotlib.transforms import nonsingular
from pandas.compat import lrange
import pandas.compat as compat
import pandas.lib as lib
import pandas.core.common as com
from pandas.core.index import Index
from pandas.core.series import Series
from pandas.tseries.index import date_range
import pandas.tseries.tools as tools
import pandas.tseries.frequencies as frequencies
from pandas.tseries.frequencies import FreqGroup
from pandas.tseries.period import Period, PeriodIndex
def register():
units.registry[lib.Timestamp] = DatetimeConverter()
units.registry[Period] = PeriodConverter()
units.registry[pydt.datetime] = DatetimeConverter()
units.registry[pydt.date] = DatetimeConverter()
units.registry[pydt.time] = TimeConverter()
units.registry[np.datetime64] = DatetimeConverter()
def _to_ordinalf(tm):
tot_sec = (tm.hour * 3600 + tm.minute * 60 + tm.second +
float(tm.microsecond / 1e6))
return tot_sec
def time2num(d):
if isinstance(d, compat.string_types):
parsed = tools.to_datetime(d)
if not isinstance(parsed, datetime):
raise ValueError('Could not parse time %s' % d)
return _to_ordinalf(parsed.time())
if isinstance(d, pydt.time):
return _to_ordinalf(d)
return d
class TimeConverter(units.ConversionInterface):
@staticmethod
def convert(value, unit, axis):
valid_types = (str, pydt.time)
if (isinstance(value, valid_types) or com.is_integer(value) or
com.is_float(value)):
return time2num(value)
if isinstance(value, Index):
return value.map(time2num)
if isinstance(value, (list, tuple, np.ndarray, Index)):
return [time2num(x) for x in value]
return value
@staticmethod
def axisinfo(unit, axis):
if unit != 'time':
return None
majloc = AutoLocator()
majfmt = TimeFormatter(majloc)
return units.AxisInfo(majloc=majloc, majfmt=majfmt, label='time')
@staticmethod
def default_units(x, axis):
return 'time'
### time formatter
class TimeFormatter(Formatter):
def __init__(self, locs):
self.locs = locs
def __call__(self, x, pos=0):
fmt = '%H:%M:%S'
s = int(x)
ms = int((x - s) * 1e3)
us = int((x - s) * 1e6 - ms)
m, s = divmod(s, 60)
h, m = divmod(m, 60)
_, h = divmod(h, 24)
if us != 0:
fmt += '.%6f'
elif ms != 0:
fmt += '.%3f'
return pydt.time(h, m, s, us).strftime(fmt)
### Period Conversion
class PeriodConverter(dates.DateConverter):
@staticmethod
def convert(values, units, axis):
if not hasattr(axis, 'freq'):
raise TypeError('Axis must have `freq` set to convert to Periods')
valid_types = (compat.string_types, datetime, Period, pydt.date, pydt.time)
if (isinstance(values, valid_types) or com.is_integer(values) or
com.is_float(values)):
return get_datevalue(values, axis.freq)
if isinstance(values, PeriodIndex):
return values.asfreq(axis.freq).values
if isinstance(values, Index):
return values.map(lambda x: get_datevalue(x, axis.freq))
if com.is_period_arraylike(values):
return PeriodIndex(values, freq=axis.freq).values
if isinstance(values, (list, tuple, np.ndarray, Index)):
return [get_datevalue(x, axis.freq) for x in values]
return values
def get_datevalue(date, freq):
if isinstance(date, Period):
return date.asfreq(freq).ordinal
elif isinstance(date, (compat.string_types, datetime, pydt.date, pydt.time)):
return Period(date, freq).ordinal
elif (com.is_integer(date) or com.is_float(date) or
(isinstance(date, (np.ndarray, Index)) and (date.size == 1))):
return date
elif date is None:
return None
raise ValueError("Unrecognizable date '%s'" % date)
HOURS_PER_DAY = 24.
MINUTES_PER_DAY = 60. * HOURS_PER_DAY
SECONDS_PER_DAY = 60. * MINUTES_PER_DAY
MUSECONDS_PER_DAY = 1e6 * SECONDS_PER_DAY
def _dt_to_float_ordinal(dt):
"""
Convert :mod:`datetime` to the Gregorian date as UTC float days,
preserving hours, minutes, seconds and microseconds. Return value
is a :func:`float`.
"""
if isinstance(dt, (np.ndarray, Index, Series)) and com.is_datetime64_ns_dtype(dt):
base = dates.epoch2num(dt.asi8 / 1.0E9)
else:
base = dates.date2num(dt)
return base
### Datetime Conversion
class DatetimeConverter(dates.DateConverter):
@staticmethod
def convert(values, unit, axis):
def try_parse(values):
try:
return _dt_to_float_ordinal(tools.to_datetime(values))
except Exception:
return values
if isinstance(values, (datetime, pydt.date)):
return _dt_to_float_ordinal(values)
elif isinstance(values, np.datetime64):
return _dt_to_float_ordinal(lib.Timestamp(values))
elif isinstance(values, pydt.time):
return dates.date2num(values)
elif (com.is_integer(values) or com.is_float(values)):
return values
elif isinstance(values, compat.string_types):
return try_parse(values)
elif isinstance(values, (list, tuple, np.ndarray, Index)):
if isinstance(values, Index):
values = values.values
if not isinstance(values, np.ndarray):
values = com._asarray_tuplesafe(values)
if com.is_integer_dtype(values) or com.is_float_dtype(values):
return values
try:
values = tools.to_datetime(values)
if isinstance(values, Index):
values = values.map(_dt_to_float_ordinal)
else:
values = [_dt_to_float_ordinal(x) for x in values]
except Exception:
pass
return values
@staticmethod
def axisinfo(unit, axis):
"""
Return the :class:`~matplotlib.units.AxisInfo` for *unit*.
*unit* is a tzinfo instance or None.
The *axis* argument is required but not used.
"""
tz = unit
majloc = PandasAutoDateLocator(tz=tz)
majfmt = PandasAutoDateFormatter(majloc, tz=tz)
datemin = pydt.date(2000, 1, 1)
datemax = pydt.date(2010, 1, 1)
return units.AxisInfo(majloc=majloc, majfmt=majfmt, label='',
default_limits=(datemin, datemax))
class PandasAutoDateFormatter(dates.AutoDateFormatter):
def __init__(self, locator, tz=None, defaultfmt='%Y-%m-%d'):
dates.AutoDateFormatter.__init__(self, locator, tz, defaultfmt)
# matplotlib.dates._UTC has no _utcoffset called by pandas
if self._tz is dates.UTC:
self._tz._utcoffset = self._tz.utcoffset(None)
self.scaled = {
365.0: '%Y',
30.: '%b %Y',
1.0: '%b %d %Y',
1. / 24.: '%H:%M:%S',
1. / 24. / 3600. / 1000.: '%H:%M:%S.%f'
}
def _get_fmt(self, x):
scale = float(self._locator._get_unit())
fmt = self.defaultfmt
for k in sorted(self.scaled):
if k >= scale:
fmt = self.scaled[k]
break
return fmt
def __call__(self, x, pos=0):
fmt = self._get_fmt(x)
self._formatter = dates.DateFormatter(fmt, self._tz)
return self._formatter(x, pos)
class PandasAutoDateLocator(dates.AutoDateLocator):
def get_locator(self, dmin, dmax):
'Pick the best locator based on a distance.'
delta = relativedelta(dmax, dmin)
num_days = ((delta.years * 12.0) + delta.months * 31.0) + delta.days
num_sec = (delta.hours * 60.0 + delta.minutes) * 60.0 + delta.seconds
tot_sec = num_days * 86400. + num_sec
if abs(tot_sec) < self.minticks:
self._freq = -1
locator = MilliSecondLocator(self.tz)
locator.set_axis(self.axis)
locator.set_view_interval(*self.axis.get_view_interval())
locator.set_data_interval(*self.axis.get_data_interval())
return locator
return dates.AutoDateLocator.get_locator(self, dmin, dmax)
def _get_unit(self):
return MilliSecondLocator.get_unit_generic(self._freq)
class MilliSecondLocator(dates.DateLocator):
UNIT = 1. / (24 * 3600 * 1000)
def __init__(self, tz):
dates.DateLocator.__init__(self, tz)
self._interval = 1.
def _get_unit(self):
return self.get_unit_generic(-1)
@staticmethod
def get_unit_generic(freq):
unit = dates.RRuleLocator.get_unit_generic(freq)
if unit < 0:
return MilliSecondLocator.UNIT
return unit
def __call__(self):
# if no data have been set, this will tank with a ValueError
try:
dmin, dmax = self.viewlim_to_dt()
except ValueError:
return []
if dmin > dmax:
dmax, dmin = dmin, dmax
delta = relativedelta(dmax, dmin)
# We need to cap at the endpoints of valid datetime
try:
start = dmin - delta
except ValueError:
start = _from_ordinal(1.0)
try:
stop = dmax + delta
except ValueError:
# The magic number!
stop = _from_ordinal(3652059.9999999)
nmax, nmin = dates.date2num((dmax, dmin))
num = (nmax - nmin) * 86400 * 1000
max_millis_ticks = 6
for interval in [1, 10, 50, 100, 200, 500]:
if num <= interval * (max_millis_ticks - 1):
self._interval = interval
break
else:
# We went through the whole loop without breaking, default to 1
self._interval = 1000.
estimate = (nmax - nmin) / (self._get_unit() * self._get_interval())
if estimate > self.MAXTICKS * 2:
raise RuntimeError(('MillisecondLocator estimated to generate %d '
'ticks from %s to %s: exceeds Locator.MAXTICKS'
'* 2 (%d) ') %
(estimate, dmin, dmax, self.MAXTICKS * 2))
freq = '%dL' % self._get_interval()
tz = self.tz.tzname(None)
st = _from_ordinal(dates.date2num(dmin)) # strip tz
ed = _from_ordinal(dates.date2num(dmax))
all_dates = date_range(start=st, end=ed, freq=freq, tz=tz).asobject
try:
if len(all_dates) > 0:
locs = self.raise_if_exceeds(dates.date2num(all_dates))
return locs
except Exception as e: # pragma: no cover
pass
lims = dates.date2num([dmin, dmax])
return lims
def _get_interval(self):
return self._interval
def autoscale(self):
"""
Set the view limits to include the data range.
"""
dmin, dmax = self.datalim_to_dt()
if dmin > dmax:
dmax, dmin = dmin, dmax
delta = relativedelta(dmax, dmin)
# We need to cap at the endpoints of valid datetime
try:
start = dmin - delta
except ValueError:
start = _from_ordinal(1.0)
try:
stop = dmax + delta
except ValueError:
# The magic number!
stop = _from_ordinal(3652059.9999999)
dmin, dmax = self.datalim_to_dt()
vmin = dates.date2num(dmin)
vmax = dates.date2num(dmax)
return self.nonsingular(vmin, vmax)
def _from_ordinal(x, tz=None):
ix = int(x)
dt = datetime.fromordinal(ix)
remainder = float(x) - ix
hour, remainder = divmod(24 * remainder, 1)
minute, remainder = divmod(60 * remainder, 1)
second, remainder = divmod(60 * remainder, 1)
microsecond = int(1e6 * remainder)
if microsecond < 10:
microsecond = 0 # compensate for rounding errors
dt = datetime(dt.year, dt.month, dt.day, int(hour), int(minute),
int(second), microsecond)
if tz is not None:
dt = dt.astimezone(tz)
if microsecond > 999990: # compensate for rounding errors
dt += timedelta(microseconds=1e6 - microsecond)
return dt
### Fixed frequency dynamic tick locators and formatters
##### -------------------------------------------------------------------------
#---- --- Locators ---
##### -------------------------------------------------------------------------
def _get_default_annual_spacing(nyears):
"""
Returns a default spacing between consecutive ticks for annual data.
"""
if nyears < 11:
(min_spacing, maj_spacing) = (1, 1)
elif nyears < 20:
(min_spacing, maj_spacing) = (1, 2)
elif nyears < 50:
(min_spacing, maj_spacing) = (1, 5)
elif nyears < 100:
(min_spacing, maj_spacing) = (5, 10)
elif nyears < 200:
(min_spacing, maj_spacing) = (5, 25)
elif nyears < 600:
(min_spacing, maj_spacing) = (10, 50)
else:
factor = nyears // 1000 + 1
(min_spacing, maj_spacing) = (factor * 20, factor * 100)
return (min_spacing, maj_spacing)
def period_break(dates, period):
"""
Returns the indices where the given period changes.
Parameters
----------
dates : PeriodIndex
Array of intervals to monitor.
period : string
Name of the period to monitor.
"""
current = getattr(dates, period)
previous = getattr(dates - 1, period)
return (current - previous).nonzero()[0]
def has_level_label(label_flags, vmin):
"""
Returns true if the ``label_flags`` indicate there is at least one label
for this level.
if the minimum view limit is not an exact integer, then the first tick
label won't be shown, so we must adjust for that.
"""
if label_flags.size == 0 or (label_flags.size == 1 and
label_flags[0] == 0 and
vmin % 1 > 0.0):
return False
else:
return True
def _daily_finder(vmin, vmax, freq):
periodsperday = -1
if freq >= FreqGroup.FR_HR:
if freq == FreqGroup.FR_NS:
periodsperday = 24 * 60 * 60 * 1000000000
elif freq == FreqGroup.FR_US:
periodsperday = 24 * 60 * 60 * 1000000
elif freq == FreqGroup.FR_MS:
periodsperday = 24 * 60 * 60 * 1000
elif freq == FreqGroup.FR_SEC:
periodsperday = 24 * 60 * 60
elif freq == FreqGroup.FR_MIN:
periodsperday = 24 * 60
elif freq == FreqGroup.FR_HR:
periodsperday = 24
else: # pragma: no cover
raise ValueError("unexpected frequency: %s" % freq)
periodsperyear = 365 * periodsperday
periodspermonth = 28 * periodsperday
elif freq == FreqGroup.FR_BUS:
periodsperyear = 261
periodspermonth = 19
elif freq == FreqGroup.FR_DAY:
periodsperyear = 365
periodspermonth = 28
elif frequencies.get_freq_group(freq) == FreqGroup.FR_WK:
periodsperyear = 52
periodspermonth = 3
else: # pragma: no cover
raise ValueError("unexpected frequency")
# save this for later usage
vmin_orig = vmin
(vmin, vmax) = (Period(ordinal=int(vmin), freq=freq),
Period(ordinal=int(vmax), freq=freq))
span = vmax.ordinal - vmin.ordinal + 1
dates_ = PeriodIndex(start=vmin, end=vmax, freq=freq)
# Initialize the output
info = np.zeros(span,
dtype=[('val', np.int64), ('maj', bool),
('min', bool), ('fmt', '|S20')])
info['val'][:] = dates_.values
info['fmt'][:] = ''
info['maj'][[0, -1]] = True
# .. and set some shortcuts
info_maj = info['maj']
info_min = info['min']
info_fmt = info['fmt']
def first_label(label_flags):
if (label_flags[0] == 0) and (label_flags.size > 1) and \
((vmin_orig % 1) > 0.0):
return label_flags[1]
else:
return label_flags[0]
# Case 1. Less than a month
if span <= periodspermonth:
day_start = period_break(dates_, 'day')
month_start = period_break(dates_, 'month')
def _hour_finder(label_interval, force_year_start):
_hour = dates_.hour
_prev_hour = (dates_ - 1).hour
hour_start = (_hour - _prev_hour) != 0
info_maj[day_start] = True
info_min[hour_start & (_hour % label_interval == 0)] = True
year_start = period_break(dates_, 'year')
info_fmt[hour_start & (_hour % label_interval == 0)] = '%H:%M'
info_fmt[day_start] = '%H:%M\n%d-%b'
info_fmt[year_start] = '%H:%M\n%d-%b\n%Y'
if force_year_start and not has_level_label(year_start, vmin_orig):
info_fmt[first_label(day_start)] = '%H:%M\n%d-%b\n%Y'
def _minute_finder(label_interval):
hour_start = period_break(dates_, 'hour')
_minute = dates_.minute
_prev_minute = (dates_ - 1).minute
minute_start = (_minute - _prev_minute) != 0
info_maj[hour_start] = True
info_min[minute_start & (_minute % label_interval == 0)] = True
year_start = period_break(dates_, 'year')
info_fmt = info['fmt']
info_fmt[minute_start & (_minute % label_interval == 0)] = '%H:%M'
info_fmt[day_start] = '%H:%M\n%d-%b'
info_fmt[year_start] = '%H:%M\n%d-%b\n%Y'
def _second_finder(label_interval):
minute_start = period_break(dates_, 'minute')
_second = dates_.second
_prev_second = (dates_ - 1).second
second_start = (_second - _prev_second) != 0
info['maj'][minute_start] = True
info['min'][second_start & (_second % label_interval == 0)] = True
year_start = period_break(dates_, 'year')
info_fmt = info['fmt']
info_fmt[second_start & (_second %
label_interval == 0)] = '%H:%M:%S'
info_fmt[day_start] = '%H:%M:%S\n%d-%b'
info_fmt[year_start] = '%H:%M:%S\n%d-%b\n%Y'
if span < periodsperday / 12000.0:
_second_finder(1)
elif span < periodsperday / 6000.0:
_second_finder(2)
elif span < periodsperday / 2400.0:
_second_finder(5)
elif span < periodsperday / 1200.0:
_second_finder(10)
elif span < periodsperday / 800.0:
_second_finder(15)
elif span < periodsperday / 400.0:
_second_finder(30)
elif span < periodsperday / 150.0:
_minute_finder(1)
elif span < periodsperday / 70.0:
_minute_finder(2)
elif span < periodsperday / 24.0:
_minute_finder(5)
elif span < periodsperday / 12.0:
_minute_finder(15)
elif span < periodsperday / 6.0:
_minute_finder(30)
elif span < periodsperday / 2.5:
_hour_finder(1, False)
elif span < periodsperday / 1.5:
_hour_finder(2, False)
elif span < periodsperday * 1.25:
_hour_finder(3, False)
elif span < periodsperday * 2.5:
_hour_finder(6, True)
elif span < periodsperday * 4:
_hour_finder(12, True)
else:
info_maj[month_start] = True
info_min[day_start] = True
year_start = period_break(dates_, 'year')
info_fmt = info['fmt']
info_fmt[day_start] = '%d'
info_fmt[month_start] = '%d\n%b'
info_fmt[year_start] = '%d\n%b\n%Y'
if not has_level_label(year_start, vmin_orig):
if not has_level_label(month_start, vmin_orig):
info_fmt[first_label(day_start)] = '%d\n%b\n%Y'
else:
info_fmt[first_label(month_start)] = '%d\n%b\n%Y'
# Case 2. Less than three months
elif span <= periodsperyear // 4:
month_start = period_break(dates_, 'month')
info_maj[month_start] = True
if freq < FreqGroup.FR_HR:
info['min'] = True
else:
day_start = period_break(dates_, 'day')
info['min'][day_start] = True
week_start = period_break(dates_, 'week')
year_start = period_break(dates_, 'year')
info_fmt[week_start] = '%d'
info_fmt[month_start] = '\n\n%b'
info_fmt[year_start] = '\n\n%b\n%Y'
if not has_level_label(year_start, vmin_orig):
if not has_level_label(month_start, vmin_orig):
info_fmt[first_label(week_start)] = '\n\n%b\n%Y'
else:
info_fmt[first_label(month_start)] = '\n\n%b\n%Y'
# Case 3. Less than 14 months ...............
elif span <= 1.15 * periodsperyear:
year_start = period_break(dates_, 'year')
month_start = period_break(dates_, 'month')
week_start = period_break(dates_, 'week')
info_maj[month_start] = True
info_min[week_start] = True
info_min[year_start] = False
info_min[month_start] = False
info_fmt[month_start] = '%b'
info_fmt[year_start] = '%b\n%Y'
if not has_level_label(year_start, vmin_orig):
info_fmt[first_label(month_start)] = '%b\n%Y'
# Case 4. Less than 2.5 years ...............
elif span <= 2.5 * periodsperyear:
year_start = period_break(dates_, 'year')
quarter_start = period_break(dates_, 'quarter')
month_start = period_break(dates_, 'month')
info_maj[quarter_start] = True
info_min[month_start] = True
info_fmt[quarter_start] = '%b'
info_fmt[year_start] = '%b\n%Y'
# Case 4. Less than 4 years .................
elif span <= 4 * periodsperyear:
year_start = period_break(dates_, 'year')
month_start = period_break(dates_, 'month')
info_maj[year_start] = True
info_min[month_start] = True
info_min[year_start] = False
month_break = dates_[month_start].month
jan_or_jul = month_start[(month_break == 1) | (month_break == 7)]
info_fmt[jan_or_jul] = '%b'
info_fmt[year_start] = '%b\n%Y'
# Case 5. Less than 11 years ................
elif span <= 11 * periodsperyear:
year_start = period_break(dates_, 'year')
quarter_start = period_break(dates_, 'quarter')
info_maj[year_start] = True
info_min[quarter_start] = True
info_min[year_start] = False
info_fmt[year_start] = '%Y'
# Case 6. More than 12 years ................
else:
year_start = period_break(dates_, 'year')
year_break = dates_[year_start].year
nyears = span / periodsperyear
(min_anndef, maj_anndef) = _get_default_annual_spacing(nyears)
major_idx = year_start[(year_break % maj_anndef == 0)]
info_maj[major_idx] = True
minor_idx = year_start[(year_break % min_anndef == 0)]
info_min[minor_idx] = True
info_fmt[major_idx] = '%Y'
#............................................
return info
def _monthly_finder(vmin, vmax, freq):
periodsperyear = 12
vmin_orig = vmin
(vmin, vmax) = (int(vmin), int(vmax))
span = vmax - vmin + 1
#..............
# Initialize the output
info = np.zeros(span,
dtype=[('val', int), ('maj', bool), ('min', bool),
('fmt', '|S8')])
info['val'] = np.arange(vmin, vmax + 1)
dates_ = info['val']
info['fmt'] = ''
year_start = (dates_ % 12 == 0).nonzero()[0]
info_maj = info['maj']
info_fmt = info['fmt']
#..............
if span <= 1.15 * periodsperyear:
info_maj[year_start] = True
info['min'] = True
info_fmt[:] = '%b'
info_fmt[year_start] = '%b\n%Y'
if not has_level_label(year_start, vmin_orig):
if dates_.size > 1:
idx = 1
else:
idx = 0
info_fmt[idx] = '%b\n%Y'
#..............
elif span <= 2.5 * periodsperyear:
quarter_start = (dates_ % 3 == 0).nonzero()
info_maj[year_start] = True
# TODO: Check the following : is it really info['fmt'] ?
info['fmt'][quarter_start] = True
info['min'] = True
info_fmt[quarter_start] = '%b'
info_fmt[year_start] = '%b\n%Y'
#..............
elif span <= 4 * periodsperyear:
info_maj[year_start] = True
info['min'] = True
jan_or_jul = (dates_ % 12 == 0) | (dates_ % 12 == 6)
info_fmt[jan_or_jul] = '%b'
info_fmt[year_start] = '%b\n%Y'
#..............
elif span <= 11 * periodsperyear:
quarter_start = (dates_ % 3 == 0).nonzero()
info_maj[year_start] = True
info['min'][quarter_start] = True
info_fmt[year_start] = '%Y'
#..................
else:
nyears = span / periodsperyear
(min_anndef, maj_anndef) = _get_default_annual_spacing(nyears)
years = dates_[year_start] // 12 + 1
major_idx = year_start[(years % maj_anndef == 0)]
info_maj[major_idx] = True
info['min'][year_start[(years % min_anndef == 0)]] = True
info_fmt[major_idx] = '%Y'
#..............
return info
def _quarterly_finder(vmin, vmax, freq):
periodsperyear = 4
vmin_orig = vmin
(vmin, vmax) = (int(vmin), int(vmax))
span = vmax - vmin + 1
#............................................
info = np.zeros(span,
dtype=[('val', int), ('maj', bool), ('min', bool),
('fmt', '|S8')])
info['val'] = np.arange(vmin, vmax + 1)
info['fmt'] = ''
dates_ = info['val']
info_maj = info['maj']
info_fmt = info['fmt']
year_start = (dates_ % 4 == 0).nonzero()[0]
#..............
if span <= 3.5 * periodsperyear:
info_maj[year_start] = True
info['min'] = True
info_fmt[:] = 'Q%q'
info_fmt[year_start] = 'Q%q\n%F'
if not has_level_label(year_start, vmin_orig):
if dates_.size > 1:
idx = 1
else:
idx = 0
info_fmt[idx] = 'Q%q\n%F'
#..............
elif span <= 11 * periodsperyear:
info_maj[year_start] = True
info['min'] = True
info_fmt[year_start] = '%F'
#..............
else:
years = dates_[year_start] // 4 + 1
nyears = span / periodsperyear
(min_anndef, maj_anndef) = _get_default_annual_spacing(nyears)
major_idx = year_start[(years % maj_anndef == 0)]
info_maj[major_idx] = True
info['min'][year_start[(years % min_anndef == 0)]] = True
info_fmt[major_idx] = '%F'
#..............
return info
def _annual_finder(vmin, vmax, freq):
(vmin, vmax) = (int(vmin), int(vmax + 1))
span = vmax - vmin + 1
#..............
info = np.zeros(span,
dtype=[('val', int), ('maj', bool), ('min', bool),
('fmt', '|S8')])
info['val'] = np.arange(vmin, vmax + 1)
info['fmt'] = ''
dates_ = info['val']
#..............
(min_anndef, maj_anndef) = _get_default_annual_spacing(span)
major_idx = dates_ % maj_anndef == 0
info['maj'][major_idx] = True
info['min'][(dates_ % min_anndef == 0)] = True
info['fmt'][major_idx] = '%Y'
#..............
return info
def get_finder(freq):
if isinstance(freq, compat.string_types):
freq = frequencies.get_freq(freq)
fgroup = frequencies.get_freq_group(freq)
if fgroup == FreqGroup.FR_ANN:
return _annual_finder
elif fgroup == FreqGroup.FR_QTR:
return _quarterly_finder
elif freq == FreqGroup.FR_MTH:
return _monthly_finder
elif ((freq >= FreqGroup.FR_BUS) or fgroup == FreqGroup.FR_WK):
return _daily_finder
else: # pragma: no cover
errmsg = "Unsupported frequency: %s" % (freq)
raise NotImplementedError(errmsg)
class TimeSeries_DateLocator(Locator):
"""
Locates the ticks along an axis controlled by a :class:`Series`.
Parameters
----------
freq : {var}
Valid frequency specifier.
minor_locator : {False, True}, optional
Whether the locator is for minor ticks (True) or not.
dynamic_mode : {True, False}, optional
Whether the locator should work in dynamic mode.
base : {int}, optional
quarter : {int}, optional
month : {int}, optional
day : {int}, optional
"""
def __init__(self, freq, minor_locator=False, dynamic_mode=True,
base=1, quarter=1, month=1, day=1, plot_obj=None):
if isinstance(freq, compat.string_types):
freq = frequencies.get_freq(freq)
self.freq = freq
self.base = base
(self.quarter, self.month, self.day) = (quarter, month, day)
self.isminor = minor_locator
self.isdynamic = dynamic_mode
self.offset = 0
self.plot_obj = plot_obj
self.finder = get_finder(freq)
def _get_default_locs(self, vmin, vmax):
"Returns the default locations of ticks."
if self.plot_obj.date_axis_info is None:
self.plot_obj.date_axis_info = self.finder(vmin, vmax, self.freq)
locator = self.plot_obj.date_axis_info
if self.isminor:
return np.compress(locator['min'], locator['val'])
return np.compress(locator['maj'], locator['val'])
def __call__(self):
'Return the locations of the ticks.'
# axis calls Locator.set_axis inside set_m<xxxx>_formatter
vi = tuple(self.axis.get_view_interval())
if vi != self.plot_obj.view_interval:
self.plot_obj.date_axis_info = None
self.plot_obj.view_interval = vi
vmin, vmax = vi
if vmax < vmin:
vmin, vmax = vmax, vmin
if self.isdynamic:
locs = self._get_default_locs(vmin, vmax)
else: # pragma: no cover
base = self.base
(d, m) = divmod(vmin, base)
vmin = (d + 1) * base
locs = lrange(vmin, vmax + 1, base)
return locs
def autoscale(self):
"""
Sets the view limits to the nearest multiples of base that contain the
data.
"""
# requires matplotlib >= 0.98.0
(vmin, vmax) = self.axis.get_data_interval()
locs = self._get_default_locs(vmin, vmax)
(vmin, vmax) = locs[[0, -1]]
if vmin == vmax:
vmin -= 1
vmax += 1
return nonsingular(vmin, vmax)
#####-------------------------------------------------------------------------
#---- --- Formatter ---
#####-------------------------------------------------------------------------
class TimeSeries_DateFormatter(Formatter):
"""
Formats the ticks along an axis controlled by a :class:`PeriodIndex`.
Parameters
----------
freq : {int, string}
Valid frequency specifier.
minor_locator : {False, True}
Whether the current formatter should apply to minor ticks (True) or
major ticks (False).
dynamic_mode : {True, False}
Whether the formatter works in dynamic mode or not.
"""
def __init__(self, freq, minor_locator=False, dynamic_mode=True,
plot_obj=None):
if isinstance(freq, compat.string_types):
freq = frequencies.get_freq(freq)
self.format = None
self.freq = freq
self.locs = []
self.formatdict = None
self.isminor = minor_locator
self.isdynamic = dynamic_mode
self.offset = 0
self.plot_obj = plot_obj
self.finder = get_finder(freq)
def _set_default_format(self, vmin, vmax):
"Returns the default ticks spacing."
if self.plot_obj.date_axis_info is None:
self.plot_obj.date_axis_info = self.finder(vmin, vmax, self.freq)
info = self.plot_obj.date_axis_info
if self.isminor:
format = np.compress(info['min'] & np.logical_not(info['maj']),
info)
else:
format = np.compress(info['maj'], info)
self.formatdict = dict([(x, f) for (x, _, _, f) in format])
return self.formatdict
def set_locs(self, locs):
'Sets the locations of the ticks'
# don't actually use the locs. This is just needed to work with
# matplotlib. Force to use vmin, vmax
self.locs = locs
(vmin, vmax) = vi = tuple(self.axis.get_view_interval())
if vi != self.plot_obj.view_interval:
self.plot_obj.date_axis_info = None
self.plot_obj.view_interval = vi
if vmax < vmin:
(vmin, vmax) = (vmax, vmin)
self._set_default_format(vmin, vmax)
def __call__(self, x, pos=0):
if self.formatdict is None:
return ''
else:
fmt = self.formatdict.pop(x, '')
return Period(ordinal=int(x), freq=self.freq).strftime(fmt)
|
GladeRom/android_external_chromium_org
|
refs/heads/gr-3.1
|
chrome/common/extensions/docs/server2/api_categorizer_test.py
|
87
|
#!/usr/bin/env python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest
from api_categorizer import APICategorizer
from compiled_file_system import CompiledFileSystem
from extensions_paths import CHROME_EXTENSIONS
from object_store_creator import ObjectStoreCreator
from test_file_system import TestFileSystem
def _ToTestData(obj):
'''Transforms |obj| into test data by turning a list of files into an object
mapping that file to its contents (derived from its name).
'''
return dict((name, name) for name in obj)
_TEST_DATA = {
'api': {
'_api_features.json': '{}',
'_manifest_features.json': '{}',
'_permission_features.json': '{}',
},
'docs': {
'templates': {
'json': {
'api_availabilities.json': '{}',
'manifest.json': '{}',
'permissions.json': '{}',
},
'public': {
'apps': _ToTestData([
'alarms.html',
'app_window.html',
'experimental_bluetooth.html',
'experimental_power.html',
'storage.html',
'sockets_udp.html'
]),
'extensions': _ToTestData([
'alarms.html',
'browserAction.html',
'experimental_history.html',
'experimental_power.html',
'infobars.html',
'storage.html',
'sockets_udp.html'
]),
},
},
}
}
class APICategorizerTest(unittest.TestCase):
def setUp(self):
self._test_file_system = TestFileSystem(
_TEST_DATA, relative_to=CHROME_EXTENSIONS)
self._compiled_file_system = CompiledFileSystem.Factory(
ObjectStoreCreator.ForTest())
def testGetAPICategory(self):
def assertGetEqual(expected, category, only_on=None):
for platform in ('apps', 'extensions'):
get_category = APICategorizer(
self._test_file_system,
self._compiled_file_system,
platform if only_on is None else only_on).GetCategory(category)
self.assertEqual(expected, get_category)
assertGetEqual('chrome', 'alarms')
assertGetEqual('private', 'musicManagerPrivate')
assertGetEqual('private', 'notDocumentedApi')
assertGetEqual('experimental', 'experimental.bluetooth', only_on='apps')
assertGetEqual('experimental', 'experimental.history', only_on='extensions')
if __name__ == '__main__':
unittest.main()
|
rabipanda/tensorflow
|
refs/heads/master
|
tensorflow/python/layers/maxout.py
|
3
|
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =============================================================================
# pylint: disable=unused-import,g-bad-import-order
"""Contains the maxout layer
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.eager import context
from tensorflow.python.framework import ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import gen_array_ops
from tensorflow.python.layers import base
def maxout(inputs, num_units, axis=-1, name=None):
"""Adds a maxout op from https://arxiv.org/abs/1302.4389
"Maxout Networks" Ian J. Goodfellow, David Warde-Farley, Mehdi Mirza, Aaron
Courville,
Yoshua Bengio
Usually the operation is performed in the filter/channel dimension. This can
also be
used after fully-connected layers to reduce number of features.
Arguments:
inputs: Tensor input
num_units: Specifies how many features will remain after maxout in the `axis`
dimension
(usually channel). This must be multiple of number of `axis`.
axis: The dimension where max pooling will be performed. Default is the
last dimension.
name: Optional scope for name_scope.
Returns:
A `Tensor` representing the results of the pooling operation.
Raises:
ValueError: if num_units is not multiple of number of features.
"""
return MaxOut(num_units=num_units, axis=axis, name=name)(inputs)
class MaxOut(base.Layer):
"""Adds a maxout op from https://arxiv.org/abs/1302.4389
"Maxout Networks" Ian J. Goodfellow, David Warde-Farley, Mehdi Mirza, Aaron
Courville, Yoshua
Bengio
Usually the operation is performed in the filter/channel dimension. This can
also be
used after fully-connected layers to reduce number of features.
Arguments:
inputs: Tensor input
num_units: Specifies how many features will remain after maxout in the
`axis` dimension
(usually channel).
This must be multiple of number of `axis`.
axis: The dimension where max pooling will be performed. Default is the
last dimension.
name: Optional scope for name_scope.
Returns:
A `Tensor` representing the results of the pooling operation.
Raises:
ValueError: if num_units is not multiple of number of features.
"""
def __init__(self, num_units, axis=-1, name=None, **kwargs):
super(MaxOut, self).__init__(name=name, trainable=False, **kwargs)
self.axis = axis
self.num_units = num_units
def call(self, inputs):
inputs = ops.convert_to_tensor(inputs)
shape = inputs.get_shape().as_list()
num_channels = shape[self.axis]
if num_channels % self.num_units:
raise ValueError('number of features({}) is not '
'a multiple of num_units({})'.format(
num_channels, self.num_units))
shape[self.axis] = -1
shape += [num_channels // self.num_units]
# Dealing with batches with arbitrary sizes
for i in range(len(shape)):
if shape[i] is None:
shape[i] = gen_array_ops.shape(inputs)[i]
outputs = math_ops.reduce_max(
gen_array_ops.reshape(inputs, shape), -1, keep_dims=False)
return outputs
|
neerajvashistha/pa-dude
|
refs/heads/master
|
lib/python2.7/site-packages/pip/_vendor/html5lib/tokenizer.py
|
1710
|
from __future__ import absolute_import, division, unicode_literals
try:
chr = unichr # flake8: noqa
except NameError:
pass
from collections import deque
from .constants import spaceCharacters
from .constants import entities
from .constants import asciiLetters, asciiUpper2Lower
from .constants import digits, hexDigits, EOF
from .constants import tokenTypes, tagTokenTypes
from .constants import replacementCharacters
from .inputstream import HTMLInputStream
from .trie import Trie
entitiesTrie = Trie(entities)
class HTMLTokenizer(object):
""" This class takes care of tokenizing HTML.
* self.currentToken
Holds the token that is currently being processed.
* self.state
Holds a reference to the method to be invoked... XXX
* self.stream
Points to HTMLInputStream object.
"""
def __init__(self, stream, encoding=None, parseMeta=True, useChardet=True,
lowercaseElementName=True, lowercaseAttrName=True, parser=None):
self.stream = HTMLInputStream(stream, encoding, parseMeta, useChardet)
self.parser = parser
# Perform case conversions?
self.lowercaseElementName = lowercaseElementName
self.lowercaseAttrName = lowercaseAttrName
# Setup the initial tokenizer state
self.escapeFlag = False
self.lastFourChars = []
self.state = self.dataState
self.escape = False
# The current token being created
self.currentToken = None
super(HTMLTokenizer, self).__init__()
def __iter__(self):
""" This is where the magic happens.
We do our usually processing through the states and when we have a token
to return we yield the token which pauses processing until the next token
is requested.
"""
self.tokenQueue = deque([])
# Start processing. When EOF is reached self.state will return False
# instead of True and the loop will terminate.
while self.state():
while self.stream.errors:
yield {"type": tokenTypes["ParseError"], "data": self.stream.errors.pop(0)}
while self.tokenQueue:
yield self.tokenQueue.popleft()
def consumeNumberEntity(self, isHex):
"""This function returns either U+FFFD or the character based on the
decimal or hexadecimal representation. It also discards ";" if present.
If not present self.tokenQueue.append({"type": tokenTypes["ParseError"]}) is invoked.
"""
allowed = digits
radix = 10
if isHex:
allowed = hexDigits
radix = 16
charStack = []
# Consume all the characters that are in range while making sure we
# don't hit an EOF.
c = self.stream.char()
while c in allowed and c is not EOF:
charStack.append(c)
c = self.stream.char()
# Convert the set of characters consumed to an int.
charAsInt = int("".join(charStack), radix)
# Certain characters get replaced with others
if charAsInt in replacementCharacters:
char = replacementCharacters[charAsInt]
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"illegal-codepoint-for-numeric-entity",
"datavars": {"charAsInt": charAsInt}})
elif ((0xD800 <= charAsInt <= 0xDFFF) or
(charAsInt > 0x10FFFF)):
char = "\uFFFD"
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"illegal-codepoint-for-numeric-entity",
"datavars": {"charAsInt": charAsInt}})
else:
# Should speed up this check somehow (e.g. move the set to a constant)
if ((0x0001 <= charAsInt <= 0x0008) or
(0x000E <= charAsInt <= 0x001F) or
(0x007F <= charAsInt <= 0x009F) or
(0xFDD0 <= charAsInt <= 0xFDEF) or
charAsInt in frozenset([0x000B, 0xFFFE, 0xFFFF, 0x1FFFE,
0x1FFFF, 0x2FFFE, 0x2FFFF, 0x3FFFE,
0x3FFFF, 0x4FFFE, 0x4FFFF, 0x5FFFE,
0x5FFFF, 0x6FFFE, 0x6FFFF, 0x7FFFE,
0x7FFFF, 0x8FFFE, 0x8FFFF, 0x9FFFE,
0x9FFFF, 0xAFFFE, 0xAFFFF, 0xBFFFE,
0xBFFFF, 0xCFFFE, 0xCFFFF, 0xDFFFE,
0xDFFFF, 0xEFFFE, 0xEFFFF, 0xFFFFE,
0xFFFFF, 0x10FFFE, 0x10FFFF])):
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data":
"illegal-codepoint-for-numeric-entity",
"datavars": {"charAsInt": charAsInt}})
try:
# Try/except needed as UCS-2 Python builds' unichar only works
# within the BMP.
char = chr(charAsInt)
except ValueError:
v = charAsInt - 0x10000
char = chr(0xD800 | (v >> 10)) + chr(0xDC00 | (v & 0x3FF))
# Discard the ; if present. Otherwise, put it back on the queue and
# invoke parseError on parser.
if c != ";":
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"numeric-entity-without-semicolon"})
self.stream.unget(c)
return char
def consumeEntity(self, allowedChar=None, fromAttribute=False):
# Initialise to the default output for when no entity is matched
output = "&"
charStack = [self.stream.char()]
if (charStack[0] in spaceCharacters or charStack[0] in (EOF, "<", "&")
or (allowedChar is not None and allowedChar == charStack[0])):
self.stream.unget(charStack[0])
elif charStack[0] == "#":
# Read the next character to see if it's hex or decimal
hex = False
charStack.append(self.stream.char())
if charStack[-1] in ("x", "X"):
hex = True
charStack.append(self.stream.char())
# charStack[-1] should be the first digit
if (hex and charStack[-1] in hexDigits) \
or (not hex and charStack[-1] in digits):
# At least one digit found, so consume the whole number
self.stream.unget(charStack[-1])
output = self.consumeNumberEntity(hex)
else:
# No digits found
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "expected-numeric-entity"})
self.stream.unget(charStack.pop())
output = "&" + "".join(charStack)
else:
# At this point in the process might have named entity. Entities
# are stored in the global variable "entities".
#
# Consume characters and compare to these to a substring of the
# entity names in the list until the substring no longer matches.
while (charStack[-1] is not EOF):
if not entitiesTrie.has_keys_with_prefix("".join(charStack)):
break
charStack.append(self.stream.char())
# At this point we have a string that starts with some characters
# that may match an entity
# Try to find the longest entity the string will match to take care
# of ¬i for instance.
try:
entityName = entitiesTrie.longest_prefix("".join(charStack[:-1]))
entityLength = len(entityName)
except KeyError:
entityName = None
if entityName is not None:
if entityName[-1] != ";":
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"named-entity-without-semicolon"})
if (entityName[-1] != ";" and fromAttribute and
(charStack[entityLength] in asciiLetters or
charStack[entityLength] in digits or
charStack[entityLength] == "=")):
self.stream.unget(charStack.pop())
output = "&" + "".join(charStack)
else:
output = entities[entityName]
self.stream.unget(charStack.pop())
output += "".join(charStack[entityLength:])
else:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"expected-named-entity"})
self.stream.unget(charStack.pop())
output = "&" + "".join(charStack)
if fromAttribute:
self.currentToken["data"][-1][1] += output
else:
if output in spaceCharacters:
tokenType = "SpaceCharacters"
else:
tokenType = "Characters"
self.tokenQueue.append({"type": tokenTypes[tokenType], "data": output})
def processEntityInAttribute(self, allowedChar):
"""This method replaces the need for "entityInAttributeValueState".
"""
self.consumeEntity(allowedChar=allowedChar, fromAttribute=True)
def emitCurrentToken(self):
"""This method is a generic handler for emitting the tags. It also sets
the state to "data" because that's what's needed after a token has been
emitted.
"""
token = self.currentToken
# Add token to the queue to be yielded
if (token["type"] in tagTokenTypes):
if self.lowercaseElementName:
token["name"] = token["name"].translate(asciiUpper2Lower)
if token["type"] == tokenTypes["EndTag"]:
if token["data"]:
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "attributes-in-end-tag"})
if token["selfClosing"]:
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "self-closing-flag-on-end-tag"})
self.tokenQueue.append(token)
self.state = self.dataState
# Below are the various tokenizer states worked out.
def dataState(self):
data = self.stream.char()
if data == "&":
self.state = self.entityDataState
elif data == "<":
self.state = self.tagOpenState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.tokenQueue.append({"type": tokenTypes["Characters"],
"data": "\u0000"})
elif data is EOF:
# Tokenization ends.
return False
elif data in spaceCharacters:
# Directly after emitting a token you switch back to the "data
# state". At that point spaceCharacters are important so they are
# emitted separately.
self.tokenQueue.append({"type": tokenTypes["SpaceCharacters"], "data":
data + self.stream.charsUntil(spaceCharacters, True)})
# No need to update lastFourChars here, since the first space will
# have already been appended to lastFourChars and will have broken
# any <!-- or --> sequences
else:
chars = self.stream.charsUntil(("&", "<", "\u0000"))
self.tokenQueue.append({"type": tokenTypes["Characters"], "data":
data + chars})
return True
def entityDataState(self):
self.consumeEntity()
self.state = self.dataState
return True
def rcdataState(self):
data = self.stream.char()
if data == "&":
self.state = self.characterReferenceInRcdata
elif data == "<":
self.state = self.rcdataLessThanSignState
elif data == EOF:
# Tokenization ends.
return False
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.tokenQueue.append({"type": tokenTypes["Characters"],
"data": "\uFFFD"})
elif data in spaceCharacters:
# Directly after emitting a token you switch back to the "data
# state". At that point spaceCharacters are important so they are
# emitted separately.
self.tokenQueue.append({"type": tokenTypes["SpaceCharacters"], "data":
data + self.stream.charsUntil(spaceCharacters, True)})
# No need to update lastFourChars here, since the first space will
# have already been appended to lastFourChars and will have broken
# any <!-- or --> sequences
else:
chars = self.stream.charsUntil(("&", "<", "\u0000"))
self.tokenQueue.append({"type": tokenTypes["Characters"], "data":
data + chars})
return True
def characterReferenceInRcdata(self):
self.consumeEntity()
self.state = self.rcdataState
return True
def rawtextState(self):
data = self.stream.char()
if data == "<":
self.state = self.rawtextLessThanSignState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.tokenQueue.append({"type": tokenTypes["Characters"],
"data": "\uFFFD"})
elif data == EOF:
# Tokenization ends.
return False
else:
chars = self.stream.charsUntil(("<", "\u0000"))
self.tokenQueue.append({"type": tokenTypes["Characters"], "data":
data + chars})
return True
def scriptDataState(self):
data = self.stream.char()
if data == "<":
self.state = self.scriptDataLessThanSignState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.tokenQueue.append({"type": tokenTypes["Characters"],
"data": "\uFFFD"})
elif data == EOF:
# Tokenization ends.
return False
else:
chars = self.stream.charsUntil(("<", "\u0000"))
self.tokenQueue.append({"type": tokenTypes["Characters"], "data":
data + chars})
return True
def plaintextState(self):
data = self.stream.char()
if data == EOF:
# Tokenization ends.
return False
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.tokenQueue.append({"type": tokenTypes["Characters"],
"data": "\uFFFD"})
else:
self.tokenQueue.append({"type": tokenTypes["Characters"], "data":
data + self.stream.charsUntil("\u0000")})
return True
def tagOpenState(self):
data = self.stream.char()
if data == "!":
self.state = self.markupDeclarationOpenState
elif data == "/":
self.state = self.closeTagOpenState
elif data in asciiLetters:
self.currentToken = {"type": tokenTypes["StartTag"],
"name": data, "data": [],
"selfClosing": False,
"selfClosingAcknowledged": False}
self.state = self.tagNameState
elif data == ">":
# XXX In theory it could be something besides a tag name. But
# do we really care?
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"expected-tag-name-but-got-right-bracket"})
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<>"})
self.state = self.dataState
elif data == "?":
# XXX In theory it could be something besides a tag name. But
# do we really care?
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"expected-tag-name-but-got-question-mark"})
self.stream.unget(data)
self.state = self.bogusCommentState
else:
# XXX
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"expected-tag-name"})
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"})
self.stream.unget(data)
self.state = self.dataState
return True
def closeTagOpenState(self):
data = self.stream.char()
if data in asciiLetters:
self.currentToken = {"type": tokenTypes["EndTag"], "name": data,
"data": [], "selfClosing": False}
self.state = self.tagNameState
elif data == ">":
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"expected-closing-tag-but-got-right-bracket"})
self.state = self.dataState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"expected-closing-tag-but-got-eof"})
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</"})
self.state = self.dataState
else:
# XXX data can be _'_...
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"expected-closing-tag-but-got-char",
"datavars": {"data": data}})
self.stream.unget(data)
self.state = self.bogusCommentState
return True
def tagNameState(self):
data = self.stream.char()
if data in spaceCharacters:
self.state = self.beforeAttributeNameState
elif data == ">":
self.emitCurrentToken()
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-tag-name"})
self.state = self.dataState
elif data == "/":
self.state = self.selfClosingStartTagState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["name"] += "\uFFFD"
else:
self.currentToken["name"] += data
# (Don't use charsUntil here, because tag names are
# very short and it's faster to not do anything fancy)
return True
def rcdataLessThanSignState(self):
data = self.stream.char()
if data == "/":
self.temporaryBuffer = ""
self.state = self.rcdataEndTagOpenState
else:
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"})
self.stream.unget(data)
self.state = self.rcdataState
return True
def rcdataEndTagOpenState(self):
data = self.stream.char()
if data in asciiLetters:
self.temporaryBuffer += data
self.state = self.rcdataEndTagNameState
else:
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</"})
self.stream.unget(data)
self.state = self.rcdataState
return True
def rcdataEndTagNameState(self):
appropriate = self.currentToken and self.currentToken["name"].lower() == self.temporaryBuffer.lower()
data = self.stream.char()
if data in spaceCharacters and appropriate:
self.currentToken = {"type": tokenTypes["EndTag"],
"name": self.temporaryBuffer,
"data": [], "selfClosing": False}
self.state = self.beforeAttributeNameState
elif data == "/" and appropriate:
self.currentToken = {"type": tokenTypes["EndTag"],
"name": self.temporaryBuffer,
"data": [], "selfClosing": False}
self.state = self.selfClosingStartTagState
elif data == ">" and appropriate:
self.currentToken = {"type": tokenTypes["EndTag"],
"name": self.temporaryBuffer,
"data": [], "selfClosing": False}
self.emitCurrentToken()
self.state = self.dataState
elif data in asciiLetters:
self.temporaryBuffer += data
else:
self.tokenQueue.append({"type": tokenTypes["Characters"],
"data": "</" + self.temporaryBuffer})
self.stream.unget(data)
self.state = self.rcdataState
return True
def rawtextLessThanSignState(self):
data = self.stream.char()
if data == "/":
self.temporaryBuffer = ""
self.state = self.rawtextEndTagOpenState
else:
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"})
self.stream.unget(data)
self.state = self.rawtextState
return True
def rawtextEndTagOpenState(self):
data = self.stream.char()
if data in asciiLetters:
self.temporaryBuffer += data
self.state = self.rawtextEndTagNameState
else:
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</"})
self.stream.unget(data)
self.state = self.rawtextState
return True
def rawtextEndTagNameState(self):
appropriate = self.currentToken and self.currentToken["name"].lower() == self.temporaryBuffer.lower()
data = self.stream.char()
if data in spaceCharacters and appropriate:
self.currentToken = {"type": tokenTypes["EndTag"],
"name": self.temporaryBuffer,
"data": [], "selfClosing": False}
self.state = self.beforeAttributeNameState
elif data == "/" and appropriate:
self.currentToken = {"type": tokenTypes["EndTag"],
"name": self.temporaryBuffer,
"data": [], "selfClosing": False}
self.state = self.selfClosingStartTagState
elif data == ">" and appropriate:
self.currentToken = {"type": tokenTypes["EndTag"],
"name": self.temporaryBuffer,
"data": [], "selfClosing": False}
self.emitCurrentToken()
self.state = self.dataState
elif data in asciiLetters:
self.temporaryBuffer += data
else:
self.tokenQueue.append({"type": tokenTypes["Characters"],
"data": "</" + self.temporaryBuffer})
self.stream.unget(data)
self.state = self.rawtextState
return True
def scriptDataLessThanSignState(self):
data = self.stream.char()
if data == "/":
self.temporaryBuffer = ""
self.state = self.scriptDataEndTagOpenState
elif data == "!":
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<!"})
self.state = self.scriptDataEscapeStartState
else:
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"})
self.stream.unget(data)
self.state = self.scriptDataState
return True
def scriptDataEndTagOpenState(self):
data = self.stream.char()
if data in asciiLetters:
self.temporaryBuffer += data
self.state = self.scriptDataEndTagNameState
else:
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</"})
self.stream.unget(data)
self.state = self.scriptDataState
return True
def scriptDataEndTagNameState(self):
appropriate = self.currentToken and self.currentToken["name"].lower() == self.temporaryBuffer.lower()
data = self.stream.char()
if data in spaceCharacters and appropriate:
self.currentToken = {"type": tokenTypes["EndTag"],
"name": self.temporaryBuffer,
"data": [], "selfClosing": False}
self.state = self.beforeAttributeNameState
elif data == "/" and appropriate:
self.currentToken = {"type": tokenTypes["EndTag"],
"name": self.temporaryBuffer,
"data": [], "selfClosing": False}
self.state = self.selfClosingStartTagState
elif data == ">" and appropriate:
self.currentToken = {"type": tokenTypes["EndTag"],
"name": self.temporaryBuffer,
"data": [], "selfClosing": False}
self.emitCurrentToken()
self.state = self.dataState
elif data in asciiLetters:
self.temporaryBuffer += data
else:
self.tokenQueue.append({"type": tokenTypes["Characters"],
"data": "</" + self.temporaryBuffer})
self.stream.unget(data)
self.state = self.scriptDataState
return True
def scriptDataEscapeStartState(self):
data = self.stream.char()
if data == "-":
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"})
self.state = self.scriptDataEscapeStartDashState
else:
self.stream.unget(data)
self.state = self.scriptDataState
return True
def scriptDataEscapeStartDashState(self):
data = self.stream.char()
if data == "-":
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"})
self.state = self.scriptDataEscapedDashDashState
else:
self.stream.unget(data)
self.state = self.scriptDataState
return True
def scriptDataEscapedState(self):
data = self.stream.char()
if data == "-":
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"})
self.state = self.scriptDataEscapedDashState
elif data == "<":
self.state = self.scriptDataEscapedLessThanSignState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.tokenQueue.append({"type": tokenTypes["Characters"],
"data": "\uFFFD"})
elif data == EOF:
self.state = self.dataState
else:
chars = self.stream.charsUntil(("<", "-", "\u0000"))
self.tokenQueue.append({"type": tokenTypes["Characters"], "data":
data + chars})
return True
def scriptDataEscapedDashState(self):
data = self.stream.char()
if data == "-":
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"})
self.state = self.scriptDataEscapedDashDashState
elif data == "<":
self.state = self.scriptDataEscapedLessThanSignState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.tokenQueue.append({"type": tokenTypes["Characters"],
"data": "\uFFFD"})
self.state = self.scriptDataEscapedState
elif data == EOF:
self.state = self.dataState
else:
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data})
self.state = self.scriptDataEscapedState
return True
def scriptDataEscapedDashDashState(self):
data = self.stream.char()
if data == "-":
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"})
elif data == "<":
self.state = self.scriptDataEscapedLessThanSignState
elif data == ">":
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": ">"})
self.state = self.scriptDataState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.tokenQueue.append({"type": tokenTypes["Characters"],
"data": "\uFFFD"})
self.state = self.scriptDataEscapedState
elif data == EOF:
self.state = self.dataState
else:
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data})
self.state = self.scriptDataEscapedState
return True
def scriptDataEscapedLessThanSignState(self):
data = self.stream.char()
if data == "/":
self.temporaryBuffer = ""
self.state = self.scriptDataEscapedEndTagOpenState
elif data in asciiLetters:
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<" + data})
self.temporaryBuffer = data
self.state = self.scriptDataDoubleEscapeStartState
else:
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"})
self.stream.unget(data)
self.state = self.scriptDataEscapedState
return True
def scriptDataEscapedEndTagOpenState(self):
data = self.stream.char()
if data in asciiLetters:
self.temporaryBuffer = data
self.state = self.scriptDataEscapedEndTagNameState
else:
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</"})
self.stream.unget(data)
self.state = self.scriptDataEscapedState
return True
def scriptDataEscapedEndTagNameState(self):
appropriate = self.currentToken and self.currentToken["name"].lower() == self.temporaryBuffer.lower()
data = self.stream.char()
if data in spaceCharacters and appropriate:
self.currentToken = {"type": tokenTypes["EndTag"],
"name": self.temporaryBuffer,
"data": [], "selfClosing": False}
self.state = self.beforeAttributeNameState
elif data == "/" and appropriate:
self.currentToken = {"type": tokenTypes["EndTag"],
"name": self.temporaryBuffer,
"data": [], "selfClosing": False}
self.state = self.selfClosingStartTagState
elif data == ">" and appropriate:
self.currentToken = {"type": tokenTypes["EndTag"],
"name": self.temporaryBuffer,
"data": [], "selfClosing": False}
self.emitCurrentToken()
self.state = self.dataState
elif data in asciiLetters:
self.temporaryBuffer += data
else:
self.tokenQueue.append({"type": tokenTypes["Characters"],
"data": "</" + self.temporaryBuffer})
self.stream.unget(data)
self.state = self.scriptDataEscapedState
return True
def scriptDataDoubleEscapeStartState(self):
data = self.stream.char()
if data in (spaceCharacters | frozenset(("/", ">"))):
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data})
if self.temporaryBuffer.lower() == "script":
self.state = self.scriptDataDoubleEscapedState
else:
self.state = self.scriptDataEscapedState
elif data in asciiLetters:
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data})
self.temporaryBuffer += data
else:
self.stream.unget(data)
self.state = self.scriptDataEscapedState
return True
def scriptDataDoubleEscapedState(self):
data = self.stream.char()
if data == "-":
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"})
self.state = self.scriptDataDoubleEscapedDashState
elif data == "<":
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"})
self.state = self.scriptDataDoubleEscapedLessThanSignState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.tokenQueue.append({"type": tokenTypes["Characters"],
"data": "\uFFFD"})
elif data == EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-script-in-script"})
self.state = self.dataState
else:
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data})
return True
def scriptDataDoubleEscapedDashState(self):
data = self.stream.char()
if data == "-":
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"})
self.state = self.scriptDataDoubleEscapedDashDashState
elif data == "<":
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"})
self.state = self.scriptDataDoubleEscapedLessThanSignState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.tokenQueue.append({"type": tokenTypes["Characters"],
"data": "\uFFFD"})
self.state = self.scriptDataDoubleEscapedState
elif data == EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-script-in-script"})
self.state = self.dataState
else:
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data})
self.state = self.scriptDataDoubleEscapedState
return True
def scriptDataDoubleEscapedDashDashState(self):
data = self.stream.char()
if data == "-":
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "-"})
elif data == "<":
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "<"})
self.state = self.scriptDataDoubleEscapedLessThanSignState
elif data == ">":
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": ">"})
self.state = self.scriptDataState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.tokenQueue.append({"type": tokenTypes["Characters"],
"data": "\uFFFD"})
self.state = self.scriptDataDoubleEscapedState
elif data == EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-script-in-script"})
self.state = self.dataState
else:
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data})
self.state = self.scriptDataDoubleEscapedState
return True
def scriptDataDoubleEscapedLessThanSignState(self):
data = self.stream.char()
if data == "/":
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "/"})
self.temporaryBuffer = ""
self.state = self.scriptDataDoubleEscapeEndState
else:
self.stream.unget(data)
self.state = self.scriptDataDoubleEscapedState
return True
def scriptDataDoubleEscapeEndState(self):
data = self.stream.char()
if data in (spaceCharacters | frozenset(("/", ">"))):
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data})
if self.temporaryBuffer.lower() == "script":
self.state = self.scriptDataEscapedState
else:
self.state = self.scriptDataDoubleEscapedState
elif data in asciiLetters:
self.tokenQueue.append({"type": tokenTypes["Characters"], "data": data})
self.temporaryBuffer += data
else:
self.stream.unget(data)
self.state = self.scriptDataDoubleEscapedState
return True
def beforeAttributeNameState(self):
data = self.stream.char()
if data in spaceCharacters:
self.stream.charsUntil(spaceCharacters, True)
elif data in asciiLetters:
self.currentToken["data"].append([data, ""])
self.state = self.attributeNameState
elif data == ">":
self.emitCurrentToken()
elif data == "/":
self.state = self.selfClosingStartTagState
elif data in ("'", '"', "=", "<"):
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"invalid-character-in-attribute-name"})
self.currentToken["data"].append([data, ""])
self.state = self.attributeNameState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["data"].append(["\uFFFD", ""])
self.state = self.attributeNameState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"expected-attribute-name-but-got-eof"})
self.state = self.dataState
else:
self.currentToken["data"].append([data, ""])
self.state = self.attributeNameState
return True
def attributeNameState(self):
data = self.stream.char()
leavingThisState = True
emitToken = False
if data == "=":
self.state = self.beforeAttributeValueState
elif data in asciiLetters:
self.currentToken["data"][-1][0] += data +\
self.stream.charsUntil(asciiLetters, True)
leavingThisState = False
elif data == ">":
# XXX If we emit here the attributes are converted to a dict
# without being checked and when the code below runs we error
# because data is a dict not a list
emitToken = True
elif data in spaceCharacters:
self.state = self.afterAttributeNameState
elif data == "/":
self.state = self.selfClosingStartTagState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["data"][-1][0] += "\uFFFD"
leavingThisState = False
elif data in ("'", '"', "<"):
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data":
"invalid-character-in-attribute-name"})
self.currentToken["data"][-1][0] += data
leavingThisState = False
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "eof-in-attribute-name"})
self.state = self.dataState
else:
self.currentToken["data"][-1][0] += data
leavingThisState = False
if leavingThisState:
# Attributes are not dropped at this stage. That happens when the
# start tag token is emitted so values can still be safely appended
# to attributes, but we do want to report the parse error in time.
if self.lowercaseAttrName:
self.currentToken["data"][-1][0] = (
self.currentToken["data"][-1][0].translate(asciiUpper2Lower))
for name, value in self.currentToken["data"][:-1]:
if self.currentToken["data"][-1][0] == name:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"duplicate-attribute"})
break
# XXX Fix for above XXX
if emitToken:
self.emitCurrentToken()
return True
def afterAttributeNameState(self):
data = self.stream.char()
if data in spaceCharacters:
self.stream.charsUntil(spaceCharacters, True)
elif data == "=":
self.state = self.beforeAttributeValueState
elif data == ">":
self.emitCurrentToken()
elif data in asciiLetters:
self.currentToken["data"].append([data, ""])
self.state = self.attributeNameState
elif data == "/":
self.state = self.selfClosingStartTagState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["data"].append(["\uFFFD", ""])
self.state = self.attributeNameState
elif data in ("'", '"', "<"):
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"invalid-character-after-attribute-name"})
self.currentToken["data"].append([data, ""])
self.state = self.attributeNameState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"expected-end-of-tag-but-got-eof"})
self.state = self.dataState
else:
self.currentToken["data"].append([data, ""])
self.state = self.attributeNameState
return True
def beforeAttributeValueState(self):
data = self.stream.char()
if data in spaceCharacters:
self.stream.charsUntil(spaceCharacters, True)
elif data == "\"":
self.state = self.attributeValueDoubleQuotedState
elif data == "&":
self.state = self.attributeValueUnQuotedState
self.stream.unget(data)
elif data == "'":
self.state = self.attributeValueSingleQuotedState
elif data == ">":
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"expected-attribute-value-but-got-right-bracket"})
self.emitCurrentToken()
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["data"][-1][1] += "\uFFFD"
self.state = self.attributeValueUnQuotedState
elif data in ("=", "<", "`"):
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"equals-in-unquoted-attribute-value"})
self.currentToken["data"][-1][1] += data
self.state = self.attributeValueUnQuotedState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"expected-attribute-value-but-got-eof"})
self.state = self.dataState
else:
self.currentToken["data"][-1][1] += data
self.state = self.attributeValueUnQuotedState
return True
def attributeValueDoubleQuotedState(self):
data = self.stream.char()
if data == "\"":
self.state = self.afterAttributeValueState
elif data == "&":
self.processEntityInAttribute('"')
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["data"][-1][1] += "\uFFFD"
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-attribute-value-double-quote"})
self.state = self.dataState
else:
self.currentToken["data"][-1][1] += data +\
self.stream.charsUntil(("\"", "&", "\u0000"))
return True
def attributeValueSingleQuotedState(self):
data = self.stream.char()
if data == "'":
self.state = self.afterAttributeValueState
elif data == "&":
self.processEntityInAttribute("'")
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["data"][-1][1] += "\uFFFD"
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-attribute-value-single-quote"})
self.state = self.dataState
else:
self.currentToken["data"][-1][1] += data +\
self.stream.charsUntil(("'", "&", "\u0000"))
return True
def attributeValueUnQuotedState(self):
data = self.stream.char()
if data in spaceCharacters:
self.state = self.beforeAttributeNameState
elif data == "&":
self.processEntityInAttribute(">")
elif data == ">":
self.emitCurrentToken()
elif data in ('"', "'", "=", "<", "`"):
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-character-in-unquoted-attribute-value"})
self.currentToken["data"][-1][1] += data
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["data"][-1][1] += "\uFFFD"
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-attribute-value-no-quotes"})
self.state = self.dataState
else:
self.currentToken["data"][-1][1] += data + self.stream.charsUntil(
frozenset(("&", ">", '"', "'", "=", "<", "`", "\u0000")) | spaceCharacters)
return True
def afterAttributeValueState(self):
data = self.stream.char()
if data in spaceCharacters:
self.state = self.beforeAttributeNameState
elif data == ">":
self.emitCurrentToken()
elif data == "/":
self.state = self.selfClosingStartTagState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-EOF-after-attribute-value"})
self.stream.unget(data)
self.state = self.dataState
else:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-character-after-attribute-value"})
self.stream.unget(data)
self.state = self.beforeAttributeNameState
return True
def selfClosingStartTagState(self):
data = self.stream.char()
if data == ">":
self.currentToken["selfClosing"] = True
self.emitCurrentToken()
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data":
"unexpected-EOF-after-solidus-in-tag"})
self.stream.unget(data)
self.state = self.dataState
else:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-character-after-solidus-in-tag"})
self.stream.unget(data)
self.state = self.beforeAttributeNameState
return True
def bogusCommentState(self):
# Make a new comment token and give it as value all the characters
# until the first > or EOF (charsUntil checks for EOF automatically)
# and emit it.
data = self.stream.charsUntil(">")
data = data.replace("\u0000", "\uFFFD")
self.tokenQueue.append(
{"type": tokenTypes["Comment"], "data": data})
# Eat the character directly after the bogus comment which is either a
# ">" or an EOF.
self.stream.char()
self.state = self.dataState
return True
def markupDeclarationOpenState(self):
charStack = [self.stream.char()]
if charStack[-1] == "-":
charStack.append(self.stream.char())
if charStack[-1] == "-":
self.currentToken = {"type": tokenTypes["Comment"], "data": ""}
self.state = self.commentStartState
return True
elif charStack[-1] in ('d', 'D'):
matched = True
for expected in (('o', 'O'), ('c', 'C'), ('t', 'T'),
('y', 'Y'), ('p', 'P'), ('e', 'E')):
charStack.append(self.stream.char())
if charStack[-1] not in expected:
matched = False
break
if matched:
self.currentToken = {"type": tokenTypes["Doctype"],
"name": "",
"publicId": None, "systemId": None,
"correct": True}
self.state = self.doctypeState
return True
elif (charStack[-1] == "[" and
self.parser is not None and
self.parser.tree.openElements and
self.parser.tree.openElements[-1].namespace != self.parser.tree.defaultNamespace):
matched = True
for expected in ["C", "D", "A", "T", "A", "["]:
charStack.append(self.stream.char())
if charStack[-1] != expected:
matched = False
break
if matched:
self.state = self.cdataSectionState
return True
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"expected-dashes-or-doctype"})
while charStack:
self.stream.unget(charStack.pop())
self.state = self.bogusCommentState
return True
def commentStartState(self):
data = self.stream.char()
if data == "-":
self.state = self.commentStartDashState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["data"] += "\uFFFD"
elif data == ">":
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"incorrect-comment"})
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-comment"})
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.currentToken["data"] += data
self.state = self.commentState
return True
def commentStartDashState(self):
data = self.stream.char()
if data == "-":
self.state = self.commentEndState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["data"] += "-\uFFFD"
elif data == ">":
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"incorrect-comment"})
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-comment"})
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.currentToken["data"] += "-" + data
self.state = self.commentState
return True
def commentState(self):
data = self.stream.char()
if data == "-":
self.state = self.commentEndDashState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["data"] += "\uFFFD"
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "eof-in-comment"})
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.currentToken["data"] += data + \
self.stream.charsUntil(("-", "\u0000"))
return True
def commentEndDashState(self):
data = self.stream.char()
if data == "-":
self.state = self.commentEndState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["data"] += "-\uFFFD"
self.state = self.commentState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-comment-end-dash"})
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.currentToken["data"] += "-" + data
self.state = self.commentState
return True
def commentEndState(self):
data = self.stream.char()
if data == ">":
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["data"] += "--\uFFFD"
self.state = self.commentState
elif data == "!":
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-bang-after-double-dash-in-comment"})
self.state = self.commentEndBangState
elif data == "-":
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-dash-after-double-dash-in-comment"})
self.currentToken["data"] += data
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-comment-double-dash"})
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
# XXX
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-char-in-comment"})
self.currentToken["data"] += "--" + data
self.state = self.commentState
return True
def commentEndBangState(self):
data = self.stream.char()
if data == ">":
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data == "-":
self.currentToken["data"] += "--!"
self.state = self.commentEndDashState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["data"] += "--!\uFFFD"
self.state = self.commentState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-comment-end-bang-state"})
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.currentToken["data"] += "--!" + data
self.state = self.commentState
return True
def doctypeState(self):
data = self.stream.char()
if data in spaceCharacters:
self.state = self.beforeDoctypeNameState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"expected-doctype-name-but-got-eof"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"need-space-after-doctype"})
self.stream.unget(data)
self.state = self.beforeDoctypeNameState
return True
def beforeDoctypeNameState(self):
data = self.stream.char()
if data in spaceCharacters:
pass
elif data == ">":
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"expected-doctype-name-but-got-right-bracket"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["name"] = "\uFFFD"
self.state = self.doctypeNameState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"expected-doctype-name-but-got-eof"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.currentToken["name"] = data
self.state = self.doctypeNameState
return True
def doctypeNameState(self):
data = self.stream.char()
if data in spaceCharacters:
self.currentToken["name"] = self.currentToken["name"].translate(asciiUpper2Lower)
self.state = self.afterDoctypeNameState
elif data == ">":
self.currentToken["name"] = self.currentToken["name"].translate(asciiUpper2Lower)
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["name"] += "\uFFFD"
self.state = self.doctypeNameState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-doctype-name"})
self.currentToken["correct"] = False
self.currentToken["name"] = self.currentToken["name"].translate(asciiUpper2Lower)
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.currentToken["name"] += data
return True
def afterDoctypeNameState(self):
data = self.stream.char()
if data in spaceCharacters:
pass
elif data == ">":
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data is EOF:
self.currentToken["correct"] = False
self.stream.unget(data)
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-doctype"})
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
if data in ("p", "P"):
matched = True
for expected in (("u", "U"), ("b", "B"), ("l", "L"),
("i", "I"), ("c", "C")):
data = self.stream.char()
if data not in expected:
matched = False
break
if matched:
self.state = self.afterDoctypePublicKeywordState
return True
elif data in ("s", "S"):
matched = True
for expected in (("y", "Y"), ("s", "S"), ("t", "T"),
("e", "E"), ("m", "M")):
data = self.stream.char()
if data not in expected:
matched = False
break
if matched:
self.state = self.afterDoctypeSystemKeywordState
return True
# All the characters read before the current 'data' will be
# [a-zA-Z], so they're garbage in the bogus doctype and can be
# discarded; only the latest character might be '>' or EOF
# and needs to be ungetted
self.stream.unget(data)
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"expected-space-or-right-bracket-in-doctype", "datavars":
{"data": data}})
self.currentToken["correct"] = False
self.state = self.bogusDoctypeState
return True
def afterDoctypePublicKeywordState(self):
data = self.stream.char()
if data in spaceCharacters:
self.state = self.beforeDoctypePublicIdentifierState
elif data in ("'", '"'):
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-char-in-doctype"})
self.stream.unget(data)
self.state = self.beforeDoctypePublicIdentifierState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.stream.unget(data)
self.state = self.beforeDoctypePublicIdentifierState
return True
def beforeDoctypePublicIdentifierState(self):
data = self.stream.char()
if data in spaceCharacters:
pass
elif data == "\"":
self.currentToken["publicId"] = ""
self.state = self.doctypePublicIdentifierDoubleQuotedState
elif data == "'":
self.currentToken["publicId"] = ""
self.state = self.doctypePublicIdentifierSingleQuotedState
elif data == ">":
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-end-of-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-char-in-doctype"})
self.currentToken["correct"] = False
self.state = self.bogusDoctypeState
return True
def doctypePublicIdentifierDoubleQuotedState(self):
data = self.stream.char()
if data == "\"":
self.state = self.afterDoctypePublicIdentifierState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["publicId"] += "\uFFFD"
elif data == ">":
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-end-of-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.currentToken["publicId"] += data
return True
def doctypePublicIdentifierSingleQuotedState(self):
data = self.stream.char()
if data == "'":
self.state = self.afterDoctypePublicIdentifierState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["publicId"] += "\uFFFD"
elif data == ">":
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-end-of-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.currentToken["publicId"] += data
return True
def afterDoctypePublicIdentifierState(self):
data = self.stream.char()
if data in spaceCharacters:
self.state = self.betweenDoctypePublicAndSystemIdentifiersState
elif data == ">":
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data == '"':
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-char-in-doctype"})
self.currentToken["systemId"] = ""
self.state = self.doctypeSystemIdentifierDoubleQuotedState
elif data == "'":
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-char-in-doctype"})
self.currentToken["systemId"] = ""
self.state = self.doctypeSystemIdentifierSingleQuotedState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-char-in-doctype"})
self.currentToken["correct"] = False
self.state = self.bogusDoctypeState
return True
def betweenDoctypePublicAndSystemIdentifiersState(self):
data = self.stream.char()
if data in spaceCharacters:
pass
elif data == ">":
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data == '"':
self.currentToken["systemId"] = ""
self.state = self.doctypeSystemIdentifierDoubleQuotedState
elif data == "'":
self.currentToken["systemId"] = ""
self.state = self.doctypeSystemIdentifierSingleQuotedState
elif data == EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-char-in-doctype"})
self.currentToken["correct"] = False
self.state = self.bogusDoctypeState
return True
def afterDoctypeSystemKeywordState(self):
data = self.stream.char()
if data in spaceCharacters:
self.state = self.beforeDoctypeSystemIdentifierState
elif data in ("'", '"'):
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-char-in-doctype"})
self.stream.unget(data)
self.state = self.beforeDoctypeSystemIdentifierState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.stream.unget(data)
self.state = self.beforeDoctypeSystemIdentifierState
return True
def beforeDoctypeSystemIdentifierState(self):
data = self.stream.char()
if data in spaceCharacters:
pass
elif data == "\"":
self.currentToken["systemId"] = ""
self.state = self.doctypeSystemIdentifierDoubleQuotedState
elif data == "'":
self.currentToken["systemId"] = ""
self.state = self.doctypeSystemIdentifierSingleQuotedState
elif data == ">":
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-char-in-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-char-in-doctype"})
self.currentToken["correct"] = False
self.state = self.bogusDoctypeState
return True
def doctypeSystemIdentifierDoubleQuotedState(self):
data = self.stream.char()
if data == "\"":
self.state = self.afterDoctypeSystemIdentifierState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["systemId"] += "\uFFFD"
elif data == ">":
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-end-of-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.currentToken["systemId"] += data
return True
def doctypeSystemIdentifierSingleQuotedState(self):
data = self.stream.char()
if data == "'":
self.state = self.afterDoctypeSystemIdentifierState
elif data == "\u0000":
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
self.currentToken["systemId"] += "\uFFFD"
elif data == ">":
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-end-of-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.currentToken["systemId"] += data
return True
def afterDoctypeSystemIdentifierState(self):
data = self.stream.char()
if data in spaceCharacters:
pass
elif data == ">":
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data is EOF:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"eof-in-doctype"})
self.currentToken["correct"] = False
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
self.tokenQueue.append({"type": tokenTypes["ParseError"], "data":
"unexpected-char-in-doctype"})
self.state = self.bogusDoctypeState
return True
def bogusDoctypeState(self):
data = self.stream.char()
if data == ">":
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
elif data is EOF:
# XXX EMIT
self.stream.unget(data)
self.tokenQueue.append(self.currentToken)
self.state = self.dataState
else:
pass
return True
def cdataSectionState(self):
data = []
while True:
data.append(self.stream.charsUntil("]"))
data.append(self.stream.charsUntil(">"))
char = self.stream.char()
if char == EOF:
break
else:
assert char == ">"
if data[-1][-2:] == "]]":
data[-1] = data[-1][:-2]
break
else:
data.append(char)
data = "".join(data)
# Deal with null here rather than in the parser
nullCount = data.count("\u0000")
if nullCount > 0:
for i in range(nullCount):
self.tokenQueue.append({"type": tokenTypes["ParseError"],
"data": "invalid-codepoint"})
data = data.replace("\u0000", "\uFFFD")
if data:
self.tokenQueue.append({"type": tokenTypes["Characters"],
"data": data})
self.state = self.dataState
return True
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.