repo_name
stringlengths 5
100
| path
stringlengths 4
375
| copies
stringclasses 991
values | size
stringlengths 4
7
| content
stringlengths 666
1M
| license
stringclasses 15
values |
---|---|---|---|---|---|
Turlough/keyczar
|
cpp/src/tools/scons/scons-local-1.2.0.d20090223/SCons/Tool/RCS.py
|
19
|
2190
|
"""SCons.Tool.RCS.py
Tool-specific initialization for RCS.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/RCS.py 4043 2009/02/23 09:06:45 scons"
import SCons.Action
import SCons.Builder
import SCons.Util
def generate(env):
"""Add a Builder factory function and construction variables for
RCS to an Environment."""
def RCSFactory(env=env):
""" """
act = SCons.Action.Action('$RCS_COCOM', '$RCS_COCOMSTR')
return SCons.Builder.Builder(action = act, env = env)
#setattr(env, 'RCS', RCSFactory)
env.RCS = RCSFactory
env['RCS'] = 'rcs'
env['RCS_CO'] = 'co'
env['RCS_COFLAGS'] = SCons.Util.CLVar('')
env['RCS_COCOM'] = '$RCS_CO $RCS_COFLAGS $TARGET'
def exists(env):
return env.Detect('rcs')
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
|
apache-2.0
|
Scille/parsec-cloud
|
parsec/core/mountpoint/thread_fs_access.py
|
1
|
2647
|
# Parsec Cloud (https://parsec.cloud) Copyright (c) AGPLv3 2016-2021 Scille SAS
import trio
class ThreadFSAccess:
def __init__(self, trio_token, workspace_fs):
self.workspace_fs = workspace_fs
self._trio_token = trio_token
def _run(self, fn, *args):
return trio.from_thread.run(fn, *args, trio_token=self._trio_token)
def _run_sync(self, fn, *args):
return trio.from_thread.run_sync(fn, *args, trio_token=self._trio_token)
# Rights check
def check_read_rights(self, path):
return self._run_sync(self.workspace_fs.transactions.check_read_rights, path)
def check_write_rights(self, path):
return self._run_sync(self.workspace_fs.transactions.check_write_rights, path)
# Entry transactions
def entry_info(self, path):
return self._run(self.workspace_fs.transactions.entry_info, path)
def entry_rename(self, source, destination, *, overwrite):
return self._run(
self.workspace_fs.transactions.entry_rename, source, destination, overwrite
)
# Folder transactions
def folder_create(self, path):
return self._run(self.workspace_fs.transactions.folder_create, path)
def folder_delete(self, path):
return self._run(self.workspace_fs.transactions.folder_delete, path)
# File transactions
def file_create(self, path, *, open):
return self._run(self.workspace_fs.transactions.file_create, path, open)
def file_open(self, path, *, write_mode):
return self._run(self.workspace_fs.transactions.file_open, path, write_mode)
def file_delete(self, path):
return self._run(self.workspace_fs.transactions.file_delete, path)
def file_resize(self, path, length):
return self._run(self.workspace_fs.transactions.file_resize, path, length)
# File descriptor transactions
def fd_close(self, fh):
return self._run(self.workspace_fs.transactions.fd_close, fh)
def fd_seek(self, fh, offset):
return self._run(self.workspace_fs.transactions.fd_seek, fh, offset)
def fd_read(self, fh, size, offset, raise_eof=False):
return self._run(self.workspace_fs.transactions.fd_read, fh, size, offset, raise_eof)
def fd_write(self, fh, data, offset, constrained=False):
return self._run(self.workspace_fs.transactions.fd_write, fh, data, offset, constrained)
def fd_resize(self, fh, length, truncate_only=False):
return self._run(self.workspace_fs.transactions.fd_resize, fh, length, truncate_only)
def fd_flush(self, fh):
return self._run(self.workspace_fs.transactions.fd_flush, fh)
|
agpl-3.0
|
hotzenklotz/Flask-React-Webpack-Server
|
server.py
|
1
|
7310
|
# System imports
import subprocess
import time
from os import path
import shutil
import numpy as np
from flask.ext.cors import CORS
from flask import *
from werkzeug import secure_filename
from flask_extensions import *
import math
# Local predicition modules
# find modules in parent_folder/predictions
# sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'prediction'))
static_assets_path = path.join(path.dirname(__file__), "dist")
app = Flask(__name__, static_folder=static_assets_path)
CORS(app)
LABEL_MAPPING = {}
def load_label_mapping():
global LABEL_MAPPING
with open(app.config["LABEL_MAPPING"], "r") as f:
for line in f:
splitted = line.split(" ")
LABEL_MAPPING[int(splitted[1])] = splitted[0]
def slice_in_chunks(els, n):
for i in range(0, len(els), n):
yield els[i:i+n]
def clear_folder(folder):
for the_file in os.listdir(folder):
file_path = os.path.join(folder, the_file)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception, e:
print e
# ----- Video -----------
import caffe
def create_frames(video_file_name, frame_rate, output_folder):
cmd = "ffmpeg -n -nostdin -i \"%s\" -r \"%d\" -qscale:v 2 \"%s/%%4d.jpg\"" % (video_file_name, frame_rate, output_folder)
subprocess.call(cmd, shell=True)
return output_folder
def create_flows(frame_folder, output_folder):
cmd = "%s %s %s 0" % (app.config["FLOW_CMD"], frame_folder, output_folder)
subprocess.call(cmd, shell=True)
return output_folder
def load_frame_data(frame_file):
return caffe.io.load_image(frame_file)
def load_frames(frame_list, w, h, transformer):
data = np.zeros((len(frame_list), 3, w, h))
for idx, frame in enumerate(frame_list):
data[idx, :, :, :] = transformer.preprocess('data', load_frame_data(frame))
return data
def frames_in_folder(folder):
return map(lambda p: os.path.join(folder, p), os.listdir(folder))
def predict_caffe(frame_files):
net = caffe.Net(app.config["CAFFE_SPATIAL_PROTO"], app.config["CAFFE_SPATIAL_MODEL"], caffe.TEST)
batch_size = app.config["CAFFE_BATCH_LIMIT"]
transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})
transformer.set_transpose('data', (2, 0, 1))
transformer.set_raw_scale('data', 255) # the reference model operates on images in [0,255] range instead of [0,1]
transformer.set_channel_swap('data', (2, 1, 0)) # the reference model has channels in BGR order instead of RGB
transformer.set_mean('data', np.load(app.config["CAFFE_SPATIAL_MEAN"]).mean(1).mean(1)) # mean pixel
caffe.set_mode_cpu()
results = np.zeros((len(frame_files), app.config["CAFFE_NUM_LABELS"]))
for cidx, chunk in enumerate(slice_in_chunks(frame_files, batch_size)):
data = load_frames(chunk, net.blobs['data'].data.shape[2], net.blobs['data'].data.shape[3], transformer)
net.blobs['data'].reshape(*data.shape)
out = net.forward_all(data=data)
print "Finished chunk %d of %d" % (cidx, math.ceil(len(frame_files) * 1.0 / batch_size))
results[cidx*batch_size: cidx*batch_size+len(chunk), :] = out['prob']
return results
# ----- Routes ----------
@app.route("/", defaults={"fall_through": ""})
@app.route("/<path:fall_through>")
def index(fall_through):
if fall_through:
return redirect(url_for("index"))
else:
return app.send_static_file("index.html")
@app.route("/dist/<path:asset_path>")
def send_static(asset_path):
return send_from_directory(static_assets_path, asset_path)
@app.route("/videos/<path:video_path>")
def send_video(video_path):
return send_file_partial(path.join(app.config["UPLOAD_FOLDER"], video_path))
@app.route("/api/upload", methods=["POST"])
def upload_video():
def is_allowed(file_name):
return len(filter(lambda ext: ext in file_name, ["avi", "mpg", "mpeg", "mkv", "webm", "mp4", "mov"])) > 0
video_file = request.files.getlist("video")[0]
if file and is_allowed(video_file.filename):
file_name = secure_filename(video_file.filename)
file_path = path.join(app.config["UPLOAD_FOLDER"], file_name)
video_file.save(file_path)
response = jsonify(get_prediction(file_path))
else:
response = bad_request("Invalid file")
return response
@app.route("/api/example/<int:example_id>")
def use_example(example_id):
if example_id <= 3:
filename = "video%s.webm" % example_id
file_path = path.join(app.config["UPLOAD_FOLDER"], "examples", filename)
response = jsonify(get_prediction(file_path))
else:
response = bad_request("Invalid Example")
return response
def bad_request(reason):
response = jsonify({"error": reason})
response.status_code = 400
return response
# -------- Prediction & Features --------
def get_prediction(file_path):
temp_dir = path.join(app.config["TEMP_FOLDER"], "frames", file_path)
shutil.rmtree(temp_dir, ignore_errors=True)
os.makedirs(temp_dir)
create_frames(file_path, 25, temp_dir)
create_flows(temp_dir)
# predictions = external_script.predict(file_path)
predictions = predict_caffe(frames_in_folder(temp_dir))
print "Shape of predicitons", predictions.shape, "Type", type(predictions)
print "Max ", np.argmax(predictions, axis=1)
file_path += "?cachebuster=%s" % time.time()
result = {
"video": {
"url": "%s" % file_path,
"framerate": 25
},
"frames": []
}
for idx, row in enumerate(predictions):
predictions_per_label = []
five_best = np.argpartition(row, -5)[-5:]
for i in five_best:
predictions_per_label.append({"label": LABEL_MAPPING[i], "prob": row[i].item()})
new_frame = {
"frameNumber": idx,
"predictions": predictions_per_label
}
result["frames"].append(new_frame)
print result
return result
if __name__ == "__main__":
# Start the server
app.config.update(
DEBUG=True,
SECRET_KEY="asassdfs",
CORS_HEADERS="Content-Type",
UPLOAD_FOLDER="videos",
TEMP_FOLDER="temp",
LABEL_MAPPING="/Users/tombocklisch/Documents/Studium/Master Project/models/label_mapping.txt",
FLOW_CMD="/Users/tombocklisch/Documents/Studium/Master Project/somefile",
CAFFE_BATCH_LIMIT=50,
CAFFE_NUM_LABELS=101,
CAFFE_SPATIAL_PROTO="/Users/tombocklisch/Documents/Studium/Master Project/models/deploy.prototxt",
CAFFE_SPATIAL_MODEL="/Users/tombocklisch/Documents/Studium/Master Project/models/_iter_70000.caffemodel",
CAFFE_SPATIAL_MEAN="/Users/tombocklisch/Documents/Studium/Master Project/models/ilsvrc_2012_mean.npy" #"/home/mpss2015/caffe/python/caffe/imagenet/ilsvrc_2012_mean.npy"
)
clear_folder(path.join(app.config["TEMP_FOLDER"], "frames"))
load_label_mapping()
# Make sure all frontend assets are compiled
subprocess.Popen("webpack")
# Start the Flask app
app.run(port=9000, threaded=True)
|
mit
|
ToontownUprising/src
|
otp/chat/ChatInputNormal.py
|
3
|
4076
|
from direct.gui.DirectGui import *
from direct.showbase import DirectObject
from pandac.PandaModules import *
import sys
from otp.otpbase import OTPGlobals
from otp.otpbase import OTPLocalizer
from toontown.chat.ChatGlobals import *
class ChatInputNormal(DirectObject.DirectObject):
def __init__(self, chatMgr):
self.chatMgr = chatMgr
self.normalPos = Vec3(-1.083, 0, 0.804)
self.whisperPos = Vec3(0.0, 0, 0.71)
self.whisperAvatarName = None
self.whisperAvatarId = None
self.toPlayer = 0
wantHistory = 0
if __dev__:
wantHistory = 1
self.wantHistory = base.config.GetBool('want-chat-history', wantHistory)
self.history = ['']
self.historySize = base.config.GetInt('chat-history-size', 10)
self.historyIndex = 0
return
def typeCallback(self, extraArgs):
messenger.send('enterNormalChat')
def delete(self):
self.ignore('arrow_up-up')
self.ignore('arrow_down-up')
self.chatFrame.destroy()
del self.chatFrame
del self.chatButton
del self.cancelButton
del self.chatEntry
del self.whisperLabel
del self.chatMgr
def activateByData(self, whisperAvatarId = None, toPlayer = 0):
self.toPlayer = toPlayer
self.whisperAvatarId = whisperAvatarId
if self.whisperAvatarId:
self.whisperAvatarName = base.talkAssistant.findName(self.whisperAvatarId, self.toPlayer)
self.chatFrame.setPos(self.whisperPos)
self.whisperLabel['text'] = OTPLocalizer.ChatInputWhisperLabel % self.whisperAvatarName
self.whisperLabel.show()
else:
self.chatFrame.setPos(self.normalPos)
self.whisperLabel.hide()
self.chatEntry['focus'] = 1
self.chatFrame.show()
if self.wantHistory:
self.accept('arrow_up-up', self.getPrevHistory)
self.accept('arrow_down-up', self.getNextHistory)
return True
def deactivate(self):
self.chatEntry.set('')
self.chatEntry['focus'] = 0
self.chatFrame.hide()
self.whisperLabel.hide()
base.win.closeIme()
self.ignore('arrow_up-up')
self.ignore('arrow_down-up')
def checkForOverRide(self):
return False
def sendChat(self, text):
if self.checkForOverRide():
self.chatEntry.enterText('')
return
self.deactivate()
self.chatMgr.fsm.request('mainMenu')
if text:
if self.toPlayer:
if self.whisperAvatarId:
self.whisperAvatarName = None
self.whisperAvatarId = None
self.toPlayer = 0
elif self.whisperAvatarId:
self.chatMgr.sendWhisperString(text, self.whisperAvatarId)
self.whisperAvatarName = None
self.whisperAvatarId = None
else:
base.talkAssistant.sendOpenTalk(text)
if self.wantHistory:
self.addToHistory(text)
return
def chatOverflow(self, overflowText):
self.sendChat(self.chatEntry.get())
def cancelButtonPressed(self):
self.chatEntry.set('')
self.chatMgr.fsm.request('mainMenu')
def chatButtonPressed(self):
self.sendChat(self.chatEntry.get())
def addToHistory(self, text):
self.history = [text] + self.history[:self.historySize - 1]
self.historyIndex = 0
def getPrevHistory(self):
self.chatEntry.set(self.history[self.historyIndex])
self.historyIndex += 1
self.historyIndex %= len(self.history)
def getNextHistory(self):
self.chatEntry.set(self.history[self.historyIndex])
self.historyIndex -= 1
self.historyIndex %= len(self.history)
def setPos(self, posX, posY = None, posZ = None):
if posX and posY and posZ:
self.chatFrame.setPos(posX, posY, posZ)
else:
self.chatFrame.setPos(posX)
|
mit
|
bitcraze/toolbelt
|
src/toolbelt/test/utils/test_git.py
|
1
|
2105
|
# -*- coding: utf-8 -*-
#
# || ____ _ __
# +------+ / __ )(_) /_______________ _____ ___
# | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
# +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
# || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
#
# Toolbelt - a utility tu run tools in docker containers
# Copyright (C) 2016 Bitcraze AB
#
# 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 unittest
from unittest.mock import MagicMock, ANY
from toolbelt.utils.git import Git
from toolbelt.utils.subproc import SubProc
class GitTest(unittest.TestCase):
def setUp(self):
self.sub_proc_mock = MagicMock(SubProc)
self.sut = Git(self.sub_proc_mock)
def test_clone(self):
# Fixture
repo = "aRepo"
destination = "path"
# Test
self.sut.clone(repo, destination)
# Assert
self.sub_proc_mock.check_call.assert_called_once_with(
["git", "clone", '--recursive', repo, destination],
stdout=ANY, stderr=ANY)
def test_clone_all_params(self):
# Fixture
repo = "aRepo"
destination = "path"
tag = "aTag"
depth = 17
# Test
self.sut.clone(repo, destination, tag, depth)
# Assert
self.sub_proc_mock.check_call.assert_called_once_with(
["git", "clone", '--recursive', '--branch=' + tag,
'--depth=' + str(depth), repo, destination],
stdout=ANY, stderr=ANY)
|
gpl-3.0
|
meabsence/python-for-android
|
python3-alpha/python3-src/Lib/test/test_dummy_threading.py
|
182
|
1807
|
from test import support
import unittest
import dummy_threading as _threading
import time
class DummyThreadingTestCase(unittest.TestCase):
class TestThread(_threading.Thread):
def run(self):
global running
global sema
global mutex
# Uncomment if testing another module, such as the real 'threading'
# module.
#delay = random.random() * 2
delay = 0
if support.verbose:
print('task', self.name, 'will run for', delay, 'sec')
sema.acquire()
mutex.acquire()
running += 1
if support.verbose:
print(running, 'tasks are running')
mutex.release()
time.sleep(delay)
if support.verbose:
print('task', self.name, 'done')
mutex.acquire()
running -= 1
if support.verbose:
print(self.name, 'is finished.', running, 'tasks are running')
mutex.release()
sema.release()
def setUp(self):
self.numtasks = 10
global sema
sema = _threading.BoundedSemaphore(value=3)
global mutex
mutex = _threading.RLock()
global running
running = 0
self.threads = []
def test_tasks(self):
for i in range(self.numtasks):
t = self.TestThread(name="<thread %d>"%i)
self.threads.append(t)
t.start()
if support.verbose:
print('waiting for all tasks to complete')
for t in self.threads:
t.join()
if support.verbose:
print('all tasks done')
def test_main():
support.run_unittest(DummyThreadingTestCase)
if __name__ == '__main__':
test_main()
|
apache-2.0
|
moomou/heron
|
heron/tools/ui/src/python/args.py
|
2
|
3283
|
# Copyright 2016 Twitter. 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.
''' args.py '''
import argparse
import heron.tools.ui.src.python.consts as consts
# pylint: disable=protected-access
class _HelpAction(argparse._HelpAction):
def __call__(self, parser, namespace, values, option_string=None):
parser.print_help()
# retrieve subparsers from parser
subparsers_actions = [
action for action in parser._actions
if isinstance(action, argparse._SubParsersAction)
]
# there will probably only be one subparser_action,
# but better save than sorry
for subparsers_action in subparsers_actions:
# get all subparsers and print help
for choice, subparser in subparsers_action.choices.items():
print "Subparser '{}'".format(choice)
print subparser.format_help()
parser.exit()
class SubcommandHelpFormatter(argparse.RawDescriptionHelpFormatter):
''' SubcommandHelpFormatter '''
def _format_action(self, action):
# pylint: disable=bad-super-call
parts = super(argparse.RawDescriptionHelpFormatter, self)._format_action(action)
if action.nargs == argparse.PARSER:
parts = "\n".join(parts.split("\n")[1:])
return parts
def add_titles(parser):
'''
:param parser:
:return:
'''
parser._positionals.title = "Required arguments"
parser._optionals.title = "Optional arguments"
return parser
def add_arguments(parser):
'''
:param parser:
:return:
'''
parser.add_argument(
'--tracker_url',
metavar='(a url; path to tracker; default: "' + consts.DEFAULT_TRACKER_URL + '")',
default=consts.DEFAULT_TRACKER_URL)
parser.add_argument(
'--address',
metavar='(an string; address to listen; default: "' + consts.DEFAULT_ADDRESS + '")',
default=consts.DEFAULT_ADDRESS)
parser.add_argument(
'--port',
metavar='(an integer; port to listen; default: ' + str(consts.DEFAULT_PORT) + ')',
type=int,
default=consts.DEFAULT_PORT)
return parser
def create_parsers():
'''
:return:
'''
parser = argparse.ArgumentParser(
epilog='For detailed documentation, go to http://heronstreaming.io',
usage="%(prog)s [options] [help]",
add_help=False)
parser = add_titles(parser)
parser = add_arguments(parser)
# create the child parser for subcommand
child_parser = argparse.ArgumentParser(
parents=[parser],
formatter_class=SubcommandHelpFormatter,
add_help=False)
# subparser for each command
subparsers = child_parser.add_subparsers(
title="Available commands")
help_parser = subparsers.add_parser(
'help',
help='Prints help',
add_help=False)
help_parser.set_defaults(help=True)
return (parser, child_parser)
|
apache-2.0
|
lyndsysimon/osf.io
|
scripts/tests/test_email_registration_contributors.py
|
60
|
2231
|
import mock
from nose.tools import * # noqa
from tests.base import OsfTestCase
from tests.factories import RegistrationFactory, UserFactory
from website import models
from scripts.email_registration_contributors import (
get_registration_contributors, send_retraction_and_embargo_addition_message,
main, MAILER, MESSAGE_NAME
)
class TestSendRetractionAndEmbargoAdditionMessage(OsfTestCase):
def setUp(self):
super(TestSendRetractionAndEmbargoAdditionMessage, self).setUp()
self.registration_contrib = UserFactory()
self.other_user = UserFactory()
self.registration = RegistrationFactory(creator=self.registration_contrib)
def tearDown(self):
super(TestSendRetractionAndEmbargoAdditionMessage, self).tearDown()
models.Node.remove()
models.User.remove()
def test_get_registration_contributors(self):
assert_equal(models.User.find().count(), 2)
registration_contributors = get_registration_contributors()
assert_equal(len(registration_contributors), 1)
@mock.patch('scripts.email_registration_contributors.send_retraction_and_embargo_addition_message')
def test_send_retraction_and_embargo_addition_message(self, mock_send_mail):
user = UserFactory()
send_retraction_and_embargo_addition_message(user, MESSAGE_NAME, MAILER, dry_run=False)
user.reload()
assert_in(MESSAGE_NAME, user.security_messages)
@mock.patch('scripts.email_registration_contributors.send_retraction_and_embargo_addition_message')
def test_dry_run_does_not_save_to_user(self, mock_send_mail):
user = UserFactory()
send_retraction_and_embargo_addition_message(user, MESSAGE_NAME, MAILER, dry_run=True)
user.reload()
assert_not_in(MESSAGE_NAME, user.security_messages)
def test_main_dry_run_True_does_save(self):
assert_equal(len(get_registration_contributors()), 1)
main(dry_run=False)
assert_equal(len(get_registration_contributors()), 0)
def test_main_dry_run_False_does_not_save(self):
assert_equal(len(get_registration_contributors()), 1)
main(dry_run=True)
assert_equal(len(get_registration_contributors()), 1)
|
apache-2.0
|
alexvanboxel/airflow
|
tests/contrib/operators/ecs_operator.py
|
8
|
7382
|
# -*- coding: utf-8 -*-
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import sys
import unittest
from copy import deepcopy
from airflow import configuration
from airflow.exceptions import AirflowException
from airflow.contrib.operators.ecs_operator import ECSOperator
try:
from unittest import mock
except ImportError:
try:
import mock
except ImportError:
mock = None
RESPONSE_WITHOUT_FAILURES = {
"failures": [],
"tasks": [
{
"containers": [
{
"containerArn": "arn:aws:ecs:us-east-1:012345678910:container/e1ed7aac-d9b2-4315-8726-d2432bf11868",
"lastStatus": "PENDING",
"name": "wordpress",
"taskArn": "arn:aws:ecs:us-east-1:012345678910:task/d8c67b3c-ac87-4ffe-a847-4785bc3a8b55"
}
],
"desiredStatus": "RUNNING",
"lastStatus": "PENDING",
"taskArn": "arn:aws:ecs:us-east-1:012345678910:task/d8c67b3c-ac87-4ffe-a847-4785bc3a8b55",
"taskDefinitionArn": "arn:aws:ecs:us-east-1:012345678910:task-definition/hello_world:11"
}
]
}
class TestECSOperator(unittest.TestCase):
@mock.patch('airflow.contrib.operators.ecs_operator.AwsHook')
def setUp(self, aws_hook_mock):
configuration.load_test_config()
self.aws_hook_mock = aws_hook_mock
self.ecs = ECSOperator(
task_id='task',
task_definition='t',
cluster='c',
overrides={},
aws_conn_id=None,
region_name='eu-west-1')
def test_init(self):
self.assertEqual(self.ecs.region_name, 'eu-west-1')
self.assertEqual(self.ecs.task_definition, 't')
self.assertEqual(self.ecs.aws_conn_id, None)
self.assertEqual(self.ecs.cluster, 'c')
self.assertEqual(self.ecs.overrides, {})
self.assertEqual(self.ecs.hook, self.aws_hook_mock.return_value)
self.aws_hook_mock.assert_called_once_with(aws_conn_id=None)
def test_template_fields_overrides(self):
self.assertEqual(self.ecs.template_fields, ('overrides',))
@mock.patch.object(ECSOperator, '_wait_for_task_ended')
@mock.patch.object(ECSOperator, '_check_success_task')
def test_execute_without_failures(self, check_mock, wait_mock):
client_mock = self.aws_hook_mock.return_value.get_client_type.return_value
client_mock.run_task.return_value = RESPONSE_WITHOUT_FAILURES
self.ecs.execute(None)
self.aws_hook_mock.return_value.get_client_type.assert_called_once_with('ecs', region_name='eu-west-1')
client_mock.run_task.assert_called_once_with(
cluster='c',
overrides={},
startedBy='Airflow',
taskDefinition='t'
)
wait_mock.assert_called_once_with()
check_mock.assert_called_once_with()
self.assertEqual(self.ecs.arn, 'arn:aws:ecs:us-east-1:012345678910:task/d8c67b3c-ac87-4ffe-a847-4785bc3a8b55')
def test_execute_with_failures(self):
client_mock = self.aws_hook_mock.return_value.get_client_type.return_value
resp_failures = deepcopy(RESPONSE_WITHOUT_FAILURES)
resp_failures['failures'].append('dummy error')
client_mock.run_task.return_value = resp_failures
with self.assertRaises(AirflowException):
self.ecs.execute(None)
self.aws_hook_mock.return_value.get_client_type.assert_called_once_with('ecs', region_name='eu-west-1')
client_mock.run_task.assert_called_once_with(
cluster='c',
overrides={},
startedBy='Airflow',
taskDefinition='t'
)
def test_wait_end_tasks(self):
client_mock = mock.Mock()
self.ecs.arn = 'arn'
self.ecs.client = client_mock
self.ecs._wait_for_task_ended()
client_mock.get_waiter.assert_called_once_with('tasks_stopped')
client_mock.get_waiter.return_value.wait.assert_called_once_with(cluster='c', tasks=['arn'])
self.assertEquals(sys.maxint, client_mock.get_waiter.return_value.config.max_attempts)
def test_check_success_tasks_raises(self):
client_mock = mock.Mock()
self.ecs.arn = 'arn'
self.ecs.client = client_mock
client_mock.describe_tasks.return_value = {
'tasks': [{
'containers': [{
'name': 'foo',
'lastStatus': 'STOPPED',
'exitCode': 1
}]
}]
}
with self.assertRaises(Exception) as e:
self.ecs._check_success_task()
self.assertEquals(str(e.exception), "This task is not in success state {'containers': [{'lastStatus': 'STOPPED', 'name': 'foo', 'exitCode': 1}]}")
client_mock.describe_tasks.assert_called_once_with(cluster='c', tasks=['arn'])
def test_check_success_tasks_raises_pending(self):
client_mock = mock.Mock()
self.ecs.client = client_mock
self.ecs.arn = 'arn'
client_mock.describe_tasks.return_value = {
'tasks': [{
'containers': [{
'name': 'container-name',
'lastStatus': 'PENDING'
}]
}]
}
with self.assertRaises(Exception) as e:
self.ecs._check_success_task()
self.assertEquals(str(e.exception), "This task is still pending {'containers': [{'lastStatus': 'PENDING', 'name': 'container-name'}]}")
client_mock.describe_tasks.assert_called_once_with(cluster='c', tasks=['arn'])
def test_check_success_tasks_raises_mutliple(self):
client_mock = mock.Mock()
self.ecs.client = client_mock
self.ecs.arn = 'arn'
client_mock.describe_tasks.return_value = {
'tasks': [{
'containers': [{
'name': 'foo',
'exitCode': 1
}, {
'name': 'bar',
'lastStatus': 'STOPPED',
'exitCode': 0
}]
}]
}
self.ecs._check_success_task()
client_mock.describe_tasks.assert_called_once_with(cluster='c', tasks=['arn'])
def test_check_success_task_not_raises(self):
client_mock = mock.Mock()
self.ecs.client = client_mock
self.ecs.arn = 'arn'
client_mock.describe_tasks.return_value = {
'tasks': [{
'containers': [{
'name': 'container-name',
'lastStatus': 'STOPPED',
'exitCode': 0
}]
}]
}
self.ecs._check_success_task()
client_mock.describe_tasks.assert_called_once_with(cluster='c', tasks=['arn'])
if __name__ == '__main__':
unittest.main()
|
apache-2.0
|
jamesblunt/sympy
|
sympy/functions/elementary/hyperbolic.py
|
4
|
31649
|
from __future__ import print_function, division
from sympy.core import S, C, sympify, cacheit
from sympy.core.function import Function, ArgumentIndexError, _coeff_isneg
from sympy.functions.elementary.miscellaneous import sqrt
###############################################################################
########################### HYPERBOLIC FUNCTIONS ##############################
###############################################################################
class HyperbolicFunction(Function):
"""
Base class for hyperbolic functions.
See Also
========
sinh, cosh, tanh, coth
"""
unbranched = True
class sinh(HyperbolicFunction):
r"""
The hyperbolic sine function, `\frac{e^x - e^{-x}}{2}`.
* sinh(x) -> Returns the hyperbolic sine of x
See Also
========
cosh, tanh, asinh
"""
def fdiff(self, argindex=1):
"""
Returns the first derivative of this function.
"""
if argindex == 1:
return cosh(self.args[0])
else:
raise ArgumentIndexError(self, argindex)
def inverse(self, argindex=1):
"""
Returns the inverse of this function.
"""
return asinh
@classmethod
def eval(cls, arg):
arg = sympify(arg)
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg is S.Infinity:
return S.Infinity
elif arg is S.NegativeInfinity:
return S.NegativeInfinity
elif arg is S.Zero:
return S.Zero
elif arg.is_negative:
return -cls(-arg)
else:
if arg is S.ComplexInfinity:
return S.NaN
i_coeff = arg.as_coefficient(S.ImaginaryUnit)
if i_coeff is not None:
return S.ImaginaryUnit * C.sin(i_coeff)
else:
if _coeff_isneg(arg):
return -cls(-arg)
if arg.func == asinh:
return arg.args[0]
if arg.func == acosh:
x = arg.args[0]
return sqrt(x - 1) * sqrt(x + 1)
if arg.func == atanh:
x = arg.args[0]
return x/sqrt(1 - x**2)
if arg.func == acoth:
x = arg.args[0]
return 1/(sqrt(x - 1) * sqrt(x + 1))
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
"""
Returns the next term in the Taylor series expansion.
"""
if n < 0 or n % 2 == 0:
return S.Zero
else:
x = sympify(x)
if len(previous_terms) > 2:
p = previous_terms[-2]
return p * x**2 / (n*(n - 1))
else:
return x**(n) / C.factorial(n)
def _eval_conjugate(self):
return self.func(self.args[0].conjugate())
def as_real_imag(self, deep=True, **hints):
"""
Returns this function as a complex coordinate.
"""
if self.args[0].is_real:
if deep:
hints['complex'] = False
return (self.expand(deep, **hints), S.Zero)
else:
return (self, S.Zero)
if deep:
re, im = self.args[0].expand(deep, **hints).as_real_imag()
else:
re, im = self.args[0].as_real_imag()
return (sinh(re)*C.cos(im), cosh(re)*C.sin(im))
def _eval_expand_complex(self, deep=True, **hints):
re_part, im_part = self.as_real_imag(deep=deep, **hints)
return re_part + im_part*S.ImaginaryUnit
def _eval_expand_trig(self, deep=True, **hints):
if deep:
arg = self.args[0].expand(deep, **hints)
else:
arg = self.args[0]
x = None
if arg.is_Add: # TODO, implement more if deep stuff here
x, y = arg.as_two_terms()
else:
coeff, terms = arg.as_coeff_Mul(rational=True)
if coeff is not S.One and coeff.is_Integer and terms is not S.One:
x = terms
y = (coeff - 1)*x
if x is not None:
return (sinh(x)*cosh(y) + sinh(y)*cosh(x)).expand(trig=True)
return sinh(arg)
def _eval_rewrite_as_tractable(self, arg):
return (C.exp(arg) - C.exp(-arg)) / 2
def _eval_rewrite_as_exp(self, arg):
return (C.exp(arg) - C.exp(-arg)) / 2
def _eval_rewrite_as_cosh(self, arg):
return -S.ImaginaryUnit*cosh(arg + S.Pi*S.ImaginaryUnit/2)
def _eval_rewrite_as_tanh(self, arg):
tanh_half = tanh(S.Half*arg)
return 2*tanh_half/(1 - tanh_half**2)
def _eval_rewrite_as_coth(self, arg):
coth_half = coth(S.Half*arg)
return 2*coth_half/(coth_half**2 - 1)
def _eval_as_leading_term(self, x):
arg = self.args[0].as_leading_term(x)
if x in arg.free_symbols and C.Order(1, x).contains(arg):
return arg
else:
return self.func(arg)
def _eval_is_real(self):
return self.args[0].is_real
def _eval_is_finite(self):
arg = self.args[0]
if arg.is_imaginary:
return True
def _sage_(self):
import sage.all as sage
return sage.sinh(self.args[0]._sage_())
class cosh(HyperbolicFunction):
r"""
The hyperbolic cosine function, `\frac{e^x + e^{-x}}{2}`.
* cosh(x) -> Returns the hyperbolic cosine of x
See Also
========
sinh, tanh, acosh
"""
def fdiff(self, argindex=1):
if argindex == 1:
return sinh(self.args[0])
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, arg):
arg = sympify(arg)
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg is S.Infinity:
return S.Infinity
elif arg is S.NegativeInfinity:
return S.Infinity
elif arg is S.Zero:
return S.One
elif arg.is_negative:
return cls(-arg)
else:
if arg is S.ComplexInfinity:
return S.NaN
i_coeff = arg.as_coefficient(S.ImaginaryUnit)
if i_coeff is not None:
return C.cos(i_coeff)
else:
if _coeff_isneg(arg):
return cls(-arg)
if arg.func == asinh:
return sqrt(1 + arg.args[0]**2)
if arg.func == acosh:
return arg.args[0]
if arg.func == atanh:
return 1/sqrt(1 - arg.args[0]**2)
if arg.func == acoth:
x = arg.args[0]
return x/(sqrt(x - 1) * sqrt(x + 1))
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
if n < 0 or n % 2 == 1:
return S.Zero
else:
x = sympify(x)
if len(previous_terms) > 2:
p = previous_terms[-2]
return p * x**2 / (n*(n - 1))
else:
return x**(n)/C.factorial(n)
def _eval_conjugate(self):
return self.func(self.args[0].conjugate())
def as_real_imag(self, deep=True, **hints):
if self.args[0].is_real:
if deep:
hints['complex'] = False
return (self.expand(deep, **hints), S.Zero)
else:
return (self, S.Zero)
if deep:
re, im = self.args[0].expand(deep, **hints).as_real_imag()
else:
re, im = self.args[0].as_real_imag()
return (cosh(re)*C.cos(im), sinh(re)*C.sin(im))
def _eval_expand_complex(self, deep=True, **hints):
re_part, im_part = self.as_real_imag(deep=deep, **hints)
return re_part + im_part*S.ImaginaryUnit
def _eval_expand_trig(self, deep=True, **hints):
if deep:
arg = self.args[0].expand(deep, **hints)
else:
arg = self.args[0]
x = None
if arg.is_Add: # TODO, implement more if deep stuff here
x, y = arg.as_two_terms()
else:
coeff, terms = arg.as_coeff_Mul(rational=True)
if coeff is not S.One and coeff.is_Integer and terms is not S.One:
x = terms
y = (coeff - 1)*x
if x is not None:
return (cosh(x)*cosh(y) + sinh(x)*sinh(y)).expand(trig=True)
return cosh(arg)
def _eval_rewrite_as_tractable(self, arg):
return (C.exp(arg) + C.exp(-arg)) / 2
def _eval_rewrite_as_exp(self, arg):
return (C.exp(arg) + C.exp(-arg)) / 2
def _eval_rewrite_as_sinh(self, arg):
return -S.ImaginaryUnit*sinh(arg + S.Pi*S.ImaginaryUnit/2)
def _eval_rewrite_as_tanh(self, arg):
tanh_half = tanh(S.Half*arg)**2
return (1 + tanh_half)/(1 - tanh_half)
def _eval_rewrite_as_coth(self, arg):
coth_half = coth(S.Half*arg)**2
return (coth_half + 1)/(coth_half - 1)
def _eval_as_leading_term(self, x):
arg = self.args[0].as_leading_term(x)
if x in arg.free_symbols and C.Order(1, x).contains(arg):
return S.One
else:
return self.func(arg)
def _eval_is_real(self):
return self.args[0].is_real
def _eval_is_finite(self):
arg = self.args[0]
if arg.is_imaginary:
return True
def _sage_(self):
import sage.all as sage
return sage.cosh(self.args[0]._sage_())
class tanh(HyperbolicFunction):
r"""
The hyperbolic tangent function, `\frac{\sinh(x)}{\cosh(x)}`.
* tanh(x) -> Returns the hyperbolic tangent of x
See Also
========
sinh, cosh, atanh
"""
def fdiff(self, argindex=1):
if argindex == 1:
return S.One - tanh(self.args[0])**2
else:
raise ArgumentIndexError(self, argindex)
def inverse(self, argindex=1):
"""
Returns the inverse of this function.
"""
return atanh
@classmethod
def eval(cls, arg):
arg = sympify(arg)
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg is S.Infinity:
return S.One
elif arg is S.NegativeInfinity:
return S.NegativeOne
elif arg is S.Zero:
return S.Zero
elif arg.is_negative:
return -cls(-arg)
else:
if arg is S.ComplexInfinity:
return S.NaN
i_coeff = arg.as_coefficient(S.ImaginaryUnit)
if i_coeff is not None:
if _coeff_isneg(i_coeff):
return -S.ImaginaryUnit * C.tan(-i_coeff)
return S.ImaginaryUnit * C.tan(i_coeff)
else:
if _coeff_isneg(arg):
return -cls(-arg)
if arg.func == asinh:
x = arg.args[0]
return x/sqrt(1 + x**2)
if arg.func == acosh:
x = arg.args[0]
return sqrt(x - 1) * sqrt(x + 1) / x
if arg.func == atanh:
return arg.args[0]
if arg.func == acoth:
return 1/arg.args[0]
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
if n < 0 or n % 2 == 0:
return S.Zero
else:
x = sympify(x)
a = 2**(n + 1)
B = C.bernoulli(n + 1)
F = C.factorial(n + 1)
return a*(a - 1) * B/F * x**n
def _eval_conjugate(self):
return self.func(self.args[0].conjugate())
def as_real_imag(self, deep=True, **hints):
if self.args[0].is_real:
if deep:
hints['complex'] = False
return (self.expand(deep, **hints), S.Zero)
else:
return (self, S.Zero)
if deep:
re, im = self.args[0].expand(deep, **hints).as_real_imag()
else:
re, im = self.args[0].as_real_imag()
denom = sinh(re)**2 + C.cos(im)**2
return (sinh(re)*cosh(re)/denom, C.sin(im)*C.cos(im)/denom)
def _eval_rewrite_as_tractable(self, arg):
neg_exp, pos_exp = C.exp(-arg), C.exp(arg)
return (pos_exp - neg_exp)/(pos_exp + neg_exp)
def _eval_rewrite_as_exp(self, arg):
neg_exp, pos_exp = C.exp(-arg), C.exp(arg)
return (pos_exp - neg_exp)/(pos_exp + neg_exp)
def _eval_rewrite_as_sinh(self, arg):
return S.ImaginaryUnit*sinh(arg)/sinh(S.Pi*S.ImaginaryUnit/2 - arg)
def _eval_rewrite_as_cosh(self, arg):
return S.ImaginaryUnit*cosh(S.Pi*S.ImaginaryUnit/2 - arg)/cosh(arg)
def _eval_rewrite_as_coth(self, arg):
return 1/coth(arg)
def _eval_as_leading_term(self, x):
arg = self.args[0].as_leading_term(x)
if x in arg.free_symbols and C.Order(1, x).contains(arg):
return arg
else:
return self.func(arg)
def _eval_is_real(self):
return self.args[0].is_real
def _eval_is_finite(self):
arg = self.args[0]
if arg.is_real:
return True
def _sage_(self):
import sage.all as sage
return sage.tanh(self.args[0]._sage_())
class coth(HyperbolicFunction):
r"""
The hyperbolic cotangent function, `\frac{\cosh(x)}{\sinh(x)}`.
* coth(x) -> Returns the hyperbolic cotangent of x
"""
def fdiff(self, argindex=1):
if argindex == 1:
return -1/sinh(self.args[0])**2
else:
raise ArgumentIndexError(self, argindex)
def inverse(self, argindex=1):
"""
Returns the inverse of this function.
"""
return acoth
@classmethod
def eval(cls, arg):
arg = sympify(arg)
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg is S.Infinity:
return S.One
elif arg is S.NegativeInfinity:
return S.NegativeOne
elif arg is S.Zero:
return S.ComplexInfinity
elif arg.is_negative:
return -cls(-arg)
else:
if arg is S.ComplexInfinity:
return S.NaN
i_coeff = arg.as_coefficient(S.ImaginaryUnit)
if i_coeff is not None:
if _coeff_isneg(i_coeff):
return S.ImaginaryUnit * C.cot(-i_coeff)
return -S.ImaginaryUnit * C.cot(i_coeff)
else:
if _coeff_isneg(arg):
return -cls(-arg)
if arg.func == asinh:
x = arg.args[0]
return sqrt(1 + x**2)/x
if arg.func == acosh:
x = arg.args[0]
return x/(sqrt(x - 1) * sqrt(x + 1))
if arg.func == atanh:
return 1/arg.args[0]
if arg.func == acoth:
return arg.args[0]
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
if n == 0:
return 1 / sympify(x)
elif n < 0 or n % 2 == 0:
return S.Zero
else:
x = sympify(x)
B = C.bernoulli(n + 1)
F = C.factorial(n + 1)
return 2**(n + 1) * B/F * x**n
def _eval_conjugate(self):
return self.func(self.args[0].conjugate())
def as_real_imag(self, deep=True, **hints):
if self.args[0].is_real:
if deep:
hints['complex'] = False
return (self.expand(deep, **hints), S.Zero)
else:
return (self, S.Zero)
if deep:
re, im = self.args[0].expand(deep, **hints).as_real_imag()
else:
re, im = self.args[0].as_real_imag()
denom = sinh(re)**2 + C.sin(im)**2
return (sinh(re)*cosh(re)/denom, -C.sin(im)*C.cos(im)/denom)
def _eval_rewrite_as_tractable(self, arg):
neg_exp, pos_exp = C.exp(-arg), C.exp(arg)
return (pos_exp + neg_exp)/(pos_exp - neg_exp)
def _eval_rewrite_as_exp(self, arg):
neg_exp, pos_exp = C.exp(-arg), C.exp(arg)
return (pos_exp + neg_exp)/(pos_exp - neg_exp)
def _eval_rewrite_as_sinh(self, arg):
return -S.ImaginaryUnit*sinh(S.Pi*S.ImaginaryUnit/2 - arg)/sinh(arg)
def _eval_rewrite_as_cosh(self, arg):
return -S.ImaginaryUnit*cosh(arg)/cosh(S.Pi*S.ImaginaryUnit/2 - arg)
def _eval_rewrite_as_tanh(self, arg):
return 1/tanh(arg)
def _eval_as_leading_term(self, x):
arg = self.args[0].as_leading_term(x)
if x in arg.free_symbols and C.Order(1, x).contains(arg):
return 1/arg
else:
return self.func(arg)
def _sage_(self):
import sage.all as sage
return sage.coth(self.args[0]._sage_())
class ReciprocalHyperbolicFunction(HyperbolicFunction):
"""Base class for reciprocal functions of hyperbolic functions. """
#To be defined in class
_reciprocal_of = None
_is_even = None
_is_odd = None
@classmethod
def eval(cls, arg):
if arg.could_extract_minus_sign():
if cls._is_even:
return cls(-arg)
if cls._is_odd:
return -cls(-arg)
t = cls._reciprocal_of.eval(arg)
if hasattr(arg, 'inverse') and arg.inverse() == cls:
return arg.args[0]
return 1/t if t != None else t
def _call_reciprocal(self, method_name, *args, **kwargs):
# Calls method_name on _reciprocal_of
o = self._reciprocal_of(self.args[0])
return getattr(o, method_name)(*args, **kwargs)
def _calculate_reciprocal(self, method_name, *args, **kwargs):
# If calling method_name on _reciprocal_of returns a value != None
# then return the reciprocal of that value
t = self._call_reciprocal(method_name, *args, **kwargs)
return 1/t if t != None else t
def _rewrite_reciprocal(self, method_name, arg):
# Special handling for rewrite functions. If reciprocal rewrite returns
# unmodified expression, then return None
t = self._call_reciprocal(method_name, arg)
if t != None and t != self._reciprocal_of(arg):
return 1/t
def _eval_rewrite_as_exp(self, arg):
return self._rewrite_reciprocal("_eval_rewrite_as_exp", arg)
def _eval_rewrite_as_tractable(self, arg):
return self._rewrite_reciprocal("_eval_rewrite_as_tractable", arg)
def _eval_rewrite_as_tanh(self, arg):
return self._rewrite_reciprocal("_eval_rewrite_as_tanh", arg)
def _eval_rewrite_as_coth(self, arg):
return self._rewrite_reciprocal("_eval_rewrite_as_coth", arg)
def as_real_imag(self, deep = True, **hints):
return (1 / self._reciprocal_of(self.args[0])).as_real_imag(deep, **hints)
def _eval_conjugate(self):
return self.func(self.args[0].conjugate())
def _eval_expand_complex(self, deep=True, **hints):
re_part, im_part = self.as_real_imag(deep=True, **hints)
return re_part + S.ImaginaryUnit*im_part
def _eval_as_leading_term(self, x):
return (1/self._reciprocal_of(self.args[0]))._eval_as_leading_term(x)
def _eval_is_real(self):
return self._reciprocal_of(args[0]).is_real
def _eval_is_finite(self):
return (1/self._reciprocal_of(args[0])).is_finite
class csch(ReciprocalHyperbolicFunction):
r"""
The hyperbolic cosecant function, `\frac{2}{e^x - e^{-x}}`
* csch(x) -> Returns the hyperbolic cosecant of x
See Also
========
sinh, cosh, tanh, sech, asinh, acosh
"""
_reciprocal_of = sinh
_is_odd = True
def fdiff(self, argindex=1):
"""
Returns the first derivative of this function
"""
if argindex == 1:
return -coth(self.args[0]) * csch(self.args[0])
else:
raise ArgumentIndexError(self, argindex)
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
"""
Returns the next term in the Taylor series expansion
"""
if n == 0:
return 1/sympify(x)
elif n < 0 or n % 2 == 0:
return S.Zero
else:
x = sympify(x)
B = C.bernoulli(n + 1)
F = C.factorial(n + 1)
return 2 * (1 - 2**n) * B/F * x**n
def _eval_rewrite_as_cosh(self, arg):
return S.ImaginaryUnit / cosh(arg + S.ImaginaryUnit * S.Pi / 2)
def _sage_(self):
import sage.all as sage
return sage.csch(self.args[0]._sage_())
class sech(ReciprocalHyperbolicFunction):
r"""
The hyperbolic secant function, `\frac{2}{e^x + e^{-x}}`
* sech(x) -> Returns the hyperbolic secant of x
See Also
========
sinh, cosh, tanh, coth, csch, asinh, acosh
"""
_reciprocal_of = cosh
_is_even = True
def fdiff(self, argindex=1):
if argindex == 1:
return - tanh(self.args[0])*sech(self.args[0])
else:
raise ArgumentIndexError(self, argindex)
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
if n < 0 or n % 2 == 1:
return S.Zero
else:
x = sympify(x)
return C.euler(n) / C.factorial(n) * x**(n)
def _eval_rewrite_as_sinh(self, arg):
return S.ImaginaryUnit / sinh(arg + S.ImaginaryUnit * S.Pi /2)
def _sage_(self):
import sage.all as sage
return sage.sech(self.args[0]._sage_())
###############################################################################
############################# HYPERBOLIC INVERSES #############################
###############################################################################
class asinh(Function):
"""
The inverse hyperbolic sine function.
* asinh(x) -> Returns the inverse hyperbolic sine of x
See Also
========
acosh, atanh, sinh
"""
def fdiff(self, argindex=1):
if argindex == 1:
return 1/sqrt(self.args[0]**2 + 1)
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, arg):
arg = sympify(arg)
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg is S.Infinity:
return S.Infinity
elif arg is S.NegativeInfinity:
return S.NegativeInfinity
elif arg is S.Zero:
return S.Zero
elif arg is S.One:
return C.log(sqrt(2) + 1)
elif arg is S.NegativeOne:
return C.log(sqrt(2) - 1)
elif arg.is_negative:
return -cls(-arg)
else:
if arg is S.ComplexInfinity:
return S.ComplexInfinity
i_coeff = arg.as_coefficient(S.ImaginaryUnit)
if i_coeff is not None:
return S.ImaginaryUnit * C.asin(i_coeff)
else:
if _coeff_isneg(arg):
return -cls(-arg)
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
if n < 0 or n % 2 == 0:
return S.Zero
else:
x = sympify(x)
if len(previous_terms) >= 2 and n > 2:
p = previous_terms[-2]
return -p * (n - 2)**2/(n*(n - 1)) * x**2
else:
k = (n - 1) // 2
R = C.RisingFactorial(S.Half, k)
F = C.factorial(k)
return (-1)**k * R / F * x**n / n
def _eval_as_leading_term(self, x):
arg = self.args[0].as_leading_term(x)
if x in arg.free_symbols and C.Order(1, x).contains(arg):
return arg
else:
return self.func(arg)
def inverse(self, argindex=1):
"""
Returns the inverse of this function.
"""
return sinh
def _sage_(self):
import sage.all as sage
return sage.asinh(self.args[0]._sage_())
class acosh(Function):
"""
The inverse hyperbolic cosine function.
* acosh(x) -> Returns the inverse hyperbolic cosine of x
See Also
========
asinh, atanh, cosh
"""
def fdiff(self, argindex=1):
if argindex == 1:
return 1/sqrt(self.args[0]**2 - 1)
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, arg):
arg = sympify(arg)
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg is S.Infinity:
return S.Infinity
elif arg is S.NegativeInfinity:
return S.Infinity
elif arg is S.Zero:
return S.Pi*S.ImaginaryUnit / 2
elif arg is S.One:
return S.Zero
elif arg is S.NegativeOne:
return S.Pi*S.ImaginaryUnit
if arg.is_number:
cst_table = {
S.ImaginaryUnit: C.log(S.ImaginaryUnit*(1 + sqrt(2))),
-S.ImaginaryUnit: C.log(-S.ImaginaryUnit*(1 + sqrt(2))),
S.Half: S.Pi/3,
-S.Half: 2*S.Pi/3,
sqrt(2)/2: S.Pi/4,
-sqrt(2)/2: 3*S.Pi/4,
1/sqrt(2): S.Pi/4,
-1/sqrt(2): 3*S.Pi/4,
sqrt(3)/2: S.Pi/6,
-sqrt(3)/2: 5*S.Pi/6,
(sqrt(3) - 1)/sqrt(2**3): 5*S.Pi/12,
-(sqrt(3) - 1)/sqrt(2**3): 7*S.Pi/12,
sqrt(2 + sqrt(2))/2: S.Pi/8,
-sqrt(2 + sqrt(2))/2: 7*S.Pi/8,
sqrt(2 - sqrt(2))/2: 3*S.Pi/8,
-sqrt(2 - sqrt(2))/2: 5*S.Pi/8,
(1 + sqrt(3))/(2*sqrt(2)): S.Pi/12,
-(1 + sqrt(3))/(2*sqrt(2)): 11*S.Pi/12,
(sqrt(5) + 1)/4: S.Pi/5,
-(sqrt(5) + 1)/4: 4*S.Pi/5
}
if arg in cst_table:
if arg.is_real:
return cst_table[arg]*S.ImaginaryUnit
return cst_table[arg]
if arg is S.ComplexInfinity:
return S.Infinity
i_coeff = arg.as_coefficient(S.ImaginaryUnit)
if i_coeff is not None:
if _coeff_isneg(i_coeff):
return S.ImaginaryUnit * C.acos(i_coeff)
return S.ImaginaryUnit * C.acos(-i_coeff)
else:
if _coeff_isneg(arg):
return -cls(-arg)
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
if n == 0:
return S.Pi*S.ImaginaryUnit / 2
elif n < 0 or n % 2 == 0:
return S.Zero
else:
x = sympify(x)
if len(previous_terms) >= 2 and n > 2:
p = previous_terms[-2]
return p * (n - 2)**2/(n*(n - 1)) * x**2
else:
k = (n - 1) // 2
R = C.RisingFactorial(S.Half, k)
F = C.factorial(k)
return -R / F * S.ImaginaryUnit * x**n / n
def _eval_as_leading_term(self, x):
arg = self.args[0].as_leading_term(x)
if x in arg.free_symbols and C.Order(1, x).contains(arg):
return S.ImaginaryUnit*S.Pi/2
else:
return self.func(arg)
def inverse(self, argindex=1):
"""
Returns the inverse of this function.
"""
return cosh
def _sage_(self):
import sage.all as sage
return sage.acosh(self.args[0]._sage_())
class atanh(Function):
"""
The inverse hyperbolic tangent function.
* atanh(x) -> Returns the inverse hyperbolic tangent of x
See Also
========
asinh, acosh, tanh
"""
def fdiff(self, argindex=1):
if argindex == 1:
return 1/(1 - self.args[0]**2)
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, arg):
arg = sympify(arg)
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg is S.Zero:
return S.Zero
elif arg is S.One:
return S.Infinity
elif arg is S.NegativeOne:
return S.NegativeInfinity
elif arg is S.Infinity:
return -S.ImaginaryUnit * C.atan(arg)
elif arg is S.NegativeInfinity:
return S.ImaginaryUnit * C.atan(-arg)
elif arg.is_negative:
return -cls(-arg)
else:
if arg is S.ComplexInfinity:
return S.NaN
i_coeff = arg.as_coefficient(S.ImaginaryUnit)
if i_coeff is not None:
return S.ImaginaryUnit * C.atan(i_coeff)
else:
if _coeff_isneg(arg):
return -cls(-arg)
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
if n < 0 or n % 2 == 0:
return S.Zero
else:
x = sympify(x)
return x**n / n
def _eval_as_leading_term(self, x):
arg = self.args[0].as_leading_term(x)
if x in arg.free_symbols and C.Order(1, x).contains(arg):
return arg
else:
return self.func(arg)
def inverse(self, argindex=1):
"""
Returns the inverse of this function.
"""
return tanh
def _sage_(self):
import sage.all as sage
return sage.atanh(self.args[0]._sage_())
class acoth(Function):
"""
The inverse hyperbolic cotangent function.
* acoth(x) -> Returns the inverse hyperbolic cotangent of x
"""
def fdiff(self, argindex=1):
if argindex == 1:
return 1/(1 - self.args[0]**2)
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, arg):
arg = sympify(arg)
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg is S.Infinity:
return S.Zero
elif arg is S.NegativeInfinity:
return S.Zero
elif arg is S.Zero:
return S.Pi*S.ImaginaryUnit / 2
elif arg is S.One:
return S.Infinity
elif arg is S.NegativeOne:
return S.NegativeInfinity
elif arg.is_negative:
return -cls(-arg)
else:
if arg is S.ComplexInfinity:
return 0
i_coeff = arg.as_coefficient(S.ImaginaryUnit)
if i_coeff is not None:
return -S.ImaginaryUnit * C.acot(i_coeff)
else:
if _coeff_isneg(arg):
return -cls(-arg)
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
if n == 0:
return S.Pi*S.ImaginaryUnit / 2
elif n < 0 or n % 2 == 0:
return S.Zero
else:
x = sympify(x)
return x**n / n
def _eval_as_leading_term(self, x):
arg = self.args[0].as_leading_term(x)
if x in arg.free_symbols and C.Order(1, x).contains(arg):
return S.ImaginaryUnit*S.Pi/2
else:
return self.func(arg)
def inverse(self, argindex=1):
"""
Returns the inverse of this function.
"""
return coth
def _sage_(self):
import sage.all as sage
return sage.acoth(self.args[0]._sage_())
|
bsd-3-clause
|
hansonrobotics/perception
|
test/test_perception.py
|
1
|
7152
|
#!/usr/bin/env python
# Copyright (c) 2013-2018 Hanson Robotics, Ltd.
import unittest
import os
import yaml
import roslaunch
import rostopic
from roslaunch import core
from testing_tools.misc import wait_for, wait_for_message
from genpy.message import fill_message_args
from sensor_msgs.msg import JointState
from tf.msg import tfMessage
from roslaunch import nodeprocess
nodeprocess._TIMEOUT_SIGINT = 2
nodeprocess._TIMEOUT_SIGTERM = 1
CWD = os.path.abspath(os.path.dirname(__file__))
PKG = 'perception'
class PerceptionTest(unittest.TestCase):
def setUp(self):
self.run_id = 'test_perception'
config = roslaunch.config.ROSLaunchConfig()
config.add_node(
core.Node(
package='perception', node_type='joint_state_publisher.py',
name='state_publisher')
)
self.joints = ['Eyes_Pitch', 'Eye_L', 'Eye_R', 'roll_base_joint',
'pitch_base_joint', 'yaw_joint', 'roll_neck_joint',
'pitch_neck_joint']
config.add_param(core.Param('/state_publisher/pau_joints',
';'.join(self.joints)))
config.add_node(
core.Node(
package='perception', node_type='faces_tf2_broadcaster.py',
name='faces_broadcaster')
)
self.runner = roslaunch.launch.ROSLaunchRunner(
self.run_id, config, is_rostest=True)
self.runner.launch()
for node in config.nodes:
wait_for('%s/%s' % (node.namespace, node.name))
def tearDown(self):
self.runner.stop()
def check_msg(self, msg_str, expects):
pub, msg_class = rostopic.create_publisher(
'/blender_api/get_pau', 'pau2motors/pau', True)
msg = msg_class()
fill_message_args(msg, yaml.load(msg_str))
pub.publish(msg)
msg = wait_for_message('/joint_states_combined', JointState, 2)
for key in ['position', 'name']:
self.assertListEqual(list(getattr(msg, key)), expects[key])
pub.unregister()
def test_joint_states_combined(self):
msg_str = """
m_headRotation:
x: 0.0
y: 0.0
z: 0.0
w: 0.0
m_headTranslation:
x: 0.0
y: 0.0
z: 0.0
m_neckRotation:
x: 0.0
y: 0.0
z: 0.0
w: 1.0
m_eyeGazeLeftPitch: 0.0
m_eyeGazeLeftYaw: 0.0
m_eyeGazeRightPitch: 0.0
m_eyeGazeRightYaw: 0.0
m_coeffs: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]"""
expects = {
'name': self.joints,
'position': [0, 0, 0, 0, 0, 0, 0, 0]
}
self.check_msg(msg_str, expects)
def test_joint_states_combined2(self):
msg_str = """
m_headRotation:
x: 0.0
y: 0.0
z: 0.0
w: 0.0
m_headTranslation:
x: 0.0
y: 0.0
z: 0.0
m_neckRotation:
x: 0.0
y: 0.0
z: 0.0
w: 1.0
m_eyeGazeLeftPitch: 1.0
m_eyeGazeLeftYaw: 0.0
m_eyeGazeRightPitch: 0.0
m_eyeGazeRightYaw: 0.0
m_coeffs: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]"""
expects = {
'name': self.joints,
'position': [1, 0, 0, 0, 0, 0, 0, 0]
}
self.check_msg(msg_str, expects)
def test_joint_states_combined3(self):
msg_str = """
m_headRotation:
x: 0.0
y: 0.0
z: 0.0
w: 0.0
m_headTranslation:
x: 0.0
y: 0.0
z: 0.0
m_neckRotation:
x: 0.0
y: 0.0
z: 0.0
w: 1.0
m_eyeGazeLeftPitch: 0.0
m_eyeGazeLeftYaw: 1.0
m_eyeGazeRightPitch: 0.0
m_eyeGazeRightYaw: 0.0
m_coeffs: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]"""
expects = {
'name': self.joints,
'position': [0, -1, -1, 0, 0, 0, 0, 0]
}
self.check_msg(msg_str, expects)
def test_joint_states_combined4(self):
msg_str = """
m_headRotation:
x: 1.0
y: 0.0
z: 0.0
w: 0.0
m_headTranslation:
x: 0.0
y: 0.0
z: 0.0
m_neckRotation:
x: 0.0
y: 0.0
z: 0.0
w: 1.0
m_eyeGazeLeftPitch: 0.0
m_eyeGazeLeftYaw: 0.0
m_eyeGazeRightPitch: 0.0
m_eyeGazeRightYaw: 0.0
m_coeffs: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]"""
pitch_neck_joint = -1.5707963267948966
expects = {
'name': self.joints,
'position': [0, 0, 0, 0, pitch_neck_joint, 0, 0, pitch_neck_joint]
}
self.check_msg(msg_str, expects)
@unittest.skip('Not stable')
def test_joint_states_combined5(self):
msg_str = """
m_headRotation:
x: 1.0
y: 0.0
z: 0.0
w: 1.0
m_headTranslation:
x: 0.0
y: 0.0
z: 0.0
m_neckRotation:
x: 0.0
y: 0.0
z: 0.0
w: 1.0
m_eyeGazeLeftPitch: 0.0
m_eyeGazeLeftYaw: 0.0
m_eyeGazeRightPitch: 0.0
m_eyeGazeRightYaw: 0.0
m_coeffs: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]"""
pitch_neck_joint = 0.7853981633974483
expects = {
'name': self.joints,
'position': [0, 0, 0, 0, pitch_neck_joint, 0, 0, pitch_neck_joint]
}
self.check_msg(msg_str, expects)
def test_face_tf(self):
pub, msg_class = rostopic.create_publisher(
'/camera/face_locations', 'pi_face_tracker/Faces', True)
msg = msg_class()
msg_str = """faces:
- id: 1
point:
x: 0.76837966452
y: -0.132697071241
z: 0.0561996095957
attention: 0.990000009537
- id: 2
point:
x: 0.807249662369
y: -0.00428759906469
z: 0.035407830253
attention: 0.990000009537"""
fill_message_args(msg, [yaml.load(msg_str)])
pub.publish(msg)
msg = wait_for_message('/tf', tfMessage, 5)
expect_str = """
transforms:
-
header:
seq: 0
stamp:
nsecs: 752310037
frame_id: camera
child_frame_id: face_base1
transform:
translation:
x: 0.76837966452
y: -0.132697071241
z: 0.0561996095957
rotation:
x: 0.0
y: 0.0
z: 0.0
w: 1.0
"""
expect = tfMessage()
fill_message_args(expect, [yaml.load(expect_str)])
#self.assertEqual(msg.transforms[0].child_frame_id,
# expect.transforms[0].child_frame_id)
self.assertEqual(msg.transforms[0].transform,
expect.transforms[0].transform)
pub.unregister()
if __name__ == '__main__':
import rostest
rostest.rosrun(PKG, 'perception', PerceptionTest)
|
lgpl-2.1
|
theoryno3/pygr
|
tests/annotation_hg18_megatest.py
|
4
|
63613
|
import unittest
from testlib import testutil, PygrTestProgram
import ConfigParser
import os
import string
import sys
from pygr.mapping import Collection
import pygr.Data
try:
import hashlib
except ImportError:
import md5 as hashlib
config = ConfigParser.ConfigParser({'testOutputBaseDir': '.',
'smallSampleKey': ''})
config.read([os.path.join(os.path.expanduser('~'), '.pygrrc'),
os.path.join(os.path.expanduser('~'), 'pygr.cfg'),
'.pygrrc', 'pygr.cfg'])
msaDir = config.get('megatests_hg18', 'msaDir')
seqDir = config.get('megatests_hg18', 'seqDir')
smallSampleKey = config.get('megatests_hg18', 'smallSampleKey')
testInputDB = config.get('megatests', 'testInputDB')
testInputDir = config.get('megatests', 'testInputDir')
testOutputBaseDir = config.get('megatests', 'testOutputBaseDir')
if smallSampleKey:
smallSamplePostfix = '_' + smallSampleKey
else:
smallSamplePostfix = ''
## msaDir CONTAINS PRE-BUILT NLMSA
## seqDir CONTAINS GENOME ASSEMBLIES AND THEIR SEQDB FILES
## TEST INPUT/OUPTUT FOR COMPARISON, THESE FILES SHOULD BE IN THIS DIRECTORY
## exonAnnotFileName = 'Annotation_ConservedElement_Exons_hg18.txt'
## intronAnnotFileName = 'Annotation_ConservedElement_Introns_hg18.txt'
## stopAnnotFileName = 'Annotation_ConservedElement_Stop_hg18.txt'
## testDir = os.path.join(testOutputBaseDir, 'TEST_' + ''.join(tmpList)) SHOULD
## BE DELETED IF YOU WANT TO RUN IN '.'
# DIRECTIONARY FOR DOC STRING OF SEQDB
docStringDict = {
'anoCar1': 'Lizard Genome (January 2007)',
'bosTau3': 'Cow Genome (August 2006)',
'canFam2': 'Dog Genome (May 2005)',
'cavPor2': 'Guinea Pig (October 2005)',
'danRer4': 'Zebrafish Genome (March 2006)',
'dasNov1': 'Armadillo Genome (May 2005)',
'echTel1': 'Tenrec Genome (July 2005)',
'eriEur1': 'European Hedgehog (Junuary 2006)',
'equCab1': 'Horse Genome (January 2007)',
'felCat3': 'Cat Genome (March 2006)',
'fr2': 'Fugu Genome (October 2004)',
'galGal3': 'Chicken Genome (May 2006)',
'gasAcu1': 'Stickleback Genome (February 2006)',
'hg18': 'Human Genome (May 2006)',
'loxAfr1': 'Elephant Genome (May 2005)',
'mm8': 'Mouse Genome (March 2006)',
'monDom4': 'Opossum Genome (January 2006)',
'ornAna1': 'Platypus Genome (March 2007)',
'oryCun1': 'Rabbit Genome (May 2005)',
'oryLat1': 'Medaka Genome (April 2006)',
'otoGar1': 'Bushbaby Genome (December 2006)',
'panTro2': 'Chimpanzee Genome (March 2006)',
'rheMac2': 'Rhesus Genome (January 2006)',
'rn4': 'Rat Genome (November 2004)',
'sorAra1': 'Shrew (Junuary 2006)',
'tetNig1': 'Tetraodon Genome (February 2004)',
'tupBel1': 'Tree Shrew (December 2006)',
'xenTro2': 'X. tropicalis Genome (August 2005)',
}
# GENOME ASSEMBLY LIST FOR DM2 MULTIZ15WAY
msaSpeciesList = ['anoCar1', 'bosTau3', 'canFam2', 'cavPor2', 'danRer4',
'dasNov1', 'echTel1', 'equCab1', 'eriEur1', 'felCat3', 'fr2',
'galGal3', 'gasAcu1', 'hg18', 'loxAfr1', 'mm8', 'monDom4',
'ornAna1', 'oryCun1', 'oryLat1', 'otoGar1', 'panTro2',
'rheMac2', 'rn4', 'sorAra1', 'tetNig1', 'tupBel1', 'xenTro2']
class PygrBuildNLMSAMegabase(unittest.TestCase):
def setUp(self, testDir=None):
'''restrict megatest to an initially empty directory, need
large space to perform'''
import random
tmpList = [c for c in 'PygrBuildNLMSAMegabase']
random.shuffle(tmpList)
# Comment out the next line to run in current directory.
testDir = os.path.join(testOutputBaseDir, 'TEST_' + ''.join(tmpList))
if testDir is None:
testDir = 'TEST_' + ''.join(tmpList)
try:
os.mkdir(testDir)
testDir = os.path.realpath(testDir)
except:
raise IOError
self.path = testDir
try:
tmpFileName = os.path.join(testDir, 'DELETE_THIS_TEMP_FILE')
open(tmpFileName, 'w').write('A' * 1024 * 1024)
except:
raise IOError
pygr.Data.update(self.path)
from pygr import seqdb
for orgstr in msaSpeciesList:
genome = seqdb.BlastDB(os.path.join(seqDir, orgstr))
genome.__doc__ = docStringDict[orgstr]
pygr.Data.addResource('TEST.Seq.Genome.' + orgstr, genome)
pygr.Data.save()
def copyFile(self, filename): # COPY A FILE INTO TEST DIRECTORY
newname = os.path.join(self.path, os.path.basename(filename))
open(newname, 'w').write(open(filename, 'r').read())
return newname
def tearDown(self):
'delete the temporary directory and files, restore pygr.Data path'
# Delete them bottom-up for obvious reasons.
for dirpath, subdirs, files in os.walk(self.path, topdown=False):
# Note: this part may not work in directories on NFS due to
# creation of lock files (.nfsXXXXXXXXX), which will only allow
# deletion after pygr.Data has been closed.
for filename in files:
os.remove(os.path.join(dirpath, filename))
os.rmdir(dirpath)
# Restore original pygr.Data path to remedy lack of isolation
# between tests from the same run
pygr.Data.update(None)
class Build_Test(PygrBuildNLMSAMegabase):
def test_seqdb(self):
'Check pygr.Data contents'
l = pygr.Data.dir('TEST')
preList = ['TEST.Seq.Genome.' + orgstr for orgstr in msaSpeciesList]
assert l == preList
def test_collectionannot(self):
'Test building an AnnotationDB from file'
from pygr import seqdb, cnestedlist, sqlgraph
hg18 = pygr.Data.getResource('TEST.Seq.Genome.hg18')
# BUILD ANNOTATION DATABASE FOR REFSEQ EXONS
exon_slices = Collection(
filename=os.path.join(self.path, 'refGene_exonAnnot_hg18.cdb'),
intKeys=True, mode='cr', writeback=False)
exon_db = seqdb.AnnotationDB(exon_slices, hg18,
sliceAttrDict=dict(id=0, exon_id=1,
orientation=2,
gene_id=3, start=4,
stop=5))
msa = cnestedlist.NLMSA(os.path.join(self.path,
'refGene_exonAnnot_hg18'), 'w',
pairwiseMode=True, bidirectional=False)
for lines in open(os.path.join(testInputDir,
'refGene_exonAnnot%s_hg18.txt'
% smallSamplePostfix),
'r').xreadlines():
row = [x for x in lines.split('\t')] # CONVERT TO LIST SO MUTABLE
row[1] = int(row[1]) # CONVERT FROM STRING TO INTEGER
exon_slices[row[1]] = row
exon = exon_db[row[1]] # GET THE ANNOTATION OBJECT FOR THIS EXON
msa.addAnnotation(exon) # SAVE IT TO GENOME MAPPING
exon_db.clear_cache() # not really necessary; cache should autoGC
# SHELVE SHOULD BE EXPLICITLY CLOSED IN ORDER TO SAVE CURRENT CONTENTS
exon_slices.close()
msa.build() # FINALIZE GENOME ALIGNMENT INDEXES
exon_db.__doc__ = 'Exon Annotation Database for hg18'
pygr.Data.addResource('TEST.Annotation.hg18.exons', exon_db)
msa.__doc__ = 'NLMSA Exon for hg18'
pygr.Data.addResource('TEST.Annotation.NLMSA.hg18.exons', msa)
exon_schema = pygr.Data.ManyToManyRelation(hg18, exon_db,
bindAttrs=('exon1', ))
exon_schema.__doc__ = 'Exon Schema for hg18'
pygr.Data.addSchema('TEST.Annotation.NLMSA.hg18.exons', exon_schema)
# BUILD ANNOTATION DATABASE FOR REFSEQ SPLICES
splice_slices = Collection(
filename=os.path.join(self.path, 'refGene_spliceAnnot_hg18.cdb'),
intKeys=True, mode='cr', writeback=False)
splice_db = seqdb.AnnotationDB(splice_slices, hg18,
sliceAttrDict=dict(id=0, splice_id=1,
orientation=2,
gene_id=3, start=4,
stop=5))
msa = cnestedlist.NLMSA(os.path.join(self.path,
'refGene_spliceAnnot_hg18'),
'w', pairwiseMode=True, bidirectional=False)
for lines in open(os.path.join(testInputDir,
'refGene_spliceAnnot%s_hg18.txt'
% smallSamplePostfix),
'r').xreadlines():
row = [x for x in lines.split('\t')] # CONVERT TO LIST SO MUTABLE
row[1] = int(row[1]) # CONVERT FROM STRING TO INTEGER
splice_slices[row[1]] = row
# GET THE ANNOTATION OBJECT FOR THIS EXON
splice = splice_db[row[1]]
msa.addAnnotation(splice) # SAVE IT TO GENOME MAPPING
splice_db.clear_cache() # not really necessary; cache should autoGC
# SHELVE SHOULD BE EXPLICITLY CLOSED IN ORDER TO SAVE CURRENT CONTENTS
splice_slices.close()
msa.build() # FINALIZE GENOME ALIGNMENT INDEXES
splice_db.__doc__ = 'Splice Annotation Database for hg18'
pygr.Data.addResource('TEST.Annotation.hg18.splices', splice_db)
msa.__doc__ = 'NLMSA Splice for hg18'
pygr.Data.addResource('TEST.Annotation.NLMSA.hg18.splices', msa)
splice_schema = pygr.Data.ManyToManyRelation(hg18, splice_db,
bindAttrs=('splice1', ))
splice_schema.__doc__ = 'Splice Schema for hg18'
pygr.Data.addSchema('TEST.Annotation.NLMSA.hg18.splices',
splice_schema)
# BUILD ANNOTATION DATABASE FOR REFSEQ EXONS
cds_slices = Collection(
filename=os.path.join(self.path, 'refGene_cdsAnnot_hg18.cdb'),
intKeys=True, mode='cr', writeback=False)
cds_db = seqdb.AnnotationDB(cds_slices, hg18,
sliceAttrDict=dict(id=0, cds_id=1,
orientation=2,
gene_id=3, start=4,
stop=5))
msa = cnestedlist.NLMSA(os.path.join(self.path,
'refGene_cdsAnnot_hg18'), 'w',
pairwiseMode=True, bidirectional=False)
for lines in open(os.path.join(testInputDir,
'refGene_cdsAnnot%s_hg18.txt'
% smallSamplePostfix),
'r').xreadlines():
row = [x for x in lines.split('\t')] # CONVERT TO LIST SO MUTABLE
row[1] = int(row[1]) # CONVERT FROM STRING TO INTEGER
cds_slices[row[1]] = row
cds = cds_db[row[1]] # GET THE ANNOTATION OBJECT FOR THIS EXON
msa.addAnnotation(cds) # SAVE IT TO GENOME MAPPING
cds_db.clear_cache() # not really necessary; cache should autoGC
# SHELVE SHOULD BE EXPLICITLY CLOSED IN ORDER TO SAVE CURRENT CONTENTS
cds_slices.close()
msa.build() # FINALIZE GENOME ALIGNMENT INDEXES
cds_db.__doc__ = 'CDS Annotation Database for hg18'
pygr.Data.addResource('TEST.Annotation.hg18.cdss', cds_db)
msa.__doc__ = 'NLMSA CDS for hg18'
pygr.Data.addResource('TEST.Annotation.NLMSA.hg18.cdss', msa)
cds_schema = pygr.Data.ManyToManyRelation(hg18, cds_db,
bindAttrs=('cds1', ))
cds_schema.__doc__ = 'CDS Schema for hg18'
pygr.Data.addSchema('TEST.Annotation.NLMSA.hg18.cdss', cds_schema)
# BUILD ANNOTATION DATABASE FOR MOST CONSERVED ELEMENTS FROM UCSC
ucsc_slices = Collection(
filename=os.path.join(self.path, 'phastConsElements28way_hg18.cdb'),
intKeys=True, mode='cr', writeback=False)
ucsc_db = seqdb.AnnotationDB(ucsc_slices, hg18,
sliceAttrDict=dict(id=0, ucsc_id=1,
orientation=2,
gene_id=3, start=4,
stop=5))
msa = cnestedlist.NLMSA(os.path.join(self.path,
'phastConsElements28way_hg18'),
'w', pairwiseMode=True, bidirectional=False)
for lines in open(os.path.join(testInputDir,
'phastConsElements28way%s_hg18.txt'
% smallSamplePostfix),
'r').xreadlines():
row = [x for x in lines.split('\t')] # CONVERT TO LIST SO MUTABLE
row[1] = int(row[1]) # CONVERT FROM STRING TO INTEGER
ucsc_slices[row[1]] = row
ucsc = ucsc_db[row[1]] # GET THE ANNOTATION OBJECT FOR THIS EXON
msa.addAnnotation(ucsc) # SAVE IT TO GENOME MAPPING
ucsc_db.clear_cache() # not really necessary; cache should autoGC
# SHELVE SHOULD BE EXPLICITLY CLOSED IN ORDER TO SAVE CURRENT CONTENTS
ucsc_slices.close()
msa.build() # FINALIZE GENOME ALIGNMENT INDEXES
ucsc_db.__doc__ = 'Most Conserved Elements for hg18'
pygr.Data.addResource('TEST.Annotation.UCSC.hg18.mostconserved',
ucsc_db)
msa.__doc__ = 'NLMSA for Most Conserved Elements for hg18'
pygr.Data.addResource('TEST.Annotation.UCSC.NLMSA.hg18.mostconserved',
msa)
ucsc_schema = pygr.Data.ManyToManyRelation(hg18, ucsc_db,
bindAttrs=('element1', ))
ucsc_schema.__doc__ = \
'Schema for UCSC Most Conserved Elements for hg18'
pygr.Data.addSchema('TEST.Annotation.UCSC.NLMSA.hg18.mostconserved',
ucsc_schema)
# BUILD ANNOTATION DATABASE FOR SNP126 FROM UCSC
snp_slices = Collection(filename=os.path.join(self.path,
'snp126_hg18.cdb'),
intKeys=True, protocol=2, mode='cr',
writeback=False)
snp_db = seqdb.AnnotationDB(snp_slices, hg18,
sliceAttrDict=dict(id=0, snp_id=1,
orientation=2,
gene_id=3, start=4,
stop=5, score=6,
ref_NCBI=7, ref_UCSC=8,
observed=9, molType=10,
myClass=11, myValid=12,
avHet=13, avHetSE=14,
myFunc=15, locType=16,
myWeight=17))
msa = cnestedlist.NLMSA(os.path.join(self.path, 'snp126_hg18'), 'w',
pairwiseMode=True, bidirectional=False)
for lines in open(os.path.join(testInputDir, 'snp126%s_hg18.txt'
% smallSamplePostfix),
'r').xreadlines():
row = [x for x in lines.split('\t')] # CONVERT TO LIST SO MUTABLE
row[1] = int(row[1]) # CONVERT FROM STRING TO INTEGER
snp_slices[row[1]] = row
snp = snp_db[row[1]] # GET THE ANNOTATION OBJECT FOR THIS EXON
msa.addAnnotation(snp) # SAVE IT TO GENOME MAPPING
snp_db.clear_cache() # not really necessary; cache should autoGC
# SHELVE SHOULD BE EXPLICITLY CLOSED IN ORDER TO SAVE CURRENT CONTENTS
snp_slices.close()
msa.build() # FINALIZE GENOME ALIGNMENT INDEXES
snp_db.__doc__ = 'SNP126 for hg18'
pygr.Data.addResource('TEST.Annotation.UCSC.hg18.snp126', snp_db)
msa.__doc__ = 'NLMSA for SNP126 for hg18'
pygr.Data.addResource('TEST.Annotation.UCSC.NLMSA.hg18.snp126', msa)
snp_schema = pygr.Data.ManyToManyRelation(hg18, snp_db,
bindAttrs=('snp1', ))
snp_schema.__doc__ = 'Schema for UCSC SNP126 for hg18'
pygr.Data.addSchema('TEST.Annotation.UCSC.NLMSA.hg18.snp126',
snp_schema)
pygr.Data.save()
pygr.Data.clear_cache()
# QUERY TO EXON AND SPLICES ANNOTATION DATABASE
hg18 = pygr.Data.getResource('TEST.Seq.Genome.hg18')
exonmsa = pygr.Data.getResource('TEST.Annotation.NLMSA.hg18.exons')
splicemsa = pygr.Data.getResource('TEST.Annotation.NLMSA.hg18.splices')
conservedmsa = \
pygr.Data.getResource('TEST.Annotation.UCSC.NLMSA.hg18.mostconserved')
snpmsa = \
pygr.Data.getResource('TEST.Annotation.UCSC.NLMSA.hg18.snp126')
cdsmsa = pygr.Data.getResource('TEST.Annotation.NLMSA.hg18.cdss')
exons = pygr.Data.getResource('TEST.Annotation.hg18.exons')
splices = pygr.Data.getResource('TEST.Annotation.hg18.splices')
mostconserved = \
pygr.Data.getResource('TEST.Annotation.UCSC.hg18.mostconserved')
snp126 = pygr.Data.getResource('TEST.Annotation.UCSC.hg18.snp126')
cdss = pygr.Data.getResource('TEST.Annotation.hg18.cdss')
# OPEN hg18_MULTIZ28WAY NLMSA
msa = cnestedlist.NLMSA(os.path.join(msaDir, 'hg18_multiz28way'), 'r',
trypath=[seqDir])
exonAnnotFileName = os.path.join(testInputDir,
'Annotation_ConservedElement_Exons%s_hg18.txt'
% smallSamplePostfix)
intronAnnotFileName = os.path.join(testInputDir,
'Annotation_ConservedElement_Introns%s_hg18.txt'
% smallSamplePostfix)
stopAnnotFileName = os.path.join(testInputDir,
'Annotation_ConservedElement_Stop%s_hg18.txt'
% smallSamplePostfix)
newexonAnnotFileName = os.path.join(self.path, 'new_Exons_hg18.txt')
newintronAnnotFileName = os.path.join(self.path,
'new_Introns_hg18.txt')
newstopAnnotFileName = os.path.join(self.path, 'new_stop_hg18.txt')
tmpexonAnnotFileName = self.copyFile(exonAnnotFileName)
tmpintronAnnotFileName = self.copyFile(intronAnnotFileName)
tmpstopAnnotFileName = self.copyFile(stopAnnotFileName)
if smallSampleKey:
chrList = [smallSampleKey]
else:
chrList = hg18.seqLenDict.keys()
chrList.sort()
outfile = open(newexonAnnotFileName, 'w')
for chrid in chrList:
slice = hg18[chrid]
# EXON ANNOTATION DATABASE
try:
ex1 = exonmsa[slice]
except:
continue
else:
exlist1 = [(ix.exon_id, ix) for ix in ex1.keys()]
exlist1.sort()
for ixx, exon in exlist1:
saveList = []
tmp = exon.sequence
tmpexon = exons[exon.exon_id]
tmpslice = tmpexon.sequence # FOR REAL EXON COORDINATE
wlist1 = 'EXON', chrid, tmpexon.exon_id, tmpexon.gene_id, \
tmpslice.start, tmpslice.stop
try:
out1 = conservedmsa[tmp]
except KeyError:
pass
else:
elementlist = [(ix.ucsc_id, ix) for ix in out1.keys()]
elementlist.sort()
for iyy, element in elementlist:
if element.stop - element.start < 100:
continue
score = int(string.split(element.gene_id, '=')[1])
if score < 100:
continue
tmp2 = element.sequence
tmpelement = mostconserved[element.ucsc_id]
# FOR REAL ELEMENT COORDINATE
tmpslice2 = tmpelement.sequence
wlist2 = wlist1 + (tmpelement.ucsc_id,
tmpelement.gene_id,
tmpslice2.start,
tmpslice2.stop)
slicestart, sliceend = max(tmp.start, tmp2.start),\
min(tmp.stop, tmp2.stop)
if slicestart < 0 or sliceend < 0:
sys.exit('wrong query')
tmp1 = msa.seqDict['hg18.' + chrid][slicestart:
sliceend]
edges = msa[tmp1].edges()
for src, dest, e in edges:
if src.stop - src.start < 100:
continue
palign, pident = e.pAligned(), e.pIdentity()
if palign < 0.8 or pident < 0.8:
continue
palign, pident = '%.2f' % palign, \
'%.2f' % pident
wlist3 = wlist2 + ((~msa.seqDict)[src],
str(src), src.start,
src.stop,
(~msa.seqDict)[dest],
str(dest), dest.start,
dest.stop, palign, pident)
saveList.append('\t'.join(map(str, wlist3))
+ '\n')
saveList.sort()
for saveline in saveList:
outfile.write(saveline)
outfile.close()
md5old = hashlib.md5()
md5old.update(open(tmpexonAnnotFileName, 'r').read())
md5new = hashlib.md5()
md5new.update(open(newexonAnnotFileName, 'r').read())
assert md5old.digest() == md5new.digest()
outfile = open(newintronAnnotFileName, 'w')
for chrid in chrList:
slice = hg18[chrid]
# SPLICE ANNOTATION DATABASE
try:
sp1 = splicemsa[slice]
except:
continue
else:
splist1 = [(ix.splice_id, ix) for ix in sp1.keys()]
splist1.sort()
for ixx, splice in splist1:
saveList = []
tmp = splice.sequence
tmpsplice = splices[splice.splice_id]
tmpslice = tmpsplice.sequence # FOR REAL EXON COORDINATE
wlist1 = 'INTRON', chrid, tmpsplice.splice_id, \
tmpsplice.gene_id, tmpslice.start, tmpslice.stop
try:
out1 = conservedmsa[tmp]
except KeyError:
pass
else:
elementlist = [(ix.ucsc_id, ix) for ix in out1.keys()]
elementlist.sort()
for iyy, element in elementlist:
if element.stop - element.start < 100:
continue
score = int(string.split(element.gene_id, '=')[1])
if score < 100:
continue
tmp2 = element.sequence
tmpelement = mostconserved[element.ucsc_id]
# FOR REAL ELEMENT COORDINATE
tmpslice2 = tmpelement.sequence
wlist2 = wlist1 + (tmpelement.ucsc_id,
tmpelement.gene_id,
tmpslice2.start,
tmpslice2.stop)
slicestart, sliceend = max(tmp.start, tmp2.start),\
min(tmp.stop, tmp2.stop)
if slicestart < 0 or sliceend < 0:
sys.exit('wrong query')
tmp1 = msa.seqDict['hg18.' + chrid][slicestart:
sliceend]
edges = msa[tmp1].edges()
for src, dest, e in edges:
if src.stop - src.start < 100:
continue
palign, pident = e.pAligned(), e.pIdentity()
if palign < 0.8 or pident < 0.8:
continue
palign, pident = '%.2f' % palign, \
'%.2f' % pident
wlist3 = wlist2 + ((~msa.seqDict)[src],
str(src), src.start,
src.stop,
(~msa.seqDict)[dest],
str(dest), dest.start,
dest.stop, palign, pident)
saveList.append('\t'.join(map(str, wlist3))
+ '\n')
saveList.sort()
for saveline in saveList:
outfile.write(saveline)
# SNP IN SPLICE SITES
saveList = []
gt = tmpslice[:2]
ag = tmpslice[-2:]
try:
gtout = snpmsa[gt]
agout = snpmsa[ag]
except KeyError:
pass
else:
gtlist = gtout.keys()
aglist = agout.keys()
for snp in gtlist:
tmpsnp = snp.sequence
annsnp = snp126[snp.snp_id]
wlist2 = ('SNP5', chrid, tmpsplice.gene_id,
gt.start, gt.stop, str(gt)) + \
(annsnp.snp_id, tmpsnp.start, tmpsnp.stop,
str(tmpsnp), annsnp.gene_id,
annsnp.ref_NCBI, annsnp.ref_UCSC,
annsnp.observed, annsnp.molType,
annsnp.myClass, annsnp.myValid)
tmp1 = msa.seqDict['hg18.' + chrid][abs(gt.start):\
abs(gt.stop)]
edges = msa[tmp1].edges()
for src, dest, e in edges:
if src.stop - src.start != 2 or \
dest.stop - dest.start != 2:
continue
palign, pident = e.pAligned(), e.pIdentity()
palign, pident = '%.2f' % palign, \
'%.2f' % pident
wlist3 = wlist2 + ((~msa.seqDict)[src],
str(src), src.start,
src.stop,
(~msa.seqDict)[dest],
str(dest), dest.start,
dest.stop, palign, pident)
saveList.append('\t'.join(map(str, wlist3))
+ '\n')
for snp in aglist:
tmpsnp = snp.sequence
annsnp = snp126[snp.snp_id]
wlist2 = ('SNP3', chrid, tmpsplice.gene_id,
ag.start, ag.stop, str(ag)) + \
(annsnp.snp_id, tmpsnp.start, tmpsnp.stop,
str(tmpsnp), annsnp.gene_id,
annsnp.ref_NCBI, annsnp.ref_UCSC,
annsnp.observed, annsnp.molType,
annsnp.myClass, annsnp.myValid)
tmp1 = msa.seqDict['hg18.' + chrid][abs(ag.start):\
abs(ag.stop)]
edges = msa[tmp1].edges()
for src, dest, e in edges:
if src.stop - src.start != 2 or \
dest.stop - dest.start != 2:
continue
palign, pident = e.pAligned(), e.pIdentity()
palign, pident = '%.2f' % palign, \
'%.2f' % pident
wlist3 = wlist2 + ((~msa.seqDict)[src],
str(src), src.start,
src.stop,
(~msa.seqDict)[dest],
str(dest), dest.start,
dest.stop, palign, pident)
saveList.append('\t'.join(map(str, wlist3))
+ '\n')
saveList.sort()
for saveline in saveList:
outfile.write(saveline)
outfile.close()
md5old = hashlib.md5()
md5old.update(open(tmpintronAnnotFileName, 'r').read())
md5new = hashlib.md5()
md5new.update(open(newintronAnnotFileName, 'r').read())
assert md5old.digest() == md5new.digest()
outfile = open(newstopAnnotFileName, 'w')
for chrid in chrList:
slice = hg18[chrid]
# STOP ANNOTATION DATABASE
try:
cds1 = cdsmsa[slice]
except:
continue
else:
cdslist1 = [(ix.cds_id, ix) for ix in cds1.keys()]
cdslist1.sort()
for ixx, cds in cdslist1:
saveList = []
tmp = cds.sequence
tmpcds = cdss[cds.cds_id]
tmpslice = tmpcds.sequence # FOR REAL EXON COORDINATE
wlist1 = 'STOP', chrid, tmpcds.cds_id, tmpcds.gene_id, \
tmpslice.start, tmpslice.stop
if tmpslice.start < 0:
stopstart, stopend = -tmpslice.stop, -tmpslice.start
stop = -hg18[chrid][stopstart:stopstart+3]
else:
stopstart, stopend = tmpslice.start, tmpslice.stop
stop = hg18[chrid][stopend-3:stopend]
if str(stop).upper() not in ('TAA', 'TAG', 'TGA'):
continue
try:
snp1 = snpmsa[stop]
except KeyError:
pass
else:
snplist = [(ix.snp_id, ix) for ix in snp1.keys()]
snplist.sort()
for iyy, snp in snplist:
tmpsnp = snp.sequence
annsnp = snp126[snp.snp_id]
wlist2 = wlist1 + (str(stop), stop.start,
stop.stop) + \
(annsnp.snp_id, tmpsnp.start, tmpsnp.stop,
str(tmpsnp), annsnp.gene_id,
annsnp.ref_NCBI, annsnp.ref_UCSC,
annsnp.observed, annsnp.molType,
annsnp.myClass, annsnp.myValid)
if tmpslice.start < 0:
tmp1 = -msa.seqDict['hg18.' + chrid]\
[stopstart:stopstart + 3]
else:
tmp1 = msa.seqDict['hg18.' + chrid]\
[stopend - 3:stopend]
edges = msa[tmp1].edges()
for src, dest, e in edges:
if src.stop - src.start != 3 or \
dest.stop - dest.start != 3:
continue
palign, pident = e.pAligned(), e.pIdentity()
palign, pident = '%.2f' % palign, \
'%.2f' % pident
if str(dest).upper() not in ('TAA', 'TAG',
'TGA'):
nonstr = 'NONSENSE'
else:
nonstr = 'STOP'
wlist3 = wlist2 + ((~msa.seqDict)[src],
str(src), src.start,
src.stop,
(~msa.seqDict)[dest],
str(dest), dest.start,
dest.stop, palign, pident,
nonstr)
saveList.append('\t'.join(map(str, wlist3))
+ '\n')
saveList.sort()
for saveline in saveList:
outfile.write(saveline)
outfile.close()
md5old = hashlib.md5()
md5old.update(open(tmpstopAnnotFileName, 'r').read())
md5new = hashlib.md5()
md5new.update(open(newstopAnnotFileName, 'r').read())
assert md5old.digest() == md5new.digest()
def test_mysqlannot(self):
'Test building an AnnotationDB from MySQL'
from pygr import seqdb, cnestedlist, sqlgraph
hg18 = pygr.Data.getResource('TEST.Seq.Genome.hg18')
# BUILD ANNOTATION DATABASE FOR REFSEQ EXONS: MYSQL VERSION
exon_slices = sqlgraph.SQLTableClustered(
'%s.pygr_refGene_exonAnnot%s_hg18' % (testInputDB,
smallSamplePostfix),
clusterKey='chromosome', maxCache=0)
exon_db = seqdb.AnnotationDB(exon_slices, hg18,
sliceAttrDict=dict(id='chromosome',
gene_id='name',
exon_id='exon_id'))
msa = cnestedlist.NLMSA(os.path.join(self.path,
'refGene_exonAnnot_SQL_hg18'),
'w', pairwiseMode=True, bidirectional=False)
for id in exon_db:
msa.addAnnotation(exon_db[id])
exon_db.clear_cache() # not really necessary; cache should autoGC
exon_slices.clear_cache()
msa.build()
exon_db.__doc__ = 'SQL Exon Annotation Database for hg18'
pygr.Data.addResource('TEST.Annotation.SQL.hg18.exons', exon_db)
msa.__doc__ = 'SQL NLMSA Exon for hg18'
pygr.Data.addResource('TEST.Annotation.NLMSA.SQL.hg18.exons', msa)
exon_schema = pygr.Data.ManyToManyRelation(hg18, exon_db,
bindAttrs=('exon2', ))
exon_schema.__doc__ = 'SQL Exon Schema for hg18'
pygr.Data.addSchema('TEST.Annotation.NLMSA.SQL.hg18.exons',
exon_schema)
# BUILD ANNOTATION DATABASE FOR REFSEQ SPLICES: MYSQL VERSION
splice_slices = sqlgraph.SQLTableClustered(
'%s.pygr_refGene_spliceAnnot%s_hg18' % (testInputDB,
smallSamplePostfix),
clusterKey='chromosome', maxCache=0)
splice_db = seqdb.AnnotationDB(splice_slices, hg18,
sliceAttrDict=dict(id='chromosome',
gene_id='name',
splice_id='splice_id'))
msa = cnestedlist.NLMSA(os.path.join(self.path,
'refGene_spliceAnnot_SQL_hg18'),
'w', pairwiseMode=True, bidirectional=False)
for id in splice_db:
msa.addAnnotation(splice_db[id])
splice_db.clear_cache() # not really necessary; cache should autoGC
splice_slices.clear_cache()
msa.build()
splice_db.__doc__ = 'SQL Splice Annotation Database for hg18'
pygr.Data.addResource('TEST.Annotation.SQL.hg18.splices', splice_db)
msa.__doc__ = 'SQL NLMSA Splice for hg18'
pygr.Data.addResource('TEST.Annotation.NLMSA.SQL.hg18.splices', msa)
splice_schema = pygr.Data.ManyToManyRelation(hg18, splice_db,
bindAttrs=('splice2', ))
splice_schema.__doc__ = 'SQL Splice Schema for hg18'
pygr.Data.addSchema('TEST.Annotation.NLMSA.SQL.hg18.splices',
splice_schema)
# BUILD ANNOTATION DATABASE FOR REFSEQ EXONS: MYSQL VERSION
cds_slices = sqlgraph.SQLTableClustered(
'%s.pygr_refGene_cdsAnnot%s_hg18' % (testInputDB,
smallSamplePostfix),
clusterKey='chromosome', maxCache=0)
cds_db = seqdb.AnnotationDB(cds_slices, hg18,
sliceAttrDict=dict(id='chromosome',
gene_id='name',
cds_id='cds_id'))
msa = cnestedlist.NLMSA(os.path.join(self.path,
'refGene_cdsAnnot_SQL_hg18'), 'w',
pairwiseMode=True, bidirectional=False)
for id in cds_db:
msa.addAnnotation(cds_db[id])
cds_db.clear_cache() # not really necessary; cache should autoGC
cds_slices.clear_cache()
msa.build()
cds_db.__doc__ = 'SQL CDS Annotation Database for hg18'
pygr.Data.addResource('TEST.Annotation.SQL.hg18.cdss', cds_db)
msa.__doc__ = 'SQL NLMSA CDS for hg18'
pygr.Data.addResource('TEST.Annotation.NLMSA.SQL.hg18.cdss', msa)
cds_schema = pygr.Data.ManyToManyRelation(hg18, cds_db,
bindAttrs=('cds2', ))
cds_schema.__doc__ = 'SQL CDS Schema for hg18'
pygr.Data.addSchema('TEST.Annotation.NLMSA.SQL.hg18.cdss', cds_schema)
# BUILD ANNOTATION DATABASE FOR MOST CONSERVED ELEMENTS FROM UCSC:
# MYSQL VERSION
ucsc_slices = \
sqlgraph.SQLTableClustered('%s.pygr_phastConsElements28way%s_hg18'
% (testInputDB, smallSamplePostfix),
clusterKey='chromosome', maxCache=0)
ucsc_db = seqdb.AnnotationDB(ucsc_slices, hg18,
sliceAttrDict=dict(id='chromosome',
gene_id='name',
ucsc_id='ucsc_id'))
msa = cnestedlist.NLMSA(os.path.join(self.path,
'phastConsElements28way_SQL_hg18'),
'w', pairwiseMode=True, bidirectional=False)
for id in ucsc_db:
msa.addAnnotation(ucsc_db[id])
ucsc_db.clear_cache() # not really necessary; cache should autoGC
ucsc_slices.clear_cache()
msa.build()
ucsc_db.__doc__ = 'SQL Most Conserved Elements for hg18'
pygr.Data.addResource('TEST.Annotation.UCSC.SQL.hg18.mostconserved',
ucsc_db)
msa.__doc__ = 'SQL NLMSA for Most Conserved Elements for hg18'
pygr.Data.addResource(
'TEST.Annotation.UCSC.NLMSA.SQL.hg18.mostconserved', msa)
ucsc_schema = pygr.Data.ManyToManyRelation(hg18, ucsc_db,
bindAttrs=('element2', ))
ucsc_schema.__doc__ = \
'SQL Schema for UCSC Most Conserved Elements for hg18'
pygr.Data.addSchema(
'TEST.Annotation.UCSC.NLMSA.SQL.hg18.mostconserved', ucsc_schema)
# BUILD ANNOTATION DATABASE FOR SNP126 FROM UCSC: MYSQL VERSION
snp_slices = sqlgraph.SQLTableClustered('%s.pygr_snp126%s_hg18'
% (testInputDB,
smallSamplePostfix),
clusterKey='clusterKey',
maxCache=0)
snp_db = seqdb.AnnotationDB(snp_slices, hg18,
sliceAttrDict=dict(id='chromosome',
gene_id='name',
snp_id='snp_id',
score='score',
ref_NCBI='ref_NCBI',
ref_UCSC='ref_UCSC',
observed='observed',
molType='molType',
myClass='myClass',
myValid='myValid',
avHet='avHet',
avHetSE='avHetSE',
myFunc='myFunc',
locType='locType',
myWeight='myWeight'))
msa = cnestedlist.NLMSA(os.path.join(self.path, 'snp126_SQL_hg18'),
'w', pairwiseMode=True, bidirectional=False)
for id in snp_db:
msa.addAnnotation(snp_db[id])
snp_db.clear_cache() # not really necessary; cache should autoGC
snp_slices.clear_cache()
msa.build()
snp_db.__doc__ = 'SQL SNP126 for hg18'
pygr.Data.addResource('TEST.Annotation.UCSC.SQL.hg18.snp126', snp_db)
msa.__doc__ = 'SQL NLMSA for SNP126 for hg18'
pygr.Data.addResource('TEST.Annotation.UCSC.NLMSA.SQL.hg18.snp126',
msa)
snp_schema = pygr.Data.ManyToManyRelation(hg18, snp_db,
bindAttrs=('snp2', ))
snp_schema.__doc__ = 'SQL Schema for UCSC SNP126 for hg18'
pygr.Data.addSchema('TEST.Annotation.UCSC.NLMSA.SQL.hg18.snp126',
snp_schema)
pygr.Data.save()
pygr.Data.clear_cache()
# QUERY TO EXON AND SPLICES ANNOTATION DATABASE
hg18 = pygr.Data.getResource('TEST.Seq.Genome.hg18')
exonmsa = pygr.Data.getResource('TEST.Annotation.NLMSA.SQL.hg18.exons')
splicemsa = \
pygr.Data.getResource('TEST.Annotation.NLMSA.SQL.hg18.splices')
conservedmsa = \
pygr.Data.getResource('TEST.Annotation.UCSC.NLMSA.SQL.hg18.mostconserved')
snpmsa = \
pygr.Data.getResource('TEST.Annotation.UCSC.NLMSA.SQL.hg18.snp126')
cdsmsa = pygr.Data.getResource('TEST.Annotation.NLMSA.SQL.hg18.cdss')
exons = pygr.Data.getResource('TEST.Annotation.SQL.hg18.exons')
splices = pygr.Data.getResource('TEST.Annotation.SQL.hg18.splices')
mostconserved = \
pygr.Data.getResource('TEST.Annotation.UCSC.SQL.hg18.mostconserved')
snp126 = pygr.Data.getResource('TEST.Annotation.UCSC.SQL.hg18.snp126')
cdss = pygr.Data.getResource('TEST.Annotation.SQL.hg18.cdss')
# OPEN hg18_MULTIZ28WAY NLMSA
msa = cnestedlist.NLMSA(os.path.join(msaDir, 'hg18_multiz28way'), 'r',
trypath=[seqDir])
exonAnnotFileName = os.path.join(testInputDir,
'Annotation_ConservedElement_Exons%s_hg18.txt'
% smallSamplePostfix)
intronAnnotFileName = os.path.join(testInputDir,
'Annotation_ConservedElement_Introns%s_hg18.txt'
% smallSamplePostfix)
stopAnnotFileName = os.path.join(testInputDir,
'Annotation_ConservedElement_Stop%s_hg18.txt'
% smallSamplePostfix)
newexonAnnotFileName = os.path.join(self.path, 'new_Exons_hg18.txt')
newintronAnnotFileName = os.path.join(self.path,
'new_Introns_hg18.txt')
newstopAnnotFileName = os.path.join(self.path, 'new_stop_hg18.txt')
tmpexonAnnotFileName = self.copyFile(exonAnnotFileName)
tmpintronAnnotFileName = self.copyFile(intronAnnotFileName)
tmpstopAnnotFileName = self.copyFile(stopAnnotFileName)
if smallSampleKey:
chrList = [smallSampleKey]
else:
chrList = hg18.seqLenDict.keys()
chrList.sort()
outfile = open(newexonAnnotFileName, 'w')
for chrid in chrList:
slice = hg18[chrid]
# EXON ANNOTATION DATABASE
try:
ex1 = exonmsa[slice]
except:
continue
else:
exlist1 = [(ix.exon_id, ix) for ix in ex1.keys()]
exlist1.sort()
for ixx, exon in exlist1:
saveList = []
tmp = exon.sequence
tmpexon = exons[exon.exon_id]
tmpslice = tmpexon.sequence # FOR REAL EXON COORDINATE
wlist1 = 'EXON', chrid, tmpexon.exon_id, tmpexon.gene_id, \
tmpslice.start, tmpslice.stop
try:
out1 = conservedmsa[tmp]
except KeyError:
pass
else:
elementlist = [(ix.ucsc_id, ix) for ix in out1.keys()]
elementlist.sort()
for iyy, element in elementlist:
if element.stop - element.start < 100:
continue
score = int(string.split(element.gene_id, '=')[1])
if score < 100:
continue
tmp2 = element.sequence
tmpelement = mostconserved[element.ucsc_id]
# FOR REAL ELEMENT COORDINATE
tmpslice2 = tmpelement.sequence
wlist2 = wlist1 + (tmpelement.ucsc_id,
tmpelement.gene_id,
tmpslice2.start,
tmpslice2.stop)
slicestart, sliceend = max(tmp.start, tmp2.start),\
min(tmp.stop, tmp2.stop)
if slicestart < 0 or sliceend < 0:
sys.exit('wrong query')
tmp1 = msa.seqDict['hg18.' + chrid][slicestart:
sliceend]
edges = msa[tmp1].edges()
for src, dest, e in edges:
if src.stop - src.start < 100:
continue
palign, pident = e.pAligned(), e.pIdentity()
if palign < 0.8 or pident < 0.8:
continue
palign, pident = '%.2f' % palign, \
'%.2f' % pident
wlist3 = wlist2 + ((~msa.seqDict)[src],
str(src), src.start,
src.stop,
(~msa.seqDict)[dest],
str(dest), dest.start,
dest.stop, palign, pident)
saveList.append('\t'.join(map(str, wlist3))
+ '\n')
saveList.sort()
for saveline in saveList:
outfile.write(saveline)
outfile.close()
md5old = hashlib.md5()
md5old.update(open(tmpexonAnnotFileName, 'r').read())
md5new = hashlib.md5()
md5new.update(open(newexonAnnotFileName, 'r').read())
assert md5old.digest() == md5new.digest()
outfile = open(newintronAnnotFileName, 'w')
for chrid in chrList:
slice = hg18[chrid]
# SPLICE ANNOTATION DATABASE
try:
sp1 = splicemsa[slice]
except:
continue
else:
splist1 = [(ix.splice_id, ix) for ix in sp1.keys()]
splist1.sort()
for ixx, splice in splist1:
saveList = []
tmp = splice.sequence
tmpsplice = splices[splice.splice_id]
tmpslice = tmpsplice.sequence # FOR REAL EXON COORDINATE
wlist1 = 'INTRON', chrid, tmpsplice.splice_id, \
tmpsplice.gene_id, tmpslice.start, tmpslice.stop
try:
out1 = conservedmsa[tmp]
except KeyError:
pass
else:
elementlist = [(ix.ucsc_id, ix) for ix in out1.keys()]
elementlist.sort()
for iyy, element in elementlist:
if element.stop - element.start < 100:
continue
score = int(string.split(element.gene_id, '=')[1])
if score < 100:
continue
tmp2 = element.sequence
tmpelement = mostconserved[element.ucsc_id]
# FOR REAL ELEMENT COORDINATE
tmpslice2 = tmpelement.sequence
wlist2 = wlist1 + (tmpelement.ucsc_id,
tmpelement.gene_id,
tmpslice2.start,
tmpslice2.stop)
slicestart, sliceend = max(tmp.start, tmp2.start),\
min(tmp.stop, tmp2.stop)
if slicestart < 0 or sliceend < 0:
sys.exit('wrong query')
tmp1 = msa.seqDict['hg18.' + chrid][slicestart:
sliceend]
edges = msa[tmp1].edges()
for src, dest, e in edges:
if src.stop - src.start < 100:
continue
palign, pident = e.pAligned(), e.pIdentity()
if palign < 0.8 or pident < 0.8:
continue
palign, pident = '%.2f' % palign, \
'%.2f' % pident
wlist3 = wlist2 + ((~msa.seqDict)[src],
str(src), src.start,
src.stop,
(~msa.seqDict)[dest],
str(dest), dest.start,
dest.stop, palign, pident)
saveList.append('\t'.join(map(str, wlist3))
+ '\n')
saveList.sort()
for saveline in saveList:
outfile.write(saveline)
# SNP IN SPLICE SITES
saveList = []
gt = tmpslice[:2]
ag = tmpslice[-2:]
try:
gtout = snpmsa[gt]
agout = snpmsa[ag]
except KeyError:
pass
else:
gtlist = gtout.keys()
aglist = agout.keys()
for snp in gtlist:
tmpsnp = snp.sequence
annsnp = snp126[snp.snp_id]
wlist2 = ('SNP5', chrid, tmpsplice.gene_id,
gt.start, gt.stop, str(gt)) + \
(annsnp.snp_id, tmpsnp.start, tmpsnp.stop,
str(tmpsnp), annsnp.gene_id,
annsnp.ref_NCBI, annsnp.ref_UCSC,
annsnp.observed, annsnp.molType,
annsnp.myClass, annsnp.myValid)
tmp1 = msa.seqDict['hg18.' + chrid][abs(gt.start):
abs(gt.stop)]
edges = msa[tmp1].edges()
for src, dest, e in edges:
if src.stop - src.start != 2 or \
dest.stop - dest.start != 2:
continue
palign, pident = e.pAligned(), e.pIdentity()
palign, pident = '%.2f' % palign, \
'%.2f' % pident
wlist3 = wlist2 + ((~msa.seqDict)[src],
str(src), src.start,
src.stop,
(~msa.seqDict)[dest],
str(dest), dest.start,
dest.stop, palign, pident)
saveList.append('\t'.join(map(str, wlist3))
+ '\n')
for snp in aglist:
tmpsnp = snp.sequence
annsnp = snp126[snp.snp_id]
wlist2 = ('SNP3', chrid, tmpsplice.gene_id,
ag.start, ag.stop, str(ag)) + \
(annsnp.snp_id, tmpsnp.start, tmpsnp.stop,
str(tmpsnp), annsnp.gene_id,
annsnp.ref_NCBI, annsnp.ref_UCSC,
annsnp.observed, annsnp.molType,
annsnp.myClass, annsnp.myValid)
tmp1 = msa.seqDict['hg18.' + chrid][abs(ag.start):
abs(ag.stop)]
edges = msa[tmp1].edges()
for src, dest, e in edges:
if src.stop - src.start != 2 or \
dest.stop - dest.start != 2:
continue
palign, pident = e.pAligned(), e.pIdentity()
palign, pident = '%.2f' % palign, \
'%.2f' % pident
wlist3 = wlist2 + ((~msa.seqDict)[src],
str(src), src.start,
src.stop,
(~msa.seqDict)[dest],
str(dest), dest.start,
dest.stop, palign, pident)
saveList.append('\t'.join(map(str, wlist3))
+ '\n')
saveList.sort()
for saveline in saveList:
outfile.write(saveline)
outfile.close()
md5old = hashlib.md5()
md5old.update(open(tmpintronAnnotFileName, 'r').read())
md5new = hashlib.md5()
md5new.update(open(newintronAnnotFileName, 'r').read())
assert md5old.digest() == md5new.digest()
outfile = open(newstopAnnotFileName, 'w')
for chrid in chrList:
slice = hg18[chrid]
# STOP ANNOTATION DATABASE
try:
cds1 = cdsmsa[slice]
except:
continue
else:
cdslist1 = [(ix.cds_id, ix) for ix in cds1.keys()]
cdslist1.sort()
for ixx, cds in cdslist1:
saveList = []
tmp = cds.sequence
tmpcds = cdss[cds.cds_id]
tmpslice = tmpcds.sequence # FOR REAL EXON COORDINATE
wlist1 = 'STOP', chrid, tmpcds.cds_id, tmpcds.gene_id, \
tmpslice.start, tmpslice.stop
if tmpslice.start < 0:
stopstart, stopend = -tmpslice.stop, -tmpslice.start
stop = -hg18[chrid][stopstart:stopstart+3]
else:
stopstart, stopend = tmpslice.start, tmpslice.stop
stop = hg18[chrid][stopend-3:stopend]
if str(stop).upper() not in ('TAA', 'TAG', 'TGA'):
continue
try:
snp1 = snpmsa[stop]
except KeyError:
pass
else:
snplist = [(ix.snp_id, ix) for ix in snp1.keys()]
snplist.sort()
for iyy, snp in snplist:
tmpsnp = snp.sequence
annsnp = snp126[snp.snp_id]
wlist2 = wlist1 + (str(stop), stop.start,
stop.stop) + (annsnp.snp_id,
tmpsnp.start,
tmpsnp.stop,
str(tmpsnp),
annsnp.gene_id,
annsnp.ref_NCBI,
annsnp.ref_UCSC,
annsnp.observed,
annsnp.molType,
annsnp.myClass,
annsnp.myValid)
if tmpslice.start < 0:
tmp1 = -msa.seqDict['hg18.' + chrid]\
[stopstart:stopstart + 3]
else:
tmp1 = msa.seqDict['hg18.' + chrid]\
[stopend - 3:stopend]
edges = msa[tmp1].edges()
for src, dest, e in edges:
if src.stop - src.start != 3 or \
dest.stop - dest.start != 3:
continue
palign, pident = e.pAligned(), e.pIdentity()
palign, pident = '%.2f' % palign, '%.2f' \
% pident
if str(dest).upper() not in ('TAA', 'TAG',
'TGA'):
nonstr = 'NONSENSE'
else:
nonstr = 'STOP'
wlist3 = wlist2 + ((~msa.seqDict)[src],
str(src), src.start,
src.stop,
(~msa.seqDict)[dest],
str(dest), dest.start,
dest.stop, palign, pident,
nonstr)
saveList.append('\t'.join(map(str, wlist3))
+ '\n')
saveList.sort()
for saveline in saveList:
outfile.write(saveline)
outfile.close()
md5old = hashlib.md5()
md5old.update(open(tmpstopAnnotFileName, 'r').read())
md5new = hashlib.md5()
md5new.update(open(newstopAnnotFileName, 'r').read())
assert md5old.digest() == md5new.digest()
if __name__ == '__main__':
PygrTestProgram(verbosity=2)
|
bsd-3-clause
|
Alwnikrotikz/volatility
|
volatility/plugins/overlays/windows/win2003_sp2_x64_vtypes.py
|
58
|
337862
|
ntkrnlmp_types = {
'LIST_ENTRY64' : [ 0x10, {
'Flink' : [ 0x0, ['unsigned long long']],
'Blink' : [ 0x8, ['unsigned long long']],
} ],
'LIST_ENTRY32' : [ 0x8, {
'Flink' : [ 0x0, ['unsigned long']],
'Blink' : [ 0x4, ['unsigned long']],
} ],
'__unnamed_1015' : [ 0x8, {
'LowPart' : [ 0x0, ['unsigned long']],
'HighPart' : [ 0x4, ['unsigned long']],
} ],
'_ULARGE_INTEGER' : [ 0x8, {
'LowPart' : [ 0x0, ['unsigned long']],
'HighPart' : [ 0x4, ['unsigned long']],
'u' : [ 0x0, ['__unnamed_1015']],
'QuadPart' : [ 0x0, ['unsigned long long']],
} ],
'_LIST_ENTRY' : [ 0x10, {
'Flink' : [ 0x0, ['pointer64', ['_LIST_ENTRY']]],
'Blink' : [ 0x8, ['pointer64', ['_LIST_ENTRY']]],
} ],
'_IMAGE_NT_HEADERS64' : [ 0x108, {
'Signature' : [ 0x0, ['unsigned long']],
'FileHeader' : [ 0x4, ['_IMAGE_FILE_HEADER']],
'OptionalHeader' : [ 0x18, ['_IMAGE_OPTIONAL_HEADER64']],
} ],
'__unnamed_1026' : [ 0x8, {
'LowPart' : [ 0x0, ['unsigned long']],
'HighPart' : [ 0x4, ['long']],
} ],
'_LARGE_INTEGER' : [ 0x8, {
'LowPart' : [ 0x0, ['unsigned long']],
'HighPart' : [ 0x4, ['long']],
'u' : [ 0x0, ['__unnamed_1026']],
'QuadPart' : [ 0x0, ['long long']],
} ],
'_RTL_BITMAP' : [ 0x10, {
'SizeOfBitMap' : [ 0x0, ['unsigned long']],
'Buffer' : [ 0x8, ['pointer64', ['unsigned long']]],
} ],
'_LUID' : [ 0x8, {
'LowPart' : [ 0x0, ['unsigned long']],
'HighPart' : [ 0x4, ['long']],
} ],
'_KPRCB' : [ 0x2480, {
'MxCsr' : [ 0x0, ['unsigned long']],
'Number' : [ 0x4, ['unsigned char']],
'NestingLevel' : [ 0x5, ['unsigned char']],
'InterruptRequest' : [ 0x6, ['unsigned char']],
'IdleHalt' : [ 0x7, ['unsigned char']],
'CurrentThread' : [ 0x8, ['pointer64', ['_KTHREAD']]],
'NextThread' : [ 0x10, ['pointer64', ['_KTHREAD']]],
'IdleThread' : [ 0x18, ['pointer64', ['_KTHREAD']]],
'UserRsp' : [ 0x20, ['unsigned long long']],
'RspBase' : [ 0x28, ['unsigned long long']],
'PrcbLock' : [ 0x30, ['unsigned long long']],
'SetMember' : [ 0x38, ['unsigned long long']],
'ProcessorState' : [ 0x40, ['_KPROCESSOR_STATE']],
'CpuType' : [ 0x5f0, ['unsigned char']],
'CpuID' : [ 0x5f1, ['unsigned char']],
'CpuStep' : [ 0x5f2, ['unsigned short']],
'MHz' : [ 0x5f4, ['unsigned long']],
'HalReserved' : [ 0x5f8, ['array', 8, ['unsigned long long']]],
'MinorVersion' : [ 0x638, ['unsigned short']],
'MajorVersion' : [ 0x63a, ['unsigned short']],
'BuildType' : [ 0x63c, ['unsigned char']],
'CpuVendor' : [ 0x63d, ['unsigned char']],
'InitialApicId' : [ 0x63e, ['unsigned char']],
'LogicalProcessorsPerPhysicalProcessor' : [ 0x63f, ['unsigned char']],
'ApicMask' : [ 0x640, ['unsigned long']],
'CFlushSize' : [ 0x644, ['unsigned char']],
'PrcbPad0x' : [ 0x645, ['array', 3, ['unsigned char']]],
'AcpiReserved' : [ 0x648, ['pointer64', ['void']]],
'PrcbPad00' : [ 0x650, ['array', 4, ['unsigned long long']]],
'LockQueue' : [ 0x670, ['array', 33, ['_KSPIN_LOCK_QUEUE']]],
'PPLookasideList' : [ 0x880, ['array', 16, ['_PP_LOOKASIDE_LIST']]],
'PPNPagedLookasideList' : [ 0x980, ['array', 32, ['_PP_LOOKASIDE_LIST']]],
'PPPagedLookasideList' : [ 0xb80, ['array', 32, ['_PP_LOOKASIDE_LIST']]],
'PacketBarrier' : [ 0xd80, ['unsigned long long']],
'DeferredReadyListHead' : [ 0xd88, ['_SINGLE_LIST_ENTRY']],
'MmPageFaultCount' : [ 0xd90, ['long']],
'MmCopyOnWriteCount' : [ 0xd94, ['long']],
'MmTransitionCount' : [ 0xd98, ['long']],
'MmCacheTransitionCount' : [ 0xd9c, ['long']],
'MmDemandZeroCount' : [ 0xda0, ['long']],
'MmPageReadCount' : [ 0xda4, ['long']],
'MmPageReadIoCount' : [ 0xda8, ['long']],
'MmCacheReadCount' : [ 0xdac, ['long']],
'MmCacheIoCount' : [ 0xdb0, ['long']],
'MmDirtyPagesWriteCount' : [ 0xdb4, ['long']],
'MmDirtyWriteIoCount' : [ 0xdb8, ['long']],
'MmMappedPagesWriteCount' : [ 0xdbc, ['long']],
'MmMappedWriteIoCount' : [ 0xdc0, ['long']],
'LookasideIrpFloat' : [ 0xdc4, ['long']],
'KeSystemCalls' : [ 0xdc8, ['unsigned long']],
'IoReadOperationCount' : [ 0xdcc, ['long']],
'IoWriteOperationCount' : [ 0xdd0, ['long']],
'IoOtherOperationCount' : [ 0xdd4, ['long']],
'IoReadTransferCount' : [ 0xdd8, ['_LARGE_INTEGER']],
'IoWriteTransferCount' : [ 0xde0, ['_LARGE_INTEGER']],
'IoOtherTransferCount' : [ 0xde8, ['_LARGE_INTEGER']],
'KeContextSwitches' : [ 0xdf0, ['unsigned long']],
'PrcbPad2' : [ 0xdf4, ['array', 12, ['unsigned char']]],
'TargetSet' : [ 0xe00, ['unsigned long long']],
'IpiFrozen' : [ 0xe08, ['unsigned long']],
'PrcbPad3' : [ 0xe0c, ['array', 116, ['unsigned char']]],
'RequestMailbox' : [ 0xe80, ['array', 64, ['_REQUEST_MAILBOX']]],
'SenderSummary' : [ 0x1e80, ['unsigned long long']],
'PrcbPad4' : [ 0x1e88, ['array', 120, ['unsigned char']]],
'DpcData' : [ 0x1f00, ['array', 2, ['_KDPC_DATA']]],
'DpcStack' : [ 0x1f40, ['pointer64', ['void']]],
'SavedRsp' : [ 0x1f48, ['pointer64', ['void']]],
'MaximumDpcQueueDepth' : [ 0x1f50, ['long']],
'DpcRequestRate' : [ 0x1f54, ['unsigned long']],
'MinimumDpcRate' : [ 0x1f58, ['unsigned long']],
'DpcInterruptRequested' : [ 0x1f5c, ['unsigned char']],
'DpcThreadRequested' : [ 0x1f5d, ['unsigned char']],
'DpcRoutineActive' : [ 0x1f5e, ['unsigned char']],
'DpcThreadActive' : [ 0x1f5f, ['unsigned char']],
'TimerHand' : [ 0x1f60, ['unsigned long long']],
'TimerRequest' : [ 0x1f60, ['unsigned long long']],
'TickOffset' : [ 0x1f68, ['long']],
'MasterOffset' : [ 0x1f6c, ['long']],
'DpcLastCount' : [ 0x1f70, ['unsigned long']],
'ThreadDpcEnable' : [ 0x1f74, ['unsigned char']],
'QuantumEnd' : [ 0x1f75, ['unsigned char']],
'PrcbPad50' : [ 0x1f76, ['unsigned char']],
'IdleSchedule' : [ 0x1f77, ['unsigned char']],
'DpcSetEventRequest' : [ 0x1f78, ['long']],
'PrcbPad40' : [ 0x1f7c, ['long']],
'DpcThread' : [ 0x1f80, ['pointer64', ['void']]],
'DpcEvent' : [ 0x1f88, ['_KEVENT']],
'CallDpc' : [ 0x1fa0, ['_KDPC']],
'PrcbPad7' : [ 0x1fe0, ['array', 4, ['unsigned long long']]],
'WaitListHead' : [ 0x2000, ['_LIST_ENTRY']],
'ReadySummary' : [ 0x2010, ['unsigned long']],
'QueueIndex' : [ 0x2014, ['unsigned long']],
'DispatcherReadyListHead' : [ 0x2018, ['array', 32, ['_LIST_ENTRY']]],
'InterruptCount' : [ 0x2218, ['unsigned long']],
'KernelTime' : [ 0x221c, ['unsigned long']],
'UserTime' : [ 0x2220, ['unsigned long']],
'DpcTime' : [ 0x2224, ['unsigned long']],
'InterruptTime' : [ 0x2228, ['unsigned long']],
'AdjustDpcThreshold' : [ 0x222c, ['unsigned long']],
'SkipTick' : [ 0x2230, ['unsigned char']],
'DebuggerSavedIRQL' : [ 0x2231, ['unsigned char']],
'PollSlot' : [ 0x2232, ['unsigned char']],
'PrcbPad8' : [ 0x2233, ['array', 13, ['unsigned char']]],
'ParentNode' : [ 0x2240, ['pointer64', ['_KNODE']]],
'MultiThreadProcessorSet' : [ 0x2248, ['unsigned long long']],
'MultiThreadSetMaster' : [ 0x2250, ['pointer64', ['_KPRCB']]],
'Sleeping' : [ 0x2258, ['long']],
'PrcbPad90' : [ 0x225c, ['array', 1, ['unsigned long']]],
'DebugDpcTime' : [ 0x2260, ['unsigned long']],
'PageColor' : [ 0x2264, ['unsigned long']],
'NodeColor' : [ 0x2268, ['unsigned long']],
'NodeShiftedColor' : [ 0x226c, ['unsigned long']],
'SecondaryColorMask' : [ 0x2270, ['unsigned long']],
'PrcbPad9' : [ 0x2274, ['array', 12, ['unsigned char']]],
'CcFastReadNoWait' : [ 0x2280, ['unsigned long']],
'CcFastReadWait' : [ 0x2284, ['unsigned long']],
'CcFastReadNotPossible' : [ 0x2288, ['unsigned long']],
'CcCopyReadNoWait' : [ 0x228c, ['unsigned long']],
'CcCopyReadWait' : [ 0x2290, ['unsigned long']],
'CcCopyReadNoWaitMiss' : [ 0x2294, ['unsigned long']],
'KeAlignmentFixupCount' : [ 0x2298, ['unsigned long']],
'KeDcacheFlushCount' : [ 0x229c, ['unsigned long']],
'KeExceptionDispatchCount' : [ 0x22a0, ['unsigned long']],
'KeFirstLevelTbFills' : [ 0x22a4, ['unsigned long']],
'KeFloatingEmulationCount' : [ 0x22a8, ['unsigned long']],
'KeIcacheFlushCount' : [ 0x22ac, ['unsigned long']],
'KeSecondLevelTbFills' : [ 0x22b0, ['unsigned long']],
'VendorString' : [ 0x22b4, ['array', 13, ['unsigned char']]],
'PrcbPad10' : [ 0x22c1, ['array', 2, ['unsigned char']]],
'FeatureBits' : [ 0x22c4, ['unsigned long']],
'UpdateSignature' : [ 0x22c8, ['_LARGE_INTEGER']],
'PowerState' : [ 0x22d0, ['_PROCESSOR_POWER_STATE']],
'Cache' : [ 0x2440, ['array', 5, ['_CACHE_DESCRIPTOR']]],
'CacheCount' : [ 0x247c, ['unsigned long']],
} ],
'_SINGLE_LIST_ENTRY' : [ 0x8, {
'Next' : [ 0x0, ['pointer64', ['_SINGLE_LIST_ENTRY']]],
} ],
'_KDPC' : [ 0x40, {
'Type' : [ 0x0, ['unsigned char']],
'Importance' : [ 0x1, ['unsigned char']],
'Number' : [ 0x2, ['unsigned char']],
'Expedite' : [ 0x3, ['unsigned char']],
'DpcListEntry' : [ 0x8, ['_LIST_ENTRY']],
'DeferredRoutine' : [ 0x18, ['pointer64', ['void']]],
'DeferredContext' : [ 0x20, ['pointer64', ['void']]],
'SystemArgument1' : [ 0x28, ['pointer64', ['void']]],
'SystemArgument2' : [ 0x30, ['pointer64', ['void']]],
'DpcData' : [ 0x38, ['pointer64', ['void']]],
} ],
'_KERNEL_STACK_CONTROL' : [ 0x200, {
'XmmSaveArea' : [ 0x0, ['_XMM_SAVE_AREA32']],
'Fill' : [ 0x0, ['array', 432, ['unsigned char']]],
'Current' : [ 0x1b0, ['_KERNEL_STACK_SEGMENT']],
'Previous' : [ 0x1d8, ['_KERNEL_STACK_SEGMENT']],
} ],
'_KTHREAD' : [ 0x308, {
'Header' : [ 0x0, ['_DISPATCHER_HEADER']],
'MutantListHead' : [ 0x18, ['_LIST_ENTRY']],
'InitialStack' : [ 0x28, ['pointer64', ['void']]],
'StackLimit' : [ 0x30, ['pointer64', ['void']]],
'KernelStack' : [ 0x38, ['pointer64', ['void']]],
'ThreadLock' : [ 0x40, ['unsigned long long']],
'ApcState' : [ 0x48, ['_KAPC_STATE']],
'ApcStateFill' : [ 0x48, ['array', 43, ['unsigned char']]],
'ApcQueueable' : [ 0x73, ['unsigned char']],
'NextProcessor' : [ 0x74, ['unsigned char']],
'DeferredProcessor' : [ 0x75, ['unsigned char']],
'AdjustReason' : [ 0x76, ['unsigned char']],
'AdjustIncrement' : [ 0x77, ['unsigned char']],
'ApcQueueLock' : [ 0x78, ['unsigned long long']],
'WaitStatus' : [ 0x80, ['long long']],
'WaitBlockList' : [ 0x88, ['pointer64', ['_KWAIT_BLOCK']]],
'GateObject' : [ 0x88, ['pointer64', ['_KGATE']]],
'Alertable' : [ 0x90, ['unsigned char']],
'WaitNext' : [ 0x91, ['unsigned char']],
'WaitReason' : [ 0x92, ['unsigned char']],
'Priority' : [ 0x93, ['unsigned char']],
'EnableStackSwap' : [ 0x94, ['unsigned char']],
'SwapBusy' : [ 0x95, ['unsigned char']],
'Alerted' : [ 0x96, ['array', 2, ['unsigned char']]],
'WaitListEntry' : [ 0x98, ['_LIST_ENTRY']],
'SwapListEntry' : [ 0x98, ['_SINGLE_LIST_ENTRY']],
'Queue' : [ 0xa8, ['pointer64', ['_KQUEUE']]],
'Teb' : [ 0xb0, ['pointer64', ['void']]],
'Timer' : [ 0xb8, ['_KTIMER']],
'TimerFill' : [ 0xb8, ['array', 60, ['unsigned char']]],
'AutoAlignment' : [ 0xf4, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'DisableBoost' : [ 0xf4, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]],
'GuiThread' : [ 0xf4, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]],
'ReservedFlags' : [ 0xf4, ['BitField', dict(start_bit = 3, end_bit = 32, native_type='unsigned long')]],
'ThreadFlags' : [ 0xf4, ['long']],
'WaitBlock' : [ 0xf8, ['array', 4, ['_KWAIT_BLOCK']]],
'WaitBlockFill0' : [ 0xf8, ['array', 43, ['unsigned char']]],
'SystemAffinityActive' : [ 0x123, ['unsigned char']],
'WaitBlockFill1' : [ 0xf8, ['array', 91, ['unsigned char']]],
'PreviousMode' : [ 0x153, ['unsigned char']],
'WaitBlockFill2' : [ 0xf8, ['array', 139, ['unsigned char']]],
'ResourceIndex' : [ 0x183, ['unsigned char']],
'WaitBlockFill3' : [ 0xf8, ['array', 187, ['unsigned char']]],
'LargeStack' : [ 0x1b3, ['unsigned char']],
'WaitBlockFill4' : [ 0xf8, ['array', 44, ['unsigned char']]],
'ContextSwitches' : [ 0x124, ['unsigned long']],
'WaitBlockFill5' : [ 0xf8, ['array', 92, ['unsigned char']]],
'State' : [ 0x154, ['unsigned char']],
'NpxState' : [ 0x155, ['unsigned char']],
'WaitIrql' : [ 0x156, ['unsigned char']],
'WaitMode' : [ 0x157, ['unsigned char']],
'WaitBlockFill6' : [ 0xf8, ['array', 140, ['unsigned char']]],
'WaitTime' : [ 0x184, ['unsigned long']],
'WaitBlockFill7' : [ 0xf8, ['array', 188, ['unsigned char']]],
'KernelApcDisable' : [ 0x1b4, ['short']],
'SpecialApcDisable' : [ 0x1b6, ['short']],
'CombinedApcDisable' : [ 0x1b4, ['unsigned long']],
'QueueListEntry' : [ 0x1b8, ['_LIST_ENTRY']],
'TrapFrame' : [ 0x1c8, ['pointer64', ['_KTRAP_FRAME']]],
'CallbackStack' : [ 0x1d0, ['pointer64', ['void']]],
'ApcStateIndex' : [ 0x1d8, ['unsigned char']],
'IdealProcessor' : [ 0x1d9, ['unsigned char']],
'Preempted' : [ 0x1da, ['unsigned char']],
'ProcessReadyQueue' : [ 0x1db, ['unsigned char']],
'KernelStackResident' : [ 0x1dc, ['unsigned char']],
'BasePriority' : [ 0x1dd, ['unsigned char']],
'PriorityDecrement' : [ 0x1de, ['unsigned char']],
'Saturation' : [ 0x1df, ['unsigned char']],
'UserAffinity' : [ 0x1e0, ['unsigned long long']],
'Process' : [ 0x1e8, ['pointer64', ['_KPROCESS']]],
'Affinity' : [ 0x1f0, ['unsigned long long']],
'ApcStatePointer' : [ 0x1f8, ['array', 2, ['pointer64', ['_KAPC_STATE']]]],
'SavedApcState' : [ 0x208, ['_KAPC_STATE']],
'SavedApcStateFill' : [ 0x208, ['array', 43, ['unsigned char']]],
'FreezeCount' : [ 0x233, ['unsigned char']],
'SuspendCount' : [ 0x234, ['unsigned char']],
'UserIdealProcessor' : [ 0x235, ['unsigned char']],
'CalloutActive' : [ 0x236, ['unsigned char']],
'CodePatchInProgress' : [ 0x237, ['unsigned char']],
'Win32Thread' : [ 0x238, ['pointer64', ['void']]],
'StackBase' : [ 0x240, ['pointer64', ['void']]],
'SuspendApc' : [ 0x248, ['_KAPC']],
'SuspendApcFill0' : [ 0x248, ['array', 1, ['unsigned char']]],
'Quantum' : [ 0x249, ['unsigned char']],
'SuspendApcFill1' : [ 0x248, ['array', 3, ['unsigned char']]],
'QuantumReset' : [ 0x24b, ['unsigned char']],
'SuspendApcFill2' : [ 0x248, ['array', 4, ['unsigned char']]],
'KernelTime' : [ 0x24c, ['unsigned long']],
'SuspendApcFill3' : [ 0x248, ['array', 64, ['unsigned char']]],
'TlsArray' : [ 0x288, ['pointer64', ['void']]],
'SuspendApcFill4' : [ 0x248, ['array', 72, ['unsigned char']]],
'LegoData' : [ 0x290, ['pointer64', ['void']]],
'SuspendApcFill5' : [ 0x248, ['array', 83, ['unsigned char']]],
'PowerState' : [ 0x29b, ['unsigned char']],
'UserTime' : [ 0x29c, ['unsigned long']],
'SuspendSemaphore' : [ 0x2a0, ['_KSEMAPHORE']],
'SuspendSemaphorefill' : [ 0x2a0, ['array', 28, ['unsigned char']]],
'SListFaultCount' : [ 0x2bc, ['unsigned long']],
'ThreadListEntry' : [ 0x2c0, ['_LIST_ENTRY']],
'SListFaultAddress' : [ 0x2d0, ['pointer64', ['void']]],
'ReadOperationCount' : [ 0x2d8, ['long long']],
'WriteOperationCount' : [ 0x2e0, ['long long']],
'OtherOperationCount' : [ 0x2e8, ['long long']],
'ReadTransferCount' : [ 0x2f0, ['long long']],
'WriteTransferCount' : [ 0x2f8, ['long long']],
'OtherTransferCount' : [ 0x300, ['long long']],
} ],
'_KERNEL_STACK_SEGMENT' : [ 0x28, {
'StackBase' : [ 0x0, ['unsigned long long']],
'StackLimit' : [ 0x8, ['unsigned long long']],
'KernelStack' : [ 0x10, ['unsigned long long']],
'InitialStack' : [ 0x18, ['unsigned long long']],
'ActualLimit' : [ 0x20, ['unsigned long long']],
} ],
'_FAST_MUTEX' : [ 0x38, {
'Count' : [ 0x0, ['long']],
'Owner' : [ 0x8, ['pointer64', ['_KTHREAD']]],
'Contention' : [ 0x10, ['unsigned long']],
'Gate' : [ 0x18, ['_KEVENT']],
'OldIrql' : [ 0x30, ['unsigned long']],
} ],
'_SLIST_HEADER' : [ 0x10, {
'Alignment' : [ 0x0, ['unsigned long long']],
'Region' : [ 0x8, ['unsigned long long']],
} ],
'_NPAGED_LOOKASIDE_LIST' : [ 0x80, {
'L' : [ 0x0, ['_GENERAL_LOOKASIDE']],
} ],
'_PAGED_LOOKASIDE_LIST' : [ 0x80, {
'L' : [ 0x0, ['_GENERAL_LOOKASIDE']],
} ],
'_GENERAL_LOOKASIDE' : [ 0x80, {
'ListHead' : [ 0x0, ['_SLIST_HEADER']],
'Depth' : [ 0x10, ['unsigned short']],
'MaximumDepth' : [ 0x12, ['unsigned short']],
'TotalAllocates' : [ 0x14, ['unsigned long']],
'AllocateMisses' : [ 0x18, ['unsigned long']],
'AllocateHits' : [ 0x18, ['unsigned long']],
'TotalFrees' : [ 0x1c, ['unsigned long']],
'FreeMisses' : [ 0x20, ['unsigned long']],
'FreeHits' : [ 0x20, ['unsigned long']],
'Type' : [ 0x24, ['Enumeration', dict(target = 'long', choices = {0: 'NonPagedPool', 1: 'PagedPool', 2: 'NonPagedPoolMustSucceed', 3: 'DontUseThisType', 4: 'NonPagedPoolCacheAligned', 5: 'PagedPoolCacheAligned', 6: 'NonPagedPoolCacheAlignedMustS', 7: 'MaxPoolType', 34: 'NonPagedPoolMustSucceedSession', 35: 'DontUseThisTypeSession', 32: 'NonPagedPoolSession', 36: 'NonPagedPoolCacheAlignedSession', 33: 'PagedPoolSession', 38: 'NonPagedPoolCacheAlignedMustSSession', 37: 'PagedPoolCacheAlignedSession'})]],
'Tag' : [ 0x28, ['unsigned long']],
'Size' : [ 0x2c, ['unsigned long']],
'Allocate' : [ 0x30, ['pointer64', ['void']]],
'Free' : [ 0x38, ['pointer64', ['void']]],
'ListEntry' : [ 0x40, ['_LIST_ENTRY']],
'LastTotalAllocates' : [ 0x50, ['unsigned long']],
'LastAllocateMisses' : [ 0x54, ['unsigned long']],
'LastAllocateHits' : [ 0x54, ['unsigned long']],
'Future' : [ 0x58, ['array', 2, ['unsigned long']]],
} ],
'_QUAD' : [ 0x8, {
'UseThisFieldToCopy' : [ 0x0, ['long long']],
'DoNotUseThisField' : [ 0x0, ['double']],
} ],
'_UNICODE_STRING' : [ 0x10, {
'Length' : [ 0x0, ['unsigned short']],
'MaximumLength' : [ 0x2, ['unsigned short']],
'Buffer' : [ 0x8, ['pointer64', ['unsigned short']]],
} ],
'_IO_STATUS_BLOCK' : [ 0x10, {
'Status' : [ 0x0, ['long']],
'Pointer' : [ 0x0, ['pointer64', ['void']]],
'Information' : [ 0x8, ['unsigned long long']],
} ],
'_EX_RUNDOWN_REF' : [ 0x8, {
'Count' : [ 0x0, ['unsigned long long']],
'Ptr' : [ 0x0, ['pointer64', ['void']]],
} ],
'_EX_FAST_REF' : [ 0x8, {
'Object' : [ 0x0, ['pointer64', ['void']]],
'RefCnt' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 4, native_type='unsigned long long')]],
'Value' : [ 0x0, ['unsigned long long']],
} ],
'_EX_PUSH_LOCK' : [ 0x8, {
'Locked' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long long')]],
'Waiting' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long long')]],
'Waking' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long long')]],
'MultipleShared' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long long')]],
'Shared' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 64, native_type='unsigned long long')]],
'Value' : [ 0x0, ['unsigned long long']],
'Ptr' : [ 0x0, ['pointer64', ['void']]],
} ],
'_EX_PUSH_LOCK_WAIT_BLOCK' : [ 0x40, {
'WakeGate' : [ 0x0, ['_KGATE']],
'WakeEvent' : [ 0x0, ['_KEVENT']],
'Next' : [ 0x18, ['pointer64', ['_EX_PUSH_LOCK_WAIT_BLOCK']]],
'Last' : [ 0x20, ['pointer64', ['_EX_PUSH_LOCK_WAIT_BLOCK']]],
'Previous' : [ 0x28, ['pointer64', ['_EX_PUSH_LOCK_WAIT_BLOCK']]],
'ShareCount' : [ 0x30, ['long']],
'Flags' : [ 0x34, ['long']],
} ],
'_EX_PUSH_LOCK_CACHE_AWARE' : [ 0x100, {
'Locks' : [ 0x0, ['array', 32, ['pointer64', ['_EX_PUSH_LOCK']]]],
} ],
'_ETHREAD' : [ 0x410, {
'Tcb' : [ 0x0, ['_KTHREAD']],
'CreateTime' : [ 0x308, ['_LARGE_INTEGER']],
'ExitTime' : [ 0x310, ['_LARGE_INTEGER']],
'LpcReplyChain' : [ 0x310, ['_LIST_ENTRY']],
'KeyedWaitChain' : [ 0x310, ['_LIST_ENTRY']],
'ExitStatus' : [ 0x320, ['long']],
'OfsChain' : [ 0x320, ['pointer64', ['void']]],
'PostBlockList' : [ 0x328, ['_LIST_ENTRY']],
'TerminationPort' : [ 0x338, ['pointer64', ['_TERMINATION_PORT']]],
'ReaperLink' : [ 0x338, ['pointer64', ['_ETHREAD']]],
'KeyedWaitValue' : [ 0x338, ['pointer64', ['void']]],
'ActiveTimerListLock' : [ 0x340, ['unsigned long long']],
'ActiveTimerListHead' : [ 0x348, ['_LIST_ENTRY']],
'Cid' : [ 0x358, ['_CLIENT_ID']],
'LpcReplySemaphore' : [ 0x368, ['_KSEMAPHORE']],
'KeyedWaitSemaphore' : [ 0x368, ['_KSEMAPHORE']],
'LpcReplyMessage' : [ 0x388, ['pointer64', ['void']]],
'LpcWaitingOnPort' : [ 0x388, ['pointer64', ['void']]],
'ImpersonationInfo' : [ 0x390, ['pointer64', ['_PS_IMPERSONATION_INFORMATION']]],
'IrpList' : [ 0x398, ['_LIST_ENTRY']],
'TopLevelIrp' : [ 0x3a8, ['unsigned long long']],
'DeviceToVerify' : [ 0x3b0, ['pointer64', ['_DEVICE_OBJECT']]],
'ThreadsProcess' : [ 0x3b8, ['pointer64', ['_EPROCESS']]],
'StartAddress' : [ 0x3c0, ['pointer64', ['void']]],
'Win32StartAddress' : [ 0x3c8, ['pointer64', ['void']]],
'LpcReceivedMessageId' : [ 0x3c8, ['unsigned long']],
'ThreadListEntry' : [ 0x3d0, ['_LIST_ENTRY']],
'RundownProtect' : [ 0x3e0, ['_EX_RUNDOWN_REF']],
'ThreadLock' : [ 0x3e8, ['_EX_PUSH_LOCK']],
'LpcReplyMessageId' : [ 0x3f0, ['unsigned long']],
'ReadClusterSize' : [ 0x3f4, ['unsigned long']],
'GrantedAccess' : [ 0x3f8, ['unsigned long']],
'CrossThreadFlags' : [ 0x3fc, ['unsigned long']],
'Terminated' : [ 0x3fc, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'DeadThread' : [ 0x3fc, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]],
'HideFromDebugger' : [ 0x3fc, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]],
'ActiveImpersonationInfo' : [ 0x3fc, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]],
'SystemThread' : [ 0x3fc, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long')]],
'HardErrorsAreDisabled' : [ 0x3fc, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long')]],
'BreakOnTermination' : [ 0x3fc, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned long')]],
'SkipCreationMsg' : [ 0x3fc, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned long')]],
'SkipTerminationMsg' : [ 0x3fc, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long')]],
'SameThreadPassiveFlags' : [ 0x400, ['unsigned long']],
'ActiveExWorker' : [ 0x400, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'ExWorkerCanWaitUser' : [ 0x400, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]],
'MemoryMaker' : [ 0x400, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]],
'KeyedEventInUse' : [ 0x400, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]],
'SameThreadApcFlags' : [ 0x404, ['unsigned long']],
'LpcReceivedMsgIdValid' : [ 0x404, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]],
'LpcExitThreadCalled' : [ 0x404, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned char')]],
'AddressSpaceOwner' : [ 0x404, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned char')]],
'OwnsProcessWorkingSetExclusive' : [ 0x404, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned char')]],
'OwnsProcessWorkingSetShared' : [ 0x404, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned char')]],
'OwnsSystemWorkingSetExclusive' : [ 0x404, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned char')]],
'OwnsSystemWorkingSetShared' : [ 0x404, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned char')]],
'OwnsSessionWorkingSetExclusive' : [ 0x404, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned char')]],
'OwnsSessionWorkingSetShared' : [ 0x405, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]],
'ApcNeeded' : [ 0x405, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned char')]],
'ForwardClusterOnly' : [ 0x408, ['unsigned char']],
'DisablePageFaultClustering' : [ 0x409, ['unsigned char']],
'ActiveFaultCount' : [ 0x40a, ['unsigned char']],
} ],
'_EPROCESS' : [ 0x3e0, {
'Pcb' : [ 0x0, ['_KPROCESS']],
'ProcessLock' : [ 0xb8, ['_EX_PUSH_LOCK']],
'CreateTime' : [ 0xc0, ['_LARGE_INTEGER']],
'ExitTime' : [ 0xc8, ['_LARGE_INTEGER']],
'RundownProtect' : [ 0xd0, ['_EX_RUNDOWN_REF']],
'UniqueProcessId' : [ 0xd8, ['pointer64', ['void']]],
'ActiveProcessLinks' : [ 0xe0, ['_LIST_ENTRY']],
'QuotaUsage' : [ 0xf0, ['array', 3, ['unsigned long long']]],
'QuotaPeak' : [ 0x108, ['array', 3, ['unsigned long long']]],
'CommitCharge' : [ 0x120, ['unsigned long long']],
'PeakVirtualSize' : [ 0x128, ['unsigned long long']],
'VirtualSize' : [ 0x130, ['unsigned long long']],
'SessionProcessLinks' : [ 0x138, ['_LIST_ENTRY']],
'DebugPort' : [ 0x148, ['pointer64', ['void']]],
'ExceptionPort' : [ 0x150, ['pointer64', ['void']]],
'ObjectTable' : [ 0x158, ['pointer64', ['_HANDLE_TABLE']]],
'Token' : [ 0x160, ['_EX_FAST_REF']],
'WorkingSetPage' : [ 0x168, ['unsigned long long']],
'AddressCreationLock' : [ 0x170, ['_KGUARDED_MUTEX']],
'HyperSpaceLock' : [ 0x1a8, ['unsigned long long']],
'ForkInProgress' : [ 0x1b0, ['pointer64', ['_ETHREAD']]],
'HardwareTrigger' : [ 0x1b8, ['unsigned long long']],
'PhysicalVadRoot' : [ 0x1c0, ['pointer64', ['_MM_AVL_TABLE']]],
'CloneRoot' : [ 0x1c8, ['pointer64', ['void']]],
'NumberOfPrivatePages' : [ 0x1d0, ['unsigned long long']],
'NumberOfLockedPages' : [ 0x1d8, ['unsigned long long']],
'Win32Process' : [ 0x1e0, ['pointer64', ['void']]],
'Job' : [ 0x1e8, ['pointer64', ['_EJOB']]],
'SectionObject' : [ 0x1f0, ['pointer64', ['void']]],
'SectionBaseAddress' : [ 0x1f8, ['pointer64', ['void']]],
'QuotaBlock' : [ 0x200, ['pointer64', ['_EPROCESS_QUOTA_BLOCK']]],
'WorkingSetWatch' : [ 0x208, ['pointer64', ['_PAGEFAULT_HISTORY']]],
'Win32WindowStation' : [ 0x210, ['pointer64', ['void']]],
'InheritedFromUniqueProcessId' : [ 0x218, ['pointer64', ['void']]],
'LdtInformation' : [ 0x220, ['pointer64', ['void']]],
'VadFreeHint' : [ 0x228, ['pointer64', ['void']]],
'VdmObjects' : [ 0x230, ['pointer64', ['void']]],
'DeviceMap' : [ 0x238, ['pointer64', ['void']]],
'Spare0' : [ 0x240, ['array', 3, ['pointer64', ['void']]]],
'PageDirectoryPte' : [ 0x258, ['_HARDWARE_PTE']],
'Filler' : [ 0x258, ['unsigned long long']],
'Session' : [ 0x260, ['pointer64', ['void']]],
'ImageFileName' : [ 0x268, ['array', 16, ['unsigned char']]],
'JobLinks' : [ 0x278, ['_LIST_ENTRY']],
'LockedPagesList' : [ 0x288, ['pointer64', ['void']]],
'ThreadListHead' : [ 0x290, ['_LIST_ENTRY']],
'SecurityPort' : [ 0x2a0, ['pointer64', ['void']]],
'Wow64Process' : [ 0x2a8, ['pointer64', ['_WOW64_PROCESS']]],
'ActiveThreads' : [ 0x2b0, ['unsigned long']],
'GrantedAccess' : [ 0x2b4, ['unsigned long']],
'DefaultHardErrorProcessing' : [ 0x2b8, ['unsigned long']],
'LastThreadExitStatus' : [ 0x2bc, ['long']],
'Peb' : [ 0x2c0, ['pointer64', ['_PEB']]],
'PrefetchTrace' : [ 0x2c8, ['_EX_FAST_REF']],
'ReadOperationCount' : [ 0x2d0, ['_LARGE_INTEGER']],
'WriteOperationCount' : [ 0x2d8, ['_LARGE_INTEGER']],
'OtherOperationCount' : [ 0x2e0, ['_LARGE_INTEGER']],
'ReadTransferCount' : [ 0x2e8, ['_LARGE_INTEGER']],
'WriteTransferCount' : [ 0x2f0, ['_LARGE_INTEGER']],
'OtherTransferCount' : [ 0x2f8, ['_LARGE_INTEGER']],
'CommitChargeLimit' : [ 0x300, ['unsigned long long']],
'CommitChargePeak' : [ 0x308, ['unsigned long long']],
'AweInfo' : [ 0x310, ['pointer64', ['void']]],
'SeAuditProcessCreationInfo' : [ 0x318, ['_SE_AUDIT_PROCESS_CREATION_INFO']],
'Vm' : [ 0x320, ['_MMSUPPORT']],
'Spares' : [ 0x378, ['array', 2, ['unsigned long']]],
'ModifiedPageCount' : [ 0x380, ['unsigned long']],
'JobStatus' : [ 0x384, ['unsigned long']],
'Flags' : [ 0x388, ['unsigned long']],
'CreateReported' : [ 0x388, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'NoDebugInherit' : [ 0x388, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]],
'ProcessExiting' : [ 0x388, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]],
'ProcessDelete' : [ 0x388, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]],
'Wow64SplitPages' : [ 0x388, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long')]],
'VmDeleted' : [ 0x388, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long')]],
'OutswapEnabled' : [ 0x388, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned long')]],
'Outswapped' : [ 0x388, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned long')]],
'ForkFailed' : [ 0x388, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long')]],
'Wow64VaSpace4Gb' : [ 0x388, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long')]],
'AddressSpaceInitialized' : [ 0x388, ['BitField', dict(start_bit = 10, end_bit = 12, native_type='unsigned long')]],
'SetTimerResolution' : [ 0x388, ['BitField', dict(start_bit = 12, end_bit = 13, native_type='unsigned long')]],
'BreakOnTermination' : [ 0x388, ['BitField', dict(start_bit = 13, end_bit = 14, native_type='unsigned long')]],
'SessionCreationUnderway' : [ 0x388, ['BitField', dict(start_bit = 14, end_bit = 15, native_type='unsigned long')]],
'WriteWatch' : [ 0x388, ['BitField', dict(start_bit = 15, end_bit = 16, native_type='unsigned long')]],
'ProcessInSession' : [ 0x388, ['BitField', dict(start_bit = 16, end_bit = 17, native_type='unsigned long')]],
'OverrideAddressSpace' : [ 0x388, ['BitField', dict(start_bit = 17, end_bit = 18, native_type='unsigned long')]],
'HasAddressSpace' : [ 0x388, ['BitField', dict(start_bit = 18, end_bit = 19, native_type='unsigned long')]],
'LaunchPrefetched' : [ 0x388, ['BitField', dict(start_bit = 19, end_bit = 20, native_type='unsigned long')]],
'InjectInpageErrors' : [ 0x388, ['BitField', dict(start_bit = 20, end_bit = 21, native_type='unsigned long')]],
'VmTopDown' : [ 0x388, ['BitField', dict(start_bit = 21, end_bit = 22, native_type='unsigned long')]],
'ImageNotifyDone' : [ 0x388, ['BitField', dict(start_bit = 22, end_bit = 23, native_type='unsigned long')]],
'PdeUpdateNeeded' : [ 0x388, ['BitField', dict(start_bit = 23, end_bit = 24, native_type='unsigned long')]],
'VdmAllowed' : [ 0x388, ['BitField', dict(start_bit = 24, end_bit = 25, native_type='unsigned long')]],
'SmapAllowed' : [ 0x388, ['BitField', dict(start_bit = 25, end_bit = 26, native_type='unsigned long')]],
'CreateFailed' : [ 0x388, ['BitField', dict(start_bit = 26, end_bit = 27, native_type='unsigned long')]],
'DefaultIoPriority' : [ 0x388, ['BitField', dict(start_bit = 27, end_bit = 30, native_type='unsigned long')]],
'Spare1' : [ 0x388, ['BitField', dict(start_bit = 30, end_bit = 31, native_type='unsigned long')]],
'Spare2' : [ 0x388, ['BitField', dict(start_bit = 31, end_bit = 32, native_type='unsigned long')]],
'ExitStatus' : [ 0x38c, ['long']],
'NextPageColor' : [ 0x390, ['unsigned short']],
'SubSystemMinorVersion' : [ 0x392, ['unsigned char']],
'SubSystemMajorVersion' : [ 0x393, ['unsigned char']],
'SubSystemVersion' : [ 0x392, ['unsigned short']],
'PriorityClass' : [ 0x394, ['unsigned char']],
'VadRoot' : [ 0x398, ['_MM_AVL_TABLE']],
'Cookie' : [ 0x3d8, ['unsigned long']],
} ],
'_OBJECT_HEADER' : [ 0x38, {
'PointerCount' : [ 0x0, ['long long']],
'HandleCount' : [ 0x8, ['long long']],
'NextToFree' : [ 0x8, ['pointer64', ['void']]],
'Type' : [ 0x10, ['pointer64', ['_OBJECT_TYPE']]],
'NameInfoOffset' : [ 0x18, ['unsigned char']],
'HandleInfoOffset' : [ 0x19, ['unsigned char']],
'QuotaInfoOffset' : [ 0x1a, ['unsigned char']],
'Flags' : [ 0x1b, ['unsigned char']],
'ObjectCreateInfo' : [ 0x20, ['pointer64', ['_OBJECT_CREATE_INFORMATION']]],
'QuotaBlockCharged' : [ 0x20, ['pointer64', ['void']]],
'SecurityDescriptor' : [ 0x28, ['pointer64', ['void']]],
'Body' : [ 0x30, ['_QUAD']],
} ],
'_OBJECT_HEADER_QUOTA_INFO' : [ 0x20, {
'PagedPoolCharge' : [ 0x0, ['unsigned long']],
'NonPagedPoolCharge' : [ 0x4, ['unsigned long']],
'SecurityDescriptorCharge' : [ 0x8, ['unsigned long']],
'ExclusiveProcess' : [ 0x10, ['pointer64', ['_EPROCESS']]],
'Reserved' : [ 0x18, ['unsigned long long']],
} ],
'_OBJECT_HEADER_HANDLE_INFO' : [ 0x10, {
'HandleCountDataBase' : [ 0x0, ['pointer64', ['_OBJECT_HANDLE_COUNT_DATABASE']]],
'SingleEntry' : [ 0x0, ['_OBJECT_HANDLE_COUNT_ENTRY']],
} ],
'_OBJECT_HEADER_NAME_INFO' : [ 0x20, {
'Directory' : [ 0x0, ['pointer64', ['_OBJECT_DIRECTORY']]],
'Name' : [ 0x8, ['_UNICODE_STRING']],
'QueryReferences' : [ 0x18, ['unsigned long']],
} ],
'_OBJECT_HEADER_CREATOR_INFO' : [ 0x20, {
'TypeList' : [ 0x0, ['_LIST_ENTRY']],
'CreatorUniqueProcess' : [ 0x10, ['pointer64', ['void']]],
'CreatorBackTraceIndex' : [ 0x18, ['unsigned short']],
'Reserved' : [ 0x1a, ['unsigned short']],
} ],
'_OBJECT_ATTRIBUTES' : [ 0x30, {
'Length' : [ 0x0, ['unsigned long']],
'RootDirectory' : [ 0x8, ['pointer64', ['void']]],
'ObjectName' : [ 0x10, ['pointer64', ['_UNICODE_STRING']]],
'Attributes' : [ 0x18, ['unsigned long']],
'SecurityDescriptor' : [ 0x20, ['pointer64', ['void']]],
'SecurityQualityOfService' : [ 0x28, ['pointer64', ['void']]],
} ],
'_OBJECT_TYPE' : [ 0x2c0, {
'Mutex' : [ 0x0, ['_ERESOURCE']],
'TypeList' : [ 0x68, ['_LIST_ENTRY']],
'Name' : [ 0x78, ['_UNICODE_STRING']],
'DefaultObject' : [ 0x88, ['pointer64', ['void']]],
'Index' : [ 0x90, ['unsigned long']],
'TotalNumberOfObjects' : [ 0x94, ['unsigned long']],
'TotalNumberOfHandles' : [ 0x98, ['unsigned long']],
'HighWaterNumberOfObjects' : [ 0x9c, ['unsigned long']],
'HighWaterNumberOfHandles' : [ 0xa0, ['unsigned long']],
'TypeInfo' : [ 0xa8, ['_OBJECT_TYPE_INITIALIZER']],
'Key' : [ 0x118, ['unsigned long']],
'ObjectLocks' : [ 0x120, ['array', 4, ['_ERESOURCE']]],
} ],
'_OBJECT_HANDLE_INFORMATION' : [ 0x8, {
'HandleAttributes' : [ 0x0, ['unsigned long']],
'GrantedAccess' : [ 0x4, ['unsigned long']],
} ],
'_PERFINFO_GROUPMASK' : [ 0x20, {
'Masks' : [ 0x0, ['array', 8, ['unsigned long']]],
} ],
'_KGUARDED_MUTEX' : [ 0x38, {
'Count' : [ 0x0, ['long']],
'Owner' : [ 0x8, ['pointer64', ['_KTHREAD']]],
'Contention' : [ 0x10, ['unsigned long']],
'Gate' : [ 0x18, ['_KGATE']],
'KernelApcDisable' : [ 0x30, ['short']],
'SpecialApcDisable' : [ 0x32, ['short']],
'CombinedApcDisable' : [ 0x30, ['unsigned long']],
} ],
'__unnamed_115f' : [ 0x8, {
'Long' : [ 0x0, ['unsigned long long']],
'Hard' : [ 0x0, ['_MMPTE_HARDWARE']],
'HardLarge' : [ 0x0, ['_MMPTE_HARDWARE_LARGEPAGE']],
'Flush' : [ 0x0, ['_HARDWARE_PTE']],
'Proto' : [ 0x0, ['_MMPTE_PROTOTYPE']],
'Soft' : [ 0x0, ['_MMPTE_SOFTWARE']],
'Trans' : [ 0x0, ['_MMPTE_TRANSITION']],
'Subsect' : [ 0x0, ['_MMPTE_SUBSECTION']],
'List' : [ 0x0, ['_MMPTE_LIST']],
} ],
'_MMPTE' : [ 0x8, {
'u' : [ 0x0, ['__unnamed_115f']],
} ],
'__unnamed_116a' : [ 0x8, {
'Flink' : [ 0x0, ['unsigned long long']],
'WsIndex' : [ 0x0, ['unsigned long']],
'Event' : [ 0x0, ['pointer64', ['_KEVENT']]],
'ReadStatus' : [ 0x0, ['long']],
'NextStackPfn' : [ 0x0, ['_SINGLE_LIST_ENTRY']],
} ],
'__unnamed_116c' : [ 0x8, {
'Blink' : [ 0x0, ['unsigned long long']],
'ShareCount' : [ 0x0, ['unsigned long long']],
} ],
'__unnamed_116f' : [ 0x4, {
'ReferenceCount' : [ 0x0, ['unsigned short']],
'ShortFlags' : [ 0x2, ['unsigned short']],
} ],
'__unnamed_1171' : [ 0x4, {
'ReferenceCount' : [ 0x0, ['unsigned short']],
'e1' : [ 0x2, ['_MMPFNENTRY']],
'e2' : [ 0x0, ['__unnamed_116f']],
} ],
'__unnamed_1179' : [ 0x8, {
'EntireFrame' : [ 0x0, ['unsigned long long']],
'PteFrame' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 57, native_type='unsigned long long')]],
'InPageError' : [ 0x0, ['BitField', dict(start_bit = 57, end_bit = 58, native_type='unsigned long long')]],
'VerifierAllocation' : [ 0x0, ['BitField', dict(start_bit = 58, end_bit = 59, native_type='unsigned long long')]],
'AweAllocation' : [ 0x0, ['BitField', dict(start_bit = 59, end_bit = 60, native_type='unsigned long long')]],
'Priority' : [ 0x0, ['BitField', dict(start_bit = 60, end_bit = 63, native_type='unsigned long long')]],
'MustBeCached' : [ 0x0, ['BitField', dict(start_bit = 63, end_bit = 64, native_type='unsigned long long')]],
} ],
'_MMPFN' : [ 0x30, {
'u1' : [ 0x0, ['__unnamed_116a']],
'PteAddress' : [ 0x8, ['pointer64', ['_MMPTE']]],
'u2' : [ 0x10, ['__unnamed_116c']],
'u3' : [ 0x18, ['__unnamed_1171']],
'UsedPageTableEntries' : [ 0x1c, ['unsigned long']],
'OriginalPte' : [ 0x20, ['_MMPTE']],
'AweReferenceCount' : [ 0x20, ['long']],
'u4' : [ 0x28, ['__unnamed_1179']],
} ],
'__unnamed_1180' : [ 0x8, {
'Balance' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 2, native_type='long long')]],
'Parent' : [ 0x0, ['pointer64', ['_MMVAD']]],
} ],
'__unnamed_1183' : [ 0x8, {
'LongFlags' : [ 0x0, ['unsigned long long']],
'VadFlags' : [ 0x0, ['_MMVAD_FLAGS']],
} ],
'__unnamed_1188' : [ 0x4, {
'LongFlags2' : [ 0x0, ['unsigned long']],
'VadFlags2' : [ 0x0, ['_MMVAD_FLAGS2']],
} ],
'_MMVAD' : [ 0x50, {
'u1' : [ 0x0, ['__unnamed_1180']],
'LeftChild' : [ 0x8, ['pointer64', ['_MMVAD']]],
'RightChild' : [ 0x10, ['pointer64', ['_MMVAD']]],
'StartingVpn' : [ 0x18, ['unsigned long long']],
'EndingVpn' : [ 0x20, ['unsigned long long']],
'u' : [ 0x28, ['__unnamed_1183']],
'ControlArea' : [ 0x30, ['pointer64', ['_CONTROL_AREA']]],
'FirstPrototypePte' : [ 0x38, ['pointer64', ['_MMPTE']]],
'LastContiguousPte' : [ 0x40, ['pointer64', ['_MMPTE']]],
'u2' : [ 0x48, ['__unnamed_1188']],
} ],
'_MM_AVL_TABLE' : [ 0x40, {
'BalancedRoot' : [ 0x0, ['_MMADDRESS_NODE']],
'DepthOfTree' : [ 0x28, ['BitField', dict(start_bit = 0, end_bit = 5, native_type='unsigned long long')]],
'Unused' : [ 0x28, ['BitField', dict(start_bit = 5, end_bit = 8, native_type='unsigned long long')]],
'NumberGenericTableElements' : [ 0x28, ['BitField', dict(start_bit = 8, end_bit = 64, native_type='unsigned long long')]],
'NodeHint' : [ 0x30, ['pointer64', ['void']]],
'NodeFreeHint' : [ 0x38, ['pointer64', ['void']]],
} ],
'_MMPTE_FLUSH_LIST' : [ 0xa8, {
'Count' : [ 0x0, ['unsigned long']],
'FlushVa' : [ 0x8, ['array', 20, ['pointer64', ['void']]]],
} ],
'__unnamed_119a' : [ 0x4, {
'LongFlags' : [ 0x0, ['unsigned long']],
'SubsectionFlags' : [ 0x0, ['_MMSUBSECTION_FLAGS']],
} ],
'_SUBSECTION' : [ 0x30, {
'ControlArea' : [ 0x0, ['pointer64', ['_CONTROL_AREA']]],
'u' : [ 0x8, ['__unnamed_119a']],
'StartingSector' : [ 0xc, ['unsigned long']],
'NumberOfFullSectors' : [ 0x10, ['unsigned long']],
'SubsectionBase' : [ 0x18, ['pointer64', ['_MMPTE']]],
'UnusedPtes' : [ 0x20, ['unsigned long']],
'PtesInSubsection' : [ 0x24, ['unsigned long']],
'NextSubsection' : [ 0x28, ['pointer64', ['_SUBSECTION']]],
} ],
'_MMPAGING_FILE' : [ 0x78, {
'Size' : [ 0x0, ['unsigned long long']],
'MaximumSize' : [ 0x8, ['unsigned long long']],
'MinimumSize' : [ 0x10, ['unsigned long long']],
'FreeSpace' : [ 0x18, ['unsigned long long']],
'CurrentUsage' : [ 0x20, ['unsigned long long']],
'PeakUsage' : [ 0x28, ['unsigned long long']],
'HighestPage' : [ 0x30, ['unsigned long long']],
'File' : [ 0x38, ['pointer64', ['_FILE_OBJECT']]],
'Entry' : [ 0x40, ['array', 2, ['pointer64', ['_MMMOD_WRITER_MDL_ENTRY']]]],
'PageFileName' : [ 0x50, ['_UNICODE_STRING']],
'Bitmap' : [ 0x60, ['pointer64', ['_RTL_BITMAP']]],
'PageFileNumber' : [ 0x68, ['BitField', dict(start_bit = 0, end_bit = 4, native_type='unsigned long')]],
'ReferenceCount' : [ 0x68, ['BitField', dict(start_bit = 4, end_bit = 8, native_type='unsigned long')]],
'BootPartition' : [ 0x68, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long')]],
'Reserved' : [ 0x68, ['BitField', dict(start_bit = 9, end_bit = 32, native_type='unsigned long')]],
'FileHandle' : [ 0x70, ['pointer64', ['void']]],
} ],
'_EXCEPTION_RECORD' : [ 0x98, {
'ExceptionCode' : [ 0x0, ['long']],
'ExceptionFlags' : [ 0x4, ['unsigned long']],
'ExceptionRecord' : [ 0x8, ['pointer64', ['_EXCEPTION_RECORD']]],
'ExceptionAddress' : [ 0x10, ['pointer64', ['void']]],
'NumberParameters' : [ 0x18, ['unsigned long']],
'ExceptionInformation' : [ 0x20, ['array', 15, ['unsigned long long']]],
} ],
'_EXCEPTION_RECORD64' : [ 0x98, {
'ExceptionCode' : [ 0x0, ['long']],
'ExceptionFlags' : [ 0x4, ['unsigned long']],
'ExceptionRecord' : [ 0x8, ['unsigned long long']],
'ExceptionAddress' : [ 0x10, ['unsigned long long']],
'NumberParameters' : [ 0x18, ['unsigned long']],
'__unusedAlignment' : [ 0x1c, ['unsigned long']],
'ExceptionInformation' : [ 0x20, ['array', 15, ['unsigned long long']]],
} ],
'_KTIMER' : [ 0x40, {
'Header' : [ 0x0, ['_DISPATCHER_HEADER']],
'DueTime' : [ 0x18, ['_ULARGE_INTEGER']],
'TimerListEntry' : [ 0x20, ['_LIST_ENTRY']],
'Dpc' : [ 0x30, ['pointer64', ['_KDPC']]],
'Period' : [ 0x38, ['long']],
} ],
'_KEVENT' : [ 0x18, {
'Header' : [ 0x0, ['_DISPATCHER_HEADER']],
} ],
'_KLOCK_QUEUE_HANDLE' : [ 0x18, {
'LockQueue' : [ 0x0, ['_KSPIN_LOCK_QUEUE']],
'OldIrql' : [ 0x10, ['unsigned char']],
} ],
'_KSPIN_LOCK_QUEUE' : [ 0x10, {
'Next' : [ 0x0, ['pointer64', ['_KSPIN_LOCK_QUEUE']]],
'Lock' : [ 0x8, ['pointer64', ['unsigned long long']]],
} ],
'_KQUEUE' : [ 0x40, {
'Header' : [ 0x0, ['_DISPATCHER_HEADER']],
'EntryListHead' : [ 0x18, ['_LIST_ENTRY']],
'CurrentCount' : [ 0x28, ['unsigned long']],
'MaximumCount' : [ 0x2c, ['unsigned long']],
'ThreadListHead' : [ 0x30, ['_LIST_ENTRY']],
} ],
'_KWAIT_BLOCK' : [ 0x30, {
'WaitListEntry' : [ 0x0, ['_LIST_ENTRY']],
'Thread' : [ 0x10, ['pointer64', ['_KTHREAD']]],
'Object' : [ 0x18, ['pointer64', ['void']]],
'NextWaitBlock' : [ 0x20, ['pointer64', ['_KWAIT_BLOCK']]],
'WaitKey' : [ 0x28, ['unsigned short']],
'WaitType' : [ 0x2a, ['unsigned char']],
'SpareByte' : [ 0x2b, ['unsigned char']],
'SpareLong' : [ 0x2c, ['long']],
} ],
'_KTIMER_TABLE_ENTRY' : [ 0x18, {
'Entry' : [ 0x0, ['_LIST_ENTRY']],
'Time' : [ 0x10, ['_ULARGE_INTEGER']],
} ],
'_KPROCESS' : [ 0xb8, {
'Header' : [ 0x0, ['_DISPATCHER_HEADER']],
'ProfileListHead' : [ 0x18, ['_LIST_ENTRY']],
'DirectoryTableBase' : [ 0x28, ['array', 2, ['unsigned long long']]],
'IopmOffset' : [ 0x38, ['unsigned short']],
'ActiveProcessors' : [ 0x40, ['unsigned long long']],
'KernelTime' : [ 0x48, ['unsigned long']],
'UserTime' : [ 0x4c, ['unsigned long']],
'ReadyListHead' : [ 0x50, ['_LIST_ENTRY']],
'SwapListEntry' : [ 0x60, ['_SINGLE_LIST_ENTRY']],
'Reserved1' : [ 0x68, ['pointer64', ['void']]],
'ThreadListHead' : [ 0x70, ['_LIST_ENTRY']],
'ProcessLock' : [ 0x80, ['unsigned long long']],
'Affinity' : [ 0x88, ['unsigned long long']],
'AutoAlignment' : [ 0x90, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='long')]],
'DisableBoost' : [ 0x90, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='long')]],
'DisableQuantum' : [ 0x90, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='long')]],
'ReservedFlags' : [ 0x90, ['BitField', dict(start_bit = 3, end_bit = 32, native_type='long')]],
'ProcessFlags' : [ 0x90, ['long']],
'BasePriority' : [ 0x94, ['unsigned char']],
'QuantumReset' : [ 0x95, ['unsigned char']],
'State' : [ 0x96, ['unsigned char']],
'ThreadSeed' : [ 0x97, ['unsigned char']],
'PowerState' : [ 0x98, ['unsigned char']],
'IdealNode' : [ 0x99, ['unsigned char']],
'Visited' : [ 0x9a, ['unsigned char']],
'Flags' : [ 0x9b, ['_KEXECUTE_OPTIONS']],
'ExecuteOptions' : [ 0x9b, ['unsigned char']],
'StackCount' : [ 0xa0, ['unsigned long long']],
'ProcessListEntry' : [ 0xa8, ['_LIST_ENTRY']],
} ],
'_KEXCEPTION_FRAME' : [ 0x180, {
'P1Home' : [ 0x0, ['unsigned long long']],
'P2Home' : [ 0x8, ['unsigned long long']],
'P3Home' : [ 0x10, ['unsigned long long']],
'P4Home' : [ 0x18, ['unsigned long long']],
'P5' : [ 0x20, ['unsigned long long']],
'InitialStack' : [ 0x28, ['unsigned long long']],
'Xmm6' : [ 0x30, ['_M128A']],
'Xmm7' : [ 0x40, ['_M128A']],
'Xmm8' : [ 0x50, ['_M128A']],
'Xmm9' : [ 0x60, ['_M128A']],
'Xmm10' : [ 0x70, ['_M128A']],
'Xmm11' : [ 0x80, ['_M128A']],
'Xmm12' : [ 0x90, ['_M128A']],
'Xmm13' : [ 0xa0, ['_M128A']],
'Xmm14' : [ 0xb0, ['_M128A']],
'Xmm15' : [ 0xc0, ['_M128A']],
'TrapFrame' : [ 0xd0, ['unsigned long long']],
'CallbackStack' : [ 0xd8, ['unsigned long long']],
'OutputBuffer' : [ 0xe0, ['unsigned long long']],
'OutputLength' : [ 0xe8, ['unsigned long long']],
'ExceptionRecord' : [ 0xf0, ['array', 64, ['unsigned char']]],
'MxCsr' : [ 0x130, ['unsigned long long']],
'Rbp' : [ 0x138, ['unsigned long long']],
'Rbx' : [ 0x140, ['unsigned long long']],
'Rdi' : [ 0x148, ['unsigned long long']],
'Rsi' : [ 0x150, ['unsigned long long']],
'R12' : [ 0x158, ['unsigned long long']],
'R13' : [ 0x160, ['unsigned long long']],
'R14' : [ 0x168, ['unsigned long long']],
'R15' : [ 0x170, ['unsigned long long']],
'Return' : [ 0x178, ['unsigned long long']],
} ],
'_KTRAP_FRAME' : [ 0x190, {
'P1Home' : [ 0x0, ['unsigned long long']],
'P2Home' : [ 0x8, ['unsigned long long']],
'P3Home' : [ 0x10, ['unsigned long long']],
'P4Home' : [ 0x18, ['unsigned long long']],
'P5' : [ 0x20, ['unsigned long long']],
'PreviousMode' : [ 0x28, ['unsigned char']],
'PreviousIrql' : [ 0x29, ['unsigned char']],
'FaultIndicator' : [ 0x2a, ['unsigned char']],
'ExceptionActive' : [ 0x2b, ['unsigned char']],
'MxCsr' : [ 0x2c, ['unsigned long']],
'Rax' : [ 0x30, ['unsigned long long']],
'Rcx' : [ 0x38, ['unsigned long long']],
'Rdx' : [ 0x40, ['unsigned long long']],
'R8' : [ 0x48, ['unsigned long long']],
'R9' : [ 0x50, ['unsigned long long']],
'R10' : [ 0x58, ['unsigned long long']],
'R11' : [ 0x60, ['unsigned long long']],
'GsBase' : [ 0x68, ['unsigned long long']],
'GsSwap' : [ 0x68, ['unsigned long long']],
'Xmm0' : [ 0x70, ['_M128A']],
'Xmm1' : [ 0x80, ['_M128A']],
'Xmm2' : [ 0x90, ['_M128A']],
'Xmm3' : [ 0xa0, ['_M128A']],
'Xmm4' : [ 0xb0, ['_M128A']],
'Xmm5' : [ 0xc0, ['_M128A']],
'FaultAddress' : [ 0xd0, ['unsigned long long']],
'ContextRecord' : [ 0xd0, ['unsigned long long']],
'TimeStamp' : [ 0xd0, ['unsigned long long']],
'Dr0' : [ 0xd8, ['unsigned long long']],
'Dr1' : [ 0xe0, ['unsigned long long']],
'Dr2' : [ 0xe8, ['unsigned long long']],
'Dr3' : [ 0xf0, ['unsigned long long']],
'Dr6' : [ 0xf8, ['unsigned long long']],
'Dr7' : [ 0x100, ['unsigned long long']],
'DebugControl' : [ 0x108, ['unsigned long long']],
'LastBranchToRip' : [ 0x110, ['unsigned long long']],
'LastBranchFromRip' : [ 0x118, ['unsigned long long']],
'LastExceptionToRip' : [ 0x120, ['unsigned long long']],
'LastExceptionFromRip' : [ 0x128, ['unsigned long long']],
'LastBranchControl' : [ 0x108, ['unsigned long long']],
'LastBranchMSR' : [ 0x110, ['unsigned long']],
'SegDs' : [ 0x130, ['unsigned short']],
'SegEs' : [ 0x132, ['unsigned short']],
'SegFs' : [ 0x134, ['unsigned short']],
'SegGs' : [ 0x136, ['unsigned short']],
'TrapFrame' : [ 0x138, ['unsigned long long']],
'Rbx' : [ 0x140, ['unsigned long long']],
'Rdi' : [ 0x148, ['unsigned long long']],
'Rsi' : [ 0x150, ['unsigned long long']],
'Rbp' : [ 0x158, ['unsigned long long']],
'ErrorCode' : [ 0x160, ['unsigned long long']],
'ExceptionFrame' : [ 0x160, ['unsigned long long']],
'Rip' : [ 0x168, ['unsigned long long']],
'SegCs' : [ 0x170, ['unsigned short']],
'Fill1' : [ 0x172, ['array', 3, ['unsigned short']]],
'EFlags' : [ 0x178, ['unsigned long']],
'Fill2' : [ 0x17c, ['unsigned long']],
'Rsp' : [ 0x180, ['unsigned long long']],
'SegSs' : [ 0x188, ['unsigned short']],
'Fill3' : [ 0x18a, ['array', 1, ['unsigned short']]],
'CodePatchCycle' : [ 0x18c, ['long']],
} ],
'_EXCEPTION_RECORD32' : [ 0x50, {
'ExceptionCode' : [ 0x0, ['long']],
'ExceptionFlags' : [ 0x4, ['unsigned long']],
'ExceptionRecord' : [ 0x8, ['unsigned long']],
'ExceptionAddress' : [ 0xc, ['unsigned long']],
'NumberParameters' : [ 0x10, ['unsigned long']],
'ExceptionInformation' : [ 0x14, ['array', 15, ['unsigned long']]],
} ],
'_DBGKM_EXCEPTION64' : [ 0xa0, {
'ExceptionRecord' : [ 0x0, ['_EXCEPTION_RECORD64']],
'FirstChance' : [ 0x98, ['unsigned long']],
} ],
'_DBGKM_EXCEPTION32' : [ 0x54, {
'ExceptionRecord' : [ 0x0, ['_EXCEPTION_RECORD32']],
'FirstChance' : [ 0x50, ['unsigned long']],
} ],
'_DBGKD_LOAD_SYMBOLS64' : [ 0x28, {
'PathNameLength' : [ 0x0, ['unsigned long']],
'BaseOfDll' : [ 0x8, ['unsigned long long']],
'ProcessId' : [ 0x10, ['unsigned long long']],
'CheckSum' : [ 0x18, ['unsigned long']],
'SizeOfImage' : [ 0x1c, ['unsigned long']],
'UnloadSymbols' : [ 0x20, ['unsigned char']],
} ],
'_DBGKD_LOAD_SYMBOLS32' : [ 0x18, {
'PathNameLength' : [ 0x0, ['unsigned long']],
'BaseOfDll' : [ 0x4, ['unsigned long']],
'ProcessId' : [ 0x8, ['unsigned long']],
'CheckSum' : [ 0xc, ['unsigned long']],
'SizeOfImage' : [ 0x10, ['unsigned long']],
'UnloadSymbols' : [ 0x14, ['unsigned char']],
} ],
'_DBGKD_READ_MEMORY64' : [ 0x10, {
'TargetBaseAddress' : [ 0x0, ['unsigned long long']],
'TransferCount' : [ 0x8, ['unsigned long']],
'ActualBytesRead' : [ 0xc, ['unsigned long']],
} ],
'_DBGKD_READ_MEMORY32' : [ 0xc, {
'TargetBaseAddress' : [ 0x0, ['unsigned long']],
'TransferCount' : [ 0x4, ['unsigned long']],
'ActualBytesRead' : [ 0x8, ['unsigned long']],
} ],
'_DBGKD_WRITE_MEMORY64' : [ 0x10, {
'TargetBaseAddress' : [ 0x0, ['unsigned long long']],
'TransferCount' : [ 0x8, ['unsigned long']],
'ActualBytesWritten' : [ 0xc, ['unsigned long']],
} ],
'_DBGKD_WRITE_MEMORY32' : [ 0xc, {
'TargetBaseAddress' : [ 0x0, ['unsigned long']],
'TransferCount' : [ 0x4, ['unsigned long']],
'ActualBytesWritten' : [ 0x8, ['unsigned long']],
} ],
'_DBGKD_WRITE_BREAKPOINT64' : [ 0x10, {
'BreakPointAddress' : [ 0x0, ['unsigned long long']],
'BreakPointHandle' : [ 0x8, ['unsigned long']],
} ],
'_DBGKD_WRITE_BREAKPOINT32' : [ 0x8, {
'BreakPointAddress' : [ 0x0, ['unsigned long']],
'BreakPointHandle' : [ 0x4, ['unsigned long']],
} ],
'_DBGKD_READ_WRITE_IO64' : [ 0x10, {
'IoAddress' : [ 0x0, ['unsigned long long']],
'DataSize' : [ 0x8, ['unsigned long']],
'DataValue' : [ 0xc, ['unsigned long']],
} ],
'_DBGKD_READ_WRITE_IO32' : [ 0xc, {
'DataSize' : [ 0x0, ['unsigned long']],
'IoAddress' : [ 0x4, ['unsigned long']],
'DataValue' : [ 0x8, ['unsigned long']],
} ],
'_DBGKD_READ_WRITE_IO_EXTENDED64' : [ 0x20, {
'DataSize' : [ 0x0, ['unsigned long']],
'InterfaceType' : [ 0x4, ['unsigned long']],
'BusNumber' : [ 0x8, ['unsigned long']],
'AddressSpace' : [ 0xc, ['unsigned long']],
'IoAddress' : [ 0x10, ['unsigned long long']],
'DataValue' : [ 0x18, ['unsigned long']],
} ],
'_DBGKD_READ_WRITE_IO_EXTENDED32' : [ 0x18, {
'DataSize' : [ 0x0, ['unsigned long']],
'InterfaceType' : [ 0x4, ['unsigned long']],
'BusNumber' : [ 0x8, ['unsigned long']],
'AddressSpace' : [ 0xc, ['unsigned long']],
'IoAddress' : [ 0x10, ['unsigned long']],
'DataValue' : [ 0x14, ['unsigned long']],
} ],
'_DBGKD_SET_SPECIAL_CALL32' : [ 0x4, {
'SpecialCall' : [ 0x0, ['unsigned long']],
} ],
'_DBGKD_SET_SPECIAL_CALL64' : [ 0x8, {
'SpecialCall' : [ 0x0, ['unsigned long long']],
} ],
'_DBGKD_SET_INTERNAL_BREAKPOINT32' : [ 0x8, {
'BreakpointAddress' : [ 0x0, ['unsigned long']],
'Flags' : [ 0x4, ['unsigned long']],
} ],
'_DBGKD_SET_INTERNAL_BREAKPOINT64' : [ 0x10, {
'BreakpointAddress' : [ 0x0, ['unsigned long long']],
'Flags' : [ 0x8, ['unsigned long']],
} ],
'_DBGKD_GET_INTERNAL_BREAKPOINT64' : [ 0x20, {
'BreakpointAddress' : [ 0x0, ['unsigned long long']],
'Flags' : [ 0x8, ['unsigned long']],
'Calls' : [ 0xc, ['unsigned long']],
'MaxCallsPerPeriod' : [ 0x10, ['unsigned long']],
'MinInstructions' : [ 0x14, ['unsigned long']],
'MaxInstructions' : [ 0x18, ['unsigned long']],
'TotalInstructions' : [ 0x1c, ['unsigned long']],
} ],
'_DBGKD_GET_INTERNAL_BREAKPOINT32' : [ 0x1c, {
'BreakpointAddress' : [ 0x0, ['unsigned long']],
'Flags' : [ 0x4, ['unsigned long']],
'Calls' : [ 0x8, ['unsigned long']],
'MaxCallsPerPeriod' : [ 0xc, ['unsigned long']],
'MinInstructions' : [ 0x10, ['unsigned long']],
'MaxInstructions' : [ 0x14, ['unsigned long']],
'TotalInstructions' : [ 0x18, ['unsigned long']],
} ],
'__unnamed_1240' : [ 0x28, {
'ReadMemory' : [ 0x0, ['_DBGKD_READ_MEMORY64']],
'WriteMemory' : [ 0x0, ['_DBGKD_WRITE_MEMORY64']],
'GetContext' : [ 0x0, ['_DBGKD_GET_CONTEXT']],
'SetContext' : [ 0x0, ['_DBGKD_SET_CONTEXT']],
'WriteBreakPoint' : [ 0x0, ['_DBGKD_WRITE_BREAKPOINT64']],
'RestoreBreakPoint' : [ 0x0, ['_DBGKD_RESTORE_BREAKPOINT']],
'Continue' : [ 0x0, ['_DBGKD_CONTINUE']],
'Continue2' : [ 0x0, ['_DBGKD_CONTINUE2']],
'ReadWriteIo' : [ 0x0, ['_DBGKD_READ_WRITE_IO64']],
'ReadWriteIoExtended' : [ 0x0, ['_DBGKD_READ_WRITE_IO_EXTENDED64']],
'QuerySpecialCalls' : [ 0x0, ['_DBGKD_QUERY_SPECIAL_CALLS']],
'SetSpecialCall' : [ 0x0, ['_DBGKD_SET_SPECIAL_CALL64']],
'SetInternalBreakpoint' : [ 0x0, ['_DBGKD_SET_INTERNAL_BREAKPOINT64']],
'GetInternalBreakpoint' : [ 0x0, ['_DBGKD_GET_INTERNAL_BREAKPOINT64']],
'GetVersion64' : [ 0x0, ['_DBGKD_GET_VERSION64']],
'BreakPointEx' : [ 0x0, ['_DBGKD_BREAKPOINTEX']],
'ReadWriteMsr' : [ 0x0, ['_DBGKD_READ_WRITE_MSR']],
'SearchMemory' : [ 0x0, ['_DBGKD_SEARCH_MEMORY']],
'GetSetBusData' : [ 0x0, ['_DBGKD_GET_SET_BUS_DATA']],
'FillMemory' : [ 0x0, ['_DBGKD_FILL_MEMORY']],
'QueryMemory' : [ 0x0, ['_DBGKD_QUERY_MEMORY']],
'SwitchPartition' : [ 0x0, ['_DBGKD_SWITCH_PARTITION']],
} ],
'_DBGKD_MANIPULATE_STATE64' : [ 0x38, {
'ApiNumber' : [ 0x0, ['unsigned long']],
'ProcessorLevel' : [ 0x4, ['unsigned short']],
'Processor' : [ 0x6, ['unsigned short']],
'ReturnStatus' : [ 0x8, ['long']],
'u' : [ 0x10, ['__unnamed_1240']],
} ],
'__unnamed_1247' : [ 0x28, {
'ReadMemory' : [ 0x0, ['_DBGKD_READ_MEMORY32']],
'WriteMemory' : [ 0x0, ['_DBGKD_WRITE_MEMORY32']],
'ReadMemory64' : [ 0x0, ['_DBGKD_READ_MEMORY64']],
'WriteMemory64' : [ 0x0, ['_DBGKD_WRITE_MEMORY64']],
'GetContext' : [ 0x0, ['_DBGKD_GET_CONTEXT']],
'SetContext' : [ 0x0, ['_DBGKD_SET_CONTEXT']],
'WriteBreakPoint' : [ 0x0, ['_DBGKD_WRITE_BREAKPOINT32']],
'RestoreBreakPoint' : [ 0x0, ['_DBGKD_RESTORE_BREAKPOINT']],
'Continue' : [ 0x0, ['_DBGKD_CONTINUE']],
'Continue2' : [ 0x0, ['_DBGKD_CONTINUE2']],
'ReadWriteIo' : [ 0x0, ['_DBGKD_READ_WRITE_IO32']],
'ReadWriteIoExtended' : [ 0x0, ['_DBGKD_READ_WRITE_IO_EXTENDED32']],
'QuerySpecialCalls' : [ 0x0, ['_DBGKD_QUERY_SPECIAL_CALLS']],
'SetSpecialCall' : [ 0x0, ['_DBGKD_SET_SPECIAL_CALL32']],
'SetInternalBreakpoint' : [ 0x0, ['_DBGKD_SET_INTERNAL_BREAKPOINT32']],
'GetInternalBreakpoint' : [ 0x0, ['_DBGKD_GET_INTERNAL_BREAKPOINT32']],
'GetVersion32' : [ 0x0, ['_DBGKD_GET_VERSION32']],
'BreakPointEx' : [ 0x0, ['_DBGKD_BREAKPOINTEX']],
'ReadWriteMsr' : [ 0x0, ['_DBGKD_READ_WRITE_MSR']],
'SearchMemory' : [ 0x0, ['_DBGKD_SEARCH_MEMORY']],
} ],
'_DBGKD_MANIPULATE_STATE32' : [ 0x34, {
'ApiNumber' : [ 0x0, ['unsigned long']],
'ProcessorLevel' : [ 0x4, ['unsigned short']],
'Processor' : [ 0x6, ['unsigned short']],
'ReturnStatus' : [ 0x8, ['long']],
'u' : [ 0xc, ['__unnamed_1247']],
} ],
'_SHARED_CACHE_MAP' : [ 0x1b8, {
'NodeTypeCode' : [ 0x0, ['short']],
'NodeByteSize' : [ 0x2, ['short']],
'OpenCount' : [ 0x4, ['unsigned long']],
'FileSize' : [ 0x8, ['_LARGE_INTEGER']],
'BcbList' : [ 0x10, ['_LIST_ENTRY']],
'SectionSize' : [ 0x20, ['_LARGE_INTEGER']],
'ValidDataLength' : [ 0x28, ['_LARGE_INTEGER']],
'ValidDataGoal' : [ 0x30, ['_LARGE_INTEGER']],
'InitialVacbs' : [ 0x38, ['array', 4, ['pointer64', ['_VACB']]]],
'Vacbs' : [ 0x58, ['pointer64', ['pointer64', ['_VACB']]]],
'FileObject' : [ 0x60, ['pointer64', ['_FILE_OBJECT']]],
'ActiveVacb' : [ 0x68, ['pointer64', ['_VACB']]],
'NeedToZero' : [ 0x70, ['pointer64', ['void']]],
'ActivePage' : [ 0x78, ['unsigned long']],
'NeedToZeroPage' : [ 0x7c, ['unsigned long']],
'ActiveVacbSpinLock' : [ 0x80, ['unsigned long long']],
'VacbActiveCount' : [ 0x88, ['unsigned long']],
'DirtyPages' : [ 0x8c, ['unsigned long']],
'SharedCacheMapLinks' : [ 0x90, ['_LIST_ENTRY']],
'Flags' : [ 0xa0, ['unsigned long']],
'Status' : [ 0xa4, ['long']],
'Mbcb' : [ 0xa8, ['pointer64', ['_MBCB']]],
'Section' : [ 0xb0, ['pointer64', ['void']]],
'CreateEvent' : [ 0xb8, ['pointer64', ['_KEVENT']]],
'WaitOnActiveCount' : [ 0xc0, ['pointer64', ['_KEVENT']]],
'PagesToWrite' : [ 0xc8, ['unsigned long']],
'BeyondLastFlush' : [ 0xd0, ['long long']],
'Callbacks' : [ 0xd8, ['pointer64', ['_CACHE_MANAGER_CALLBACKS']]],
'LazyWriteContext' : [ 0xe0, ['pointer64', ['void']]],
'PrivateList' : [ 0xe8, ['_LIST_ENTRY']],
'LogHandle' : [ 0xf8, ['pointer64', ['void']]],
'FlushToLsnRoutine' : [ 0x100, ['pointer64', ['void']]],
'DirtyPageThreshold' : [ 0x108, ['unsigned long']],
'LazyWritePassCount' : [ 0x10c, ['unsigned long']],
'UninitializeEvent' : [ 0x110, ['pointer64', ['_CACHE_UNINITIALIZE_EVENT']]],
'NeedToZeroVacb' : [ 0x118, ['pointer64', ['_VACB']]],
'BcbSpinLock' : [ 0x120, ['unsigned long long']],
'Reserved' : [ 0x128, ['pointer64', ['void']]],
'Event' : [ 0x130, ['_KEVENT']],
'VacbPushLock' : [ 0x148, ['_EX_PUSH_LOCK']],
'PrivateCacheMap' : [ 0x150, ['_PRIVATE_CACHE_MAP']],
'WriteBehindWorkQueueEntry' : [ 0x1b0, ['pointer64', ['void']]],
} ],
'_FILE_OBJECT' : [ 0xb8, {
'Type' : [ 0x0, ['short']],
'Size' : [ 0x2, ['short']],
'DeviceObject' : [ 0x8, ['pointer64', ['_DEVICE_OBJECT']]],
'Vpb' : [ 0x10, ['pointer64', ['_VPB']]],
'FsContext' : [ 0x18, ['pointer64', ['void']]],
'FsContext2' : [ 0x20, ['pointer64', ['void']]],
'SectionObjectPointer' : [ 0x28, ['pointer64', ['_SECTION_OBJECT_POINTERS']]],
'PrivateCacheMap' : [ 0x30, ['pointer64', ['void']]],
'FinalStatus' : [ 0x38, ['long']],
'RelatedFileObject' : [ 0x40, ['pointer64', ['_FILE_OBJECT']]],
'LockOperation' : [ 0x48, ['unsigned char']],
'DeletePending' : [ 0x49, ['unsigned char']],
'ReadAccess' : [ 0x4a, ['unsigned char']],
'WriteAccess' : [ 0x4b, ['unsigned char']],
'DeleteAccess' : [ 0x4c, ['unsigned char']],
'SharedRead' : [ 0x4d, ['unsigned char']],
'SharedWrite' : [ 0x4e, ['unsigned char']],
'SharedDelete' : [ 0x4f, ['unsigned char']],
'Flags' : [ 0x50, ['unsigned long']],
'FileName' : [ 0x58, ['_UNICODE_STRING']],
'CurrentByteOffset' : [ 0x68, ['_LARGE_INTEGER']],
'Waiters' : [ 0x70, ['unsigned long']],
'Busy' : [ 0x74, ['unsigned long']],
'LastLock' : [ 0x78, ['pointer64', ['void']]],
'Lock' : [ 0x80, ['_KEVENT']],
'Event' : [ 0x98, ['_KEVENT']],
'CompletionContext' : [ 0xb0, ['pointer64', ['_IO_COMPLETION_CONTEXT']]],
} ],
'__unnamed_126d' : [ 0x8, {
'FileOffset' : [ 0x0, ['_LARGE_INTEGER']],
'ActiveCount' : [ 0x0, ['unsigned short']],
} ],
'_VACB' : [ 0x28, {
'BaseAddress' : [ 0x0, ['pointer64', ['void']]],
'SharedCacheMap' : [ 0x8, ['pointer64', ['_SHARED_CACHE_MAP']]],
'Overlay' : [ 0x10, ['__unnamed_126d']],
'LruList' : [ 0x18, ['_LIST_ENTRY']],
} ],
'_VACB_LEVEL_REFERENCE' : [ 0x8, {
'Reference' : [ 0x0, ['long']],
'SpecialReference' : [ 0x4, ['long']],
} ],
'__unnamed_1282' : [ 0x10, {
'FreeListsInUseUlong' : [ 0x0, ['array', 4, ['unsigned long']]],
'FreeListsInUseBytes' : [ 0x0, ['array', 16, ['unsigned char']]],
} ],
'__unnamed_1284' : [ 0x2, {
'FreeListsInUseTerminate' : [ 0x0, ['unsigned short']],
'DecommitCount' : [ 0x0, ['unsigned short']],
} ],
'_HEAP' : [ 0xae8, {
'Entry' : [ 0x0, ['_HEAP_ENTRY']],
'Signature' : [ 0x10, ['unsigned long']],
'Flags' : [ 0x14, ['unsigned long']],
'ForceFlags' : [ 0x18, ['unsigned long']],
'VirtualMemoryThreshold' : [ 0x1c, ['unsigned long']],
'SegmentReserve' : [ 0x20, ['unsigned long long']],
'SegmentCommit' : [ 0x28, ['unsigned long long']],
'DeCommitFreeBlockThreshold' : [ 0x30, ['unsigned long long']],
'DeCommitTotalFreeThreshold' : [ 0x38, ['unsigned long long']],
'TotalFreeSize' : [ 0x40, ['unsigned long long']],
'MaximumAllocationSize' : [ 0x48, ['unsigned long long']],
'ProcessHeapsListIndex' : [ 0x50, ['unsigned short']],
'HeaderValidateLength' : [ 0x52, ['unsigned short']],
'HeaderValidateCopy' : [ 0x58, ['pointer64', ['void']]],
'NextAvailableTagIndex' : [ 0x60, ['unsigned short']],
'MaximumTagIndex' : [ 0x62, ['unsigned short']],
'TagEntries' : [ 0x68, ['pointer64', ['_HEAP_TAG_ENTRY']]],
'UCRSegments' : [ 0x70, ['pointer64', ['_HEAP_UCR_SEGMENT']]],
'UnusedUnCommittedRanges' : [ 0x78, ['pointer64', ['_HEAP_UNCOMMMTTED_RANGE']]],
'AlignRound' : [ 0x80, ['unsigned long long']],
'AlignMask' : [ 0x88, ['unsigned long long']],
'VirtualAllocdBlocks' : [ 0x90, ['_LIST_ENTRY']],
'Segments' : [ 0xa0, ['array', 64, ['pointer64', ['_HEAP_SEGMENT']]]],
'u' : [ 0x2a0, ['__unnamed_1282']],
'u2' : [ 0x2b0, ['__unnamed_1284']],
'AllocatorBackTraceIndex' : [ 0x2b2, ['unsigned short']],
'NonDedicatedListLength' : [ 0x2b4, ['unsigned long']],
'LargeBlocksIndex' : [ 0x2b8, ['pointer64', ['void']]],
'PseudoTagEntries' : [ 0x2c0, ['pointer64', ['_HEAP_PSEUDO_TAG_ENTRY']]],
'FreeLists' : [ 0x2c8, ['array', 128, ['_LIST_ENTRY']]],
'LockVariable' : [ 0xac8, ['pointer64', ['_HEAP_LOCK']]],
'CommitRoutine' : [ 0xad0, ['pointer64', ['void']]],
'FrontEndHeap' : [ 0xad8, ['pointer64', ['void']]],
'FrontHeapLockCount' : [ 0xae0, ['unsigned short']],
'FrontEndHeapType' : [ 0xae2, ['unsigned char']],
'LastSegmentIndex' : [ 0xae3, ['unsigned char']],
} ],
'_HEAP_ENTRY' : [ 0x10, {
'PreviousBlockPrivateData' : [ 0x0, ['pointer64', ['void']]],
'Size' : [ 0x8, ['unsigned short']],
'PreviousSize' : [ 0xa, ['unsigned short']],
'SmallTagIndex' : [ 0xc, ['unsigned char']],
'Flags' : [ 0xd, ['unsigned char']],
'UnusedBytes' : [ 0xe, ['unsigned char']],
'SegmentIndex' : [ 0xf, ['unsigned char']],
'CompactHeader' : [ 0x8, ['unsigned long long']],
} ],
'_HEAP_SEGMENT' : [ 0x68, {
'Entry' : [ 0x0, ['_HEAP_ENTRY']],
'Signature' : [ 0x10, ['unsigned long']],
'Flags' : [ 0x14, ['unsigned long']],
'Heap' : [ 0x18, ['pointer64', ['_HEAP']]],
'LargestUnCommittedRange' : [ 0x20, ['unsigned long long']],
'BaseAddress' : [ 0x28, ['pointer64', ['void']]],
'NumberOfPages' : [ 0x30, ['unsigned long']],
'FirstEntry' : [ 0x38, ['pointer64', ['_HEAP_ENTRY']]],
'LastValidEntry' : [ 0x40, ['pointer64', ['_HEAP_ENTRY']]],
'NumberOfUnCommittedPages' : [ 0x48, ['unsigned long']],
'NumberOfUnCommittedRanges' : [ 0x4c, ['unsigned long']],
'UnCommittedRanges' : [ 0x50, ['pointer64', ['_HEAP_UNCOMMMTTED_RANGE']]],
'AllocatorBackTraceIndex' : [ 0x58, ['unsigned short']],
'Reserved' : [ 0x5a, ['unsigned short']],
'LastEntryInSegment' : [ 0x60, ['pointer64', ['_HEAP_ENTRY']]],
} ],
'_HEAP_SUBSEGMENT' : [ 0x30, {
'Bucket' : [ 0x0, ['pointer64', ['void']]],
'UserBlocks' : [ 0x8, ['pointer64', ['_HEAP_USERDATA_HEADER']]],
'AggregateExchg' : [ 0x10, ['_INTERLOCK_SEQ']],
'BlockSize' : [ 0x18, ['unsigned short']],
'FreeThreshold' : [ 0x1a, ['unsigned short']],
'BlockCount' : [ 0x1c, ['unsigned short']],
'SizeIndex' : [ 0x1e, ['unsigned char']],
'AffinityIndex' : [ 0x1f, ['unsigned char']],
'Alignment' : [ 0x18, ['array', 2, ['unsigned long']]],
'SFreeListEntry' : [ 0x20, ['_SINGLE_LIST_ENTRY']],
'Lock' : [ 0x28, ['unsigned long']],
} ],
'_TOKEN' : [ 0xd0, {
'TokenSource' : [ 0x0, ['_TOKEN_SOURCE']],
'TokenId' : [ 0x10, ['_LUID']],
'AuthenticationId' : [ 0x18, ['_LUID']],
'ParentTokenId' : [ 0x20, ['_LUID']],
'ExpirationTime' : [ 0x28, ['_LARGE_INTEGER']],
'TokenLock' : [ 0x30, ['pointer64', ['_ERESOURCE']]],
'AuditPolicy' : [ 0x38, ['_SEP_AUDIT_POLICY']],
'ModifiedId' : [ 0x40, ['_LUID']],
'SessionId' : [ 0x48, ['unsigned long']],
'UserAndGroupCount' : [ 0x4c, ['unsigned long']],
'RestrictedSidCount' : [ 0x50, ['unsigned long']],
'PrivilegeCount' : [ 0x54, ['unsigned long']],
'VariableLength' : [ 0x58, ['unsigned long']],
'DynamicCharged' : [ 0x5c, ['unsigned long']],
'DynamicAvailable' : [ 0x60, ['unsigned long']],
'DefaultOwnerIndex' : [ 0x64, ['unsigned long']],
'UserAndGroups' : [ 0x68, ['pointer64', ['_SID_AND_ATTRIBUTES']]],
'RestrictedSids' : [ 0x70, ['pointer64', ['_SID_AND_ATTRIBUTES']]],
'PrimaryGroup' : [ 0x78, ['pointer64', ['void']]],
'Privileges' : [ 0x80, ['pointer64', ['_LUID_AND_ATTRIBUTES']]],
'DynamicPart' : [ 0x88, ['pointer64', ['unsigned long']]],
'DefaultDacl' : [ 0x90, ['pointer64', ['_ACL']]],
'TokenType' : [ 0x98, ['Enumeration', dict(target = 'long', choices = {1: 'TokenPrimary', 2: 'TokenImpersonation'})]],
'ImpersonationLevel' : [ 0x9c, ['Enumeration', dict(target = 'long', choices = {0: 'SecurityAnonymous', 1: 'SecurityIdentification', 2: 'SecurityImpersonation', 3: 'SecurityDelegation'})]],
'TokenFlags' : [ 0xa0, ['unsigned char']],
'TokenInUse' : [ 0xa1, ['unsigned char']],
'ProxyData' : [ 0xa8, ['pointer64', ['_SECURITY_TOKEN_PROXY_DATA']]],
'AuditData' : [ 0xb0, ['pointer64', ['_SECURITY_TOKEN_AUDIT_DATA']]],
'LogonSession' : [ 0xb8, ['pointer64', ['_SEP_LOGON_SESSION_REFERENCES']]],
'OriginatingLogonSession' : [ 0xc0, ['_LUID']],
'VariablePart' : [ 0xc8, ['unsigned long']],
} ],
'_SEP_LOGON_SESSION_REFERENCES' : [ 0x20, {
'Next' : [ 0x0, ['pointer64', ['_SEP_LOGON_SESSION_REFERENCES']]],
'LogonId' : [ 0x8, ['_LUID']],
'ReferenceCount' : [ 0x10, ['unsigned long']],
'Flags' : [ 0x14, ['unsigned long']],
'pDeviceMap' : [ 0x18, ['pointer64', ['_DEVICE_MAP']]],
} ],
'_TEB' : [ 0x17d8, {
'NtTib' : [ 0x0, ['_NT_TIB']],
'EnvironmentPointer' : [ 0x38, ['pointer64', ['void']]],
'ClientId' : [ 0x40, ['_CLIENT_ID']],
'ActiveRpcHandle' : [ 0x50, ['pointer64', ['void']]],
'ThreadLocalStoragePointer' : [ 0x58, ['pointer64', ['void']]],
'ProcessEnvironmentBlock' : [ 0x60, ['pointer64', ['_PEB']]],
'LastErrorValue' : [ 0x68, ['unsigned long']],
'CountOfOwnedCriticalSections' : [ 0x6c, ['unsigned long']],
'CsrClientThread' : [ 0x70, ['pointer64', ['void']]],
'Win32ThreadInfo' : [ 0x78, ['pointer64', ['void']]],
'User32Reserved' : [ 0x80, ['array', 26, ['unsigned long']]],
'UserReserved' : [ 0xe8, ['array', 5, ['unsigned long']]],
'WOW32Reserved' : [ 0x100, ['pointer64', ['void']]],
'CurrentLocale' : [ 0x108, ['unsigned long']],
'FpSoftwareStatusRegister' : [ 0x10c, ['unsigned long']],
'SystemReserved1' : [ 0x110, ['array', 54, ['pointer64', ['void']]]],
'ExceptionCode' : [ 0x2c0, ['long']],
'ActivationContextStackPointer' : [ 0x2c8, ['pointer64', ['_ACTIVATION_CONTEXT_STACK']]],
'SpareBytes1' : [ 0x2d0, ['array', 28, ['unsigned char']]],
'GdiTebBatch' : [ 0x2f0, ['_GDI_TEB_BATCH']],
'RealClientId' : [ 0x7d8, ['_CLIENT_ID']],
'GdiCachedProcessHandle' : [ 0x7e8, ['pointer64', ['void']]],
'GdiClientPID' : [ 0x7f0, ['unsigned long']],
'GdiClientTID' : [ 0x7f4, ['unsigned long']],
'GdiThreadLocalInfo' : [ 0x7f8, ['pointer64', ['void']]],
'Win32ClientInfo' : [ 0x800, ['array', 62, ['unsigned long long']]],
'glDispatchTable' : [ 0x9f0, ['array', 233, ['pointer64', ['void']]]],
'glReserved1' : [ 0x1138, ['array', 29, ['unsigned long long']]],
'glReserved2' : [ 0x1220, ['pointer64', ['void']]],
'glSectionInfo' : [ 0x1228, ['pointer64', ['void']]],
'glSection' : [ 0x1230, ['pointer64', ['void']]],
'glTable' : [ 0x1238, ['pointer64', ['void']]],
'glCurrentRC' : [ 0x1240, ['pointer64', ['void']]],
'glContext' : [ 0x1248, ['pointer64', ['void']]],
'LastStatusValue' : [ 0x1250, ['unsigned long']],
'StaticUnicodeString' : [ 0x1258, ['_UNICODE_STRING']],
'StaticUnicodeBuffer' : [ 0x1268, ['array', 261, ['unsigned short']]],
'DeallocationStack' : [ 0x1478, ['pointer64', ['void']]],
'TlsSlots' : [ 0x1480, ['array', 64, ['pointer64', ['void']]]],
'TlsLinks' : [ 0x1680, ['_LIST_ENTRY']],
'Vdm' : [ 0x1690, ['pointer64', ['void']]],
'ReservedForNtRpc' : [ 0x1698, ['pointer64', ['void']]],
'DbgSsReserved' : [ 0x16a0, ['array', 2, ['pointer64', ['void']]]],
'HardErrorMode' : [ 0x16b0, ['unsigned long']],
'Instrumentation' : [ 0x16b8, ['array', 14, ['pointer64', ['void']]]],
'SubProcessTag' : [ 0x1728, ['pointer64', ['void']]],
'EtwTraceData' : [ 0x1730, ['pointer64', ['void']]],
'WinSockData' : [ 0x1738, ['pointer64', ['void']]],
'GdiBatchCount' : [ 0x1740, ['unsigned long']],
'InDbgPrint' : [ 0x1744, ['unsigned char']],
'FreeStackOnTermination' : [ 0x1745, ['unsigned char']],
'HasFiberData' : [ 0x1746, ['unsigned char']],
'IdealProcessor' : [ 0x1747, ['unsigned char']],
'GuaranteedStackBytes' : [ 0x1748, ['unsigned long']],
'ReservedForPerf' : [ 0x1750, ['pointer64', ['void']]],
'ReservedForOle' : [ 0x1758, ['pointer64', ['void']]],
'WaitingOnLoaderLock' : [ 0x1760, ['unsigned long']],
'SparePointer1' : [ 0x1768, ['unsigned long long']],
'SoftPatchPtr1' : [ 0x1770, ['unsigned long long']],
'SoftPatchPtr2' : [ 0x1778, ['unsigned long long']],
'TlsExpansionSlots' : [ 0x1780, ['pointer64', ['pointer64', ['void']]]],
'DeallocationBStore' : [ 0x1788, ['pointer64', ['void']]],
'BStoreLimit' : [ 0x1790, ['pointer64', ['void']]],
'ImpersonationLocale' : [ 0x1798, ['unsigned long']],
'IsImpersonating' : [ 0x179c, ['unsigned long']],
'NlsCache' : [ 0x17a0, ['pointer64', ['void']]],
'pShimData' : [ 0x17a8, ['pointer64', ['void']]],
'HeapVirtualAffinity' : [ 0x17b0, ['unsigned long']],
'CurrentTransactionHandle' : [ 0x17b8, ['pointer64', ['void']]],
'ActiveFrame' : [ 0x17c0, ['pointer64', ['_TEB_ACTIVE_FRAME']]],
'FlsData' : [ 0x17c8, ['pointer64', ['void']]],
'SafeThunkCall' : [ 0x17d0, ['unsigned char']],
'BooleanSpare' : [ 0x17d1, ['array', 3, ['unsigned char']]],
} ],
'_HEAP_UCR_SEGMENT' : [ 0x20, {
'Next' : [ 0x0, ['pointer64', ['_HEAP_UCR_SEGMENT']]],
'ReservedSize' : [ 0x8, ['unsigned long long']],
'CommittedSize' : [ 0x10, ['unsigned long long']],
'filler' : [ 0x18, ['unsigned long']],
} ],
'_HMAP_TABLE' : [ 0x4000, {
'Table' : [ 0x0, ['array', 512, ['_HMAP_ENTRY']]],
} ],
'_ERESOURCE' : [ 0x68, {
'SystemResourcesList' : [ 0x0, ['_LIST_ENTRY']],
'OwnerTable' : [ 0x10, ['pointer64', ['_OWNER_ENTRY']]],
'ActiveCount' : [ 0x18, ['short']],
'Flag' : [ 0x1a, ['unsigned short']],
'SharedWaiters' : [ 0x20, ['pointer64', ['_KSEMAPHORE']]],
'ExclusiveWaiters' : [ 0x28, ['pointer64', ['_KEVENT']]],
'OwnerThreads' : [ 0x30, ['array', 2, ['_OWNER_ENTRY']]],
'ContentionCount' : [ 0x50, ['unsigned long']],
'NumberOfSharedWaiters' : [ 0x54, ['unsigned short']],
'NumberOfExclusiveWaiters' : [ 0x56, ['unsigned short']],
'Address' : [ 0x58, ['pointer64', ['void']]],
'CreatorBackTraceIndex' : [ 0x58, ['unsigned long long']],
'SpinLock' : [ 0x60, ['unsigned long long']],
} ],
'_OBJECT_SYMBOLIC_LINK' : [ 0x38, {
'CreationTime' : [ 0x0, ['_LARGE_INTEGER']],
'LinkTarget' : [ 0x8, ['_UNICODE_STRING']],
'LinkTargetRemaining' : [ 0x18, ['_UNICODE_STRING']],
'LinkTargetObject' : [ 0x28, ['pointer64', ['void']]],
'DosDeviceDriveIndex' : [ 0x30, ['unsigned long']],
} ],
'_POOL_BLOCK_HEAD' : [ 0x20, {
'Header' : [ 0x0, ['_POOL_HEADER']],
'List' : [ 0x10, ['_LIST_ENTRY']],
} ],
'_DISPATCHER_HEADER' : [ 0x18, {
'Type' : [ 0x0, ['unsigned char']],
'Absolute' : [ 0x1, ['unsigned char']],
'NpxIrql' : [ 0x1, ['unsigned char']],
'Size' : [ 0x2, ['unsigned char']],
'Hand' : [ 0x2, ['unsigned char']],
'Inserted' : [ 0x3, ['unsigned char']],
'DebugActive' : [ 0x3, ['unsigned char']],
'Lock' : [ 0x0, ['long']],
'SignalState' : [ 0x4, ['long']],
'WaitListHead' : [ 0x8, ['_LIST_ENTRY']],
} ],
'_LDR_DATA_TABLE_ENTRY' : [ 0x98, {
'InLoadOrderLinks' : [ 0x0, ['_LIST_ENTRY']],
'InMemoryOrderLinks' : [ 0x10, ['_LIST_ENTRY']],
'InInitializationOrderLinks' : [ 0x20, ['_LIST_ENTRY']],
'DllBase' : [ 0x30, ['pointer64', ['void']]],
'EntryPoint' : [ 0x38, ['pointer64', ['void']]],
'SizeOfImage' : [ 0x40, ['unsigned long']],
'FullDllName' : [ 0x48, ['_UNICODE_STRING']],
'BaseDllName' : [ 0x58, ['_UNICODE_STRING']],
'Flags' : [ 0x68, ['unsigned long']],
'LoadCount' : [ 0x6c, ['unsigned short']],
'TlsIndex' : [ 0x6e, ['unsigned short']],
'HashLinks' : [ 0x70, ['_LIST_ENTRY']],
'SectionPointer' : [ 0x70, ['pointer64', ['void']]],
'CheckSum' : [ 0x78, ['unsigned long']],
'TimeDateStamp' : [ 0x80, ['unsigned long']],
'LoadedImports' : [ 0x80, ['pointer64', ['void']]],
'EntryPointActivationContext' : [ 0x88, ['pointer64', ['_ACTIVATION_CONTEXT']]],
'PatchInformation' : [ 0x90, ['pointer64', ['void']]],
} ],
'_HEAP_UNCOMMMTTED_RANGE' : [ 0x20, {
'Next' : [ 0x0, ['pointer64', ['_HEAP_UNCOMMMTTED_RANGE']]],
'Address' : [ 0x8, ['unsigned long long']],
'Size' : [ 0x10, ['unsigned long long']],
'filler' : [ 0x18, ['unsigned long']],
} ],
'_LUID_AND_ATTRIBUTES' : [ 0xc, {
'Luid' : [ 0x0, ['_LUID']],
'Attributes' : [ 0x8, ['unsigned long']],
} ],
'_VI_DEADLOCK_GLOBALS' : [ 0x1e0, {
'Nodes' : [ 0x0, ['array', 2, ['unsigned long']]],
'Resources' : [ 0x8, ['array', 2, ['unsigned long']]],
'Threads' : [ 0x10, ['array', 2, ['unsigned long']]],
'TimeAcquire' : [ 0x18, ['long long']],
'TimeRelease' : [ 0x20, ['long long']],
'BytesAllocated' : [ 0x28, ['unsigned long long']],
'ResourceDatabase' : [ 0x30, ['pointer64', ['_LIST_ENTRY']]],
'ThreadDatabase' : [ 0x38, ['pointer64', ['_LIST_ENTRY']]],
'AllocationFailures' : [ 0x40, ['unsigned long']],
'NodesTrimmedBasedOnAge' : [ 0x44, ['unsigned long']],
'NodesTrimmedBasedOnCount' : [ 0x48, ['unsigned long']],
'NodesSearched' : [ 0x4c, ['unsigned long']],
'MaxNodesSearched' : [ 0x50, ['unsigned long']],
'SequenceNumber' : [ 0x54, ['unsigned long']],
'RecursionDepthLimit' : [ 0x58, ['unsigned long']],
'SearchedNodesLimit' : [ 0x5c, ['unsigned long']],
'DepthLimitHits' : [ 0x60, ['unsigned long']],
'SearchLimitHits' : [ 0x64, ['unsigned long']],
'ABC_ACB_Skipped' : [ 0x68, ['unsigned long']],
'OutOfOrderReleases' : [ 0x6c, ['unsigned long']],
'NodesReleasedOutOfOrder' : [ 0x70, ['unsigned long']],
'TotalReleases' : [ 0x74, ['unsigned long']],
'RootNodesDeleted' : [ 0x78, ['unsigned long']],
'ForgetHistoryCounter' : [ 0x7c, ['unsigned long']],
'PoolTrimCounter' : [ 0x80, ['unsigned long']],
'FreeResourceList' : [ 0x88, ['_LIST_ENTRY']],
'FreeThreadList' : [ 0x98, ['_LIST_ENTRY']],
'FreeNodeList' : [ 0xa8, ['_LIST_ENTRY']],
'FreeResourceCount' : [ 0xb8, ['unsigned long']],
'FreeThreadCount' : [ 0xbc, ['unsigned long']],
'FreeNodeCount' : [ 0xc0, ['unsigned long']],
'Instigator' : [ 0xc8, ['pointer64', ['void']]],
'NumberOfParticipants' : [ 0xd0, ['unsigned long']],
'Participant' : [ 0xd8, ['array', 32, ['pointer64', ['_VI_DEADLOCK_NODE']]]],
'CacheReductionInProgress' : [ 0x1d8, ['unsigned long']],
} ],
'_THERMAL_INFORMATION' : [ 0x58, {
'ThermalStamp' : [ 0x0, ['unsigned long']],
'ThermalConstant1' : [ 0x4, ['unsigned long']],
'ThermalConstant2' : [ 0x8, ['unsigned long']],
'Processors' : [ 0x10, ['unsigned long long']],
'SamplingPeriod' : [ 0x18, ['unsigned long']],
'CurrentTemperature' : [ 0x1c, ['unsigned long']],
'PassiveTripPoint' : [ 0x20, ['unsigned long']],
'CriticalTripPoint' : [ 0x24, ['unsigned long']],
'ActiveTripPointCount' : [ 0x28, ['unsigned char']],
'ActiveTripPoint' : [ 0x2c, ['array', 10, ['unsigned long']]],
} ],
'_DBGKD_SEARCH_MEMORY' : [ 0x18, {
'SearchAddress' : [ 0x0, ['unsigned long long']],
'FoundAddress' : [ 0x0, ['unsigned long long']],
'SearchLength' : [ 0x8, ['unsigned long long']],
'PatternLength' : [ 0x10, ['unsigned long']],
} ],
'_SECTION_OBJECT' : [ 0x30, {
'StartingVa' : [ 0x0, ['pointer64', ['void']]],
'EndingVa' : [ 0x8, ['pointer64', ['void']]],
'Parent' : [ 0x10, ['pointer64', ['void']]],
'LeftChild' : [ 0x18, ['pointer64', ['void']]],
'RightChild' : [ 0x20, ['pointer64', ['void']]],
'Segment' : [ 0x28, ['pointer64', ['_SEGMENT_OBJECT']]],
} ],
'_POWER_STATE' : [ 0x4, {
'SystemState' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'DeviceState' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'PowerDeviceUnspecified', 1: 'PowerDeviceD0', 2: 'PowerDeviceD1', 3: 'PowerDeviceD2', 4: 'PowerDeviceD3', 5: 'PowerDeviceMaximum'})]],
} ],
'_KAPC' : [ 0x58, {
'Type' : [ 0x0, ['unsigned char']],
'SpareByte0' : [ 0x1, ['unsigned char']],
'Size' : [ 0x2, ['unsigned char']],
'SpareByte1' : [ 0x3, ['unsigned char']],
'SpareLong0' : [ 0x4, ['unsigned long']],
'Thread' : [ 0x8, ['pointer64', ['_KTHREAD']]],
'ApcListEntry' : [ 0x10, ['_LIST_ENTRY']],
'KernelRoutine' : [ 0x20, ['pointer64', ['void']]],
'RundownRoutine' : [ 0x28, ['pointer64', ['void']]],
'NormalRoutine' : [ 0x30, ['pointer64', ['void']]],
'NormalContext' : [ 0x38, ['pointer64', ['void']]],
'SystemArgument1' : [ 0x40, ['pointer64', ['void']]],
'SystemArgument2' : [ 0x48, ['pointer64', ['void']]],
'ApcStateIndex' : [ 0x50, ['unsigned char']],
'ApcMode' : [ 0x51, ['unsigned char']],
'Inserted' : [ 0x52, ['unsigned char']],
} ],
'_WMI_LOGGER_CONTEXT' : [ 0x280, {
'BufferSpinLock' : [ 0x0, ['unsigned long long']],
'StartTime' : [ 0x8, ['_LARGE_INTEGER']],
'LogFileHandle' : [ 0x10, ['pointer64', ['void']]],
'LoggerSemaphore' : [ 0x18, ['_KSEMAPHORE']],
'LoggerThread' : [ 0x38, ['pointer64', ['_ETHREAD']]],
'LoggerEvent' : [ 0x40, ['_KEVENT']],
'FlushEvent' : [ 0x58, ['_KEVENT']],
'LoggerStatus' : [ 0x70, ['long']],
'LoggerId' : [ 0x74, ['unsigned long']],
'BuffersAvailable' : [ 0x78, ['long']],
'UsePerfClock' : [ 0x7c, ['unsigned long']],
'WriteFailureLimit' : [ 0x80, ['unsigned long']],
'BuffersDirty' : [ 0x84, ['long']],
'BuffersInUse' : [ 0x88, ['long']],
'SwitchingInProgress' : [ 0x8c, ['unsigned long']],
'FreeList' : [ 0x90, ['_SLIST_HEADER']],
'FlushList' : [ 0xa0, ['_SLIST_HEADER']],
'WaitList' : [ 0xb0, ['_SLIST_HEADER']],
'GlobalList' : [ 0xc0, ['_SLIST_HEADER']],
'ProcessorBuffers' : [ 0xd0, ['pointer64', ['pointer64', ['_WMI_BUFFER_HEADER']]]],
'LoggerName' : [ 0xd8, ['_UNICODE_STRING']],
'LogFileName' : [ 0xe8, ['_UNICODE_STRING']],
'LogFilePattern' : [ 0xf8, ['_UNICODE_STRING']],
'NewLogFileName' : [ 0x108, ['_UNICODE_STRING']],
'EndPageMarker' : [ 0x118, ['pointer64', ['unsigned char']]],
'CollectionOn' : [ 0x120, ['long']],
'KernelTraceOn' : [ 0x124, ['unsigned long']],
'PerfLogInTransition' : [ 0x128, ['long']],
'RequestFlag' : [ 0x12c, ['unsigned long']],
'EnableFlags' : [ 0x130, ['unsigned long']],
'MaximumFileSize' : [ 0x134, ['unsigned long']],
'LoggerMode' : [ 0x138, ['unsigned long']],
'LoggerModeFlags' : [ 0x138, ['_WMI_LOGGER_MODE']],
'Wow' : [ 0x13c, ['unsigned long']],
'LastFlushedBuffer' : [ 0x140, ['unsigned long']],
'RefCount' : [ 0x144, ['unsigned long']],
'FlushTimer' : [ 0x148, ['unsigned long']],
'FirstBufferOffset' : [ 0x150, ['_LARGE_INTEGER']],
'ByteOffset' : [ 0x158, ['_LARGE_INTEGER']],
'BufferAgeLimit' : [ 0x160, ['_LARGE_INTEGER']],
'MaximumBuffers' : [ 0x168, ['unsigned long']],
'MinimumBuffers' : [ 0x16c, ['unsigned long']],
'EventsLost' : [ 0x170, ['unsigned long']],
'BuffersWritten' : [ 0x174, ['unsigned long']],
'LogBuffersLost' : [ 0x178, ['unsigned long']],
'RealTimeBuffersLost' : [ 0x17c, ['unsigned long']],
'BufferSize' : [ 0x180, ['unsigned long']],
'NumberOfBuffers' : [ 0x184, ['long']],
'SequencePtr' : [ 0x188, ['pointer64', ['long']]],
'InstanceGuid' : [ 0x190, ['_GUID']],
'LoggerHeader' : [ 0x1a0, ['pointer64', ['void']]],
'GetCpuClock' : [ 0x1a8, ['pointer64', ['void']]],
'ClientSecurityContext' : [ 0x1b0, ['_SECURITY_CLIENT_CONTEXT']],
'LoggerExtension' : [ 0x1f8, ['pointer64', ['void']]],
'ReleaseQueue' : [ 0x200, ['long']],
'EnableFlagExtension' : [ 0x204, ['_TRACE_ENABLE_FLAG_EXTENSION']],
'LocalSequence' : [ 0x208, ['unsigned long']],
'MaximumIrql' : [ 0x20c, ['unsigned long']],
'EnableFlagArray' : [ 0x210, ['pointer64', ['unsigned long']]],
'LoggerMutex' : [ 0x218, ['_KMUTANT']],
'MutexCount' : [ 0x250, ['long']],
'FileCounter' : [ 0x254, ['long']],
'BufferCallback' : [ 0x258, ['pointer64', ['void']]],
'CallbackContext' : [ 0x260, ['pointer64', ['void']]],
'PoolType' : [ 0x268, ['Enumeration', dict(target = 'long', choices = {0: 'NonPagedPool', 1: 'PagedPool', 2: 'NonPagedPoolMustSucceed', 3: 'DontUseThisType', 4: 'NonPagedPoolCacheAligned', 5: 'PagedPoolCacheAligned', 6: 'NonPagedPoolCacheAlignedMustS', 7: 'MaxPoolType', 34: 'NonPagedPoolMustSucceedSession', 35: 'DontUseThisTypeSession', 32: 'NonPagedPoolSession', 36: 'NonPagedPoolCacheAlignedSession', 33: 'PagedPoolSession', 38: 'NonPagedPoolCacheAlignedMustSSession', 37: 'PagedPoolCacheAlignedSession'})]],
'ReferenceSystemTime' : [ 0x270, ['_LARGE_INTEGER']],
'ReferenceTimeStamp' : [ 0x278, ['_LARGE_INTEGER']],
} ],
'_SEGMENT_OBJECT' : [ 0x48, {
'BaseAddress' : [ 0x0, ['pointer64', ['void']]],
'TotalNumberOfPtes' : [ 0x8, ['unsigned long']],
'SizeOfSegment' : [ 0x10, ['_LARGE_INTEGER']],
'NonExtendedPtes' : [ 0x18, ['unsigned long']],
'ImageCommitment' : [ 0x1c, ['unsigned long']],
'ControlArea' : [ 0x20, ['pointer64', ['_CONTROL_AREA']]],
'Subsection' : [ 0x28, ['pointer64', ['_SUBSECTION']]],
'LargeControlArea' : [ 0x30, ['pointer64', ['_LARGE_CONTROL_AREA']]],
'MmSectionFlags' : [ 0x38, ['pointer64', ['_MMSECTION_FLAGS']]],
'MmSubSectionFlags' : [ 0x40, ['pointer64', ['_MMSUBSECTION_FLAGS']]],
} ],
'__unnamed_13b7' : [ 0x4, {
'LongFlags' : [ 0x0, ['unsigned long']],
'Flags' : [ 0x0, ['_MMSECTION_FLAGS']],
} ],
'_CONTROL_AREA' : [ 0x48, {
'Segment' : [ 0x0, ['pointer64', ['_SEGMENT']]],
'DereferenceList' : [ 0x8, ['_LIST_ENTRY']],
'NumberOfSectionReferences' : [ 0x18, ['unsigned long']],
'NumberOfPfnReferences' : [ 0x1c, ['unsigned long']],
'NumberOfMappedViews' : [ 0x20, ['unsigned long']],
'NumberOfSystemCacheViews' : [ 0x24, ['unsigned long']],
'NumberOfUserReferences' : [ 0x28, ['unsigned long']],
'u' : [ 0x2c, ['__unnamed_13b7']],
'FilePointer' : [ 0x30, ['pointer64', ['_FILE_OBJECT']]],
'WaitingForDeletion' : [ 0x38, ['pointer64', ['_EVENT_COUNTER']]],
'ModifiedWriteCount' : [ 0x40, ['unsigned short']],
'FlushInProgressCount' : [ 0x42, ['unsigned short']],
'WritableUserReferences' : [ 0x44, ['unsigned long']],
} ],
'_HANDLE_TABLE' : [ 0x70, {
'TableCode' : [ 0x0, ['unsigned long long']],
'QuotaProcess' : [ 0x8, ['pointer64', ['_EPROCESS']]],
'UniqueProcessId' : [ 0x10, ['pointer64', ['void']]],
'HandleTableLock' : [ 0x18, ['array', 4, ['_EX_PUSH_LOCK']]],
'HandleTableList' : [ 0x38, ['_LIST_ENTRY']],
'HandleContentionEvent' : [ 0x48, ['_EX_PUSH_LOCK']],
'DebugInfo' : [ 0x50, ['pointer64', ['_HANDLE_TRACE_DEBUG_INFO']]],
'ExtraInfoPages' : [ 0x58, ['long']],
'FirstFree' : [ 0x5c, ['unsigned long']],
'LastFree' : [ 0x60, ['unsigned long']],
'NextHandleNeedingPool' : [ 0x64, ['unsigned long']],
'HandleCount' : [ 0x68, ['long']],
'Flags' : [ 0x6c, ['unsigned long']],
'StrictFIFO' : [ 0x6c, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]],
} ],
'_POOL_HEADER' : [ 0x10, {
'PreviousSize' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 8, native_type='unsigned long')]],
'PoolIndex' : [ 0x0, ['BitField', dict(start_bit = 8, end_bit = 16, native_type='unsigned long')]],
'BlockSize' : [ 0x0, ['BitField', dict(start_bit = 16, end_bit = 24, native_type='unsigned long')]],
'PoolType' : [ 0x0, ['BitField', dict(start_bit = 24, end_bit = 32, native_type='unsigned long')]],
'Ulong1' : [ 0x0, ['unsigned long']],
'PoolTag' : [ 0x4, ['unsigned long']],
'ProcessBilled' : [ 0x8, ['pointer64', ['_EPROCESS']]],
'AllocatorBackTraceIndex' : [ 0x8, ['unsigned short']],
'PoolTagHash' : [ 0xa, ['unsigned short']],
} ],
'_MMVAD_FLAGS2' : [ 0x4, {
'FileOffset' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 24, native_type='unsigned long')]],
'SecNoChange' : [ 0x0, ['BitField', dict(start_bit = 24, end_bit = 25, native_type='unsigned long')]],
'OneSecured' : [ 0x0, ['BitField', dict(start_bit = 25, end_bit = 26, native_type='unsigned long')]],
'MultipleSecured' : [ 0x0, ['BitField', dict(start_bit = 26, end_bit = 27, native_type='unsigned long')]],
'ReadOnly' : [ 0x0, ['BitField', dict(start_bit = 27, end_bit = 28, native_type='unsigned long')]],
'LongVad' : [ 0x0, ['BitField', dict(start_bit = 28, end_bit = 29, native_type='unsigned long')]],
'ExtendableFile' : [ 0x0, ['BitField', dict(start_bit = 29, end_bit = 30, native_type='unsigned long')]],
'Inherit' : [ 0x0, ['BitField', dict(start_bit = 30, end_bit = 31, native_type='unsigned long')]],
'CopyOnWrite' : [ 0x0, ['BitField', dict(start_bit = 31, end_bit = 32, native_type='unsigned long')]],
} ],
'_TEB_ACTIVE_FRAME' : [ 0x18, {
'Flags' : [ 0x0, ['unsigned long']],
'Previous' : [ 0x8, ['pointer64', ['_TEB_ACTIVE_FRAME']]],
'Context' : [ 0x10, ['pointer64', ['_TEB_ACTIVE_FRAME_CONTEXT']]],
} ],
'_XMM_SAVE_AREA32' : [ 0x200, {
'ControlWord' : [ 0x0, ['unsigned short']],
'StatusWord' : [ 0x2, ['unsigned short']],
'TagWord' : [ 0x4, ['unsigned char']],
'Reserved1' : [ 0x5, ['unsigned char']],
'ErrorOpcode' : [ 0x6, ['unsigned short']],
'ErrorOffset' : [ 0x8, ['unsigned long']],
'ErrorSelector' : [ 0xc, ['unsigned short']],
'Reserved2' : [ 0xe, ['unsigned short']],
'DataOffset' : [ 0x10, ['unsigned long']],
'DataSelector' : [ 0x14, ['unsigned short']],
'Reserved3' : [ 0x16, ['unsigned short']],
'MxCsr' : [ 0x18, ['unsigned long']],
'MxCsr_Mask' : [ 0x1c, ['unsigned long']],
'FloatRegisters' : [ 0x20, ['array', 8, ['_M128A']]],
'XmmRegisters' : [ 0xa0, ['array', 16, ['_M128A']]],
'Reserved4' : [ 0x1a0, ['array', 96, ['unsigned char']]],
} ],
'_MMPTE_PROTOTYPE' : [ 0x8, {
'Valid' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long long')]],
'Unused0' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 8, native_type='unsigned long long')]],
'ReadOnly' : [ 0x0, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long long')]],
'Unused1' : [ 0x0, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long long')]],
'Prototype' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long long')]],
'Protection' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 16, native_type='unsigned long long')]],
'ProtoAddress' : [ 0x0, ['BitField', dict(start_bit = 16, end_bit = 64, native_type='long long')]],
} ],
'_MMSUPPORT' : [ 0x58, {
'WorkingSetExpansionLinks' : [ 0x0, ['_LIST_ENTRY']],
'LastTrimTime' : [ 0x10, ['_LARGE_INTEGER']],
'Flags' : [ 0x18, ['_MMSUPPORT_FLAGS']],
'PageFaultCount' : [ 0x1c, ['unsigned long']],
'PeakWorkingSetSize' : [ 0x20, ['unsigned long']],
'GrowthSinceLastEstimate' : [ 0x24, ['unsigned long']],
'MinimumWorkingSetSize' : [ 0x28, ['unsigned long']],
'MaximumWorkingSetSize' : [ 0x2c, ['unsigned long']],
'VmWorkingSetList' : [ 0x30, ['pointer64', ['_MMWSL']]],
'Claim' : [ 0x38, ['unsigned long']],
'NextEstimationSlot' : [ 0x3c, ['unsigned long']],
'NextAgingSlot' : [ 0x40, ['unsigned long']],
'EstimatedAvailable' : [ 0x44, ['unsigned long']],
'WorkingSetSize' : [ 0x48, ['unsigned long']],
'WorkingSetMutex' : [ 0x50, ['_EX_PUSH_LOCK']],
} ],
'_EX_WORK_QUEUE' : [ 0x58, {
'WorkerQueue' : [ 0x0, ['_KQUEUE']],
'DynamicThreadCount' : [ 0x40, ['unsigned long']],
'WorkItemsProcessed' : [ 0x44, ['unsigned long']],
'WorkItemsProcessedLastPass' : [ 0x48, ['unsigned long']],
'QueueDepthLastPass' : [ 0x4c, ['unsigned long']],
'Info' : [ 0x50, ['EX_QUEUE_WORKER_INFO']],
} ],
'_MMSUBSECTION_FLAGS' : [ 0x4, {
'ReadOnly' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'ReadWrite' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]],
'SubsectionStatic' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]],
'GlobalMemory' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]],
'Protection' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 9, native_type='unsigned long')]],
'Spare' : [ 0x0, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long')]],
'StartingSector4132' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 20, native_type='unsigned long')]],
'SectorEndOffset' : [ 0x0, ['BitField', dict(start_bit = 20, end_bit = 32, native_type='unsigned long')]],
} ],
'_KMUTANT' : [ 0x38, {
'Header' : [ 0x0, ['_DISPATCHER_HEADER']],
'MutantListEntry' : [ 0x18, ['_LIST_ENTRY']],
'OwnerThread' : [ 0x28, ['pointer64', ['_KTHREAD']]],
'Abandoned' : [ 0x30, ['unsigned char']],
'ApcDisable' : [ 0x31, ['unsigned char']],
} ],
'_HEAP_TAG_ENTRY' : [ 0x48, {
'Allocs' : [ 0x0, ['unsigned long']],
'Frees' : [ 0x4, ['unsigned long']],
'Size' : [ 0x8, ['unsigned long long']],
'TagIndex' : [ 0x10, ['unsigned short']],
'CreatorBackTraceIndex' : [ 0x12, ['unsigned short']],
'TagName' : [ 0x14, ['array', 24, ['unsigned short']]],
} ],
'_EPROCESS_QUOTA_BLOCK' : [ 0x78, {
'QuotaEntry' : [ 0x0, ['array', 3, ['_EPROCESS_QUOTA_ENTRY']]],
'QuotaList' : [ 0x60, ['_LIST_ENTRY']],
'ReferenceCount' : [ 0x70, ['unsigned long']],
'ProcessCount' : [ 0x74, ['unsigned long']],
} ],
'_NT_TIB' : [ 0x38, {
'ExceptionList' : [ 0x0, ['pointer64', ['_EXCEPTION_REGISTRATION_RECORD']]],
'StackBase' : [ 0x8, ['pointer64', ['void']]],
'StackLimit' : [ 0x10, ['pointer64', ['void']]],
'SubSystemTib' : [ 0x18, ['pointer64', ['void']]],
'FiberData' : [ 0x20, ['pointer64', ['void']]],
'Version' : [ 0x20, ['unsigned long']],
'ArbitraryUserPointer' : [ 0x28, ['pointer64', ['void']]],
'Self' : [ 0x30, ['pointer64', ['_NT_TIB']]],
} ],
'_EVENT_COUNTER' : [ 0x30, {
'ListEntry' : [ 0x0, ['_SLIST_ENTRY']],
'RefCount' : [ 0x10, ['unsigned long']],
'Event' : [ 0x18, ['_KEVENT']],
} ],
'_EJOB' : [ 0x220, {
'Event' : [ 0x0, ['_KEVENT']],
'JobLinks' : [ 0x18, ['_LIST_ENTRY']],
'ProcessListHead' : [ 0x28, ['_LIST_ENTRY']],
'JobLock' : [ 0x38, ['_ERESOURCE']],
'TotalUserTime' : [ 0xa0, ['_LARGE_INTEGER']],
'TotalKernelTime' : [ 0xa8, ['_LARGE_INTEGER']],
'ThisPeriodTotalUserTime' : [ 0xb0, ['_LARGE_INTEGER']],
'ThisPeriodTotalKernelTime' : [ 0xb8, ['_LARGE_INTEGER']],
'TotalPageFaultCount' : [ 0xc0, ['unsigned long']],
'TotalProcesses' : [ 0xc4, ['unsigned long']],
'ActiveProcesses' : [ 0xc8, ['unsigned long']],
'TotalTerminatedProcesses' : [ 0xcc, ['unsigned long']],
'PerProcessUserTimeLimit' : [ 0xd0, ['_LARGE_INTEGER']],
'PerJobUserTimeLimit' : [ 0xd8, ['_LARGE_INTEGER']],
'LimitFlags' : [ 0xe0, ['unsigned long']],
'MinimumWorkingSetSize' : [ 0xe8, ['unsigned long long']],
'MaximumWorkingSetSize' : [ 0xf0, ['unsigned long long']],
'ActiveProcessLimit' : [ 0xf8, ['unsigned long']],
'Affinity' : [ 0x100, ['unsigned long long']],
'PriorityClass' : [ 0x108, ['unsigned char']],
'UIRestrictionsClass' : [ 0x10c, ['unsigned long']],
'SecurityLimitFlags' : [ 0x110, ['unsigned long']],
'Token' : [ 0x118, ['pointer64', ['void']]],
'Filter' : [ 0x120, ['pointer64', ['_PS_JOB_TOKEN_FILTER']]],
'EndOfJobTimeAction' : [ 0x128, ['unsigned long']],
'CompletionPort' : [ 0x130, ['pointer64', ['void']]],
'CompletionKey' : [ 0x138, ['pointer64', ['void']]],
'SessionId' : [ 0x140, ['unsigned long']],
'SchedulingClass' : [ 0x144, ['unsigned long']],
'ReadOperationCount' : [ 0x148, ['unsigned long long']],
'WriteOperationCount' : [ 0x150, ['unsigned long long']],
'OtherOperationCount' : [ 0x158, ['unsigned long long']],
'ReadTransferCount' : [ 0x160, ['unsigned long long']],
'WriteTransferCount' : [ 0x168, ['unsigned long long']],
'OtherTransferCount' : [ 0x170, ['unsigned long long']],
'IoInfo' : [ 0x178, ['_IO_COUNTERS']],
'ProcessMemoryLimit' : [ 0x1a8, ['unsigned long long']],
'JobMemoryLimit' : [ 0x1b0, ['unsigned long long']],
'PeakProcessMemoryUsed' : [ 0x1b8, ['unsigned long long']],
'PeakJobMemoryUsed' : [ 0x1c0, ['unsigned long long']],
'CurrentJobMemoryUsed' : [ 0x1c8, ['unsigned long long']],
'MemoryLimitsLock' : [ 0x1d0, ['_KGUARDED_MUTEX']],
'JobSetLinks' : [ 0x208, ['_LIST_ENTRY']],
'MemberLevel' : [ 0x218, ['unsigned long']],
'JobFlags' : [ 0x21c, ['unsigned long']],
} ],
'_LARGE_CONTROL_AREA' : [ 0x68, {
'Segment' : [ 0x0, ['pointer64', ['_SEGMENT']]],
'DereferenceList' : [ 0x8, ['_LIST_ENTRY']],
'NumberOfSectionReferences' : [ 0x18, ['unsigned long']],
'NumberOfPfnReferences' : [ 0x1c, ['unsigned long']],
'NumberOfMappedViews' : [ 0x20, ['unsigned long']],
'NumberOfSystemCacheViews' : [ 0x24, ['unsigned long']],
'NumberOfUserReferences' : [ 0x28, ['unsigned long']],
'u' : [ 0x2c, ['__unnamed_13b7']],
'FilePointer' : [ 0x30, ['pointer64', ['_FILE_OBJECT']]],
'WaitingForDeletion' : [ 0x38, ['pointer64', ['_EVENT_COUNTER']]],
'ModifiedWriteCount' : [ 0x40, ['unsigned short']],
'FlushInProgressCount' : [ 0x42, ['unsigned short']],
'WritableUserReferences' : [ 0x44, ['unsigned long']],
'StartingFrame' : [ 0x48, ['unsigned long long']],
'UserGlobalList' : [ 0x50, ['_LIST_ENTRY']],
'SessionId' : [ 0x60, ['unsigned long']],
} ],
'_GUID' : [ 0x10, {
'Data1' : [ 0x0, ['unsigned long']],
'Data2' : [ 0x4, ['unsigned short']],
'Data3' : [ 0x6, ['unsigned short']],
'Data4' : [ 0x8, ['array', 8, ['unsigned char']]],
} ],
'_KGATE' : [ 0x18, {
'Header' : [ 0x0, ['_DISPATCHER_HEADER']],
} ],
'_PS_JOB_TOKEN_FILTER' : [ 0x38, {
'CapturedSidCount' : [ 0x0, ['unsigned long']],
'CapturedSids' : [ 0x8, ['pointer64', ['_SID_AND_ATTRIBUTES']]],
'CapturedSidsLength' : [ 0x10, ['unsigned long']],
'CapturedGroupCount' : [ 0x14, ['unsigned long']],
'CapturedGroups' : [ 0x18, ['pointer64', ['_SID_AND_ATTRIBUTES']]],
'CapturedGroupsLength' : [ 0x20, ['unsigned long']],
'CapturedPrivilegeCount' : [ 0x24, ['unsigned long']],
'CapturedPrivileges' : [ 0x28, ['pointer64', ['_LUID_AND_ATTRIBUTES']]],
'CapturedPrivilegesLength' : [ 0x30, ['unsigned long']],
} ],
'_MM_DRIVER_VERIFIER_DATA' : [ 0x80, {
'Level' : [ 0x0, ['unsigned long']],
'RaiseIrqls' : [ 0x4, ['unsigned long']],
'AcquireSpinLocks' : [ 0x8, ['unsigned long']],
'SynchronizeExecutions' : [ 0xc, ['unsigned long']],
'AllocationsAttempted' : [ 0x10, ['unsigned long']],
'AllocationsSucceeded' : [ 0x14, ['unsigned long']],
'AllocationsSucceededSpecialPool' : [ 0x18, ['unsigned long']],
'AllocationsWithNoTag' : [ 0x1c, ['unsigned long']],
'TrimRequests' : [ 0x20, ['unsigned long']],
'Trims' : [ 0x24, ['unsigned long']],
'AllocationsFailed' : [ 0x28, ['unsigned long']],
'AllocationsFailedDeliberately' : [ 0x2c, ['unsigned long']],
'Loads' : [ 0x30, ['unsigned long']],
'Unloads' : [ 0x34, ['unsigned long']],
'UnTrackedPool' : [ 0x38, ['unsigned long']],
'UserTrims' : [ 0x3c, ['unsigned long']],
'CurrentPagedPoolAllocations' : [ 0x40, ['unsigned long']],
'CurrentNonPagedPoolAllocations' : [ 0x44, ['unsigned long']],
'PeakPagedPoolAllocations' : [ 0x48, ['unsigned long']],
'PeakNonPagedPoolAllocations' : [ 0x4c, ['unsigned long']],
'PagedBytes' : [ 0x50, ['unsigned long long']],
'NonPagedBytes' : [ 0x58, ['unsigned long long']],
'PeakPagedBytes' : [ 0x60, ['unsigned long long']],
'PeakNonPagedBytes' : [ 0x68, ['unsigned long long']],
'BurstAllocationsFailedDeliberately' : [ 0x70, ['unsigned long']],
'SessionTrims' : [ 0x74, ['unsigned long']],
'Reserved' : [ 0x78, ['array', 2, ['unsigned long']]],
} ],
'_IMAGE_FILE_HEADER' : [ 0x14, {
'Machine' : [ 0x0, ['unsigned short']],
'NumberOfSections' : [ 0x2, ['unsigned short']],
'TimeDateStamp' : [ 0x4, ['unsigned long']],
'PointerToSymbolTable' : [ 0x8, ['unsigned long']],
'NumberOfSymbols' : [ 0xc, ['unsigned long']],
'SizeOfOptionalHeader' : [ 0x10, ['unsigned short']],
'Characteristics' : [ 0x12, ['unsigned short']],
} ],
'_MMPTE_HARDWARE' : [ 0x8, {
'Valid' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long long')]],
'Writable' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long long')]],
'Owner' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long long')]],
'WriteThrough' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long long')]],
'CacheDisable' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long long')]],
'Accessed' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long long')]],
'Dirty' : [ 0x0, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned long long')]],
'LargePage' : [ 0x0, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned long long')]],
'Global' : [ 0x0, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long long')]],
'CopyOnWrite' : [ 0x0, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long long')]],
'Prototype' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long long')]],
'Write' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned long long')]],
'PageFrameNumber' : [ 0x0, ['BitField', dict(start_bit = 12, end_bit = 40, native_type='unsigned long long')]],
'reserved1' : [ 0x0, ['BitField', dict(start_bit = 40, end_bit = 52, native_type='unsigned long long')]],
'SoftwareWsIndex' : [ 0x0, ['BitField', dict(start_bit = 52, end_bit = 63, native_type='unsigned long long')]],
'NoExecute' : [ 0x0, ['BitField', dict(start_bit = 63, end_bit = 64, native_type='unsigned long long')]],
} ],
'_IO_COMPLETION_CONTEXT' : [ 0x10, {
'Port' : [ 0x0, ['pointer64', ['void']]],
'Key' : [ 0x8, ['pointer64', ['void']]],
} ],
'_CALL_HASH_ENTRY' : [ 0x28, {
'ListEntry' : [ 0x0, ['_LIST_ENTRY']],
'CallersAddress' : [ 0x10, ['pointer64', ['void']]],
'CallersCaller' : [ 0x18, ['pointer64', ['void']]],
'CallCount' : [ 0x20, ['unsigned long']],
} ],
'_HMAP_ENTRY' : [ 0x20, {
'BlockAddress' : [ 0x0, ['unsigned long long']],
'BinAddress' : [ 0x8, ['unsigned long long']],
'CmView' : [ 0x10, ['pointer64', ['_CM_VIEW_OF_FILE']]],
'MemAlloc' : [ 0x18, ['unsigned long']],
} ],
'_DBGKD_SET_CONTEXT' : [ 0x4, {
'ContextFlags' : [ 0x0, ['unsigned long']],
} ],
'_MMSECTION_FLAGS' : [ 0x4, {
'BeingDeleted' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'BeingCreated' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]],
'BeingPurged' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]],
'NoModifiedWriting' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]],
'FailAllIo' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long')]],
'Image' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long')]],
'Based' : [ 0x0, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned long')]],
'File' : [ 0x0, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned long')]],
'Networked' : [ 0x0, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long')]],
'NoCache' : [ 0x0, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long')]],
'PhysicalMemory' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long')]],
'CopyOnWrite' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned long')]],
'Reserve' : [ 0x0, ['BitField', dict(start_bit = 12, end_bit = 13, native_type='unsigned long')]],
'Commit' : [ 0x0, ['BitField', dict(start_bit = 13, end_bit = 14, native_type='unsigned long')]],
'FloppyMedia' : [ 0x0, ['BitField', dict(start_bit = 14, end_bit = 15, native_type='unsigned long')]],
'WasPurged' : [ 0x0, ['BitField', dict(start_bit = 15, end_bit = 16, native_type='unsigned long')]],
'UserReference' : [ 0x0, ['BitField', dict(start_bit = 16, end_bit = 17, native_type='unsigned long')]],
'GlobalMemory' : [ 0x0, ['BitField', dict(start_bit = 17, end_bit = 18, native_type='unsigned long')]],
'DeleteOnClose' : [ 0x0, ['BitField', dict(start_bit = 18, end_bit = 19, native_type='unsigned long')]],
'FilePointerNull' : [ 0x0, ['BitField', dict(start_bit = 19, end_bit = 20, native_type='unsigned long')]],
'DebugSymbolsLoaded' : [ 0x0, ['BitField', dict(start_bit = 20, end_bit = 21, native_type='unsigned long')]],
'SetMappedFileIoComplete' : [ 0x0, ['BitField', dict(start_bit = 21, end_bit = 22, native_type='unsigned long')]],
'CollidedFlush' : [ 0x0, ['BitField', dict(start_bit = 22, end_bit = 23, native_type='unsigned long')]],
'NoChange' : [ 0x0, ['BitField', dict(start_bit = 23, end_bit = 24, native_type='unsigned long')]],
'filler0' : [ 0x0, ['BitField', dict(start_bit = 24, end_bit = 25, native_type='unsigned long')]],
'ImageMappedInSystemSpace' : [ 0x0, ['BitField', dict(start_bit = 25, end_bit = 26, native_type='unsigned long')]],
'UserWritable' : [ 0x0, ['BitField', dict(start_bit = 26, end_bit = 27, native_type='unsigned long')]],
'Accessed' : [ 0x0, ['BitField', dict(start_bit = 27, end_bit = 28, native_type='unsigned long')]],
'GlobalOnlyPerSession' : [ 0x0, ['BitField', dict(start_bit = 28, end_bit = 29, native_type='unsigned long')]],
'Rom' : [ 0x0, ['BitField', dict(start_bit = 29, end_bit = 30, native_type='unsigned long')]],
'WriteCombined' : [ 0x0, ['BitField', dict(start_bit = 30, end_bit = 31, native_type='unsigned long')]],
'filler' : [ 0x0, ['BitField', dict(start_bit = 31, end_bit = 32, native_type='unsigned long')]],
} ],
'_DEFERRED_WRITE' : [ 0x50, {
'NodeTypeCode' : [ 0x0, ['short']],
'NodeByteSize' : [ 0x2, ['short']],
'FileObject' : [ 0x8, ['pointer64', ['_FILE_OBJECT']]],
'BytesToWrite' : [ 0x10, ['unsigned long']],
'DeferredWriteLinks' : [ 0x18, ['_LIST_ENTRY']],
'Event' : [ 0x28, ['pointer64', ['_KEVENT']]],
'PostRoutine' : [ 0x30, ['pointer64', ['void']]],
'Context1' : [ 0x38, ['pointer64', ['void']]],
'Context2' : [ 0x40, ['pointer64', ['void']]],
'LimitModifiedPages' : [ 0x48, ['unsigned char']],
} ],
'_TRACE_ENABLE_FLAG_EXTENSION' : [ 0x4, {
'Offset' : [ 0x0, ['unsigned short']],
'Length' : [ 0x2, ['unsigned char']],
'Flag' : [ 0x3, ['unsigned char']],
} ],
'_SID_AND_ATTRIBUTES' : [ 0x10, {
'Sid' : [ 0x0, ['pointer64', ['void']]],
'Attributes' : [ 0x8, ['unsigned long']],
} ],
'_HIVE_LIST_ENTRY' : [ 0x30, {
'Name' : [ 0x0, ['pointer64', ['unsigned short']]],
'BaseName' : [ 0x8, ['pointer64', ['unsigned short']]],
'CmHive' : [ 0x10, ['pointer64', ['_CMHIVE']]],
'HHiveFlags' : [ 0x18, ['unsigned long']],
'CmHiveFlags' : [ 0x1c, ['unsigned long']],
'CmHive2' : [ 0x20, ['pointer64', ['_CMHIVE']]],
'ThreadFinished' : [ 0x28, ['unsigned char']],
'ThreadStarted' : [ 0x29, ['unsigned char']],
'Allocate' : [ 0x2a, ['unsigned char']],
} ],
'_MMVAD_FLAGS' : [ 0x8, {
'CommitCharge' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 51, native_type='unsigned long long')]],
'NoChange' : [ 0x0, ['BitField', dict(start_bit = 51, end_bit = 52, native_type='unsigned long long')]],
'VadType' : [ 0x0, ['BitField', dict(start_bit = 52, end_bit = 55, native_type='unsigned long long')]],
'MemCommit' : [ 0x0, ['BitField', dict(start_bit = 55, end_bit = 56, native_type='unsigned long long')]],
'Protection' : [ 0x0, ['BitField', dict(start_bit = 56, end_bit = 61, native_type='unsigned long long')]],
'Spare' : [ 0x0, ['BitField', dict(start_bit = 61, end_bit = 63, native_type='unsigned long long')]],
'PrivateMemory' : [ 0x0, ['BitField', dict(start_bit = 63, end_bit = 64, native_type='unsigned long long')]],
} ],
'_PS_IMPERSONATION_INFORMATION' : [ 0x10, {
'Token' : [ 0x0, ['pointer64', ['void']]],
'CopyOnOpen' : [ 0x8, ['unsigned char']],
'EffectiveOnly' : [ 0x9, ['unsigned char']],
'ImpersonationLevel' : [ 0xc, ['Enumeration', dict(target = 'long', choices = {0: 'SecurityAnonymous', 1: 'SecurityIdentification', 2: 'SecurityImpersonation', 3: 'SecurityDelegation'})]],
} ],
'__unnamed_1472' : [ 0x8, {
'LegacyDeviceNode' : [ 0x0, ['pointer64', ['_DEVICE_NODE']]],
'PendingDeviceRelations' : [ 0x0, ['pointer64', ['_DEVICE_RELATIONS']]],
} ],
'__unnamed_1474' : [ 0x8, {
'NextResourceDeviceNode' : [ 0x0, ['pointer64', ['_DEVICE_NODE']]],
} ],
'__unnamed_1478' : [ 0x20, {
'DockStatus' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'DOCK_NOTDOCKDEVICE', 1: 'DOCK_QUIESCENT', 2: 'DOCK_ARRIVING', 3: 'DOCK_DEPARTING', 4: 'DOCK_EJECTIRP_COMPLETED'})]],
'ListEntry' : [ 0x8, ['_LIST_ENTRY']],
'SerialNumber' : [ 0x18, ['pointer64', ['unsigned short']]],
} ],
'_DEVICE_NODE' : [ 0x1c0, {
'Sibling' : [ 0x0, ['pointer64', ['_DEVICE_NODE']]],
'Child' : [ 0x8, ['pointer64', ['_DEVICE_NODE']]],
'Parent' : [ 0x10, ['pointer64', ['_DEVICE_NODE']]],
'LastChild' : [ 0x18, ['pointer64', ['_DEVICE_NODE']]],
'Level' : [ 0x20, ['unsigned long']],
'Notify' : [ 0x28, ['pointer64', ['_PO_DEVICE_NOTIFY']]],
'State' : [ 0x30, ['Enumeration', dict(target = 'long', choices = {768: 'DeviceNodeUnspecified', 769: 'DeviceNodeUninitialized', 770: 'DeviceNodeInitialized', 771: 'DeviceNodeDriversAdded', 772: 'DeviceNodeResourcesAssigned', 773: 'DeviceNodeStartPending', 774: 'DeviceNodeStartCompletion', 775: 'DeviceNodeStartPostWork', 776: 'DeviceNodeStarted', 777: 'DeviceNodeQueryStopped', 778: 'DeviceNodeStopped', 779: 'DeviceNodeRestartCompletion', 780: 'DeviceNodeEnumeratePending', 781: 'DeviceNodeEnumerateCompletion', 782: 'DeviceNodeAwaitingQueuedDeletion', 783: 'DeviceNodeAwaitingQueuedRemoval', 784: 'DeviceNodeQueryRemoved', 785: 'DeviceNodeRemovePendingCloses', 786: 'DeviceNodeRemoved', 787: 'DeviceNodeDeletePendingCloses', 788: 'DeviceNodeDeleted', 789: 'MaxDeviceNodeState'})]],
'PreviousState' : [ 0x34, ['Enumeration', dict(target = 'long', choices = {768: 'DeviceNodeUnspecified', 769: 'DeviceNodeUninitialized', 770: 'DeviceNodeInitialized', 771: 'DeviceNodeDriversAdded', 772: 'DeviceNodeResourcesAssigned', 773: 'DeviceNodeStartPending', 774: 'DeviceNodeStartCompletion', 775: 'DeviceNodeStartPostWork', 776: 'DeviceNodeStarted', 777: 'DeviceNodeQueryStopped', 778: 'DeviceNodeStopped', 779: 'DeviceNodeRestartCompletion', 780: 'DeviceNodeEnumeratePending', 781: 'DeviceNodeEnumerateCompletion', 782: 'DeviceNodeAwaitingQueuedDeletion', 783: 'DeviceNodeAwaitingQueuedRemoval', 784: 'DeviceNodeQueryRemoved', 785: 'DeviceNodeRemovePendingCloses', 786: 'DeviceNodeRemoved', 787: 'DeviceNodeDeletePendingCloses', 788: 'DeviceNodeDeleted', 789: 'MaxDeviceNodeState'})]],
'StateHistory' : [ 0x38, ['array', -80, ['Enumeration', dict(target = 'long', choices = {768: 'DeviceNodeUnspecified', 769: 'DeviceNodeUninitialized', 770: 'DeviceNodeInitialized', 771: 'DeviceNodeDriversAdded', 772: 'DeviceNodeResourcesAssigned', 773: 'DeviceNodeStartPending', 774: 'DeviceNodeStartCompletion', 775: 'DeviceNodeStartPostWork', 776: 'DeviceNodeStarted', 777: 'DeviceNodeQueryStopped', 778: 'DeviceNodeStopped', 779: 'DeviceNodeRestartCompletion', 780: 'DeviceNodeEnumeratePending', 781: 'DeviceNodeEnumerateCompletion', 782: 'DeviceNodeAwaitingQueuedDeletion', 783: 'DeviceNodeAwaitingQueuedRemoval', 784: 'DeviceNodeQueryRemoved', 785: 'DeviceNodeRemovePendingCloses', 786: 'DeviceNodeRemoved', 787: 'DeviceNodeDeletePendingCloses', 788: 'DeviceNodeDeleted', 789: 'MaxDeviceNodeState'})]]],
'StateHistoryEntry' : [ 0x88, ['unsigned long']],
'CompletionStatus' : [ 0x8c, ['long']],
'PendingIrp' : [ 0x90, ['pointer64', ['_IRP']]],
'Flags' : [ 0x98, ['unsigned long']],
'UserFlags' : [ 0x9c, ['unsigned long']],
'Problem' : [ 0xa0, ['unsigned long']],
'PhysicalDeviceObject' : [ 0xa8, ['pointer64', ['_DEVICE_OBJECT']]],
'ResourceList' : [ 0xb0, ['pointer64', ['_CM_RESOURCE_LIST']]],
'ResourceListTranslated' : [ 0xb8, ['pointer64', ['_CM_RESOURCE_LIST']]],
'InstancePath' : [ 0xc0, ['_UNICODE_STRING']],
'ServiceName' : [ 0xd0, ['_UNICODE_STRING']],
'DuplicatePDO' : [ 0xe0, ['pointer64', ['_DEVICE_OBJECT']]],
'ResourceRequirements' : [ 0xe8, ['pointer64', ['_IO_RESOURCE_REQUIREMENTS_LIST']]],
'InterfaceType' : [ 0xf0, ['Enumeration', dict(target = 'long', choices = {0: 'Internal', 1: 'Isa', 2: 'Eisa', 3: 'MicroChannel', 4: 'TurboChannel', 5: 'PCIBus', 6: 'VMEBus', 7: 'NuBus', 8: 'PCMCIABus', 9: 'CBus', 10: 'MPIBus', 11: 'MPSABus', 12: 'ProcessorInternal', 13: 'InternalPowerBus', 14: 'PNPISABus', 15: 'PNPBus', 16: 'MaximumInterfaceType', -1: 'InterfaceTypeUndefined'})]],
'BusNumber' : [ 0xf4, ['unsigned long']],
'ChildInterfaceType' : [ 0xf8, ['Enumeration', dict(target = 'long', choices = {0: 'Internal', 1: 'Isa', 2: 'Eisa', 3: 'MicroChannel', 4: 'TurboChannel', 5: 'PCIBus', 6: 'VMEBus', 7: 'NuBus', 8: 'PCMCIABus', 9: 'CBus', 10: 'MPIBus', 11: 'MPSABus', 12: 'ProcessorInternal', 13: 'InternalPowerBus', 14: 'PNPISABus', 15: 'PNPBus', 16: 'MaximumInterfaceType', -1: 'InterfaceTypeUndefined'})]],
'ChildBusNumber' : [ 0xfc, ['unsigned long']],
'ChildBusTypeIndex' : [ 0x100, ['unsigned short']],
'RemovalPolicy' : [ 0x102, ['unsigned char']],
'HardwareRemovalPolicy' : [ 0x103, ['unsigned char']],
'TargetDeviceNotify' : [ 0x108, ['_LIST_ENTRY']],
'DeviceArbiterList' : [ 0x118, ['_LIST_ENTRY']],
'DeviceTranslatorList' : [ 0x128, ['_LIST_ENTRY']],
'NoTranslatorMask' : [ 0x138, ['unsigned short']],
'QueryTranslatorMask' : [ 0x13a, ['unsigned short']],
'NoArbiterMask' : [ 0x13c, ['unsigned short']],
'QueryArbiterMask' : [ 0x13e, ['unsigned short']],
'OverUsed1' : [ 0x140, ['__unnamed_1472']],
'OverUsed2' : [ 0x148, ['__unnamed_1474']],
'BootResources' : [ 0x150, ['pointer64', ['_CM_RESOURCE_LIST']]],
'CapabilityFlags' : [ 0x158, ['unsigned long']],
'DockInfo' : [ 0x160, ['__unnamed_1478']],
'DisableableDepends' : [ 0x180, ['unsigned long']],
'PendedSetInterfaceState' : [ 0x188, ['_LIST_ENTRY']],
'LegacyBusListEntry' : [ 0x198, ['_LIST_ENTRY']],
'DriverUnloadRetryCount' : [ 0x1a8, ['unsigned long']],
'PreviousParent' : [ 0x1b0, ['pointer64', ['_DEVICE_NODE']]],
'DeletedChildren' : [ 0x1b8, ['unsigned long']],
} ],
'__unnamed_147d' : [ 0x68, {
'CriticalSection' : [ 0x0, ['_RTL_CRITICAL_SECTION']],
'Resource' : [ 0x0, ['_ERESOURCE']],
} ],
'_HEAP_LOCK' : [ 0x68, {
'Lock' : [ 0x0, ['__unnamed_147d']],
} ],
'_PEB64' : [ 0x358, {
'InheritedAddressSpace' : [ 0x0, ['unsigned char']],
'ReadImageFileExecOptions' : [ 0x1, ['unsigned char']],
'BeingDebugged' : [ 0x2, ['unsigned char']],
'BitField' : [ 0x3, ['unsigned char']],
'ImageUsesLargePages' : [ 0x3, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]],
'SpareBits' : [ 0x3, ['BitField', dict(start_bit = 1, end_bit = 8, native_type='unsigned char')]],
'Mutant' : [ 0x8, ['unsigned long long']],
'ImageBaseAddress' : [ 0x10, ['unsigned long long']],
'Ldr' : [ 0x18, ['unsigned long long']],
'ProcessParameters' : [ 0x20, ['unsigned long long']],
'SubSystemData' : [ 0x28, ['unsigned long long']],
'ProcessHeap' : [ 0x30, ['unsigned long long']],
'FastPebLock' : [ 0x38, ['unsigned long long']],
'AtlThunkSListPtr' : [ 0x40, ['unsigned long long']],
'SparePtr2' : [ 0x48, ['unsigned long long']],
'EnvironmentUpdateCount' : [ 0x50, ['unsigned long']],
'KernelCallbackTable' : [ 0x58, ['unsigned long long']],
'SystemReserved' : [ 0x60, ['array', 1, ['unsigned long']]],
'SpareUlong' : [ 0x64, ['unsigned long']],
'FreeList' : [ 0x68, ['unsigned long long']],
'TlsExpansionCounter' : [ 0x70, ['unsigned long']],
'TlsBitmap' : [ 0x78, ['unsigned long long']],
'TlsBitmapBits' : [ 0x80, ['array', 2, ['unsigned long']]],
'ReadOnlySharedMemoryBase' : [ 0x88, ['unsigned long long']],
'ReadOnlySharedMemoryHeap' : [ 0x90, ['unsigned long long']],
'ReadOnlyStaticServerData' : [ 0x98, ['unsigned long long']],
'AnsiCodePageData' : [ 0xa0, ['unsigned long long']],
'OemCodePageData' : [ 0xa8, ['unsigned long long']],
'UnicodeCaseTableData' : [ 0xb0, ['unsigned long long']],
'NumberOfProcessors' : [ 0xb8, ['unsigned long']],
'NtGlobalFlag' : [ 0xbc, ['unsigned long']],
'CriticalSectionTimeout' : [ 0xc0, ['_LARGE_INTEGER']],
'HeapSegmentReserve' : [ 0xc8, ['unsigned long long']],
'HeapSegmentCommit' : [ 0xd0, ['unsigned long long']],
'HeapDeCommitTotalFreeThreshold' : [ 0xd8, ['unsigned long long']],
'HeapDeCommitFreeBlockThreshold' : [ 0xe0, ['unsigned long long']],
'NumberOfHeaps' : [ 0xe8, ['unsigned long']],
'MaximumNumberOfHeaps' : [ 0xec, ['unsigned long']],
'ProcessHeaps' : [ 0xf0, ['unsigned long long']],
'GdiSharedHandleTable' : [ 0xf8, ['unsigned long long']],
'ProcessStarterHelper' : [ 0x100, ['unsigned long long']],
'GdiDCAttributeList' : [ 0x108, ['unsigned long']],
'LoaderLock' : [ 0x110, ['unsigned long long']],
'OSMajorVersion' : [ 0x118, ['unsigned long']],
'OSMinorVersion' : [ 0x11c, ['unsigned long']],
'OSBuildNumber' : [ 0x120, ['unsigned short']],
'OSCSDVersion' : [ 0x122, ['unsigned short']],
'OSPlatformId' : [ 0x124, ['unsigned long']],
'ImageSubsystem' : [ 0x128, ['unsigned long']],
'ImageSubsystemMajorVersion' : [ 0x12c, ['unsigned long']],
'ImageSubsystemMinorVersion' : [ 0x130, ['unsigned long']],
'ImageProcessAffinityMask' : [ 0x138, ['unsigned long long']],
'GdiHandleBuffer' : [ 0x140, ['array', 60, ['unsigned long']]],
'PostProcessInitRoutine' : [ 0x230, ['unsigned long long']],
'TlsExpansionBitmap' : [ 0x238, ['unsigned long long']],
'TlsExpansionBitmapBits' : [ 0x240, ['array', 32, ['unsigned long']]],
'SessionId' : [ 0x2c0, ['unsigned long']],
'AppCompatFlags' : [ 0x2c8, ['_ULARGE_INTEGER']],
'AppCompatFlagsUser' : [ 0x2d0, ['_ULARGE_INTEGER']],
'pShimData' : [ 0x2d8, ['unsigned long long']],
'AppCompatInfo' : [ 0x2e0, ['unsigned long long']],
'CSDVersion' : [ 0x2e8, ['_STRING64']],
'ActivationContextData' : [ 0x2f8, ['unsigned long long']],
'ProcessAssemblyStorageMap' : [ 0x300, ['unsigned long long']],
'SystemDefaultActivationContextData' : [ 0x308, ['unsigned long long']],
'SystemAssemblyStorageMap' : [ 0x310, ['unsigned long long']],
'MinimumStackCommit' : [ 0x318, ['unsigned long long']],
'FlsCallback' : [ 0x320, ['unsigned long long']],
'FlsListHead' : [ 0x328, ['LIST_ENTRY64']],
'FlsBitmap' : [ 0x338, ['unsigned long long']],
'FlsBitmapBits' : [ 0x340, ['array', 4, ['unsigned long']]],
'FlsHighIndex' : [ 0x350, ['unsigned long']],
} ],
'_KIDTENTRY64' : [ 0x10, {
'OffsetLow' : [ 0x0, ['unsigned short']],
'Selector' : [ 0x2, ['unsigned short']],
'IstIndex' : [ 0x4, ['BitField', dict(start_bit = 0, end_bit = 3, native_type='unsigned short')]],
'Reserved0' : [ 0x4, ['BitField', dict(start_bit = 3, end_bit = 8, native_type='unsigned short')]],
'Type' : [ 0x4, ['BitField', dict(start_bit = 8, end_bit = 13, native_type='unsigned short')]],
'Dpl' : [ 0x4, ['BitField', dict(start_bit = 13, end_bit = 15, native_type='unsigned short')]],
'Present' : [ 0x4, ['BitField', dict(start_bit = 15, end_bit = 16, native_type='unsigned short')]],
'OffsetMiddle' : [ 0x6, ['unsigned short']],
'OffsetHigh' : [ 0x8, ['unsigned long']],
'Reserved1' : [ 0xc, ['unsigned long']],
'Alignment' : [ 0x0, ['unsigned long long']],
} ],
'_KPCR' : [ 0x2600, {
'NtTib' : [ 0x0, ['_NT_TIB']],
'GdtBase' : [ 0x0, ['pointer64', ['_KGDTENTRY64']]],
'TssBase' : [ 0x8, ['pointer64', ['_KTSS64']]],
'PerfGlobalGroupMask' : [ 0x10, ['pointer64', ['void']]],
'Self' : [ 0x18, ['pointer64', ['_KPCR']]],
'CurrentPrcb' : [ 0x20, ['pointer64', ['_KPRCB']]],
'LockArray' : [ 0x28, ['pointer64', ['_KSPIN_LOCK_QUEUE']]],
'Used_Self' : [ 0x30, ['pointer64', ['void']]],
'IdtBase' : [ 0x38, ['pointer64', ['_KIDTENTRY64']]],
'Unused' : [ 0x40, ['array', 2, ['unsigned long long']]],
'Irql' : [ 0x50, ['unsigned char']],
'SecondLevelCacheAssociativity' : [ 0x51, ['unsigned char']],
'ObsoleteNumber' : [ 0x52, ['unsigned char']],
'Fill0' : [ 0x53, ['unsigned char']],
'Unused0' : [ 0x54, ['array', 3, ['unsigned long']]],
'MajorVersion' : [ 0x60, ['unsigned short']],
'MinorVersion' : [ 0x62, ['unsigned short']],
'StallScaleFactor' : [ 0x64, ['unsigned long']],
'Unused1' : [ 0x68, ['array', 3, ['pointer64', ['void']]]],
'KernelReserved' : [ 0x80, ['array', 15, ['unsigned long']]],
'SecondLevelCacheSize' : [ 0xbc, ['unsigned long']],
'HalReserved' : [ 0xc0, ['array', 16, ['unsigned long']]],
'Unused2' : [ 0x100, ['unsigned long']],
'KdVersionBlock' : [ 0x108, ['pointer64', ['void']]],
'Unused3' : [ 0x110, ['pointer64', ['void']]],
'PcrAlign1' : [ 0x118, ['array', 24, ['unsigned long']]],
'Prcb' : [ 0x180, ['_KPRCB']],
} ],
'_MMCOLOR_TABLES' : [ 0x18, {
'Flink' : [ 0x0, ['unsigned long long']],
'Blink' : [ 0x8, ['pointer64', ['void']]],
'Count' : [ 0x10, ['unsigned long long']],
} ],
'_ACL' : [ 0x8, {
'AclRevision' : [ 0x0, ['unsigned char']],
'Sbz1' : [ 0x1, ['unsigned char']],
'AclSize' : [ 0x2, ['unsigned short']],
'AceCount' : [ 0x4, ['unsigned short']],
'Sbz2' : [ 0x6, ['unsigned short']],
} ],
'_DBGKD_FILL_MEMORY' : [ 0x10, {
'Address' : [ 0x0, ['unsigned long long']],
'Length' : [ 0x8, ['unsigned long']],
'Flags' : [ 0xc, ['unsigned short']],
'PatternLength' : [ 0xe, ['unsigned short']],
} ],
'_PP_LOOKASIDE_LIST' : [ 0x10, {
'P' : [ 0x0, ['pointer64', ['_GENERAL_LOOKASIDE']]],
'L' : [ 0x8, ['pointer64', ['_GENERAL_LOOKASIDE']]],
} ],
'_PHYSICAL_MEMORY_RUN' : [ 0x10, {
'BasePage' : [ 0x0, ['unsigned long long']],
'PageCount' : [ 0x8, ['unsigned long long']],
} ],
'__unnamed_14ad' : [ 0x4, {
'LongFlags' : [ 0x0, ['unsigned long']],
'Flags' : [ 0x0, ['_MM_SESSION_SPACE_FLAGS']],
} ],
'_MM_SESSION_SPACE' : [ 0x1d80, {
'GlobalVirtualAddress' : [ 0x0, ['pointer64', ['_MM_SESSION_SPACE']]],
'ReferenceCount' : [ 0x8, ['long']],
'u' : [ 0xc, ['__unnamed_14ad']],
'SessionId' : [ 0x10, ['unsigned long']],
'ProcessList' : [ 0x18, ['_LIST_ENTRY']],
'LastProcessSwappedOutTime' : [ 0x28, ['_LARGE_INTEGER']],
'SessionPageDirectoryIndex' : [ 0x30, ['unsigned long long']],
'NonPagablePages' : [ 0x38, ['unsigned long long']],
'CommittedPages' : [ 0x40, ['unsigned long long']],
'PagedPoolStart' : [ 0x48, ['pointer64', ['void']]],
'PagedPoolEnd' : [ 0x50, ['pointer64', ['void']]],
'PagedPoolBasePde' : [ 0x58, ['pointer64', ['_MMPTE']]],
'Color' : [ 0x60, ['unsigned long']],
'ResidentProcessCount' : [ 0x64, ['long']],
'SessionPoolAllocationFailures' : [ 0x68, ['array', 4, ['unsigned long']]],
'ImageList' : [ 0x78, ['_LIST_ENTRY']],
'LocaleId' : [ 0x88, ['unsigned long']],
'AttachCount' : [ 0x8c, ['unsigned long']],
'AttachEvent' : [ 0x90, ['_KEVENT']],
'LastProcess' : [ 0xa8, ['pointer64', ['_EPROCESS']]],
'ProcessReferenceToSession' : [ 0xb0, ['long']],
'WsListEntry' : [ 0xb8, ['_LIST_ENTRY']],
'Lookaside' : [ 0x100, ['array', 21, ['_GENERAL_LOOKASIDE']]],
'Session' : [ 0xb80, ['_MMSESSION']],
'PagedPoolMutex' : [ 0xbe8, ['_KGUARDED_MUTEX']],
'PagedPoolInfo' : [ 0xc20, ['_MM_PAGED_POOL_INFO']],
'Vm' : [ 0xc60, ['_MMSUPPORT']],
'Wsle' : [ 0xcb8, ['pointer64', ['_MMWSLE']]],
'Win32KDriverUnload' : [ 0xcc0, ['pointer64', ['void']]],
'PagedPool' : [ 0xcc8, ['_POOL_DESCRIPTOR']],
'PageDirectory' : [ 0x1d10, ['_MMPTE']],
'SpecialPoolFirstPte' : [ 0x1d18, ['pointer64', ['_MMPTE']]],
'SpecialPoolLastPte' : [ 0x1d20, ['pointer64', ['_MMPTE']]],
'NextPdeForSpecialPoolExpansion' : [ 0x1d28, ['pointer64', ['_MMPTE']]],
'LastPdeForSpecialPoolExpansion' : [ 0x1d30, ['pointer64', ['_MMPTE']]],
'SpecialPagesInUse' : [ 0x1d38, ['unsigned long long']],
'ImageLoadingCount' : [ 0x1d40, ['long']],
} ],
'_PEB' : [ 0x358, {
'InheritedAddressSpace' : [ 0x0, ['unsigned char']],
'ReadImageFileExecOptions' : [ 0x1, ['unsigned char']],
'BeingDebugged' : [ 0x2, ['unsigned char']],
'BitField' : [ 0x3, ['unsigned char']],
'ImageUsesLargePages' : [ 0x3, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]],
'SpareBits' : [ 0x3, ['BitField', dict(start_bit = 1, end_bit = 8, native_type='unsigned char')]],
'Mutant' : [ 0x8, ['pointer64', ['void']]],
'ImageBaseAddress' : [ 0x10, ['pointer64', ['void']]],
'Ldr' : [ 0x18, ['pointer64', ['_PEB_LDR_DATA']]],
'ProcessParameters' : [ 0x20, ['pointer64', ['_RTL_USER_PROCESS_PARAMETERS']]],
'SubSystemData' : [ 0x28, ['pointer64', ['void']]],
'ProcessHeap' : [ 0x30, ['pointer64', ['void']]],
'FastPebLock' : [ 0x38, ['pointer64', ['_RTL_CRITICAL_SECTION']]],
'AtlThunkSListPtr' : [ 0x40, ['pointer64', ['void']]],
'SparePtr2' : [ 0x48, ['pointer64', ['void']]],
'EnvironmentUpdateCount' : [ 0x50, ['unsigned long']],
'KernelCallbackTable' : [ 0x58, ['pointer64', ['void']]],
'SystemReserved' : [ 0x60, ['array', 1, ['unsigned long']]],
'SpareUlong' : [ 0x64, ['unsigned long']],
'FreeList' : [ 0x68, ['pointer64', ['_PEB_FREE_BLOCK']]],
'TlsExpansionCounter' : [ 0x70, ['unsigned long']],
'TlsBitmap' : [ 0x78, ['pointer64', ['void']]],
'TlsBitmapBits' : [ 0x80, ['array', 2, ['unsigned long']]],
'ReadOnlySharedMemoryBase' : [ 0x88, ['pointer64', ['void']]],
'ReadOnlySharedMemoryHeap' : [ 0x90, ['pointer64', ['void']]],
'ReadOnlyStaticServerData' : [ 0x98, ['pointer64', ['pointer64', ['void']]]],
'AnsiCodePageData' : [ 0xa0, ['pointer64', ['void']]],
'OemCodePageData' : [ 0xa8, ['pointer64', ['void']]],
'UnicodeCaseTableData' : [ 0xb0, ['pointer64', ['void']]],
'NumberOfProcessors' : [ 0xb8, ['unsigned long']],
'NtGlobalFlag' : [ 0xbc, ['unsigned long']],
'CriticalSectionTimeout' : [ 0xc0, ['_LARGE_INTEGER']],
'HeapSegmentReserve' : [ 0xc8, ['unsigned long long']],
'HeapSegmentCommit' : [ 0xd0, ['unsigned long long']],
'HeapDeCommitTotalFreeThreshold' : [ 0xd8, ['unsigned long long']],
'HeapDeCommitFreeBlockThreshold' : [ 0xe0, ['unsigned long long']],
'NumberOfHeaps' : [ 0xe8, ['unsigned long']],
'MaximumNumberOfHeaps' : [ 0xec, ['unsigned long']],
'ProcessHeaps' : [ 0xf0, ['pointer64', ['pointer64', ['void']]]],
'GdiSharedHandleTable' : [ 0xf8, ['pointer64', ['void']]],
'ProcessStarterHelper' : [ 0x100, ['pointer64', ['void']]],
'GdiDCAttributeList' : [ 0x108, ['unsigned long']],
'LoaderLock' : [ 0x110, ['pointer64', ['_RTL_CRITICAL_SECTION']]],
'OSMajorVersion' : [ 0x118, ['unsigned long']],
'OSMinorVersion' : [ 0x11c, ['unsigned long']],
'OSBuildNumber' : [ 0x120, ['unsigned short']],
'OSCSDVersion' : [ 0x122, ['unsigned short']],
'OSPlatformId' : [ 0x124, ['unsigned long']],
'ImageSubsystem' : [ 0x128, ['unsigned long']],
'ImageSubsystemMajorVersion' : [ 0x12c, ['unsigned long']],
'ImageSubsystemMinorVersion' : [ 0x130, ['unsigned long']],
'ImageProcessAffinityMask' : [ 0x138, ['unsigned long long']],
'GdiHandleBuffer' : [ 0x140, ['array', 60, ['unsigned long']]],
'PostProcessInitRoutine' : [ 0x230, ['pointer64', ['void']]],
'TlsExpansionBitmap' : [ 0x238, ['pointer64', ['void']]],
'TlsExpansionBitmapBits' : [ 0x240, ['array', 32, ['unsigned long']]],
'SessionId' : [ 0x2c0, ['unsigned long']],
'AppCompatFlags' : [ 0x2c8, ['_ULARGE_INTEGER']],
'AppCompatFlagsUser' : [ 0x2d0, ['_ULARGE_INTEGER']],
'pShimData' : [ 0x2d8, ['pointer64', ['void']]],
'AppCompatInfo' : [ 0x2e0, ['pointer64', ['void']]],
'CSDVersion' : [ 0x2e8, ['_UNICODE_STRING']],
'ActivationContextData' : [ 0x2f8, ['pointer64', ['_ACTIVATION_CONTEXT_DATA']]],
'ProcessAssemblyStorageMap' : [ 0x300, ['pointer64', ['_ASSEMBLY_STORAGE_MAP']]],
'SystemDefaultActivationContextData' : [ 0x308, ['pointer64', ['_ACTIVATION_CONTEXT_DATA']]],
'SystemAssemblyStorageMap' : [ 0x310, ['pointer64', ['_ASSEMBLY_STORAGE_MAP']]],
'MinimumStackCommit' : [ 0x318, ['unsigned long long']],
'FlsCallback' : [ 0x320, ['pointer64', ['pointer64', ['void']]]],
'FlsListHead' : [ 0x328, ['_LIST_ENTRY']],
'FlsBitmap' : [ 0x338, ['pointer64', ['void']]],
'FlsBitmapBits' : [ 0x340, ['array', 4, ['unsigned long']]],
'FlsHighIndex' : [ 0x350, ['unsigned long']],
} ],
'_HEAP_FREE_ENTRY' : [ 0x20, {
'PreviousBlockPrivateData' : [ 0x0, ['pointer64', ['void']]],
'Size' : [ 0x8, ['unsigned short']],
'PreviousSize' : [ 0xa, ['unsigned short']],
'SmallTagIndex' : [ 0xc, ['unsigned char']],
'Flags' : [ 0xd, ['unsigned char']],
'UnusedBytes' : [ 0xe, ['unsigned char']],
'SegmentIndex' : [ 0xf, ['unsigned char']],
'CompactHeader' : [ 0x8, ['unsigned long long']],
'FreeList' : [ 0x10, ['_LIST_ENTRY']],
} ],
'_DBGKD_GET_CONTEXT' : [ 0x4, {
'Unused' : [ 0x0, ['unsigned long']],
} ],
'_TEB_ACTIVE_FRAME_CONTEXT' : [ 0x10, {
'Flags' : [ 0x0, ['unsigned long']],
'FrameName' : [ 0x8, ['pointer64', ['unsigned char']]],
} ],
'_MMPTE_SOFTWARE' : [ 0x8, {
'Valid' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long long')]],
'PageFileLow' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 5, native_type='unsigned long long')]],
'Protection' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 10, native_type='unsigned long long')]],
'Prototype' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long long')]],
'Transition' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned long long')]],
'UsedPageTableEntries' : [ 0x0, ['BitField', dict(start_bit = 12, end_bit = 22, native_type='unsigned long long')]],
'Reserved' : [ 0x0, ['BitField', dict(start_bit = 22, end_bit = 32, native_type='unsigned long long')]],
'PageFileHigh' : [ 0x0, ['BitField', dict(start_bit = 32, end_bit = 64, native_type='unsigned long long')]],
} ],
'_IO_RESOURCE_REQUIREMENTS_LIST' : [ 0x48, {
'ListSize' : [ 0x0, ['unsigned long']],
'InterfaceType' : [ 0x4, ['Enumeration', dict(target = 'long', choices = {0: 'Internal', 1: 'Isa', 2: 'Eisa', 3: 'MicroChannel', 4: 'TurboChannel', 5: 'PCIBus', 6: 'VMEBus', 7: 'NuBus', 8: 'PCMCIABus', 9: 'CBus', 10: 'MPIBus', 11: 'MPSABus', 12: 'ProcessorInternal', 13: 'InternalPowerBus', 14: 'PNPISABus', 15: 'PNPBus', 16: 'MaximumInterfaceType', -1: 'InterfaceTypeUndefined'})]],
'BusNumber' : [ 0x8, ['unsigned long']],
'SlotNumber' : [ 0xc, ['unsigned long']],
'Reserved' : [ 0x10, ['array', 3, ['unsigned long']]],
'AlternativeLists' : [ 0x1c, ['unsigned long']],
'List' : [ 0x20, ['array', 1, ['_IO_RESOURCE_LIST']]],
} ],
'__unnamed_14dd' : [ 0x10, {
'IoStatus' : [ 0x0, ['_IO_STATUS_BLOCK']],
'LastByte' : [ 0x0, ['_LARGE_INTEGER']],
} ],
'_MMMOD_WRITER_MDL_ENTRY' : [ 0xa8, {
'Links' : [ 0x0, ['_LIST_ENTRY']],
'WriteOffset' : [ 0x10, ['_LARGE_INTEGER']],
'u' : [ 0x18, ['__unnamed_14dd']],
'Irp' : [ 0x28, ['pointer64', ['_IRP']]],
'LastPageToWrite' : [ 0x30, ['unsigned long long']],
'PagingListHead' : [ 0x38, ['pointer64', ['_MMMOD_WRITER_LISTHEAD']]],
'CurrentList' : [ 0x40, ['pointer64', ['_LIST_ENTRY']]],
'PagingFile' : [ 0x48, ['pointer64', ['_MMPAGING_FILE']]],
'File' : [ 0x50, ['pointer64', ['_FILE_OBJECT']]],
'ControlArea' : [ 0x58, ['pointer64', ['_CONTROL_AREA']]],
'FileResource' : [ 0x60, ['pointer64', ['_ERESOURCE']]],
'IssueTime' : [ 0x68, ['_LARGE_INTEGER']],
'Mdl' : [ 0x70, ['_MDL']],
'Page' : [ 0xa0, ['array', 1, ['unsigned long long']]],
} ],
'_CACHE_UNINITIALIZE_EVENT' : [ 0x20, {
'Next' : [ 0x0, ['pointer64', ['_CACHE_UNINITIALIZE_EVENT']]],
'Event' : [ 0x8, ['_KEVENT']],
} ],
'_SECURITY_TOKEN_AUDIT_DATA' : [ 0xc, {
'Length' : [ 0x0, ['unsigned long']],
'GrantMask' : [ 0x4, ['unsigned long']],
'DenyMask' : [ 0x8, ['unsigned long']],
} ],
'_CM_RESOURCE_LIST' : [ 0x28, {
'Count' : [ 0x0, ['unsigned long']],
'List' : [ 0x4, ['array', 1, ['_CM_FULL_RESOURCE_DESCRIPTOR']]],
} ],
'_TEB32' : [ 0xfbc, {
'NtTib' : [ 0x0, ['_NT_TIB32']],
'EnvironmentPointer' : [ 0x1c, ['unsigned long']],
'ClientId' : [ 0x20, ['_CLIENT_ID32']],
'ActiveRpcHandle' : [ 0x28, ['unsigned long']],
'ThreadLocalStoragePointer' : [ 0x2c, ['unsigned long']],
'ProcessEnvironmentBlock' : [ 0x30, ['unsigned long']],
'LastErrorValue' : [ 0x34, ['unsigned long']],
'CountOfOwnedCriticalSections' : [ 0x38, ['unsigned long']],
'CsrClientThread' : [ 0x3c, ['unsigned long']],
'Win32ThreadInfo' : [ 0x40, ['unsigned long']],
'User32Reserved' : [ 0x44, ['array', 26, ['unsigned long']]],
'UserReserved' : [ 0xac, ['array', 5, ['unsigned long']]],
'WOW32Reserved' : [ 0xc0, ['unsigned long']],
'CurrentLocale' : [ 0xc4, ['unsigned long']],
'FpSoftwareStatusRegister' : [ 0xc8, ['unsigned long']],
'SystemReserved1' : [ 0xcc, ['array', 54, ['unsigned long']]],
'ExceptionCode' : [ 0x1a4, ['long']],
'ActivationContextStackPointer' : [ 0x1a8, ['unsigned long']],
'SpareBytes1' : [ 0x1ac, ['array', 40, ['unsigned char']]],
'GdiTebBatch' : [ 0x1d4, ['_GDI_TEB_BATCH32']],
'RealClientId' : [ 0x6b4, ['_CLIENT_ID32']],
'GdiCachedProcessHandle' : [ 0x6bc, ['unsigned long']],
'GdiClientPID' : [ 0x6c0, ['unsigned long']],
'GdiClientTID' : [ 0x6c4, ['unsigned long']],
'GdiThreadLocalInfo' : [ 0x6c8, ['unsigned long']],
'Win32ClientInfo' : [ 0x6cc, ['array', 62, ['unsigned long']]],
'glDispatchTable' : [ 0x7c4, ['array', 233, ['unsigned long']]],
'glReserved1' : [ 0xb68, ['array', 29, ['unsigned long']]],
'glReserved2' : [ 0xbdc, ['unsigned long']],
'glSectionInfo' : [ 0xbe0, ['unsigned long']],
'glSection' : [ 0xbe4, ['unsigned long']],
'glTable' : [ 0xbe8, ['unsigned long']],
'glCurrentRC' : [ 0xbec, ['unsigned long']],
'glContext' : [ 0xbf0, ['unsigned long']],
'LastStatusValue' : [ 0xbf4, ['unsigned long']],
'StaticUnicodeString' : [ 0xbf8, ['_STRING32']],
'StaticUnicodeBuffer' : [ 0xc00, ['array', 261, ['unsigned short']]],
'DeallocationStack' : [ 0xe0c, ['unsigned long']],
'TlsSlots' : [ 0xe10, ['array', 64, ['unsigned long']]],
'TlsLinks' : [ 0xf10, ['LIST_ENTRY32']],
'Vdm' : [ 0xf18, ['unsigned long']],
'ReservedForNtRpc' : [ 0xf1c, ['unsigned long']],
'DbgSsReserved' : [ 0xf20, ['array', 2, ['unsigned long']]],
'HardErrorMode' : [ 0xf28, ['unsigned long']],
'Instrumentation' : [ 0xf2c, ['array', 14, ['unsigned long']]],
'SubProcessTag' : [ 0xf64, ['unsigned long']],
'EtwTraceData' : [ 0xf68, ['unsigned long']],
'WinSockData' : [ 0xf6c, ['unsigned long']],
'GdiBatchCount' : [ 0xf70, ['unsigned long']],
'InDbgPrint' : [ 0xf74, ['unsigned char']],
'FreeStackOnTermination' : [ 0xf75, ['unsigned char']],
'HasFiberData' : [ 0xf76, ['unsigned char']],
'IdealProcessor' : [ 0xf77, ['unsigned char']],
'GuaranteedStackBytes' : [ 0xf78, ['unsigned long']],
'ReservedForPerf' : [ 0xf7c, ['unsigned long']],
'ReservedForOle' : [ 0xf80, ['unsigned long']],
'WaitingOnLoaderLock' : [ 0xf84, ['unsigned long']],
'SparePointer1' : [ 0xf88, ['unsigned long']],
'SoftPatchPtr1' : [ 0xf8c, ['unsigned long']],
'SoftPatchPtr2' : [ 0xf90, ['unsigned long']],
'TlsExpansionSlots' : [ 0xf94, ['unsigned long']],
'ImpersonationLocale' : [ 0xf98, ['unsigned long']],
'IsImpersonating' : [ 0xf9c, ['unsigned long']],
'NlsCache' : [ 0xfa0, ['unsigned long']],
'pShimData' : [ 0xfa4, ['unsigned long']],
'HeapVirtualAffinity' : [ 0xfa8, ['unsigned long']],
'CurrentTransactionHandle' : [ 0xfac, ['unsigned long']],
'ActiveFrame' : [ 0xfb0, ['unsigned long']],
'FlsData' : [ 0xfb4, ['unsigned long']],
'SafeThunkCall' : [ 0xfb8, ['unsigned char']],
'BooleanSpare' : [ 0xfb9, ['array', 3, ['unsigned char']]],
} ],
'_CM_FULL_RESOURCE_DESCRIPTOR' : [ 0x24, {
'InterfaceType' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'Internal', 1: 'Isa', 2: 'Eisa', 3: 'MicroChannel', 4: 'TurboChannel', 5: 'PCIBus', 6: 'VMEBus', 7: 'NuBus', 8: 'PCMCIABus', 9: 'CBus', 10: 'MPIBus', 11: 'MPSABus', 12: 'ProcessorInternal', 13: 'InternalPowerBus', 14: 'PNPISABus', 15: 'PNPBus', 16: 'MaximumInterfaceType', -1: 'InterfaceTypeUndefined'})]],
'BusNumber' : [ 0x4, ['unsigned long']],
'PartialResourceList' : [ 0x8, ['_CM_PARTIAL_RESOURCE_LIST']],
} ],
'_EPROCESS_QUOTA_ENTRY' : [ 0x20, {
'Usage' : [ 0x0, ['unsigned long long']],
'Limit' : [ 0x8, ['unsigned long long']],
'Peak' : [ 0x10, ['unsigned long long']],
'Return' : [ 0x18, ['unsigned long long']],
} ],
'__unnamed_1502' : [ 0x50, {
'CellData' : [ 0x0, ['_CELL_DATA']],
'List' : [ 0x0, ['array', 1, ['unsigned long long']]],
} ],
'_CM_CACHED_VALUE_INDEX' : [ 0x58, {
'CellIndex' : [ 0x0, ['unsigned long']],
'Data' : [ 0x8, ['__unnamed_1502']],
} ],
'_WMI_BUFFER_HEADER' : [ 0x48, {
'Wnode' : [ 0x0, ['_WNODE_HEADER']],
'Reserved1' : [ 0x0, ['unsigned long long']],
'Reserved2' : [ 0x8, ['unsigned long long']],
'Reserved3' : [ 0x10, ['_LARGE_INTEGER']],
'Alignment' : [ 0x18, ['pointer64', ['void']]],
'SlistEntry' : [ 0x20, ['_SINGLE_LIST_ENTRY']],
'Entry' : [ 0x18, ['_LIST_ENTRY']],
'ReferenceCount' : [ 0x0, ['long']],
'SavedOffset' : [ 0x4, ['unsigned long']],
'CurrentOffset' : [ 0x8, ['unsigned long']],
'UsePerfClock' : [ 0xc, ['unsigned long']],
'TimeStamp' : [ 0x10, ['_LARGE_INTEGER']],
'Guid' : [ 0x18, ['_GUID']],
'ClientContext' : [ 0x28, ['_WMI_CLIENT_CONTEXT']],
'State' : [ 0x2c, ['_WMI_BUFFER_STATE']],
'Flags' : [ 0x2c, ['unsigned long']],
'Offset' : [ 0x30, ['unsigned long']],
'BufferFlag' : [ 0x34, ['unsigned short']],
'BufferType' : [ 0x36, ['unsigned short']],
'InstanceGuid' : [ 0x38, ['_GUID']],
'LoggerContext' : [ 0x38, ['pointer64', ['void']]],
'GlobalEntry' : [ 0x40, ['_SINGLE_LIST_ENTRY']],
} ],
'_KSEMAPHORE' : [ 0x20, {
'Header' : [ 0x0, ['_DISPATCHER_HEADER']],
'Limit' : [ 0x18, ['long']],
} ],
'_PROCESSOR_POWER_STATE' : [ 0x170, {
'IdleFunction' : [ 0x0, ['pointer64', ['void']]],
'Idle0KernelTimeLimit' : [ 0x8, ['unsigned long']],
'Idle0LastTime' : [ 0xc, ['unsigned long']],
'IdleHandlers' : [ 0x10, ['pointer64', ['void']]],
'IdleState' : [ 0x18, ['pointer64', ['void']]],
'IdleHandlersCount' : [ 0x20, ['unsigned long']],
'LastCheck' : [ 0x28, ['unsigned long long']],
'IdleTimes' : [ 0x30, ['PROCESSOR_IDLE_TIMES']],
'IdleTime1' : [ 0x50, ['unsigned long']],
'PromotionCheck' : [ 0x54, ['unsigned long']],
'IdleTime2' : [ 0x58, ['unsigned long']],
'CurrentThrottle' : [ 0x5c, ['unsigned char']],
'ThermalThrottleLimit' : [ 0x5d, ['unsigned char']],
'CurrentThrottleIndex' : [ 0x5e, ['unsigned char']],
'ThermalThrottleIndex' : [ 0x5f, ['unsigned char']],
'LastKernelUserTime' : [ 0x60, ['unsigned long']],
'LastIdleThreadKernelTime' : [ 0x64, ['unsigned long']],
'PackageIdleStartTime' : [ 0x68, ['unsigned long']],
'PackageIdleTime' : [ 0x6c, ['unsigned long']],
'DebugCount' : [ 0x70, ['unsigned long']],
'LastSysTime' : [ 0x74, ['unsigned long']],
'TotalIdleStateTime' : [ 0x78, ['array', 3, ['unsigned long long']]],
'TotalIdleTransitions' : [ 0x90, ['array', 3, ['unsigned long']]],
'PreviousC3StateTime' : [ 0xa0, ['unsigned long long']],
'KneeThrottleIndex' : [ 0xa8, ['unsigned char']],
'ThrottleLimitIndex' : [ 0xa9, ['unsigned char']],
'PerfStatesCount' : [ 0xaa, ['unsigned char']],
'ProcessorMinThrottle' : [ 0xab, ['unsigned char']],
'ProcessorMaxThrottle' : [ 0xac, ['unsigned char']],
'EnableIdleAccounting' : [ 0xad, ['unsigned char']],
'LastC3Percentage' : [ 0xae, ['unsigned char']],
'LastAdjustedBusyPercentage' : [ 0xaf, ['unsigned char']],
'PromotionCount' : [ 0xb0, ['unsigned long']],
'DemotionCount' : [ 0xb4, ['unsigned long']],
'ErrorCount' : [ 0xb8, ['unsigned long']],
'RetryCount' : [ 0xbc, ['unsigned long']],
'Flags' : [ 0xc0, ['unsigned long']],
'PerfCounterFrequency' : [ 0xc8, ['_LARGE_INTEGER']],
'PerfTickCount' : [ 0xd0, ['unsigned long']],
'PerfTimer' : [ 0xd8, ['_KTIMER']],
'PerfDpc' : [ 0x118, ['_KDPC']],
'PerfStates' : [ 0x158, ['pointer64', ['PROCESSOR_PERF_STATE']]],
'PerfSetThrottle' : [ 0x160, ['pointer64', ['void']]],
'LastC3KernelUserTime' : [ 0x168, ['unsigned long']],
'LastPackageIdleTime' : [ 0x16c, ['unsigned long']],
} ],
'_DBGKD_READ_WRITE_MSR' : [ 0xc, {
'Msr' : [ 0x0, ['unsigned long']],
'DataValueLow' : [ 0x4, ['unsigned long']],
'DataValueHigh' : [ 0x8, ['unsigned long']],
} ],
'_MMPFNENTRY' : [ 0x2, {
'Modified' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned short')]],
'ReadInProgress' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned short')]],
'WriteInProgress' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned short')]],
'PrototypePte' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned short')]],
'PageColor' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 8, native_type='unsigned short')]],
'PageLocation' : [ 0x0, ['BitField', dict(start_bit = 8, end_bit = 11, native_type='unsigned short')]],
'RemovalRequested' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned short')]],
'CacheAttribute' : [ 0x0, ['BitField', dict(start_bit = 12, end_bit = 14, native_type='unsigned short')]],
'Rom' : [ 0x0, ['BitField', dict(start_bit = 14, end_bit = 15, native_type='unsigned short')]],
'ParityError' : [ 0x0, ['BitField', dict(start_bit = 15, end_bit = 16, native_type='unsigned short')]],
} ],
'_IO_COUNTERS' : [ 0x30, {
'ReadOperationCount' : [ 0x0, ['unsigned long long']],
'WriteOperationCount' : [ 0x8, ['unsigned long long']],
'OtherOperationCount' : [ 0x10, ['unsigned long long']],
'ReadTransferCount' : [ 0x18, ['unsigned long long']],
'WriteTransferCount' : [ 0x20, ['unsigned long long']],
'OtherTransferCount' : [ 0x28, ['unsigned long long']],
} ],
'_TOKEN_SOURCE' : [ 0x10, {
'SourceName' : [ 0x0, ['array', 8, ['unsigned char']]],
'SourceIdentifier' : [ 0x8, ['_LUID']],
} ],
'_DBGKD_QUERY_MEMORY' : [ 0x18, {
'Address' : [ 0x0, ['unsigned long long']],
'Reserved' : [ 0x8, ['unsigned long long']],
'AddressSpace' : [ 0x10, ['unsigned long']],
'Flags' : [ 0x14, ['unsigned long']],
} ],
'_DEVICE_OBJECT_POWER_EXTENSION' : [ 0x80, {
'IdleCount' : [ 0x0, ['long']],
'ConservationIdleTime' : [ 0x4, ['unsigned long']],
'PerformanceIdleTime' : [ 0x8, ['unsigned long']],
'DeviceObject' : [ 0x10, ['pointer64', ['_DEVICE_OBJECT']]],
'IdleList' : [ 0x18, ['_LIST_ENTRY']],
'DeviceType' : [ 0x28, ['unsigned char']],
'State' : [ 0x2c, ['Enumeration', dict(target = 'long', choices = {0: 'PowerDeviceUnspecified', 1: 'PowerDeviceD0', 2: 'PowerDeviceD1', 3: 'PowerDeviceD2', 4: 'PowerDeviceD3', 5: 'PowerDeviceMaximum'})]],
'NotifySourceList' : [ 0x30, ['_LIST_ENTRY']],
'NotifyTargetList' : [ 0x40, ['_LIST_ENTRY']],
'PowerChannelSummary' : [ 0x50, ['_POWER_CHANNEL_SUMMARY']],
'Volume' : [ 0x70, ['_LIST_ENTRY']],
} ],
'_MMSUPPORT_FLAGS' : [ 0x4, {
'SessionSpace' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]],
'BeingTrimmed' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned char')]],
'SessionLeader' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned char')]],
'TrimHard' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned char')]],
'MaximumWorkingSetHard' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned char')]],
'ForceTrim' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned char')]],
'MinimumWorkingSetHard' : [ 0x0, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned char')]],
'Available0' : [ 0x0, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned char')]],
'MemoryPriority' : [ 0x1, ['BitField', dict(start_bit = 0, end_bit = 8, native_type='unsigned char')]],
'GrowWsleHash' : [ 0x2, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned short')]],
'AcquiredUnsafe' : [ 0x2, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned short')]],
'Available' : [ 0x2, ['BitField', dict(start_bit = 2, end_bit = 16, native_type='unsigned short')]],
} ],
'EX_QUEUE_WORKER_INFO' : [ 0x4, {
'QueueDisabled' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'MakeThreadsAsNecessary' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]],
'WaitMode' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]],
'WorkerCount' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 32, native_type='unsigned long')]],
'QueueWorkerInfo' : [ 0x0, ['long']],
} ],
'PROCESSOR_PERF_STATE' : [ 0x20, {
'PercentFrequency' : [ 0x0, ['unsigned char']],
'MinCapacity' : [ 0x1, ['unsigned char']],
'Power' : [ 0x2, ['unsigned short']],
'IncreaseLevel' : [ 0x4, ['unsigned char']],
'DecreaseLevel' : [ 0x5, ['unsigned char']],
'Flags' : [ 0x6, ['unsigned short']],
'IncreaseTime' : [ 0x8, ['unsigned long']],
'DecreaseTime' : [ 0xc, ['unsigned long']],
'IncreaseCount' : [ 0x10, ['unsigned long']],
'DecreaseCount' : [ 0x14, ['unsigned long']],
'PerformanceTime' : [ 0x18, ['unsigned long long']],
} ],
'PROCESSOR_IDLE_TIMES' : [ 0x20, {
'StartTime' : [ 0x0, ['unsigned long long']],
'EndTime' : [ 0x8, ['unsigned long long']],
'IdleHandlerReserved' : [ 0x10, ['array', 4, ['unsigned long']]],
} ],
'_TERMINATION_PORT' : [ 0x10, {
'Next' : [ 0x0, ['pointer64', ['_TERMINATION_PORT']]],
'Port' : [ 0x8, ['pointer64', ['void']]],
} ],
'_MMMOD_WRITER_LISTHEAD' : [ 0x28, {
'ListHead' : [ 0x0, ['_LIST_ENTRY']],
'Event' : [ 0x10, ['_KEVENT']],
} ],
'_SYSTEM_POWER_POLICY' : [ 0xe8, {
'Revision' : [ 0x0, ['unsigned long']],
'PowerButton' : [ 0x4, ['POWER_ACTION_POLICY']],
'SleepButton' : [ 0x10, ['POWER_ACTION_POLICY']],
'LidClose' : [ 0x1c, ['POWER_ACTION_POLICY']],
'LidOpenWake' : [ 0x28, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'Reserved' : [ 0x2c, ['unsigned long']],
'Idle' : [ 0x30, ['POWER_ACTION_POLICY']],
'IdleTimeout' : [ 0x3c, ['unsigned long']],
'IdleSensitivity' : [ 0x40, ['unsigned char']],
'DynamicThrottle' : [ 0x41, ['unsigned char']],
'Spare2' : [ 0x42, ['array', 2, ['unsigned char']]],
'MinSleep' : [ 0x44, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'MaxSleep' : [ 0x48, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'ReducedLatencySleep' : [ 0x4c, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'WinLogonFlags' : [ 0x50, ['unsigned long']],
'Spare3' : [ 0x54, ['unsigned long']],
'DozeS4Timeout' : [ 0x58, ['unsigned long']],
'BroadcastCapacityResolution' : [ 0x5c, ['unsigned long']],
'DischargePolicy' : [ 0x60, ['array', 4, ['SYSTEM_POWER_LEVEL']]],
'VideoTimeout' : [ 0xc0, ['unsigned long']],
'VideoDimDisplay' : [ 0xc4, ['unsigned char']],
'VideoReserved' : [ 0xc8, ['array', 3, ['unsigned long']]],
'SpindownTimeout' : [ 0xd4, ['unsigned long']],
'OptimizeForPower' : [ 0xd8, ['unsigned char']],
'FanThrottleTolerance' : [ 0xd9, ['unsigned char']],
'ForcedThrottle' : [ 0xda, ['unsigned char']],
'MinThrottle' : [ 0xdb, ['unsigned char']],
'OverThrottled' : [ 0xdc, ['POWER_ACTION_POLICY']],
} ],
'_GDI_TEB_BATCH' : [ 0x4e8, {
'Offset' : [ 0x0, ['unsigned long']],
'HDC' : [ 0x8, ['unsigned long long']],
'Buffer' : [ 0x10, ['array', 310, ['unsigned long']]],
} ],
'_POP_THERMAL_ZONE' : [ 0x120, {
'Link' : [ 0x0, ['_LIST_ENTRY']],
'State' : [ 0x10, ['unsigned char']],
'Flags' : [ 0x11, ['unsigned char']],
'Mode' : [ 0x12, ['unsigned char']],
'PendingMode' : [ 0x13, ['unsigned char']],
'ActivePoint' : [ 0x14, ['unsigned char']],
'PendingActivePoint' : [ 0x15, ['unsigned char']],
'Throttle' : [ 0x18, ['long']],
'LastTime' : [ 0x20, ['unsigned long long']],
'SampleRate' : [ 0x28, ['unsigned long']],
'LastTemp' : [ 0x2c, ['unsigned long']],
'PassiveTimer' : [ 0x30, ['_KTIMER']],
'PassiveDpc' : [ 0x70, ['_KDPC']],
'OverThrottled' : [ 0xb0, ['_POP_ACTION_TRIGGER']],
'Irp' : [ 0xc0, ['pointer64', ['_IRP']]],
'Info' : [ 0xc8, ['_THERMAL_INFORMATION']],
} ],
'_DBGKD_CONTINUE2' : [ 0x20, {
'ContinueStatus' : [ 0x0, ['long']],
'ControlSet' : [ 0x4, ['_AMD64_DBGKD_CONTROL_SET']],
'AnyControlSet' : [ 0x4, ['_DBGKD_ANY_CONTROL_SET']],
} ],
'_SECURITY_TOKEN_PROXY_DATA' : [ 0x20, {
'Length' : [ 0x0, ['unsigned long']],
'ProxyClass' : [ 0x4, ['Enumeration', dict(target = 'long', choices = {0: 'ProxyFull', 1: 'ProxyService', 2: 'ProxyTree', 3: 'ProxyDirectory'})]],
'PathInfo' : [ 0x8, ['_UNICODE_STRING']],
'ContainerMask' : [ 0x18, ['unsigned long']],
'ObjectMask' : [ 0x1c, ['unsigned long']],
} ],
'_PROCESSOR_POWER_POLICY' : [ 0x4c, {
'Revision' : [ 0x0, ['unsigned long']],
'DynamicThrottle' : [ 0x4, ['unsigned char']],
'Spare' : [ 0x5, ['array', 3, ['unsigned char']]],
'DisableCStates' : [ 0x8, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'Reserved' : [ 0x8, ['BitField', dict(start_bit = 1, end_bit = 32, native_type='unsigned long')]],
'PolicyCount' : [ 0xc, ['unsigned long']],
'Policy' : [ 0x10, ['array', 3, ['_PROCESSOR_POWER_POLICY_INFO']]],
} ],
'_OBJECT_HANDLE_COUNT_DATABASE' : [ 0x18, {
'CountEntries' : [ 0x0, ['unsigned long']],
'HandleCountEntries' : [ 0x8, ['array', 1, ['_OBJECT_HANDLE_COUNT_ENTRY']]],
} ],
'_IMAGE_DOS_HEADER' : [ 0x40, {
'e_magic' : [ 0x0, ['unsigned short']],
'e_cblp' : [ 0x2, ['unsigned short']],
'e_cp' : [ 0x4, ['unsigned short']],
'e_crlc' : [ 0x6, ['unsigned short']],
'e_cparhdr' : [ 0x8, ['unsigned short']],
'e_minalloc' : [ 0xa, ['unsigned short']],
'e_maxalloc' : [ 0xc, ['unsigned short']],
'e_ss' : [ 0xe, ['unsigned short']],
'e_sp' : [ 0x10, ['unsigned short']],
'e_csum' : [ 0x12, ['unsigned short']],
'e_ip' : [ 0x14, ['unsigned short']],
'e_cs' : [ 0x16, ['unsigned short']],
'e_lfarlc' : [ 0x18, ['unsigned short']],
'e_ovno' : [ 0x1a, ['unsigned short']],
'e_res' : [ 0x1c, ['array', 4, ['unsigned short']]],
'e_oemid' : [ 0x24, ['unsigned short']],
'e_oeminfo' : [ 0x26, ['unsigned short']],
'e_res2' : [ 0x28, ['array', 10, ['unsigned short']]],
'e_lfanew' : [ 0x3c, ['long']],
} ],
'_OWNER_ENTRY' : [ 0x10, {
'OwnerThread' : [ 0x0, ['unsigned long long']],
'OwnerCount' : [ 0x8, ['long']],
'TableSize' : [ 0x8, ['unsigned long']],
} ],
'_HEAP_VIRTUAL_ALLOC_ENTRY' : [ 0x40, {
'Entry' : [ 0x0, ['_LIST_ENTRY']],
'ExtraStuff' : [ 0x10, ['_HEAP_ENTRY_EXTRA']],
'CommitSize' : [ 0x20, ['unsigned long long']],
'ReserveSize' : [ 0x28, ['unsigned long long']],
'BusyBlock' : [ 0x30, ['_HEAP_ENTRY']],
} ],
'_RTL_ATOM_TABLE' : [ 0x70, {
'Signature' : [ 0x0, ['unsigned long']],
'CriticalSection' : [ 0x8, ['_RTL_CRITICAL_SECTION']],
'RtlHandleTable' : [ 0x30, ['_RTL_HANDLE_TABLE']],
'NumberOfBuckets' : [ 0x60, ['unsigned long']],
'Buckets' : [ 0x68, ['array', 1, ['pointer64', ['_RTL_ATOM_TABLE_ENTRY']]]],
} ],
'_TEB64' : [ 0x17d8, {
'NtTib' : [ 0x0, ['_NT_TIB64']],
'EnvironmentPointer' : [ 0x38, ['unsigned long long']],
'ClientId' : [ 0x40, ['_CLIENT_ID64']],
'ActiveRpcHandle' : [ 0x50, ['unsigned long long']],
'ThreadLocalStoragePointer' : [ 0x58, ['unsigned long long']],
'ProcessEnvironmentBlock' : [ 0x60, ['unsigned long long']],
'LastErrorValue' : [ 0x68, ['unsigned long']],
'CountOfOwnedCriticalSections' : [ 0x6c, ['unsigned long']],
'CsrClientThread' : [ 0x70, ['unsigned long long']],
'Win32ThreadInfo' : [ 0x78, ['unsigned long long']],
'User32Reserved' : [ 0x80, ['array', 26, ['unsigned long']]],
'UserReserved' : [ 0xe8, ['array', 5, ['unsigned long']]],
'WOW32Reserved' : [ 0x100, ['unsigned long long']],
'CurrentLocale' : [ 0x108, ['unsigned long']],
'FpSoftwareStatusRegister' : [ 0x10c, ['unsigned long']],
'SystemReserved1' : [ 0x110, ['array', 54, ['unsigned long long']]],
'ExceptionCode' : [ 0x2c0, ['long']],
'ActivationContextStackPointer' : [ 0x2c8, ['unsigned long long']],
'SpareBytes1' : [ 0x2d0, ['array', 28, ['unsigned char']]],
'GdiTebBatch' : [ 0x2f0, ['_GDI_TEB_BATCH64']],
'RealClientId' : [ 0x7d8, ['_CLIENT_ID64']],
'GdiCachedProcessHandle' : [ 0x7e8, ['unsigned long long']],
'GdiClientPID' : [ 0x7f0, ['unsigned long']],
'GdiClientTID' : [ 0x7f4, ['unsigned long']],
'GdiThreadLocalInfo' : [ 0x7f8, ['unsigned long long']],
'Win32ClientInfo' : [ 0x800, ['array', 62, ['unsigned long long']]],
'glDispatchTable' : [ 0x9f0, ['array', 233, ['unsigned long long']]],
'glReserved1' : [ 0x1138, ['array', 29, ['unsigned long long']]],
'glReserved2' : [ 0x1220, ['unsigned long long']],
'glSectionInfo' : [ 0x1228, ['unsigned long long']],
'glSection' : [ 0x1230, ['unsigned long long']],
'glTable' : [ 0x1238, ['unsigned long long']],
'glCurrentRC' : [ 0x1240, ['unsigned long long']],
'glContext' : [ 0x1248, ['unsigned long long']],
'LastStatusValue' : [ 0x1250, ['unsigned long']],
'StaticUnicodeString' : [ 0x1258, ['_STRING64']],
'StaticUnicodeBuffer' : [ 0x1268, ['array', 261, ['unsigned short']]],
'DeallocationStack' : [ 0x1478, ['unsigned long long']],
'TlsSlots' : [ 0x1480, ['array', 64, ['unsigned long long']]],
'TlsLinks' : [ 0x1680, ['LIST_ENTRY64']],
'Vdm' : [ 0x1690, ['unsigned long long']],
'ReservedForNtRpc' : [ 0x1698, ['unsigned long long']],
'DbgSsReserved' : [ 0x16a0, ['array', 2, ['unsigned long long']]],
'HardErrorMode' : [ 0x16b0, ['unsigned long']],
'Instrumentation' : [ 0x16b8, ['array', 14, ['unsigned long long']]],
'SubProcessTag' : [ 0x1728, ['unsigned long long']],
'EtwTraceData' : [ 0x1730, ['unsigned long long']],
'WinSockData' : [ 0x1738, ['unsigned long long']],
'GdiBatchCount' : [ 0x1740, ['unsigned long']],
'InDbgPrint' : [ 0x1744, ['unsigned char']],
'FreeStackOnTermination' : [ 0x1745, ['unsigned char']],
'HasFiberData' : [ 0x1746, ['unsigned char']],
'IdealProcessor' : [ 0x1747, ['unsigned char']],
'GuaranteedStackBytes' : [ 0x1748, ['unsigned long']],
'ReservedForPerf' : [ 0x1750, ['unsigned long long']],
'ReservedForOle' : [ 0x1758, ['unsigned long long']],
'WaitingOnLoaderLock' : [ 0x1760, ['unsigned long']],
'SparePointer1' : [ 0x1768, ['unsigned long long']],
'SoftPatchPtr1' : [ 0x1770, ['unsigned long long']],
'SoftPatchPtr2' : [ 0x1778, ['unsigned long long']],
'TlsExpansionSlots' : [ 0x1780, ['unsigned long long']],
'DeallocationBStore' : [ 0x1788, ['unsigned long long']],
'BStoreLimit' : [ 0x1790, ['unsigned long long']],
'ImpersonationLocale' : [ 0x1798, ['unsigned long']],
'IsImpersonating' : [ 0x179c, ['unsigned long']],
'NlsCache' : [ 0x17a0, ['unsigned long long']],
'pShimData' : [ 0x17a8, ['unsigned long long']],
'HeapVirtualAffinity' : [ 0x17b0, ['unsigned long']],
'CurrentTransactionHandle' : [ 0x17b8, ['unsigned long long']],
'ActiveFrame' : [ 0x17c0, ['unsigned long long']],
'FlsData' : [ 0x17c8, ['unsigned long long']],
'SafeThunkCall' : [ 0x17d0, ['unsigned char']],
'BooleanSpare' : [ 0x17d1, ['array', 3, ['unsigned char']]],
} ],
'_IMAGE_ROM_OPTIONAL_HEADER' : [ 0x38, {
'Magic' : [ 0x0, ['unsigned short']],
'MajorLinkerVersion' : [ 0x2, ['unsigned char']],
'MinorLinkerVersion' : [ 0x3, ['unsigned char']],
'SizeOfCode' : [ 0x4, ['unsigned long']],
'SizeOfInitializedData' : [ 0x8, ['unsigned long']],
'SizeOfUninitializedData' : [ 0xc, ['unsigned long']],
'AddressOfEntryPoint' : [ 0x10, ['unsigned long']],
'BaseOfCode' : [ 0x14, ['unsigned long']],
'BaseOfData' : [ 0x18, ['unsigned long']],
'BaseOfBss' : [ 0x1c, ['unsigned long']],
'GprMask' : [ 0x20, ['unsigned long']],
'CprMask' : [ 0x24, ['array', 4, ['unsigned long']]],
'GpValue' : [ 0x34, ['unsigned long']],
} ],
'_iobuf' : [ 0x30, {
'_ptr' : [ 0x0, ['pointer64', ['unsigned char']]],
'_cnt' : [ 0x8, ['long']],
'_base' : [ 0x10, ['pointer64', ['unsigned char']]],
'_flag' : [ 0x18, ['long']],
'_file' : [ 0x1c, ['long']],
'_charbuf' : [ 0x20, ['long']],
'_bufsiz' : [ 0x24, ['long']],
'_tmpfname' : [ 0x28, ['pointer64', ['unsigned char']]],
} ],
'_MMPTE_LIST' : [ 0x8, {
'Valid' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long long')]],
'OneEntry' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long long')]],
'filler0' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 5, native_type='unsigned long long')]],
'Protection' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 10, native_type='unsigned long long')]],
'Prototype' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long long')]],
'Transition' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned long long')]],
'filler1' : [ 0x0, ['BitField', dict(start_bit = 12, end_bit = 32, native_type='unsigned long long')]],
'NextEntry' : [ 0x0, ['BitField', dict(start_bit = 32, end_bit = 64, native_type='unsigned long long')]],
} ],
'_CMHIVE' : [ 0xab8, {
'Hive' : [ 0x0, ['_HHIVE']],
'FileHandles' : [ 0x578, ['array', 3, ['pointer64', ['void']]]],
'NotifyList' : [ 0x590, ['_LIST_ENTRY']],
'HiveList' : [ 0x5a0, ['_LIST_ENTRY']],
'HiveLock' : [ 0x5b0, ['_EX_PUSH_LOCK']],
'ViewLock' : [ 0x5b8, ['pointer64', ['_KGUARDED_MUTEX']]],
'WriterLock' : [ 0x5c0, ['_EX_PUSH_LOCK']],
'FlusherLock' : [ 0x5c8, ['_EX_PUSH_LOCK']],
'SecurityLock' : [ 0x5d0, ['_EX_PUSH_LOCK']],
'LRUViewListHead' : [ 0x5d8, ['_LIST_ENTRY']],
'PinViewListHead' : [ 0x5e8, ['_LIST_ENTRY']],
'FileObject' : [ 0x5f8, ['pointer64', ['_FILE_OBJECT']]],
'FileFullPath' : [ 0x600, ['_UNICODE_STRING']],
'FileUserName' : [ 0x610, ['_UNICODE_STRING']],
'MappedViews' : [ 0x620, ['unsigned short']],
'PinnedViews' : [ 0x622, ['unsigned short']],
'UseCount' : [ 0x624, ['unsigned long']],
'SecurityCount' : [ 0x628, ['unsigned long']],
'SecurityCacheSize' : [ 0x62c, ['unsigned long']],
'SecurityHitHint' : [ 0x630, ['long']],
'SecurityCache' : [ 0x638, ['pointer64', ['_CM_KEY_SECURITY_CACHE_ENTRY']]],
'SecurityHash' : [ 0x640, ['array', 64, ['_LIST_ENTRY']]],
'UnloadEvent' : [ 0xa40, ['pointer64', ['_KEVENT']]],
'RootKcb' : [ 0xa48, ['pointer64', ['_CM_KEY_CONTROL_BLOCK']]],
'Frozen' : [ 0xa50, ['unsigned char']],
'UnloadWorkItem' : [ 0xa58, ['pointer64', ['_WORK_QUEUE_ITEM']]],
'GrowOnlyMode' : [ 0xa60, ['unsigned char']],
'GrowOffset' : [ 0xa64, ['unsigned long']],
'KcbConvertListHead' : [ 0xa68, ['_LIST_ENTRY']],
'KnodeConvertListHead' : [ 0xa78, ['_LIST_ENTRY']],
'CellRemapArray' : [ 0xa88, ['pointer64', ['_CM_CELL_REMAP_BLOCK']]],
'Flags' : [ 0xa90, ['unsigned long']],
'TrustClassEntry' : [ 0xa98, ['_LIST_ENTRY']],
'FlushCount' : [ 0xaa8, ['unsigned long']],
'CreatorOwner' : [ 0xab0, ['pointer64', ['_KTHREAD']]],
} ],
'_HANDLE_TRACE_DEBUG_INFO' : [ 0xf0, {
'RefCount' : [ 0x0, ['long']],
'TableSize' : [ 0x4, ['unsigned long']],
'BitMaskFlags' : [ 0x8, ['unsigned long']],
'CloseCompactionLock' : [ 0x10, ['_FAST_MUTEX']],
'CurrentStackIndex' : [ 0x48, ['unsigned long']],
'TraceDb' : [ 0x50, ['array', 1, ['_HANDLE_TRACE_DB_ENTRY']]],
} ],
'_MDL' : [ 0x30, {
'Next' : [ 0x0, ['pointer64', ['_MDL']]],
'Size' : [ 0x8, ['short']],
'MdlFlags' : [ 0xa, ['short']],
'Process' : [ 0x10, ['pointer64', ['_EPROCESS']]],
'MappedSystemVa' : [ 0x18, ['pointer64', ['void']]],
'StartVa' : [ 0x20, ['pointer64', ['void']]],
'ByteCount' : [ 0x28, ['unsigned long']],
'ByteOffset' : [ 0x2c, ['unsigned long']],
} ],
'_HHIVE' : [ 0x578, {
'Signature' : [ 0x0, ['unsigned long']],
'GetCellRoutine' : [ 0x8, ['pointer64', ['void']]],
'ReleaseCellRoutine' : [ 0x10, ['pointer64', ['void']]],
'Allocate' : [ 0x18, ['pointer64', ['void']]],
'Free' : [ 0x20, ['pointer64', ['void']]],
'FileSetSize' : [ 0x28, ['pointer64', ['void']]],
'FileWrite' : [ 0x30, ['pointer64', ['void']]],
'FileRead' : [ 0x38, ['pointer64', ['void']]],
'FileFlush' : [ 0x40, ['pointer64', ['void']]],
'BaseBlock' : [ 0x48, ['pointer64', ['_HBASE_BLOCK']]],
'DirtyVector' : [ 0x50, ['_RTL_BITMAP']],
'DirtyCount' : [ 0x60, ['unsigned long']],
'DirtyAlloc' : [ 0x64, ['unsigned long']],
'BaseBlockAlloc' : [ 0x68, ['unsigned long']],
'Cluster' : [ 0x6c, ['unsigned long']],
'Flat' : [ 0x70, ['unsigned char']],
'ReadOnly' : [ 0x71, ['unsigned char']],
'Log' : [ 0x72, ['unsigned char']],
'DirtyFlag' : [ 0x73, ['unsigned char']],
'HiveFlags' : [ 0x74, ['unsigned long']],
'LogSize' : [ 0x78, ['unsigned long']],
'RefreshCount' : [ 0x7c, ['unsigned long']],
'StorageTypeCount' : [ 0x80, ['unsigned long']],
'Version' : [ 0x84, ['unsigned long']],
'Storage' : [ 0x88, ['array', 2, ['_DUAL']]],
} ],
'_PAGEFAULT_HISTORY' : [ 0x28, {
'CurrentIndex' : [ 0x0, ['unsigned long']],
'MaxIndex' : [ 0x4, ['unsigned long']],
'SpinLock' : [ 0x8, ['unsigned long long']],
'Reserved' : [ 0x10, ['pointer64', ['void']]],
'WatchInfo' : [ 0x18, ['array', 1, ['_PROCESS_WS_WATCH_INFORMATION']]],
} ],
'_RTL_ATOM_TABLE_ENTRY' : [ 0x18, {
'HashLink' : [ 0x0, ['pointer64', ['_RTL_ATOM_TABLE_ENTRY']]],
'HandleIndex' : [ 0x8, ['unsigned short']],
'Atom' : [ 0xa, ['unsigned short']],
'ReferenceCount' : [ 0xc, ['unsigned short']],
'Flags' : [ 0xe, ['unsigned char']],
'NameLength' : [ 0xf, ['unsigned char']],
'Name' : [ 0x10, ['array', 1, ['unsigned short']]],
} ],
'_MM_SESSION_SPACE_FLAGS' : [ 0x4, {
'Initialized' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'DeletePending' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]],
'Filler' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 32, native_type='unsigned long')]],
} ],
'_CM_PARTIAL_RESOURCE_LIST' : [ 0x1c, {
'Version' : [ 0x0, ['unsigned short']],
'Revision' : [ 0x2, ['unsigned short']],
'Count' : [ 0x4, ['unsigned long']],
'PartialDescriptors' : [ 0x8, ['array', 1, ['_CM_PARTIAL_RESOURCE_DESCRIPTOR']]],
} ],
'_OBJECT_CREATE_INFORMATION' : [ 0x48, {
'Attributes' : [ 0x0, ['unsigned long']],
'RootDirectory' : [ 0x8, ['pointer64', ['void']]],
'ParseContext' : [ 0x10, ['pointer64', ['void']]],
'ProbeMode' : [ 0x18, ['unsigned char']],
'PagedPoolCharge' : [ 0x1c, ['unsigned long']],
'NonPagedPoolCharge' : [ 0x20, ['unsigned long']],
'SecurityDescriptorCharge' : [ 0x24, ['unsigned long']],
'SecurityDescriptor' : [ 0x28, ['pointer64', ['void']]],
'SecurityQos' : [ 0x30, ['pointer64', ['_SECURITY_QUALITY_OF_SERVICE']]],
'SecurityQualityOfService' : [ 0x38, ['_SECURITY_QUALITY_OF_SERVICE']],
} ],
'_WMI_BUFFER_STATE' : [ 0x4, {
'Free' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'InUse' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]],
'Flush' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]],
'Unused' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 32, native_type='unsigned long')]],
} ],
'_MMFREE_POOL_ENTRY' : [ 0x28, {
'List' : [ 0x0, ['_LIST_ENTRY']],
'Size' : [ 0x10, ['unsigned long long']],
'Signature' : [ 0x18, ['unsigned long']],
'Owner' : [ 0x20, ['pointer64', ['_MMFREE_POOL_ENTRY']]],
} ],
'__unnamed_15d3' : [ 0x48, {
'ListEntry' : [ 0x0, ['_LIST_ENTRY']],
'Wcb' : [ 0x0, ['_WAIT_CONTEXT_BLOCK']],
} ],
'_DEVICE_OBJECT' : [ 0x150, {
'Type' : [ 0x0, ['short']],
'Size' : [ 0x2, ['unsigned short']],
'ReferenceCount' : [ 0x4, ['long']],
'DriverObject' : [ 0x8, ['pointer64', ['_DRIVER_OBJECT']]],
'NextDevice' : [ 0x10, ['pointer64', ['_DEVICE_OBJECT']]],
'AttachedDevice' : [ 0x18, ['pointer64', ['_DEVICE_OBJECT']]],
'CurrentIrp' : [ 0x20, ['pointer64', ['_IRP']]],
'Timer' : [ 0x28, ['pointer64', ['_IO_TIMER']]],
'Flags' : [ 0x30, ['unsigned long']],
'Characteristics' : [ 0x34, ['unsigned long']],
'Vpb' : [ 0x38, ['pointer64', ['_VPB']]],
'DeviceExtension' : [ 0x40, ['pointer64', ['void']]],
'DeviceType' : [ 0x48, ['unsigned long']],
'StackSize' : [ 0x4c, ['unsigned char']],
'Queue' : [ 0x50, ['__unnamed_15d3']],
'AlignmentRequirement' : [ 0x98, ['unsigned long']],
'DeviceQueue' : [ 0xa0, ['_KDEVICE_QUEUE']],
'Dpc' : [ 0xc8, ['_KDPC']],
'ActiveThreadCount' : [ 0x108, ['unsigned long']],
'SecurityDescriptor' : [ 0x110, ['pointer64', ['void']]],
'DeviceLock' : [ 0x118, ['_KEVENT']],
'SectorSize' : [ 0x130, ['unsigned short']],
'Spare1' : [ 0x132, ['unsigned short']],
'DeviceObjectExtension' : [ 0x138, ['pointer64', ['_DEVOBJ_EXTENSION']]],
'Reserved' : [ 0x140, ['pointer64', ['void']]],
} ],
'_SECTION_OBJECT_POINTERS' : [ 0x18, {
'DataSectionObject' : [ 0x0, ['pointer64', ['void']]],
'SharedCacheMap' : [ 0x8, ['pointer64', ['void']]],
'ImageSectionObject' : [ 0x10, ['pointer64', ['void']]],
} ],
'_SEP_AUDIT_POLICY' : [ 0x8, {
'PolicyElements' : [ 0x0, ['_SEP_AUDIT_POLICY_CATEGORIES']],
'PolicyOverlay' : [ 0x0, ['_SEP_AUDIT_POLICY_OVERLAY']],
'Overlay' : [ 0x0, ['unsigned long long']],
} ],
'_PEB32' : [ 0x230, {
'InheritedAddressSpace' : [ 0x0, ['unsigned char']],
'ReadImageFileExecOptions' : [ 0x1, ['unsigned char']],
'BeingDebugged' : [ 0x2, ['unsigned char']],
'BitField' : [ 0x3, ['unsigned char']],
'ImageUsesLargePages' : [ 0x3, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]],
'SpareBits' : [ 0x3, ['BitField', dict(start_bit = 1, end_bit = 8, native_type='unsigned char')]],
'Mutant' : [ 0x4, ['unsigned long']],
'ImageBaseAddress' : [ 0x8, ['unsigned long']],
'Ldr' : [ 0xc, ['unsigned long']],
'ProcessParameters' : [ 0x10, ['unsigned long']],
'SubSystemData' : [ 0x14, ['unsigned long']],
'ProcessHeap' : [ 0x18, ['unsigned long']],
'FastPebLock' : [ 0x1c, ['unsigned long']],
'AtlThunkSListPtr' : [ 0x20, ['unsigned long']],
'SparePtr2' : [ 0x24, ['unsigned long']],
'EnvironmentUpdateCount' : [ 0x28, ['unsigned long']],
'KernelCallbackTable' : [ 0x2c, ['unsigned long']],
'SystemReserved' : [ 0x30, ['array', 1, ['unsigned long']]],
'SpareUlong' : [ 0x34, ['unsigned long']],
'FreeList' : [ 0x38, ['unsigned long']],
'TlsExpansionCounter' : [ 0x3c, ['unsigned long']],
'TlsBitmap' : [ 0x40, ['unsigned long']],
'TlsBitmapBits' : [ 0x44, ['array', 2, ['unsigned long']]],
'ReadOnlySharedMemoryBase' : [ 0x4c, ['unsigned long']],
'ReadOnlySharedMemoryHeap' : [ 0x50, ['unsigned long']],
'ReadOnlyStaticServerData' : [ 0x54, ['unsigned long']],
'AnsiCodePageData' : [ 0x58, ['unsigned long']],
'OemCodePageData' : [ 0x5c, ['unsigned long']],
'UnicodeCaseTableData' : [ 0x60, ['unsigned long']],
'NumberOfProcessors' : [ 0x64, ['unsigned long']],
'NtGlobalFlag' : [ 0x68, ['unsigned long']],
'CriticalSectionTimeout' : [ 0x70, ['_LARGE_INTEGER']],
'HeapSegmentReserve' : [ 0x78, ['unsigned long']],
'HeapSegmentCommit' : [ 0x7c, ['unsigned long']],
'HeapDeCommitTotalFreeThreshold' : [ 0x80, ['unsigned long']],
'HeapDeCommitFreeBlockThreshold' : [ 0x84, ['unsigned long']],
'NumberOfHeaps' : [ 0x88, ['unsigned long']],
'MaximumNumberOfHeaps' : [ 0x8c, ['unsigned long']],
'ProcessHeaps' : [ 0x90, ['unsigned long']],
'GdiSharedHandleTable' : [ 0x94, ['unsigned long']],
'ProcessStarterHelper' : [ 0x98, ['unsigned long']],
'GdiDCAttributeList' : [ 0x9c, ['unsigned long']],
'LoaderLock' : [ 0xa0, ['unsigned long']],
'OSMajorVersion' : [ 0xa4, ['unsigned long']],
'OSMinorVersion' : [ 0xa8, ['unsigned long']],
'OSBuildNumber' : [ 0xac, ['unsigned short']],
'OSCSDVersion' : [ 0xae, ['unsigned short']],
'OSPlatformId' : [ 0xb0, ['unsigned long']],
'ImageSubsystem' : [ 0xb4, ['unsigned long']],
'ImageSubsystemMajorVersion' : [ 0xb8, ['unsigned long']],
'ImageSubsystemMinorVersion' : [ 0xbc, ['unsigned long']],
'ImageProcessAffinityMask' : [ 0xc0, ['unsigned long']],
'GdiHandleBuffer' : [ 0xc4, ['array', 34, ['unsigned long']]],
'PostProcessInitRoutine' : [ 0x14c, ['unsigned long']],
'TlsExpansionBitmap' : [ 0x150, ['unsigned long']],
'TlsExpansionBitmapBits' : [ 0x154, ['array', 32, ['unsigned long']]],
'SessionId' : [ 0x1d4, ['unsigned long']],
'AppCompatFlags' : [ 0x1d8, ['_ULARGE_INTEGER']],
'AppCompatFlagsUser' : [ 0x1e0, ['_ULARGE_INTEGER']],
'pShimData' : [ 0x1e8, ['unsigned long']],
'AppCompatInfo' : [ 0x1ec, ['unsigned long']],
'CSDVersion' : [ 0x1f0, ['_STRING32']],
'ActivationContextData' : [ 0x1f8, ['unsigned long']],
'ProcessAssemblyStorageMap' : [ 0x1fc, ['unsigned long']],
'SystemDefaultActivationContextData' : [ 0x200, ['unsigned long']],
'SystemAssemblyStorageMap' : [ 0x204, ['unsigned long']],
'MinimumStackCommit' : [ 0x208, ['unsigned long']],
'FlsCallback' : [ 0x20c, ['unsigned long']],
'FlsListHead' : [ 0x210, ['LIST_ENTRY32']],
'FlsBitmap' : [ 0x218, ['unsigned long']],
'FlsBitmapBits' : [ 0x21c, ['array', 4, ['unsigned long']]],
'FlsHighIndex' : [ 0x22c, ['unsigned long']],
} ],
'_MBCB' : [ 0xb8, {
'NodeTypeCode' : [ 0x0, ['short']],
'NodeIsInZone' : [ 0x2, ['short']],
'PagesToWrite' : [ 0x4, ['unsigned long']],
'DirtyPages' : [ 0x8, ['unsigned long']],
'Reserved' : [ 0xc, ['unsigned long']],
'BitmapRanges' : [ 0x10, ['_LIST_ENTRY']],
'ResumeWritePage' : [ 0x20, ['long long']],
'BitmapRange1' : [ 0x28, ['_BITMAP_RANGE']],
'BitmapRange2' : [ 0x58, ['_BITMAP_RANGE']],
'BitmapRange3' : [ 0x88, ['_BITMAP_RANGE']],
} ],
'_POWER_CHANNEL_SUMMARY' : [ 0x20, {
'Signature' : [ 0x0, ['unsigned long']],
'TotalCount' : [ 0x4, ['unsigned long']],
'D0Count' : [ 0x8, ['unsigned long']],
'NotifyList' : [ 0x10, ['_LIST_ENTRY']],
} ],
'_CM_VIEW_OF_FILE' : [ 0x40, {
'LRUViewList' : [ 0x0, ['_LIST_ENTRY']],
'PinViewList' : [ 0x10, ['_LIST_ENTRY']],
'FileOffset' : [ 0x20, ['unsigned long']],
'Size' : [ 0x24, ['unsigned long']],
'ViewAddress' : [ 0x28, ['pointer64', ['unsigned long long']]],
'Bcb' : [ 0x30, ['pointer64', ['void']]],
'UseCount' : [ 0x38, ['unsigned long']],
} ],
'_SLIST_ENTRY' : [ 0x10, {
'Next' : [ 0x0, ['pointer64', ['_SLIST_ENTRY']]],
} ],
'_KDEVICE_QUEUE' : [ 0x28, {
'Type' : [ 0x0, ['short']],
'Size' : [ 0x2, ['short']],
'DeviceListHead' : [ 0x8, ['_LIST_ENTRY']],
'Lock' : [ 0x18, ['unsigned long long']],
'Busy' : [ 0x20, ['unsigned char']],
'Reserved' : [ 0x20, ['BitField', dict(start_bit = 0, end_bit = 8, native_type='long long')]],
'Hint' : [ 0x20, ['BitField', dict(start_bit = 8, end_bit = 64, native_type='long long')]],
} ],
'_KUSER_SHARED_DATA' : [ 0x378, {
'TickCountLowDeprecated' : [ 0x0, ['unsigned long']],
'TickCountMultiplier' : [ 0x4, ['unsigned long']],
'InterruptTime' : [ 0x8, ['_KSYSTEM_TIME']],
'SystemTime' : [ 0x14, ['_KSYSTEM_TIME']],
'TimeZoneBias' : [ 0x20, ['_KSYSTEM_TIME']],
'ImageNumberLow' : [ 0x2c, ['unsigned short']],
'ImageNumberHigh' : [ 0x2e, ['unsigned short']],
'NtSystemRoot' : [ 0x30, ['array', 260, ['unsigned short']]],
'MaxStackTraceDepth' : [ 0x238, ['unsigned long']],
'CryptoExponent' : [ 0x23c, ['unsigned long']],
'TimeZoneId' : [ 0x240, ['unsigned long']],
'LargePageMinimum' : [ 0x244, ['unsigned long']],
'Reserved2' : [ 0x248, ['array', 7, ['unsigned long']]],
'NtProductType' : [ 0x264, ['Enumeration', dict(target = 'long', choices = {1: 'NtProductWinNt', 2: 'NtProductLanManNt', 3: 'NtProductServer'})]],
'ProductTypeIsValid' : [ 0x268, ['unsigned char']],
'NtMajorVersion' : [ 0x26c, ['unsigned long']],
'NtMinorVersion' : [ 0x270, ['unsigned long']],
'ProcessorFeatures' : [ 0x274, ['array', 64, ['unsigned char']]],
'Reserved1' : [ 0x2b4, ['unsigned long']],
'Reserved3' : [ 0x2b8, ['unsigned long']],
'TimeSlip' : [ 0x2bc, ['unsigned long']],
'AlternativeArchitecture' : [ 0x2c0, ['Enumeration', dict(target = 'long', choices = {0: 'StandardDesign', 1: 'NEC98x86', 2: 'EndAlternatives'})]],
'SystemExpirationDate' : [ 0x2c8, ['_LARGE_INTEGER']],
'SuiteMask' : [ 0x2d0, ['unsigned long']],
'KdDebuggerEnabled' : [ 0x2d4, ['unsigned char']],
'NXSupportPolicy' : [ 0x2d5, ['unsigned char']],
'ActiveConsoleId' : [ 0x2d8, ['unsigned long']],
'DismountCount' : [ 0x2dc, ['unsigned long']],
'ComPlusPackage' : [ 0x2e0, ['unsigned long']],
'LastSystemRITEventTickCount' : [ 0x2e4, ['unsigned long']],
'NumberOfPhysicalPages' : [ 0x2e8, ['unsigned long']],
'SafeBootMode' : [ 0x2ec, ['unsigned char']],
'TraceLogging' : [ 0x2f0, ['unsigned long']],
'TestRetInstruction' : [ 0x2f8, ['unsigned long long']],
'SystemCall' : [ 0x300, ['unsigned long']],
'SystemCallReturn' : [ 0x304, ['unsigned long']],
'SystemCallPad' : [ 0x308, ['array', 3, ['unsigned long long']]],
'TickCount' : [ 0x320, ['_KSYSTEM_TIME']],
'TickCountQuad' : [ 0x320, ['unsigned long long']],
'Cookie' : [ 0x330, ['unsigned long']],
'Wow64SharedInformation' : [ 0x334, ['array', 16, ['unsigned long']]],
} ],
'_OBJECT_TYPE_INITIALIZER' : [ 0x70, {
'Length' : [ 0x0, ['unsigned short']],
'UseDefaultObject' : [ 0x2, ['unsigned char']],
'CaseInsensitive' : [ 0x3, ['unsigned char']],
'InvalidAttributes' : [ 0x4, ['unsigned long']],
'GenericMapping' : [ 0x8, ['_GENERIC_MAPPING']],
'ValidAccessMask' : [ 0x18, ['unsigned long']],
'SecurityRequired' : [ 0x1c, ['unsigned char']],
'MaintainHandleCount' : [ 0x1d, ['unsigned char']],
'MaintainTypeList' : [ 0x1e, ['unsigned char']],
'PoolType' : [ 0x20, ['Enumeration', dict(target = 'long', choices = {0: 'NonPagedPool', 1: 'PagedPool', 2: 'NonPagedPoolMustSucceed', 3: 'DontUseThisType', 4: 'NonPagedPoolCacheAligned', 5: 'PagedPoolCacheAligned', 6: 'NonPagedPoolCacheAlignedMustS', 7: 'MaxPoolType', 34: 'NonPagedPoolMustSucceedSession', 35: 'DontUseThisTypeSession', 32: 'NonPagedPoolSession', 36: 'NonPagedPoolCacheAlignedSession', 33: 'PagedPoolSession', 38: 'NonPagedPoolCacheAlignedMustSSession', 37: 'PagedPoolCacheAlignedSession'})]],
'DefaultPagedPoolCharge' : [ 0x24, ['unsigned long']],
'DefaultNonPagedPoolCharge' : [ 0x28, ['unsigned long']],
'DumpProcedure' : [ 0x30, ['pointer64', ['void']]],
'OpenProcedure' : [ 0x38, ['pointer64', ['void']]],
'CloseProcedure' : [ 0x40, ['pointer64', ['void']]],
'DeleteProcedure' : [ 0x48, ['pointer64', ['void']]],
'ParseProcedure' : [ 0x50, ['pointer64', ['void']]],
'SecurityProcedure' : [ 0x58, ['pointer64', ['void']]],
'QueryNameProcedure' : [ 0x60, ['pointer64', ['void']]],
'OkayToCloseProcedure' : [ 0x68, ['pointer64', ['void']]],
} ],
'_WMI_LOGGER_MODE' : [ 0x4, {
'SequentialFile' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'CircularFile' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]],
'AppendFile' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]],
'Unused1' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 8, native_type='unsigned long')]],
'RealTime' : [ 0x0, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long')]],
'DelayOpenFile' : [ 0x0, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long')]],
'BufferOnly' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long')]],
'PrivateLogger' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned long')]],
'AddHeader' : [ 0x0, ['BitField', dict(start_bit = 12, end_bit = 13, native_type='unsigned long')]],
'UseExisting' : [ 0x0, ['BitField', dict(start_bit = 13, end_bit = 14, native_type='unsigned long')]],
'UseGlobalSequence' : [ 0x0, ['BitField', dict(start_bit = 14, end_bit = 15, native_type='unsigned long')]],
'UseLocalSequence' : [ 0x0, ['BitField', dict(start_bit = 15, end_bit = 16, native_type='unsigned long')]],
'Unused2' : [ 0x0, ['BitField', dict(start_bit = 16, end_bit = 32, native_type='unsigned long')]],
} ],
'_KPROCESSOR_STATE' : [ 0x5b0, {
'SpecialRegisters' : [ 0x0, ['_KSPECIAL_REGISTERS']],
'ContextFrame' : [ 0xe0, ['_CONTEXT']],
} ],
'__unnamed_162d' : [ 0x10, {
'List' : [ 0x0, ['_LIST_ENTRY']],
'Secured' : [ 0x0, ['_MMADDRESS_LIST']],
} ],
'__unnamed_1633' : [ 0x8, {
'Banked' : [ 0x0, ['pointer64', ['_MMBANKED_SECTION']]],
'ExtendedInfo' : [ 0x0, ['pointer64', ['_MMEXTEND_INFO']]],
} ],
'_MMVAD_LONG' : [ 0x68, {
'u1' : [ 0x0, ['__unnamed_1180']],
'LeftChild' : [ 0x8, ['pointer64', ['_MMVAD']]],
'RightChild' : [ 0x10, ['pointer64', ['_MMVAD']]],
'StartingVpn' : [ 0x18, ['unsigned long long']],
'EndingVpn' : [ 0x20, ['unsigned long long']],
'u' : [ 0x28, ['__unnamed_1183']],
'ControlArea' : [ 0x30, ['pointer64', ['_CONTROL_AREA']]],
'FirstPrototypePte' : [ 0x38, ['pointer64', ['_MMPTE']]],
'LastContiguousPte' : [ 0x40, ['pointer64', ['_MMPTE']]],
'u2' : [ 0x48, ['__unnamed_1188']],
'u3' : [ 0x50, ['__unnamed_162d']],
'u4' : [ 0x60, ['__unnamed_1633']],
} ],
'_KEXECUTE_OPTIONS' : [ 0x1, {
'ExecuteDisable' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]],
'ExecuteEnable' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned char')]],
'DisableThunkEmulation' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned char')]],
'Permanent' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned char')]],
'ExecuteDispatchEnable' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned char')]],
'ImageDispatchEnable' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned char')]],
'Spare' : [ 0x0, ['BitField', dict(start_bit = 6, end_bit = 8, native_type='unsigned char')]],
} ],
'_POOL_DESCRIPTOR' : [ 0x1048, {
'PoolType' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'NonPagedPool', 1: 'PagedPool', 2: 'NonPagedPoolMustSucceed', 3: 'DontUseThisType', 4: 'NonPagedPoolCacheAligned', 5: 'PagedPoolCacheAligned', 6: 'NonPagedPoolCacheAlignedMustS', 7: 'MaxPoolType', 34: 'NonPagedPoolMustSucceedSession', 35: 'DontUseThisTypeSession', 32: 'NonPagedPoolSession', 36: 'NonPagedPoolCacheAlignedSession', 33: 'PagedPoolSession', 38: 'NonPagedPoolCacheAlignedMustSSession', 37: 'PagedPoolCacheAlignedSession'})]],
'PoolIndex' : [ 0x4, ['unsigned long']],
'RunningAllocs' : [ 0x8, ['unsigned long']],
'RunningDeAllocs' : [ 0xc, ['unsigned long']],
'TotalPages' : [ 0x10, ['unsigned long']],
'TotalBigPages' : [ 0x14, ['unsigned long']],
'Threshold' : [ 0x18, ['unsigned long']],
'LockAddress' : [ 0x20, ['pointer64', ['void']]],
'PendingFrees' : [ 0x28, ['pointer64', ['void']]],
'PendingFreeDepth' : [ 0x30, ['long']],
'TotalBytes' : [ 0x38, ['unsigned long long']],
'Spare0' : [ 0x40, ['unsigned long long']],
'ListHeads' : [ 0x48, ['array', 256, ['_LIST_ENTRY']]],
} ],
'_HARDWARE_PTE' : [ 0x8, {
'Valid' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long long')]],
'Write' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long long')]],
'Owner' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long long')]],
'WriteThrough' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long long')]],
'CacheDisable' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long long')]],
'Accessed' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long long')]],
'Dirty' : [ 0x0, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned long long')]],
'LargePage' : [ 0x0, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned long long')]],
'Global' : [ 0x0, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long long')]],
'CopyOnWrite' : [ 0x0, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long long')]],
'Prototype' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long long')]],
'reserved0' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned long long')]],
'PageFrameNumber' : [ 0x0, ['BitField', dict(start_bit = 12, end_bit = 40, native_type='unsigned long long')]],
'reserved1' : [ 0x0, ['BitField', dict(start_bit = 40, end_bit = 52, native_type='unsigned long long')]],
'SoftwareWsIndex' : [ 0x0, ['BitField', dict(start_bit = 52, end_bit = 63, native_type='unsigned long long')]],
'NoExecute' : [ 0x0, ['BitField', dict(start_bit = 63, end_bit = 64, native_type='unsigned long long')]],
} ],
'_WOW64_PROCESS' : [ 0x8, {
'Wow64' : [ 0x0, ['pointer64', ['void']]],
} ],
'_PEB_LDR_DATA' : [ 0x48, {
'Length' : [ 0x0, ['unsigned long']],
'Initialized' : [ 0x4, ['unsigned char']],
'SsHandle' : [ 0x8, ['pointer64', ['void']]],
'InLoadOrderModuleList' : [ 0x10, ['_LIST_ENTRY']],
'InMemoryOrderModuleList' : [ 0x20, ['_LIST_ENTRY']],
'InInitializationOrderModuleList' : [ 0x30, ['_LIST_ENTRY']],
'EntryInProgress' : [ 0x40, ['pointer64', ['void']]],
} ],
'_DBGKD_SWITCH_PARTITION' : [ 0x4, {
'Partition' : [ 0x0, ['unsigned long']],
} ],
'_DBGKD_GET_VERSION32' : [ 0x28, {
'MajorVersion' : [ 0x0, ['unsigned short']],
'MinorVersion' : [ 0x2, ['unsigned short']],
'ProtocolVersion' : [ 0x4, ['unsigned short']],
'Flags' : [ 0x6, ['unsigned short']],
'KernBase' : [ 0x8, ['unsigned long']],
'PsLoadedModuleList' : [ 0xc, ['unsigned long']],
'MachineType' : [ 0x10, ['unsigned short']],
'ThCallbackStack' : [ 0x12, ['unsigned short']],
'NextCallback' : [ 0x14, ['unsigned short']],
'FramePointer' : [ 0x16, ['unsigned short']],
'KiCallUserMode' : [ 0x18, ['unsigned long']],
'KeUserCallbackDispatcher' : [ 0x1c, ['unsigned long']],
'BreakpointWithStatus' : [ 0x20, ['unsigned long']],
'DebuggerDataList' : [ 0x24, ['unsigned long']],
} ],
'_MM_PAGED_POOL_INFO' : [ 0x40, {
'PagedPoolAllocationMap' : [ 0x0, ['pointer64', ['_RTL_BITMAP']]],
'EndOfPagedPoolBitmap' : [ 0x8, ['pointer64', ['_RTL_BITMAP']]],
'FirstPteForPagedPool' : [ 0x10, ['pointer64', ['_MMPTE']]],
'LastPteForPagedPool' : [ 0x18, ['pointer64', ['_MMPTE']]],
'NextPdeForPagedPoolExpansion' : [ 0x20, ['pointer64', ['_MMPTE']]],
'PagedPoolHint' : [ 0x28, ['unsigned long']],
'PagedPoolCommit' : [ 0x30, ['unsigned long long']],
'AllocatedPagedPool' : [ 0x38, ['unsigned long long']],
} ],
'_INTERLOCK_SEQ' : [ 0x8, {
'Depth' : [ 0x0, ['unsigned short']],
'FreeEntryOffset' : [ 0x2, ['unsigned short']],
'OffsetAndDepth' : [ 0x0, ['unsigned long']],
'Sequence' : [ 0x4, ['unsigned long']],
'Exchg' : [ 0x0, ['long long']],
} ],
'_VPB' : [ 0x60, {
'Type' : [ 0x0, ['short']],
'Size' : [ 0x2, ['short']],
'Flags' : [ 0x4, ['unsigned short']],
'VolumeLabelLength' : [ 0x6, ['unsigned short']],
'DeviceObject' : [ 0x8, ['pointer64', ['_DEVICE_OBJECT']]],
'RealDevice' : [ 0x10, ['pointer64', ['_DEVICE_OBJECT']]],
'SerialNumber' : [ 0x18, ['unsigned long']],
'ReferenceCount' : [ 0x1c, ['unsigned long']],
'VolumeLabel' : [ 0x20, ['array', 32, ['unsigned short']]],
} ],
'_CACHE_DESCRIPTOR' : [ 0xc, {
'Level' : [ 0x0, ['unsigned char']],
'Associativity' : [ 0x1, ['unsigned char']],
'LineSize' : [ 0x2, ['unsigned short']],
'Size' : [ 0x4, ['unsigned long']],
'Type' : [ 0x8, ['Enumeration', dict(target = 'long', choices = {0: 'CacheUnified', 1: 'CacheInstruction', 2: 'CacheData', 3: 'CacheTrace'})]],
} ],
'_MMSESSION' : [ 0x68, {
'SystemSpaceViewLock' : [ 0x0, ['_KGUARDED_MUTEX']],
'SystemSpaceViewLockPointer' : [ 0x38, ['pointer64', ['_KGUARDED_MUTEX']]],
'SystemSpaceViewStart' : [ 0x40, ['pointer64', ['unsigned char']]],
'SystemSpaceViewTable' : [ 0x48, ['pointer64', ['_MMVIEW']]],
'SystemSpaceHashSize' : [ 0x50, ['unsigned long']],
'SystemSpaceHashEntries' : [ 0x54, ['unsigned long']],
'SystemSpaceHashKey' : [ 0x58, ['unsigned long']],
'BitmapFailures' : [ 0x5c, ['unsigned long']],
'SystemSpaceBitMap' : [ 0x60, ['pointer64', ['_RTL_BITMAP']]],
} ],
'_GENERIC_MAPPING' : [ 0x10, {
'GenericRead' : [ 0x0, ['unsigned long']],
'GenericWrite' : [ 0x4, ['unsigned long']],
'GenericExecute' : [ 0x8, ['unsigned long']],
'GenericAll' : [ 0xc, ['unsigned long']],
} ],
'_DBGKD_RESTORE_BREAKPOINT' : [ 0x4, {
'BreakPointHandle' : [ 0x0, ['unsigned long']],
} ],
'_EXCEPTION_REGISTRATION_RECORD' : [ 0x10, {
'Next' : [ 0x0, ['pointer64', ['_EXCEPTION_REGISTRATION_RECORD']]],
'Handler' : [ 0x8, ['pointer64', ['void']]],
} ],
'_SEP_AUDIT_POLICY_OVERLAY' : [ 0x8, {
'PolicyBits' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 36, native_type='unsigned long long')]],
'SetBit' : [ 0x0, ['BitField', dict(start_bit = 36, end_bit = 37, native_type='unsigned long long')]],
} ],
'_POOL_TRACKER_BIG_PAGES' : [ 0x18, {
'Va' : [ 0x0, ['pointer64', ['void']]],
'Key' : [ 0x8, ['unsigned long']],
'NumberOfPages' : [ 0xc, ['unsigned long']],
'QuotaObject' : [ 0x10, ['pointer64', ['void']]],
} ],
'_PROCESS_WS_WATCH_INFORMATION' : [ 0x10, {
'FaultingPc' : [ 0x0, ['pointer64', ['void']]],
'FaultingVa' : [ 0x8, ['pointer64', ['void']]],
} ],
'_MMPTE_SUBSECTION' : [ 0x8, {
'Valid' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long long')]],
'Unused0' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 5, native_type='unsigned long long')]],
'Protection' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 10, native_type='unsigned long long')]],
'Prototype' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long long')]],
'Unused1' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 16, native_type='unsigned long long')]],
'SubsectionAddress' : [ 0x0, ['BitField', dict(start_bit = 16, end_bit = 64, native_type='long long')]],
} ],
'_VI_DEADLOCK_NODE' : [ 0xd0, {
'Parent' : [ 0x0, ['pointer64', ['_VI_DEADLOCK_NODE']]],
'ChildrenList' : [ 0x8, ['_LIST_ENTRY']],
'SiblingsList' : [ 0x18, ['_LIST_ENTRY']],
'ResourceList' : [ 0x28, ['_LIST_ENTRY']],
'FreeListEntry' : [ 0x28, ['_LIST_ENTRY']],
'Root' : [ 0x38, ['pointer64', ['_VI_DEADLOCK_RESOURCE']]],
'ThreadEntry' : [ 0x40, ['pointer64', ['_VI_DEADLOCK_THREAD']]],
'Active' : [ 0x48, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'OnlyTryAcquireUsed' : [ 0x48, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]],
'ReleasedOutOfOrder' : [ 0x48, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]],
'SequenceNumber' : [ 0x48, ['BitField', dict(start_bit = 3, end_bit = 32, native_type='unsigned long')]],
'StackTrace' : [ 0x50, ['array', 8, ['pointer64', ['void']]]],
'ParentStackTrace' : [ 0x90, ['array', 8, ['pointer64', ['void']]]],
} ],
'_SECURITY_QUALITY_OF_SERVICE' : [ 0xc, {
'Length' : [ 0x0, ['unsigned long']],
'ImpersonationLevel' : [ 0x4, ['Enumeration', dict(target = 'long', choices = {0: 'SecurityAnonymous', 1: 'SecurityIdentification', 2: 'SecurityImpersonation', 3: 'SecurityDelegation'})]],
'ContextTrackingMode' : [ 0x8, ['unsigned char']],
'EffectiveOnly' : [ 0x9, ['unsigned char']],
} ],
'_UNEXPECTED_INTERRUPT' : [ 0x10, {
'PushImmOp' : [ 0x0, ['unsigned char']],
'PushImm' : [ 0x1, ['unsigned long']],
'PushRbp' : [ 0x5, ['unsigned char']],
'JmpOp' : [ 0x6, ['unsigned char']],
'JmpOffset' : [ 0x7, ['long']],
} ],
'_CONTEXT' : [ 0x4d0, {
'P1Home' : [ 0x0, ['unsigned long long']],
'P2Home' : [ 0x8, ['unsigned long long']],
'P3Home' : [ 0x10, ['unsigned long long']],
'P4Home' : [ 0x18, ['unsigned long long']],
'P5Home' : [ 0x20, ['unsigned long long']],
'P6Home' : [ 0x28, ['unsigned long long']],
'ContextFlags' : [ 0x30, ['unsigned long']],
'MxCsr' : [ 0x34, ['unsigned long']],
'SegCs' : [ 0x38, ['unsigned short']],
'SegDs' : [ 0x3a, ['unsigned short']],
'SegEs' : [ 0x3c, ['unsigned short']],
'SegFs' : [ 0x3e, ['unsigned short']],
'SegGs' : [ 0x40, ['unsigned short']],
'SegSs' : [ 0x42, ['unsigned short']],
'EFlags' : [ 0x44, ['unsigned long']],
'Dr0' : [ 0x48, ['unsigned long long']],
'Dr1' : [ 0x50, ['unsigned long long']],
'Dr2' : [ 0x58, ['unsigned long long']],
'Dr3' : [ 0x60, ['unsigned long long']],
'Dr6' : [ 0x68, ['unsigned long long']],
'Dr7' : [ 0x70, ['unsigned long long']],
'Rax' : [ 0x78, ['unsigned long long']],
'Rcx' : [ 0x80, ['unsigned long long']],
'Rdx' : [ 0x88, ['unsigned long long']],
'Rbx' : [ 0x90, ['unsigned long long']],
'Rsp' : [ 0x98, ['unsigned long long']],
'Rbp' : [ 0xa0, ['unsigned long long']],
'Rsi' : [ 0xa8, ['unsigned long long']],
'Rdi' : [ 0xb0, ['unsigned long long']],
'R8' : [ 0xb8, ['unsigned long long']],
'R9' : [ 0xc0, ['unsigned long long']],
'R10' : [ 0xc8, ['unsigned long long']],
'R11' : [ 0xd0, ['unsigned long long']],
'R12' : [ 0xd8, ['unsigned long long']],
'R13' : [ 0xe0, ['unsigned long long']],
'R14' : [ 0xe8, ['unsigned long long']],
'R15' : [ 0xf0, ['unsigned long long']],
'Rip' : [ 0xf8, ['unsigned long long']],
'FltSave' : [ 0x100, ['_XMM_SAVE_AREA32']],
'Header' : [ 0x100, ['array', 2, ['_M128A']]],
'Legacy' : [ 0x120, ['array', 8, ['_M128A']]],
'Xmm0' : [ 0x1a0, ['_M128A']],
'Xmm1' : [ 0x1b0, ['_M128A']],
'Xmm2' : [ 0x1c0, ['_M128A']],
'Xmm3' : [ 0x1d0, ['_M128A']],
'Xmm4' : [ 0x1e0, ['_M128A']],
'Xmm5' : [ 0x1f0, ['_M128A']],
'Xmm6' : [ 0x200, ['_M128A']],
'Xmm7' : [ 0x210, ['_M128A']],
'Xmm8' : [ 0x220, ['_M128A']],
'Xmm9' : [ 0x230, ['_M128A']],
'Xmm10' : [ 0x240, ['_M128A']],
'Xmm11' : [ 0x250, ['_M128A']],
'Xmm12' : [ 0x260, ['_M128A']],
'Xmm13' : [ 0x270, ['_M128A']],
'Xmm14' : [ 0x280, ['_M128A']],
'Xmm15' : [ 0x290, ['_M128A']],
'VectorRegister' : [ 0x300, ['array', 26, ['_M128A']]],
'VectorControl' : [ 0x4a0, ['unsigned long long']],
'DebugControl' : [ 0x4a8, ['unsigned long long']],
'LastBranchToRip' : [ 0x4b0, ['unsigned long long']],
'LastBranchFromRip' : [ 0x4b8, ['unsigned long long']],
'LastExceptionToRip' : [ 0x4c0, ['unsigned long long']],
'LastExceptionFromRip' : [ 0x4c8, ['unsigned long long']],
} ],
'_MMPTE_HARDWARE_LARGEPAGE' : [ 0x8, {
'Valid' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long long')]],
'Write' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long long')]],
'Owner' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long long')]],
'WriteThrough' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long long')]],
'CacheDisable' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long long')]],
'Accessed' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long long')]],
'Dirty' : [ 0x0, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned long long')]],
'LargePage' : [ 0x0, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned long long')]],
'Global' : [ 0x0, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long long')]],
'CopyOnWrite' : [ 0x0, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long long')]],
'Prototype' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long long')]],
'reserved0' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned long long')]],
'PAT' : [ 0x0, ['BitField', dict(start_bit = 12, end_bit = 13, native_type='unsigned long long')]],
'reserved1' : [ 0x0, ['BitField', dict(start_bit = 13, end_bit = 21, native_type='unsigned long long')]],
'PageFrameNumber' : [ 0x0, ['BitField', dict(start_bit = 21, end_bit = 40, native_type='unsigned long long')]],
'reserved2' : [ 0x0, ['BitField', dict(start_bit = 40, end_bit = 64, native_type='unsigned long long')]],
} ],
'_DBGKD_QUERY_SPECIAL_CALLS' : [ 0x4, {
'NumberOfSpecialCalls' : [ 0x0, ['unsigned long']],
} ],
'CMP_OFFSET_ARRAY' : [ 0x18, {
'FileOffset' : [ 0x0, ['unsigned long']],
'DataBuffer' : [ 0x8, ['pointer64', ['void']]],
'DataLength' : [ 0x10, ['unsigned long']],
} ],
'_PCI_PDO_EXTENSION' : [ 0x120, {
'Next' : [ 0x0, ['pointer64', ['_PCI_PDO_EXTENSION']]],
'ExtensionType' : [ 0x8, ['Enumeration', dict(target = 'long', choices = {1768116272: 'PciPdoExtensionType', 1768116273: 'PciFdoExtensionType', 1768116274: 'PciArb_Io', 1768116275: 'PciArb_Memory', 1768116276: 'PciArb_Interrupt', 1768116277: 'PciArb_BusNumber', 1768116278: 'PciTrans_Interrupt', 1768116279: 'PciInterface_BusHandler', 1768116280: 'PciInterface_IntRouteHandler', 1768116281: 'PciInterface_PciCb', 1768116282: 'PciInterface_LegacyDeviceDetection', 1768116283: 'PciInterface_PmeHandler', 1768116284: 'PciInterface_DevicePresent', 1768116285: 'PciInterface_NativeIde', 1768116286: 'PciInterface_Location', 1768116287: 'PciInterface_AgpTarget'})]],
'IrpDispatchTable' : [ 0x10, ['pointer64', ['_PCI_MJ_DISPATCH_TABLE']]],
'DeviceState' : [ 0x18, ['unsigned char']],
'TentativeNextState' : [ 0x19, ['unsigned char']],
'SecondaryExtLock' : [ 0x20, ['_KEVENT']],
'Slot' : [ 0x38, ['_PCI_SLOT_NUMBER']],
'PhysicalDeviceObject' : [ 0x40, ['pointer64', ['_DEVICE_OBJECT']]],
'ParentFdoExtension' : [ 0x48, ['pointer64', ['_PCI_FDO_EXTENSION']]],
'SecondaryExtension' : [ 0x50, ['_SINGLE_LIST_ENTRY']],
'BusInterfaceReferenceCount' : [ 0x58, ['unsigned long']],
'AgpInterfaceReferenceCount' : [ 0x5c, ['unsigned long']],
'VendorId' : [ 0x60, ['unsigned short']],
'DeviceId' : [ 0x62, ['unsigned short']],
'SubsystemVendorId' : [ 0x64, ['unsigned short']],
'SubsystemId' : [ 0x66, ['unsigned short']],
'RevisionId' : [ 0x68, ['unsigned char']],
'ProgIf' : [ 0x69, ['unsigned char']],
'SubClass' : [ 0x6a, ['unsigned char']],
'BaseClass' : [ 0x6b, ['unsigned char']],
'AdditionalResourceCount' : [ 0x6c, ['unsigned char']],
'AdjustedInterruptLine' : [ 0x6d, ['unsigned char']],
'InterruptPin' : [ 0x6e, ['unsigned char']],
'RawInterruptLine' : [ 0x6f, ['unsigned char']],
'CapabilitiesPtr' : [ 0x70, ['unsigned char']],
'SavedLatencyTimer' : [ 0x71, ['unsigned char']],
'SavedCacheLineSize' : [ 0x72, ['unsigned char']],
'HeaderType' : [ 0x73, ['unsigned char']],
'NotPresent' : [ 0x74, ['unsigned char']],
'ReportedMissing' : [ 0x75, ['unsigned char']],
'ExpectedWritebackFailure' : [ 0x76, ['unsigned char']],
'NoTouchPmeEnable' : [ 0x77, ['unsigned char']],
'LegacyDriver' : [ 0x78, ['unsigned char']],
'UpdateHardware' : [ 0x79, ['unsigned char']],
'MovedDevice' : [ 0x7a, ['unsigned char']],
'DisablePowerDown' : [ 0x7b, ['unsigned char']],
'NeedsHotPlugConfiguration' : [ 0x7c, ['unsigned char']],
'IDEInNativeMode' : [ 0x7d, ['unsigned char']],
'BIOSAllowsIDESwitchToNativeMode' : [ 0x7e, ['unsigned char']],
'IoSpaceUnderNativeIdeControl' : [ 0x7f, ['unsigned char']],
'OnDebugPath' : [ 0x80, ['unsigned char']],
'IoSpaceNotRequired' : [ 0x81, ['unsigned char']],
'PowerState' : [ 0x88, ['PCI_POWER_STATE']],
'Dependent' : [ 0xd8, ['PCI_HEADER_TYPE_DEPENDENT']],
'HackFlags' : [ 0xe0, ['unsigned long long']],
'Resources' : [ 0xe8, ['pointer64', ['PCI_FUNCTION_RESOURCES']]],
'BridgeFdoExtension' : [ 0xf0, ['pointer64', ['_PCI_FDO_EXTENSION']]],
'NextBridge' : [ 0xf8, ['pointer64', ['_PCI_PDO_EXTENSION']]],
'NextHashEntry' : [ 0x100, ['pointer64', ['_PCI_PDO_EXTENSION']]],
'Lock' : [ 0x108, ['_PCI_LOCK']],
'PowerCapabilities' : [ 0x118, ['_PCI_PMC']],
'TargetAgpCapabilityId' : [ 0x11a, ['unsigned char']],
'CommandEnables' : [ 0x11c, ['unsigned short']],
'InitialCommand' : [ 0x11e, ['unsigned short']],
} ],
'_HMAP_DIRECTORY' : [ 0x2000, {
'Directory' : [ 0x0, ['array', 1024, ['pointer64', ['_HMAP_TABLE']]]],
} ],
'_NT_TIB32' : [ 0x1c, {
'ExceptionList' : [ 0x0, ['unsigned long']],
'StackBase' : [ 0x4, ['unsigned long']],
'StackLimit' : [ 0x8, ['unsigned long']],
'SubSystemTib' : [ 0xc, ['unsigned long']],
'FiberData' : [ 0x10, ['unsigned long']],
'Version' : [ 0x10, ['unsigned long']],
'ArbitraryUserPointer' : [ 0x14, ['unsigned long']],
'Self' : [ 0x18, ['unsigned long']],
} ],
'_SECURITY_DESCRIPTOR' : [ 0x28, {
'Revision' : [ 0x0, ['unsigned char']],
'Sbz1' : [ 0x1, ['unsigned char']],
'Control' : [ 0x2, ['unsigned short']],
'Owner' : [ 0x8, ['pointer64', ['void']]],
'Group' : [ 0x10, ['pointer64', ['void']]],
'Sacl' : [ 0x18, ['pointer64', ['_ACL']]],
'Dacl' : [ 0x20, ['pointer64', ['_ACL']]],
} ],
'__unnamed_16a5' : [ 0x10, {
'UserData' : [ 0x0, ['pointer64', ['void']]],
'Owner' : [ 0x8, ['pointer64', ['void']]],
} ],
'__unnamed_16a7' : [ 0x10, {
'ListHead' : [ 0x0, ['_LIST_ENTRY']],
} ],
'_RTLP_RANGE_LIST_ENTRY' : [ 0x38, {
'Start' : [ 0x0, ['unsigned long long']],
'End' : [ 0x8, ['unsigned long long']],
'Allocated' : [ 0x10, ['__unnamed_16a5']],
'Merged' : [ 0x10, ['__unnamed_16a7']],
'Attributes' : [ 0x20, ['unsigned char']],
'PublicFlags' : [ 0x21, ['unsigned char']],
'PrivateFlags' : [ 0x22, ['unsigned short']],
'ListEntry' : [ 0x28, ['_LIST_ENTRY']],
} ],
'_KAPC_STATE' : [ 0x30, {
'ApcListHead' : [ 0x0, ['array', 2, ['_LIST_ENTRY']]],
'Process' : [ 0x20, ['pointer64', ['_KPROCESS']]],
'KernelApcInProgress' : [ 0x28, ['unsigned char']],
'KernelApcPending' : [ 0x29, ['unsigned char']],
'UserApcPending' : [ 0x2a, ['unsigned char']],
} ],
'_HEAP_STOP_ON_VALUES' : [ 0x30, {
'AllocAddress' : [ 0x0, ['unsigned long long']],
'AllocTag' : [ 0x8, ['_HEAP_STOP_ON_TAG']],
'ReAllocAddress' : [ 0x10, ['unsigned long long']],
'ReAllocTag' : [ 0x18, ['_HEAP_STOP_ON_TAG']],
'FreeAddress' : [ 0x20, ['unsigned long long']],
'FreeTag' : [ 0x28, ['_HEAP_STOP_ON_TAG']],
} ],
'_DEVICE_RELATIONS' : [ 0x10, {
'Count' : [ 0x0, ['unsigned long']],
'Objects' : [ 0x8, ['array', 1, ['pointer64', ['_DEVICE_OBJECT']]]],
} ],
'_DEVICE_MAP' : [ 0x38, {
'DosDevicesDirectory' : [ 0x0, ['pointer64', ['_OBJECT_DIRECTORY']]],
'GlobalDosDevicesDirectory' : [ 0x8, ['pointer64', ['_OBJECT_DIRECTORY']]],
'ReferenceCount' : [ 0x10, ['unsigned long']],
'DriveMap' : [ 0x14, ['unsigned long']],
'DriveType' : [ 0x18, ['array', 32, ['unsigned char']]],
} ],
'_HEAP_PSEUDO_TAG_ENTRY' : [ 0x10, {
'Allocs' : [ 0x0, ['unsigned long']],
'Frees' : [ 0x4, ['unsigned long']],
'Size' : [ 0x8, ['unsigned long long']],
} ],
'_IO_RESOURCE_LIST' : [ 0x28, {
'Version' : [ 0x0, ['unsigned short']],
'Revision' : [ 0x2, ['unsigned short']],
'Count' : [ 0x4, ['unsigned long']],
'Descriptors' : [ 0x8, ['array', 1, ['_IO_RESOURCE_DESCRIPTOR']]],
} ],
'_MMBANKED_SECTION' : [ 0x38, {
'BasePhysicalPage' : [ 0x0, ['unsigned long long']],
'BasedPte' : [ 0x8, ['pointer64', ['_MMPTE']]],
'BankSize' : [ 0x10, ['unsigned long']],
'BankShift' : [ 0x14, ['unsigned long']],
'BankedRoutine' : [ 0x18, ['pointer64', ['void']]],
'Context' : [ 0x20, ['pointer64', ['void']]],
'CurrentMappedPte' : [ 0x28, ['pointer64', ['_MMPTE']]],
'BankTemplate' : [ 0x30, ['array', 1, ['_MMPTE']]],
} ],
'_RTL_CRITICAL_SECTION' : [ 0x28, {
'DebugInfo' : [ 0x0, ['pointer64', ['_RTL_CRITICAL_SECTION_DEBUG']]],
'LockCount' : [ 0x8, ['long']],
'RecursionCount' : [ 0xc, ['long']],
'OwningThread' : [ 0x10, ['pointer64', ['void']]],
'LockSemaphore' : [ 0x18, ['pointer64', ['void']]],
'SpinCount' : [ 0x20, ['unsigned long long']],
} ],
'_KTSS64' : [ 0x68, {
'Reserved0' : [ 0x0, ['unsigned long']],
'Rsp0' : [ 0x4, ['unsigned long long']],
'Rsp1' : [ 0xc, ['unsigned long long']],
'Rsp2' : [ 0x14, ['unsigned long long']],
'Ist' : [ 0x1c, ['array', 8, ['unsigned long long']]],
'Reserved1' : [ 0x5c, ['unsigned long long']],
'Reserved2' : [ 0x64, ['unsigned short']],
'IoMapBase' : [ 0x66, ['unsigned short']],
} ],
'__unnamed_16d2' : [ 0x5, {
'Acquired' : [ 0x0, ['unsigned char']],
'CacheLineSize' : [ 0x1, ['unsigned char']],
'LatencyTimer' : [ 0x2, ['unsigned char']],
'EnablePERR' : [ 0x3, ['unsigned char']],
'EnableSERR' : [ 0x4, ['unsigned char']],
} ],
'_PCI_FDO_EXTENSION' : [ 0x130, {
'List' : [ 0x0, ['_SINGLE_LIST_ENTRY']],
'ExtensionType' : [ 0x8, ['Enumeration', dict(target = 'long', choices = {1768116272: 'PciPdoExtensionType', 1768116273: 'PciFdoExtensionType', 1768116274: 'PciArb_Io', 1768116275: 'PciArb_Memory', 1768116276: 'PciArb_Interrupt', 1768116277: 'PciArb_BusNumber', 1768116278: 'PciTrans_Interrupt', 1768116279: 'PciInterface_BusHandler', 1768116280: 'PciInterface_IntRouteHandler', 1768116281: 'PciInterface_PciCb', 1768116282: 'PciInterface_LegacyDeviceDetection', 1768116283: 'PciInterface_PmeHandler', 1768116284: 'PciInterface_DevicePresent', 1768116285: 'PciInterface_NativeIde', 1768116286: 'PciInterface_Location', 1768116287: 'PciInterface_AgpTarget'})]],
'IrpDispatchTable' : [ 0x10, ['pointer64', ['_PCI_MJ_DISPATCH_TABLE']]],
'DeviceState' : [ 0x18, ['unsigned char']],
'TentativeNextState' : [ 0x19, ['unsigned char']],
'SecondaryExtLock' : [ 0x20, ['_KEVENT']],
'PhysicalDeviceObject' : [ 0x38, ['pointer64', ['_DEVICE_OBJECT']]],
'FunctionalDeviceObject' : [ 0x40, ['pointer64', ['_DEVICE_OBJECT']]],
'AttachedDeviceObject' : [ 0x48, ['pointer64', ['_DEVICE_OBJECT']]],
'ChildListLock' : [ 0x50, ['_KEVENT']],
'ChildPdoList' : [ 0x68, ['pointer64', ['_PCI_PDO_EXTENSION']]],
'BusRootFdoExtension' : [ 0x70, ['pointer64', ['_PCI_FDO_EXTENSION']]],
'ParentFdoExtension' : [ 0x78, ['pointer64', ['_PCI_FDO_EXTENSION']]],
'ChildBridgePdoList' : [ 0x80, ['pointer64', ['_PCI_PDO_EXTENSION']]],
'PciBusInterface' : [ 0x88, ['pointer64', ['_PCI_BUS_INTERFACE_STANDARD']]],
'MaxSubordinateBus' : [ 0x90, ['unsigned char']],
'BusHandler' : [ 0x98, ['pointer64', ['_BUS_HANDLER']]],
'BaseBus' : [ 0xa0, ['unsigned char']],
'Fake' : [ 0xa1, ['unsigned char']],
'ChildDelete' : [ 0xa2, ['unsigned char']],
'Scanned' : [ 0xa3, ['unsigned char']],
'ArbitersInitialized' : [ 0xa4, ['unsigned char']],
'BrokenVideoHackApplied' : [ 0xa5, ['unsigned char']],
'Hibernated' : [ 0xa6, ['unsigned char']],
'PowerState' : [ 0xa8, ['PCI_POWER_STATE']],
'SecondaryExtension' : [ 0xf8, ['_SINGLE_LIST_ENTRY']],
'ChildWaitWakeCount' : [ 0x100, ['unsigned long']],
'PreservedConfig' : [ 0x108, ['pointer64', ['_PCI_COMMON_CONFIG']]],
'Lock' : [ 0x110, ['_PCI_LOCK']],
'HotPlugParameters' : [ 0x120, ['__unnamed_16d2']],
'BusHackFlags' : [ 0x128, ['unsigned long']],
} ],
'__unnamed_16d6' : [ 0xc, {
'Start' : [ 0x0, ['_LARGE_INTEGER']],
'Length' : [ 0x8, ['unsigned long']],
} ],
'__unnamed_16d8' : [ 0x10, {
'Level' : [ 0x0, ['unsigned long']],
'Vector' : [ 0x4, ['unsigned long']],
'Affinity' : [ 0x8, ['unsigned long long']],
} ],
'__unnamed_16da' : [ 0xc, {
'Channel' : [ 0x0, ['unsigned long']],
'Port' : [ 0x4, ['unsigned long']],
'Reserved1' : [ 0x8, ['unsigned long']],
} ],
'__unnamed_16dc' : [ 0xc, {
'Data' : [ 0x0, ['array', 3, ['unsigned long']]],
} ],
'__unnamed_16de' : [ 0xc, {
'Start' : [ 0x0, ['unsigned long']],
'Length' : [ 0x4, ['unsigned long']],
'Reserved' : [ 0x8, ['unsigned long']],
} ],
'__unnamed_16e0' : [ 0xc, {
'DataSize' : [ 0x0, ['unsigned long']],
'Reserved1' : [ 0x4, ['unsigned long']],
'Reserved2' : [ 0x8, ['unsigned long']],
} ],
'__unnamed_16e2' : [ 0x10, {
'Generic' : [ 0x0, ['__unnamed_16d6']],
'Port' : [ 0x0, ['__unnamed_16d6']],
'Interrupt' : [ 0x0, ['__unnamed_16d8']],
'Memory' : [ 0x0, ['__unnamed_16d6']],
'Dma' : [ 0x0, ['__unnamed_16da']],
'DevicePrivate' : [ 0x0, ['__unnamed_16dc']],
'BusNumber' : [ 0x0, ['__unnamed_16de']],
'DeviceSpecificData' : [ 0x0, ['__unnamed_16e0']],
} ],
'_CM_PARTIAL_RESOURCE_DESCRIPTOR' : [ 0x14, {
'Type' : [ 0x0, ['unsigned char']],
'ShareDisposition' : [ 0x1, ['unsigned char']],
'Flags' : [ 0x2, ['unsigned short']],
'u' : [ 0x4, ['__unnamed_16e2']],
} ],
'_SYSPTES_HEADER' : [ 0x18, {
'ListHead' : [ 0x0, ['_LIST_ENTRY']],
'Count' : [ 0x10, ['unsigned long long']],
} ],
'_WAIT_CONTEXT_BLOCK' : [ 0x48, {
'WaitQueueEntry' : [ 0x0, ['_KDEVICE_QUEUE_ENTRY']],
'DeviceRoutine' : [ 0x18, ['pointer64', ['void']]],
'DeviceContext' : [ 0x20, ['pointer64', ['void']]],
'NumberOfMapRegisters' : [ 0x28, ['unsigned long']],
'DeviceObject' : [ 0x30, ['pointer64', ['void']]],
'CurrentIrp' : [ 0x38, ['pointer64', ['void']]],
'BufferChainingDpc' : [ 0x40, ['pointer64', ['_KDPC']]],
} ],
'_REQUEST_MAILBOX' : [ 0x40, {
'RequestSummary' : [ 0x0, ['long long']],
'RequestPacket' : [ 0x8, ['_KREQUEST_PACKET']],
'Virtual' : [ 0x8, ['array', 7, ['pointer64', ['void']]]],
} ],
'_CM_KEY_CONTROL_BLOCK' : [ 0xb0, {
'RefCount' : [ 0x0, ['unsigned long']],
'ExtFlags' : [ 0x4, ['BitField', dict(start_bit = 0, end_bit = 8, native_type='unsigned long')]],
'PrivateAlloc' : [ 0x4, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long')]],
'Delete' : [ 0x4, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long')]],
'DelayedCloseIndex' : [ 0x4, ['BitField', dict(start_bit = 10, end_bit = 22, native_type='unsigned long')]],
'TotalLevels' : [ 0x4, ['BitField', dict(start_bit = 22, end_bit = 32, native_type='unsigned long')]],
'KeyHash' : [ 0x8, ['_CM_KEY_HASH']],
'ConvKey' : [ 0x8, ['unsigned long']],
'NextHash' : [ 0x10, ['pointer64', ['_CM_KEY_HASH']]],
'KeyHive' : [ 0x18, ['pointer64', ['_HHIVE']]],
'KeyCell' : [ 0x20, ['unsigned long']],
'ParentKcb' : [ 0x28, ['pointer64', ['_CM_KEY_CONTROL_BLOCK']]],
'NameBlock' : [ 0x30, ['pointer64', ['_CM_NAME_CONTROL_BLOCK']]],
'CachedSecurity' : [ 0x38, ['pointer64', ['_CM_KEY_SECURITY_CACHE']]],
'ValueCache' : [ 0x40, ['_CACHED_CHILD_LIST']],
'IndexHint' : [ 0x50, ['pointer64', ['_CM_INDEX_HINT_BLOCK']]],
'HashKey' : [ 0x50, ['unsigned long']],
'SubKeyCount' : [ 0x50, ['unsigned long']],
'KeyBodyListHead' : [ 0x58, ['_LIST_ENTRY']],
'FreeListEntry' : [ 0x58, ['_LIST_ENTRY']],
'KeyBodyArray' : [ 0x68, ['array', 4, ['pointer64', ['_CM_KEY_BODY']]]],
'DelayCloseEntry' : [ 0x88, ['pointer64', ['void']]],
'KcbLastWriteTime' : [ 0x90, ['_LARGE_INTEGER']],
'KcbMaxNameLen' : [ 0x98, ['unsigned short']],
'KcbMaxValueNameLen' : [ 0x9a, ['unsigned short']],
'KcbMaxValueDataLen' : [ 0x9c, ['unsigned long']],
'KcbUserFlags' : [ 0xa0, ['BitField', dict(start_bit = 0, end_bit = 4, native_type='unsigned long')]],
'KcbVirtControlFlags' : [ 0xa0, ['BitField', dict(start_bit = 4, end_bit = 8, native_type='unsigned long')]],
'KcbDebug' : [ 0xa0, ['BitField', dict(start_bit = 8, end_bit = 16, native_type='unsigned long')]],
'Flags' : [ 0xa0, ['BitField', dict(start_bit = 16, end_bit = 32, native_type='unsigned long')]],
'RealKeyName' : [ 0xa8, ['pointer64', ['unsigned char']]],
} ],
'_M128A' : [ 0x10, {
'Low' : [ 0x0, ['unsigned long long']],
'High' : [ 0x8, ['long long']],
} ],
'_PCI_BUS_INTERFACE_STANDARD' : [ 0x40, {
'Size' : [ 0x0, ['unsigned short']],
'Version' : [ 0x2, ['unsigned short']],
'Context' : [ 0x8, ['pointer64', ['void']]],
'InterfaceReference' : [ 0x10, ['pointer64', ['void']]],
'InterfaceDereference' : [ 0x18, ['pointer64', ['void']]],
'ReadConfig' : [ 0x20, ['pointer64', ['void']]],
'WriteConfig' : [ 0x28, ['pointer64', ['void']]],
'PinToLine' : [ 0x30, ['pointer64', ['void']]],
'LineToPin' : [ 0x38, ['pointer64', ['void']]],
} ],
'_WORK_QUEUE_ITEM' : [ 0x20, {
'List' : [ 0x0, ['_LIST_ENTRY']],
'WorkerRoutine' : [ 0x10, ['pointer64', ['void']]],
'Parameter' : [ 0x18, ['pointer64', ['void']]],
} ],
'_PI_RESOURCE_ARBITER_ENTRY' : [ 0x70, {
'DeviceArbiterList' : [ 0x0, ['_LIST_ENTRY']],
'ResourceType' : [ 0x10, ['unsigned char']],
'ArbiterInterface' : [ 0x18, ['pointer64', ['_ARBITER_INTERFACE']]],
'Level' : [ 0x20, ['unsigned long']],
'ResourceList' : [ 0x28, ['_LIST_ENTRY']],
'BestResourceList' : [ 0x38, ['_LIST_ENTRY']],
'BestConfig' : [ 0x48, ['_LIST_ENTRY']],
'ActiveArbiterList' : [ 0x58, ['_LIST_ENTRY']],
'State' : [ 0x68, ['unsigned char']],
'ResourcesChanged' : [ 0x69, ['unsigned char']],
} ],
'_SEP_AUDIT_POLICY_CATEGORIES' : [ 0x8, {
'System' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 4, native_type='unsigned long')]],
'Logon' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 8, native_type='unsigned long')]],
'ObjectAccess' : [ 0x0, ['BitField', dict(start_bit = 8, end_bit = 12, native_type='unsigned long')]],
'PrivilegeUse' : [ 0x0, ['BitField', dict(start_bit = 12, end_bit = 16, native_type='unsigned long')]],
'DetailedTracking' : [ 0x0, ['BitField', dict(start_bit = 16, end_bit = 20, native_type='unsigned long')]],
'PolicyChange' : [ 0x0, ['BitField', dict(start_bit = 20, end_bit = 24, native_type='unsigned long')]],
'AccountManagement' : [ 0x0, ['BitField', dict(start_bit = 24, end_bit = 28, native_type='unsigned long')]],
'DirectoryServiceAccess' : [ 0x0, ['BitField', dict(start_bit = 28, end_bit = 32, native_type='unsigned long')]],
'AccountLogon' : [ 0x4, ['BitField', dict(start_bit = 0, end_bit = 4, native_type='unsigned long')]],
} ],
'_CM_KEY_HASH' : [ 0x20, {
'ConvKey' : [ 0x0, ['unsigned long']],
'NextHash' : [ 0x8, ['pointer64', ['_CM_KEY_HASH']]],
'KeyHive' : [ 0x10, ['pointer64', ['_HHIVE']]],
'KeyCell' : [ 0x18, ['unsigned long']],
} ],
'__unnamed_1726' : [ 0x8, {
'MasterIrp' : [ 0x0, ['pointer64', ['_IRP']]],
'IrpCount' : [ 0x0, ['long']],
'SystemBuffer' : [ 0x0, ['pointer64', ['void']]],
} ],
'__unnamed_172b' : [ 0x10, {
'UserApcRoutine' : [ 0x0, ['pointer64', ['void']]],
'UserApcContext' : [ 0x8, ['pointer64', ['void']]],
} ],
'__unnamed_172d' : [ 0x10, {
'AsynchronousParameters' : [ 0x0, ['__unnamed_172b']],
'AllocationSize' : [ 0x0, ['_LARGE_INTEGER']],
} ],
'__unnamed_1735' : [ 0x50, {
'DeviceQueueEntry' : [ 0x0, ['_KDEVICE_QUEUE_ENTRY']],
'DriverContext' : [ 0x0, ['array', 4, ['pointer64', ['void']]]],
'Thread' : [ 0x20, ['pointer64', ['_ETHREAD']]],
'AuxiliaryBuffer' : [ 0x28, ['pointer64', ['unsigned char']]],
'ListEntry' : [ 0x30, ['_LIST_ENTRY']],
'CurrentStackLocation' : [ 0x40, ['pointer64', ['_IO_STACK_LOCATION']]],
'PacketType' : [ 0x40, ['unsigned long']],
'OriginalFileObject' : [ 0x48, ['pointer64', ['_FILE_OBJECT']]],
} ],
'__unnamed_1737' : [ 0x58, {
'Overlay' : [ 0x0, ['__unnamed_1735']],
'Apc' : [ 0x0, ['_KAPC']],
'CompletionKey' : [ 0x0, ['pointer64', ['void']]],
} ],
'_IRP' : [ 0xd0, {
'Type' : [ 0x0, ['short']],
'Size' : [ 0x2, ['unsigned short']],
'MdlAddress' : [ 0x8, ['pointer64', ['_MDL']]],
'Flags' : [ 0x10, ['unsigned long']],
'AssociatedIrp' : [ 0x18, ['__unnamed_1726']],
'ThreadListEntry' : [ 0x20, ['_LIST_ENTRY']],
'IoStatus' : [ 0x30, ['_IO_STATUS_BLOCK']],
'RequestorMode' : [ 0x40, ['unsigned char']],
'PendingReturned' : [ 0x41, ['unsigned char']],
'StackCount' : [ 0x42, ['unsigned char']],
'CurrentLocation' : [ 0x43, ['unsigned char']],
'Cancel' : [ 0x44, ['unsigned char']],
'CancelIrql' : [ 0x45, ['unsigned char']],
'ApcEnvironment' : [ 0x46, ['unsigned char']],
'AllocationFlags' : [ 0x47, ['unsigned char']],
'UserIosb' : [ 0x48, ['pointer64', ['_IO_STATUS_BLOCK']]],
'UserEvent' : [ 0x50, ['pointer64', ['_KEVENT']]],
'Overlay' : [ 0x58, ['__unnamed_172d']],
'CancelRoutine' : [ 0x68, ['pointer64', ['void']]],
'UserBuffer' : [ 0x70, ['pointer64', ['void']]],
'Tail' : [ 0x78, ['__unnamed_1737']],
} ],
'_PCI_LOCK' : [ 0x10, {
'Atom' : [ 0x0, ['unsigned long long']],
'OldIrql' : [ 0x8, ['unsigned char']],
} ],
'_CM_KEY_SECURITY_CACHE_ENTRY' : [ 0x10, {
'Cell' : [ 0x0, ['unsigned long']],
'CachedSecurity' : [ 0x8, ['pointer64', ['_CM_KEY_SECURITY_CACHE']]],
} ],
'_GDI_TEB_BATCH32' : [ 0x4e0, {
'Offset' : [ 0x0, ['unsigned long']],
'HDC' : [ 0x4, ['unsigned long']],
'Buffer' : [ 0x8, ['array', 310, ['unsigned long']]],
} ],
'__unnamed_1744' : [ 0x4, {
'PhysicalAddress' : [ 0x0, ['unsigned long']],
'VirtualSize' : [ 0x0, ['unsigned long']],
} ],
'_IMAGE_SECTION_HEADER' : [ 0x28, {
'Name' : [ 0x0, ['array', 8, ['unsigned char']]],
'Misc' : [ 0x8, ['__unnamed_1744']],
'VirtualAddress' : [ 0xc, ['unsigned long']],
'SizeOfRawData' : [ 0x10, ['unsigned long']],
'PointerToRawData' : [ 0x14, ['unsigned long']],
'PointerToRelocations' : [ 0x18, ['unsigned long']],
'PointerToLinenumbers' : [ 0x1c, ['unsigned long']],
'NumberOfRelocations' : [ 0x20, ['unsigned short']],
'NumberOfLinenumbers' : [ 0x22, ['unsigned short']],
'Characteristics' : [ 0x24, ['unsigned long']],
} ],
'__unnamed_174a' : [ 0x4, {
'Level' : [ 0x0, ['unsigned long']],
} ],
'_POP_ACTION_TRIGGER' : [ 0x10, {
'Type' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'PolicyDeviceSystemButton', 1: 'PolicyDeviceThermalZone', 2: 'PolicyDeviceBattery', 3: 'PolicyInitiatePowerActionAPI', 4: 'PolicySetPowerStateAPI', 5: 'PolicyImmediateDozeS4', 6: 'PolicySystemIdle'})]],
'Flags' : [ 0x4, ['unsigned char']],
'Spare' : [ 0x5, ['array', 3, ['unsigned char']]],
'Battery' : [ 0x8, ['__unnamed_174a']],
'Wait' : [ 0x8, ['pointer64', ['_POP_TRIGGER_WAIT']]],
} ],
'_ETIMER' : [ 0x108, {
'KeTimer' : [ 0x0, ['_KTIMER']],
'TimerApc' : [ 0x40, ['_KAPC']],
'TimerDpc' : [ 0x98, ['_KDPC']],
'ActiveTimerListEntry' : [ 0xd8, ['_LIST_ENTRY']],
'Lock' : [ 0xe8, ['unsigned long long']],
'Period' : [ 0xf0, ['long']],
'ApcAssociated' : [ 0xf4, ['unsigned char']],
'WakeTimer' : [ 0xf5, ['unsigned char']],
'WakeTimerListEntry' : [ 0xf8, ['_LIST_ENTRY']],
} ],
'_DBGKD_BREAKPOINTEX' : [ 0x8, {
'BreakPointCount' : [ 0x0, ['unsigned long']],
'ContinueStatus' : [ 0x4, ['long']],
} ],
'_IMAGE_OPTIONAL_HEADER64' : [ 0xf0, {
'Magic' : [ 0x0, ['unsigned short']],
'MajorLinkerVersion' : [ 0x2, ['unsigned char']],
'MinorLinkerVersion' : [ 0x3, ['unsigned char']],
'SizeOfCode' : [ 0x4, ['unsigned long']],
'SizeOfInitializedData' : [ 0x8, ['unsigned long']],
'SizeOfUninitializedData' : [ 0xc, ['unsigned long']],
'AddressOfEntryPoint' : [ 0x10, ['unsigned long']],
'BaseOfCode' : [ 0x14, ['unsigned long']],
'ImageBase' : [ 0x18, ['unsigned long long']],
'SectionAlignment' : [ 0x20, ['unsigned long']],
'FileAlignment' : [ 0x24, ['unsigned long']],
'MajorOperatingSystemVersion' : [ 0x28, ['unsigned short']],
'MinorOperatingSystemVersion' : [ 0x2a, ['unsigned short']],
'MajorImageVersion' : [ 0x2c, ['unsigned short']],
'MinorImageVersion' : [ 0x2e, ['unsigned short']],
'MajorSubsystemVersion' : [ 0x30, ['unsigned short']],
'MinorSubsystemVersion' : [ 0x32, ['unsigned short']],
'Win32VersionValue' : [ 0x34, ['unsigned long']],
'SizeOfImage' : [ 0x38, ['unsigned long']],
'SizeOfHeaders' : [ 0x3c, ['unsigned long']],
'CheckSum' : [ 0x40, ['unsigned long']],
'Subsystem' : [ 0x44, ['unsigned short']],
'DllCharacteristics' : [ 0x46, ['unsigned short']],
'SizeOfStackReserve' : [ 0x48, ['unsigned long long']],
'SizeOfStackCommit' : [ 0x50, ['unsigned long long']],
'SizeOfHeapReserve' : [ 0x58, ['unsigned long long']],
'SizeOfHeapCommit' : [ 0x60, ['unsigned long long']],
'LoaderFlags' : [ 0x68, ['unsigned long']],
'NumberOfRvaAndSizes' : [ 0x6c, ['unsigned long']],
'DataDirectory' : [ 0x70, ['array', 16, ['_IMAGE_DATA_DIRECTORY']]],
} ],
'_CM_CELL_REMAP_BLOCK' : [ 0x8, {
'OldCell' : [ 0x0, ['unsigned long']],
'NewCell' : [ 0x4, ['unsigned long']],
} ],
'_PCI_PMC' : [ 0x2, {
'Version' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 3, native_type='unsigned char')]],
'PMEClock' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned char')]],
'Rsvd1' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned char')]],
'DeviceSpecificInitialization' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned char')]],
'Rsvd2' : [ 0x0, ['BitField', dict(start_bit = 6, end_bit = 8, native_type='unsigned char')]],
'Support' : [ 0x1, ['_PM_SUPPORT']],
} ],
'_DBGKD_CONTINUE' : [ 0x4, {
'ContinueStatus' : [ 0x0, ['long']],
} ],
'__unnamed_1764' : [ 0x8, {
'VirtualAddress' : [ 0x0, ['pointer64', ['void']]],
'Long' : [ 0x0, ['unsigned long long']],
'e1' : [ 0x0, ['_MMWSLENTRY']],
} ],
'_MMWSLE' : [ 0x8, {
'u1' : [ 0x0, ['__unnamed_1764']],
} ],
'_EXCEPTION_POINTERS' : [ 0x10, {
'ExceptionRecord' : [ 0x0, ['pointer64', ['_EXCEPTION_RECORD']]],
'ContextRecord' : [ 0x8, ['pointer64', ['_CONTEXT']]],
} ],
'__unnamed_176c' : [ 0x8, {
'Balance' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 2, native_type='long long')]],
'Parent' : [ 0x0, ['pointer64', ['_MMADDRESS_NODE']]],
} ],
'_MMADDRESS_NODE' : [ 0x28, {
'u1' : [ 0x0, ['__unnamed_176c']],
'LeftChild' : [ 0x8, ['pointer64', ['_MMADDRESS_NODE']]],
'RightChild' : [ 0x10, ['pointer64', ['_MMADDRESS_NODE']]],
'StartingVpn' : [ 0x18, ['unsigned long long']],
'EndingVpn' : [ 0x20, ['unsigned long long']],
} ],
'_RTL_USER_PROCESS_PARAMETERS' : [ 0x3f0, {
'MaximumLength' : [ 0x0, ['unsigned long']],
'Length' : [ 0x4, ['unsigned long']],
'Flags' : [ 0x8, ['unsigned long']],
'DebugFlags' : [ 0xc, ['unsigned long']],
'ConsoleHandle' : [ 0x10, ['pointer64', ['void']]],
'ConsoleFlags' : [ 0x18, ['unsigned long']],
'StandardInput' : [ 0x20, ['pointer64', ['void']]],
'StandardOutput' : [ 0x28, ['pointer64', ['void']]],
'StandardError' : [ 0x30, ['pointer64', ['void']]],
'CurrentDirectory' : [ 0x38, ['_CURDIR']],
'DllPath' : [ 0x50, ['_UNICODE_STRING']],
'ImagePathName' : [ 0x60, ['_UNICODE_STRING']],
'CommandLine' : [ 0x70, ['_UNICODE_STRING']],
'Environment' : [ 0x80, ['pointer64', ['void']]],
'StartingX' : [ 0x88, ['unsigned long']],
'StartingY' : [ 0x8c, ['unsigned long']],
'CountX' : [ 0x90, ['unsigned long']],
'CountY' : [ 0x94, ['unsigned long']],
'CountCharsX' : [ 0x98, ['unsigned long']],
'CountCharsY' : [ 0x9c, ['unsigned long']],
'FillAttribute' : [ 0xa0, ['unsigned long']],
'WindowFlags' : [ 0xa4, ['unsigned long']],
'ShowWindowFlags' : [ 0xa8, ['unsigned long']],
'WindowTitle' : [ 0xb0, ['_UNICODE_STRING']],
'DesktopInfo' : [ 0xc0, ['_UNICODE_STRING']],
'ShellInfo' : [ 0xd0, ['_UNICODE_STRING']],
'RuntimeData' : [ 0xe0, ['_UNICODE_STRING']],
'CurrentDirectores' : [ 0xf0, ['array', 32, ['_RTL_DRIVE_LETTER_CURDIR']]],
} ],
'_CACHE_MANAGER_CALLBACKS' : [ 0x20, {
'AcquireForLazyWrite' : [ 0x0, ['pointer64', ['void']]],
'ReleaseFromLazyWrite' : [ 0x8, ['pointer64', ['void']]],
'AcquireForReadAhead' : [ 0x10, ['pointer64', ['void']]],
'ReleaseFromReadAhead' : [ 0x18, ['pointer64', ['void']]],
} ],
'_KSPECIAL_REGISTERS' : [ 0xd8, {
'Cr0' : [ 0x0, ['unsigned long long']],
'Cr2' : [ 0x8, ['unsigned long long']],
'Cr3' : [ 0x10, ['unsigned long long']],
'Cr4' : [ 0x18, ['unsigned long long']],
'KernelDr0' : [ 0x20, ['unsigned long long']],
'KernelDr1' : [ 0x28, ['unsigned long long']],
'KernelDr2' : [ 0x30, ['unsigned long long']],
'KernelDr3' : [ 0x38, ['unsigned long long']],
'KernelDr6' : [ 0x40, ['unsigned long long']],
'KernelDr7' : [ 0x48, ['unsigned long long']],
'Gdtr' : [ 0x50, ['_KDESCRIPTOR']],
'Idtr' : [ 0x60, ['_KDESCRIPTOR']],
'Tr' : [ 0x70, ['unsigned short']],
'Ldtr' : [ 0x72, ['unsigned short']],
'MxCsr' : [ 0x74, ['unsigned long']],
'DebugControl' : [ 0x78, ['unsigned long long']],
'LastBranchToRip' : [ 0x80, ['unsigned long long']],
'LastBranchFromRip' : [ 0x88, ['unsigned long long']],
'LastExceptionToRip' : [ 0x90, ['unsigned long long']],
'LastExceptionFromRip' : [ 0x98, ['unsigned long long']],
'Cr8' : [ 0xa0, ['unsigned long long']],
'MsrGsBase' : [ 0xa8, ['unsigned long long']],
'MsrGsSwap' : [ 0xb0, ['unsigned long long']],
'MsrStar' : [ 0xb8, ['unsigned long long']],
'MsrLStar' : [ 0xc0, ['unsigned long long']],
'MsrCStar' : [ 0xc8, ['unsigned long long']],
'MsrSyscallMask' : [ 0xd0, ['unsigned long long']],
} ],
'_CELL_DATA' : [ 0x50, {
'u' : [ 0x0, ['_u']],
} ],
'_SE_AUDIT_PROCESS_CREATION_INFO' : [ 0x8, {
'ImageFileName' : [ 0x0, ['pointer64', ['_OBJECT_NAME_INFORMATION']]],
} ],
'_HEAP_ENTRY_EXTRA' : [ 0x10, {
'AllocatorBackTraceIndex' : [ 0x0, ['unsigned short']],
'TagIndex' : [ 0x2, ['unsigned short']],
'Settable' : [ 0x8, ['unsigned long long']],
'ZeroInit' : [ 0x0, ['unsigned long long']],
'ZeroInit1' : [ 0x8, ['unsigned long long']],
} ],
'_VI_DEADLOCK_RESOURCE' : [ 0xf8, {
'Type' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'VfDeadlockUnknown', 1: 'VfDeadlockMutex', 2: 'VfDeadlockMutexAbandoned', 3: 'VfDeadlockFastMutex', 4: 'VfDeadlockFastMutexUnsafe', 5: 'VfDeadlockSpinLock', 6: 'VfDeadlockQueuedSpinLock', 7: 'VfDeadlockTypeMaximum'})]],
'NodeCount' : [ 0x4, ['BitField', dict(start_bit = 0, end_bit = 16, native_type='unsigned long')]],
'RecursionCount' : [ 0x4, ['BitField', dict(start_bit = 16, end_bit = 32, native_type='unsigned long')]],
'ResourceAddress' : [ 0x8, ['pointer64', ['void']]],
'ThreadOwner' : [ 0x10, ['pointer64', ['_VI_DEADLOCK_THREAD']]],
'ResourceList' : [ 0x18, ['_LIST_ENTRY']],
'HashChainList' : [ 0x28, ['_LIST_ENTRY']],
'FreeListEntry' : [ 0x28, ['_LIST_ENTRY']],
'StackTrace' : [ 0x38, ['array', 8, ['pointer64', ['void']]]],
'LastAcquireTrace' : [ 0x78, ['array', 8, ['pointer64', ['void']]]],
'LastReleaseTrace' : [ 0xb8, ['array', 8, ['pointer64', ['void']]]],
} ],
'_OBJECT_HANDLE_COUNT_ENTRY' : [ 0x10, {
'Process' : [ 0x0, ['pointer64', ['_EPROCESS']]],
'HandleCount' : [ 0x8, ['unsigned long']],
} ],
'_CLIENT_ID' : [ 0x10, {
'UniqueProcess' : [ 0x0, ['pointer64', ['void']]],
'UniqueThread' : [ 0x8, ['pointer64', ['void']]],
} ],
'_PEB_FREE_BLOCK' : [ 0x10, {
'Next' : [ 0x0, ['pointer64', ['_PEB_FREE_BLOCK']]],
'Size' : [ 0x8, ['unsigned long']],
} ],
'_PO_DEVICE_NOTIFY' : [ 0x48, {
'Link' : [ 0x0, ['_LIST_ENTRY']],
'TargetDevice' : [ 0x10, ['pointer64', ['_DEVICE_OBJECT']]],
'WakeNeeded' : [ 0x18, ['unsigned char']],
'OrderLevel' : [ 0x19, ['unsigned char']],
'DeviceObject' : [ 0x20, ['pointer64', ['_DEVICE_OBJECT']]],
'Node' : [ 0x28, ['pointer64', ['void']]],
'DeviceName' : [ 0x30, ['pointer64', ['unsigned short']]],
'DriverName' : [ 0x38, ['pointer64', ['unsigned short']]],
'ChildCount' : [ 0x40, ['unsigned long']],
'ActiveChild' : [ 0x44, ['unsigned long']],
} ],
'_MMPFNLIST' : [ 0x20, {
'Total' : [ 0x0, ['unsigned long long']],
'ListName' : [ 0x8, ['Enumeration', dict(target = 'long', choices = {0: 'ZeroedPageList', 1: 'FreePageList', 2: 'StandbyPageList', 3: 'ModifiedPageList', 4: 'ModifiedNoWritePageList', 5: 'BadPageList', 6: 'ActiveAndValid', 7: 'TransitionPage'})]],
'Flink' : [ 0x10, ['unsigned long long']],
'Blink' : [ 0x18, ['unsigned long long']],
} ],
'__unnamed_1795' : [ 0x4, {
'Spare' : [ 0x0, ['array', 4, ['unsigned char']]],
} ],
'__unnamed_1797' : [ 0x4, {
'PrimaryBus' : [ 0x0, ['unsigned char']],
'SecondaryBus' : [ 0x1, ['unsigned char']],
'SubordinateBus' : [ 0x2, ['unsigned char']],
'SubtractiveDecode' : [ 0x3, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]],
'IsaBitSet' : [ 0x3, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned char')]],
'VgaBitSet' : [ 0x3, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned char')]],
'WeChangedBusNumbers' : [ 0x3, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned char')]],
'IsaBitRequired' : [ 0x3, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned char')]],
} ],
'PCI_HEADER_TYPE_DEPENDENT' : [ 0x4, {
'type0' : [ 0x0, ['__unnamed_1795']],
'type1' : [ 0x0, ['__unnamed_1797']],
'type2' : [ 0x0, ['__unnamed_1797']],
} ],
'_DBGKD_GET_SET_BUS_DATA' : [ 0x14, {
'BusDataType' : [ 0x0, ['unsigned long']],
'BusNumber' : [ 0x4, ['unsigned long']],
'SlotNumber' : [ 0x8, ['unsigned long']],
'Offset' : [ 0xc, ['unsigned long']],
'Length' : [ 0x10, ['unsigned long']],
} ],
'_KINTERRUPT' : [ 0x80, {
'Type' : [ 0x0, ['short']],
'Size' : [ 0x2, ['short']],
'InterruptListEntry' : [ 0x8, ['_LIST_ENTRY']],
'ServiceRoutine' : [ 0x18, ['pointer64', ['void']]],
'ServiceContext' : [ 0x20, ['pointer64', ['void']]],
'SpinLock' : [ 0x28, ['unsigned long long']],
'TickCount' : [ 0x30, ['unsigned long']],
'ActualLock' : [ 0x38, ['pointer64', ['unsigned long long']]],
'DispatchAddress' : [ 0x40, ['pointer64', ['void']]],
'Vector' : [ 0x48, ['unsigned long']],
'Irql' : [ 0x4c, ['unsigned char']],
'SynchronizeIrql' : [ 0x4d, ['unsigned char']],
'FloatingSave' : [ 0x4e, ['unsigned char']],
'Connected' : [ 0x4f, ['unsigned char']],
'Number' : [ 0x50, ['unsigned char']],
'ShareVector' : [ 0x51, ['unsigned char']],
'Mode' : [ 0x54, ['Enumeration', dict(target = 'long', choices = {0: 'LevelSensitive', 1: 'Latched'})]],
'ServiceCount' : [ 0x58, ['unsigned long']],
'DispatchCount' : [ 0x5c, ['unsigned long']],
'TrapFrame' : [ 0x60, ['pointer64', ['_KTRAP_FRAME']]],
'Reserved' : [ 0x68, ['pointer64', ['void']]],
'DispatchCode' : [ 0x70, ['array', 4, ['unsigned long']]],
} ],
'_SECURITY_CLIENT_CONTEXT' : [ 0x48, {
'SecurityQos' : [ 0x0, ['_SECURITY_QUALITY_OF_SERVICE']],
'ClientToken' : [ 0x10, ['pointer64', ['void']]],
'DirectlyAccessClientToken' : [ 0x18, ['unsigned char']],
'DirectAccessEffectiveOnly' : [ 0x19, ['unsigned char']],
'ServerIsRemote' : [ 0x1a, ['unsigned char']],
'ClientTokenControl' : [ 0x1c, ['_TOKEN_CONTROL']],
} ],
'_BITMAP_RANGE' : [ 0x30, {
'Links' : [ 0x0, ['_LIST_ENTRY']],
'BasePage' : [ 0x10, ['long long']],
'FirstDirtyPage' : [ 0x18, ['unsigned long']],
'LastDirtyPage' : [ 0x1c, ['unsigned long']],
'DirtyPages' : [ 0x20, ['unsigned long']],
'Bitmap' : [ 0x28, ['pointer64', ['unsigned long']]],
} ],
'_PCI_ARBITER_INSTANCE' : [ 0x190, {
'Header' : [ 0x0, ['PCI_SECONDARY_EXTENSION']],
'Interface' : [ 0x18, ['pointer64', ['_PCI_INTERFACE']]],
'BusFdoExtension' : [ 0x20, ['pointer64', ['_PCI_FDO_EXTENSION']]],
'InstanceName' : [ 0x28, ['array', 24, ['unsigned short']]],
'CommonInstance' : [ 0x58, ['_ARBITER_INSTANCE']],
} ],
'_NT_TIB64' : [ 0x38, {
'ExceptionList' : [ 0x0, ['unsigned long long']],
'StackBase' : [ 0x8, ['unsigned long long']],
'StackLimit' : [ 0x10, ['unsigned long long']],
'SubSystemTib' : [ 0x18, ['unsigned long long']],
'FiberData' : [ 0x20, ['unsigned long long']],
'Version' : [ 0x20, ['unsigned long']],
'ArbitraryUserPointer' : [ 0x28, ['unsigned long long']],
'Self' : [ 0x30, ['unsigned long long']],
} ],
'_HANDLE_TRACE_DB_ENTRY' : [ 0xa0, {
'ClientId' : [ 0x0, ['_CLIENT_ID']],
'Handle' : [ 0x10, ['pointer64', ['void']]],
'Type' : [ 0x18, ['unsigned long']],
'StackTrace' : [ 0x20, ['array', 16, ['pointer64', ['void']]]],
} ],
'_BUS_EXTENSION_LIST' : [ 0x10, {
'Next' : [ 0x0, ['pointer64', ['void']]],
'BusExtension' : [ 0x8, ['pointer64', ['_PI_BUS_EXTENSION']]],
} ],
'_PCI_MJ_DISPATCH_TABLE' : [ 0x40, {
'PnpIrpMaximumMinorFunction' : [ 0x0, ['unsigned long']],
'PnpIrpDispatchTable' : [ 0x8, ['pointer64', ['_PCI_MN_DISPATCH_TABLE']]],
'PowerIrpMaximumMinorFunction' : [ 0x10, ['unsigned long']],
'PowerIrpDispatchTable' : [ 0x18, ['pointer64', ['_PCI_MN_DISPATCH_TABLE']]],
'SystemControlIrpDispatchStyle' : [ 0x20, ['Enumeration', dict(target = 'long', choices = {0: 'IRP_COMPLETE', 1: 'IRP_DOWNWARD', 2: 'IRP_UPWARD', 3: 'IRP_DISPATCH'})]],
'SystemControlIrpDispatchFunction' : [ 0x28, ['pointer64', ['void']]],
'OtherIrpDispatchStyle' : [ 0x30, ['Enumeration', dict(target = 'long', choices = {0: 'IRP_COMPLETE', 1: 'IRP_DOWNWARD', 2: 'IRP_UPWARD', 3: 'IRP_DISPATCH'})]],
'OtherIrpDispatchFunction' : [ 0x38, ['pointer64', ['void']]],
} ],
'_POP_TRIGGER_WAIT' : [ 0x38, {
'Event' : [ 0x0, ['_KEVENT']],
'Status' : [ 0x18, ['long']],
'Link' : [ 0x20, ['_LIST_ENTRY']],
'Trigger' : [ 0x30, ['pointer64', ['_POP_ACTION_TRIGGER']]],
} ],
'_IO_TIMER' : [ 0x30, {
'Type' : [ 0x0, ['short']],
'TimerFlag' : [ 0x2, ['short']],
'TimerList' : [ 0x8, ['_LIST_ENTRY']],
'TimerRoutine' : [ 0x18, ['pointer64', ['void']]],
'Context' : [ 0x20, ['pointer64', ['void']]],
'DeviceObject' : [ 0x28, ['pointer64', ['_DEVICE_OBJECT']]],
} ],
'_MMWSLENTRY' : [ 0x8, {
'Valid' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long long')]],
'LockedInWs' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long long')]],
'LockedInMemory' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long long')]],
'Protection' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 8, native_type='unsigned long long')]],
'Hashed' : [ 0x0, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long long')]],
'Direct' : [ 0x0, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long long')]],
'Age' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 12, native_type='unsigned long long')]],
'VirtualPageNumber' : [ 0x0, ['BitField', dict(start_bit = 12, end_bit = 64, native_type='unsigned long long')]],
} ],
'__unnamed_17da' : [ 0x4, {
'BaseMiddle' : [ 0x0, ['unsigned char']],
'Flags1' : [ 0x1, ['unsigned char']],
'Flags2' : [ 0x2, ['unsigned char']],
'BaseHigh' : [ 0x3, ['unsigned char']],
} ],
'__unnamed_17de' : [ 0x4, {
'BaseMiddle' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 8, native_type='unsigned long')]],
'Type' : [ 0x0, ['BitField', dict(start_bit = 8, end_bit = 13, native_type='unsigned long')]],
'Dpl' : [ 0x0, ['BitField', dict(start_bit = 13, end_bit = 15, native_type='unsigned long')]],
'Present' : [ 0x0, ['BitField', dict(start_bit = 15, end_bit = 16, native_type='unsigned long')]],
'LimitHigh' : [ 0x0, ['BitField', dict(start_bit = 16, end_bit = 20, native_type='unsigned long')]],
'System' : [ 0x0, ['BitField', dict(start_bit = 20, end_bit = 21, native_type='unsigned long')]],
'LongMode' : [ 0x0, ['BitField', dict(start_bit = 21, end_bit = 22, native_type='unsigned long')]],
'DefaultBig' : [ 0x0, ['BitField', dict(start_bit = 22, end_bit = 23, native_type='unsigned long')]],
'Granularity' : [ 0x0, ['BitField', dict(start_bit = 23, end_bit = 24, native_type='unsigned long')]],
'BaseHigh' : [ 0x0, ['BitField', dict(start_bit = 24, end_bit = 32, native_type='unsigned long')]],
} ],
'_KGDTENTRY64' : [ 0x10, {
'LimitLow' : [ 0x0, ['unsigned short']],
'BaseLow' : [ 0x2, ['unsigned short']],
'Bytes' : [ 0x4, ['__unnamed_17da']],
'Bits' : [ 0x4, ['__unnamed_17de']],
'BaseUpper' : [ 0x8, ['unsigned long']],
'MustBeZero' : [ 0xc, ['unsigned long']],
'Alignment' : [ 0x0, ['unsigned long long']],
} ],
'_OBJECT_DIRECTORY' : [ 0x140, {
'HashBuckets' : [ 0x0, ['array', 37, ['pointer64', ['_OBJECT_DIRECTORY_ENTRY']]]],
'Lock' : [ 0x128, ['_EX_PUSH_LOCK']],
'DeviceMap' : [ 0x130, ['pointer64', ['_DEVICE_MAP']]],
'SessionId' : [ 0x138, ['unsigned long']],
} ],
'_WMI_CLIENT_CONTEXT' : [ 0x4, {
'ProcessorNumber' : [ 0x0, ['unsigned char']],
'Alignment' : [ 0x1, ['unsigned char']],
'LoggerId' : [ 0x2, ['unsigned short']],
} ],
'_HEAP_LOOKASIDE' : [ 0x40, {
'ListHead' : [ 0x0, ['_SLIST_HEADER']],
'Depth' : [ 0x10, ['unsigned short']],
'MaximumDepth' : [ 0x12, ['unsigned short']],
'TotalAllocates' : [ 0x14, ['unsigned long']],
'AllocateMisses' : [ 0x18, ['unsigned long']],
'TotalFrees' : [ 0x1c, ['unsigned long']],
'FreeMisses' : [ 0x20, ['unsigned long']],
'LastTotalAllocates' : [ 0x24, ['unsigned long']],
'LastAllocateMisses' : [ 0x28, ['unsigned long']],
'Counters' : [ 0x2c, ['array', 2, ['unsigned long']]],
} ],
'_CLIENT_ID64' : [ 0x10, {
'UniqueProcess' : [ 0x0, ['unsigned long long']],
'UniqueThread' : [ 0x8, ['unsigned long long']],
} ],
'_KDPC_DATA' : [ 0x20, {
'DpcListHead' : [ 0x0, ['_LIST_ENTRY']],
'DpcLock' : [ 0x10, ['unsigned long long']],
'DpcQueueDepth' : [ 0x18, ['long']],
'DpcCount' : [ 0x1c, ['unsigned long']],
} ],
'_ARBITER_INTERFACE' : [ 0x30, {
'Size' : [ 0x0, ['unsigned short']],
'Version' : [ 0x2, ['unsigned short']],
'Context' : [ 0x8, ['pointer64', ['void']]],
'InterfaceReference' : [ 0x10, ['pointer64', ['void']]],
'InterfaceDereference' : [ 0x18, ['pointer64', ['void']]],
'ArbiterHandler' : [ 0x20, ['pointer64', ['void']]],
'Flags' : [ 0x28, ['unsigned long']],
} ],
'_AMD64_DBGKD_CONTROL_SET' : [ 0x1c, {
'TraceFlag' : [ 0x0, ['unsigned long']],
'Dr7' : [ 0x4, ['unsigned long long']],
'CurrentSymbolStart' : [ 0xc, ['unsigned long long']],
'CurrentSymbolEnd' : [ 0x14, ['unsigned long long']],
} ],
'_CALL_PERFORMANCE_DATA' : [ 0x408, {
'SpinLock' : [ 0x0, ['unsigned long long']],
'HashTable' : [ 0x8, ['array', 64, ['_LIST_ENTRY']]],
} ],
'_MMWSL' : [ 0x80, {
'FirstFree' : [ 0x0, ['unsigned long']],
'FirstDynamic' : [ 0x4, ['unsigned long']],
'LastEntry' : [ 0x8, ['unsigned long']],
'NextSlot' : [ 0xc, ['unsigned long']],
'Wsle' : [ 0x10, ['pointer64', ['_MMWSLE']]],
'LastInitializedWsle' : [ 0x18, ['unsigned long']],
'NonDirectCount' : [ 0x1c, ['unsigned long']],
'HashTable' : [ 0x20, ['pointer64', ['_MMWSLE_HASH']]],
'HashTableSize' : [ 0x28, ['unsigned long']],
'NumberOfCommittedPageTables' : [ 0x2c, ['unsigned long']],
'HashTableStart' : [ 0x30, ['pointer64', ['void']]],
'HighestPermittedHashAddress' : [ 0x38, ['pointer64', ['void']]],
'NumberOfImageWaiters' : [ 0x40, ['unsigned long']],
'VadBitMapHint' : [ 0x44, ['unsigned long']],
'HighestUserAddress' : [ 0x48, ['pointer64', ['void']]],
'MaximumUserPageTablePages' : [ 0x50, ['unsigned long']],
'MaximumUserPageDirectoryPages' : [ 0x54, ['unsigned long']],
'CommittedPageTables' : [ 0x58, ['pointer64', ['unsigned long']]],
'NumberOfCommittedPageDirectories' : [ 0x60, ['unsigned long']],
'CommittedPageDirectories' : [ 0x68, ['pointer64', ['unsigned long']]],
'NumberOfCommittedPageDirectoryParents' : [ 0x70, ['unsigned long']],
'CommittedPageDirectoryParents' : [ 0x78, ['array', 1, ['unsigned long long']]],
} ],
'_ACTIVATION_CONTEXT_STACK' : [ 0x28, {
'ActiveFrame' : [ 0x0, ['pointer64', ['_RTL_ACTIVATION_CONTEXT_STACK_FRAME']]],
'FrameListCache' : [ 0x8, ['_LIST_ENTRY']],
'Flags' : [ 0x18, ['unsigned long']],
'NextCookieSequenceNumber' : [ 0x1c, ['unsigned long']],
'StackId' : [ 0x20, ['unsigned long']],
} ],
'_RTL_DRIVE_LETTER_CURDIR' : [ 0x18, {
'Flags' : [ 0x0, ['unsigned short']],
'Length' : [ 0x2, ['unsigned short']],
'TimeStamp' : [ 0x4, ['unsigned long']],
'DosPath' : [ 0x8, ['_STRING']],
} ],
'PCI_FUNCTION_RESOURCES' : [ 0x170, {
'Limit' : [ 0x0, ['array', 7, ['_IO_RESOURCE_DESCRIPTOR']]],
'Current' : [ 0xe0, ['array', 7, ['_CM_PARTIAL_RESOURCE_DESCRIPTOR']]],
} ],
'_WNODE_HEADER' : [ 0x30, {
'BufferSize' : [ 0x0, ['unsigned long']],
'ProviderId' : [ 0x4, ['unsigned long']],
'HistoricalContext' : [ 0x8, ['unsigned long long']],
'Version' : [ 0x8, ['unsigned long']],
'Linkage' : [ 0xc, ['unsigned long']],
'CountLost' : [ 0x10, ['unsigned long']],
'KernelHandle' : [ 0x10, ['pointer64', ['void']]],
'TimeStamp' : [ 0x10, ['_LARGE_INTEGER']],
'Guid' : [ 0x18, ['_GUID']],
'ClientContext' : [ 0x28, ['unsigned long']],
'Flags' : [ 0x2c, ['unsigned long']],
} ],
'__unnamed_1811' : [ 0x8, {
'ImageCommitment' : [ 0x0, ['unsigned long long']],
'CreatingProcess' : [ 0x0, ['pointer64', ['_EPROCESS']]],
} ],
'__unnamed_1815' : [ 0x8, {
'ImageInformation' : [ 0x0, ['pointer64', ['_SECTION_IMAGE_INFORMATION']]],
'FirstMappedVa' : [ 0x0, ['pointer64', ['void']]],
} ],
'_SEGMENT' : [ 0x68, {
'ControlArea' : [ 0x0, ['pointer64', ['_CONTROL_AREA']]],
'TotalNumberOfPtes' : [ 0x8, ['unsigned long']],
'NonExtendedPtes' : [ 0xc, ['unsigned long']],
'Spare0' : [ 0x10, ['unsigned long']],
'SizeOfSegment' : [ 0x18, ['unsigned long long']],
'SegmentPteTemplate' : [ 0x20, ['_MMPTE']],
'NumberOfCommittedPages' : [ 0x28, ['unsigned long long']],
'ExtendInfo' : [ 0x30, ['pointer64', ['_MMEXTEND_INFO']]],
'SegmentFlags' : [ 0x38, ['_SEGMENT_FLAGS']],
'BasedAddress' : [ 0x40, ['pointer64', ['void']]],
'u1' : [ 0x48, ['__unnamed_1811']],
'u2' : [ 0x50, ['__unnamed_1815']],
'PrototypePte' : [ 0x58, ['pointer64', ['_MMPTE']]],
'ThePtes' : [ 0x60, ['array', 1, ['_MMPTE']]],
} ],
'_PCI_COMMON_EXTENSION' : [ 0x38, {
'Next' : [ 0x0, ['pointer64', ['void']]],
'ExtensionType' : [ 0x8, ['Enumeration', dict(target = 'long', choices = {1768116272: 'PciPdoExtensionType', 1768116273: 'PciFdoExtensionType', 1768116274: 'PciArb_Io', 1768116275: 'PciArb_Memory', 1768116276: 'PciArb_Interrupt', 1768116277: 'PciArb_BusNumber', 1768116278: 'PciTrans_Interrupt', 1768116279: 'PciInterface_BusHandler', 1768116280: 'PciInterface_IntRouteHandler', 1768116281: 'PciInterface_PciCb', 1768116282: 'PciInterface_LegacyDeviceDetection', 1768116283: 'PciInterface_PmeHandler', 1768116284: 'PciInterface_DevicePresent', 1768116285: 'PciInterface_NativeIde', 1768116286: 'PciInterface_Location', 1768116287: 'PciInterface_AgpTarget'})]],
'IrpDispatchTable' : [ 0x10, ['pointer64', ['_PCI_MJ_DISPATCH_TABLE']]],
'DeviceState' : [ 0x18, ['unsigned char']],
'TentativeNextState' : [ 0x19, ['unsigned char']],
'SecondaryExtLock' : [ 0x20, ['_KEVENT']],
} ],
'_MI_VERIFIER_DRIVER_ENTRY' : [ 0xa0, {
'Links' : [ 0x0, ['_LIST_ENTRY']],
'Loads' : [ 0x10, ['unsigned long']],
'Unloads' : [ 0x14, ['unsigned long']],
'BaseName' : [ 0x18, ['_UNICODE_STRING']],
'StartAddress' : [ 0x28, ['pointer64', ['void']]],
'EndAddress' : [ 0x30, ['pointer64', ['void']]],
'Flags' : [ 0x38, ['unsigned long']],
'Signature' : [ 0x40, ['unsigned long long']],
'PoolPageHeaders' : [ 0x50, ['_SLIST_HEADER']],
'PoolTrackers' : [ 0x60, ['_SLIST_HEADER']],
'CurrentPagedPoolAllocations' : [ 0x70, ['unsigned long']],
'CurrentNonPagedPoolAllocations' : [ 0x74, ['unsigned long']],
'PeakPagedPoolAllocations' : [ 0x78, ['unsigned long']],
'PeakNonPagedPoolAllocations' : [ 0x7c, ['unsigned long']],
'PagedBytes' : [ 0x80, ['unsigned long long']],
'NonPagedBytes' : [ 0x88, ['unsigned long long']],
'PeakPagedBytes' : [ 0x90, ['unsigned long long']],
'PeakNonPagedBytes' : [ 0x98, ['unsigned long long']],
} ],
'_PRIVATE_CACHE_MAP' : [ 0x60, {
'NodeTypeCode' : [ 0x0, ['short']],
'Flags' : [ 0x0, ['_PRIVATE_CACHE_MAP_FLAGS']],
'UlongFlags' : [ 0x0, ['unsigned long']],
'ReadAheadMask' : [ 0x4, ['unsigned long']],
'FileObject' : [ 0x8, ['pointer64', ['_FILE_OBJECT']]],
'FileOffset1' : [ 0x10, ['_LARGE_INTEGER']],
'BeyondLastByte1' : [ 0x18, ['_LARGE_INTEGER']],
'FileOffset2' : [ 0x20, ['_LARGE_INTEGER']],
'BeyondLastByte2' : [ 0x28, ['_LARGE_INTEGER']],
'ReadAheadOffset' : [ 0x30, ['array', 2, ['_LARGE_INTEGER']]],
'ReadAheadLength' : [ 0x40, ['array', 2, ['unsigned long']]],
'ReadAheadSpinLock' : [ 0x48, ['unsigned long long']],
'PrivateLinks' : [ 0x50, ['_LIST_ENTRY']],
} ],
'_RTL_HANDLE_TABLE' : [ 0x30, {
'MaximumNumberOfHandles' : [ 0x0, ['unsigned long']],
'SizeOfHandleTableEntry' : [ 0x4, ['unsigned long']],
'Reserved' : [ 0x8, ['array', 2, ['unsigned long']]],
'FreeHandles' : [ 0x10, ['pointer64', ['_RTL_HANDLE_TABLE_ENTRY']]],
'CommittedHandles' : [ 0x18, ['pointer64', ['_RTL_HANDLE_TABLE_ENTRY']]],
'UnCommittedHandles' : [ 0x20, ['pointer64', ['_RTL_HANDLE_TABLE_ENTRY']]],
'MaxReservedHandles' : [ 0x28, ['pointer64', ['_RTL_HANDLE_TABLE_ENTRY']]],
} ],
'_POP_IDLE_HANDLER' : [ 0x28, {
'Latency' : [ 0x0, ['unsigned long']],
'TimeCheck' : [ 0x4, ['unsigned long']],
'DemoteLimit' : [ 0x8, ['unsigned long']],
'PromoteLimit' : [ 0xc, ['unsigned long']],
'PromoteCount' : [ 0x10, ['unsigned long']],
'Demote' : [ 0x14, ['unsigned char']],
'Promote' : [ 0x15, ['unsigned char']],
'PromotePercent' : [ 0x16, ['unsigned char']],
'DemotePercent' : [ 0x17, ['unsigned char']],
'State' : [ 0x18, ['unsigned char']],
'Spare' : [ 0x19, ['array', 3, ['unsigned char']]],
'IdleFunction' : [ 0x20, ['pointer64', ['void']]],
} ],
'SYSTEM_POWER_CAPABILITIES' : [ 0x4c, {
'PowerButtonPresent' : [ 0x0, ['unsigned char']],
'SleepButtonPresent' : [ 0x1, ['unsigned char']],
'LidPresent' : [ 0x2, ['unsigned char']],
'SystemS1' : [ 0x3, ['unsigned char']],
'SystemS2' : [ 0x4, ['unsigned char']],
'SystemS3' : [ 0x5, ['unsigned char']],
'SystemS4' : [ 0x6, ['unsigned char']],
'SystemS5' : [ 0x7, ['unsigned char']],
'HiberFilePresent' : [ 0x8, ['unsigned char']],
'FullWake' : [ 0x9, ['unsigned char']],
'VideoDimPresent' : [ 0xa, ['unsigned char']],
'ApmPresent' : [ 0xb, ['unsigned char']],
'UpsPresent' : [ 0xc, ['unsigned char']],
'ThermalControl' : [ 0xd, ['unsigned char']],
'ProcessorThrottle' : [ 0xe, ['unsigned char']],
'ProcessorMinThrottle' : [ 0xf, ['unsigned char']],
'ProcessorMaxThrottle' : [ 0x10, ['unsigned char']],
'spare2' : [ 0x11, ['array', 4, ['unsigned char']]],
'DiskSpinDown' : [ 0x15, ['unsigned char']],
'spare3' : [ 0x16, ['array', 8, ['unsigned char']]],
'SystemBatteriesPresent' : [ 0x1e, ['unsigned char']],
'BatteriesAreShortTerm' : [ 0x1f, ['unsigned char']],
'BatteryScale' : [ 0x20, ['array', 3, ['BATTERY_REPORTING_SCALE']]],
'AcOnLineWake' : [ 0x38, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'SoftLidWake' : [ 0x3c, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'RtcWake' : [ 0x40, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'MinDeviceWakeState' : [ 0x44, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'DefaultLowLatencyWake' : [ 0x48, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
} ],
'_DEVOBJ_EXTENSION' : [ 0x50, {
'Type' : [ 0x0, ['short']],
'Size' : [ 0x2, ['unsigned short']],
'DeviceObject' : [ 0x8, ['pointer64', ['_DEVICE_OBJECT']]],
'PowerFlags' : [ 0x10, ['unsigned long']],
'Dope' : [ 0x18, ['pointer64', ['_DEVICE_OBJECT_POWER_EXTENSION']]],
'ExtensionFlags' : [ 0x20, ['unsigned long']],
'DeviceNode' : [ 0x28, ['pointer64', ['void']]],
'AttachedTo' : [ 0x30, ['pointer64', ['_DEVICE_OBJECT']]],
'StartIoCount' : [ 0x38, ['long']],
'StartIoKey' : [ 0x3c, ['long']],
'StartIoFlags' : [ 0x40, ['unsigned long']],
'Vpb' : [ 0x48, ['pointer64', ['_VPB']]],
} ],
'_DBGKD_GET_VERSION64' : [ 0x28, {
'MajorVersion' : [ 0x0, ['unsigned short']],
'MinorVersion' : [ 0x2, ['unsigned short']],
'ProtocolVersion' : [ 0x4, ['unsigned char']],
'KdSecondaryVersion' : [ 0x5, ['unsigned char']],
'Flags' : [ 0x6, ['unsigned short']],
'MachineType' : [ 0x8, ['unsigned short']],
'MaxPacketType' : [ 0xa, ['unsigned char']],
'MaxStateChange' : [ 0xb, ['unsigned char']],
'MaxManipulate' : [ 0xc, ['unsigned char']],
'Simulation' : [ 0xd, ['unsigned char']],
'Unused' : [ 0xe, ['array', 1, ['unsigned short']]],
'KernBase' : [ 0x10, ['unsigned long long']],
'PsLoadedModuleList' : [ 0x18, ['unsigned long long']],
'DebuggerDataList' : [ 0x20, ['unsigned long long']],
} ],
'_STRING32' : [ 0x8, {
'Length' : [ 0x0, ['unsigned short']],
'MaximumLength' : [ 0x2, ['unsigned short']],
'Buffer' : [ 0x4, ['unsigned long']],
} ],
'_MMVIEW' : [ 0x10, {
'Entry' : [ 0x0, ['unsigned long long']],
'ControlArea' : [ 0x8, ['pointer64', ['_CONTROL_AREA']]],
} ],
'_KSYSTEM_TIME' : [ 0xc, {
'LowPart' : [ 0x0, ['unsigned long']],
'High1Time' : [ 0x4, ['long']],
'High2Time' : [ 0x8, ['long']],
} ],
'PCI_SECONDARY_EXTENSION' : [ 0x18, {
'List' : [ 0x0, ['_SINGLE_LIST_ENTRY']],
'ExtensionType' : [ 0x8, ['Enumeration', dict(target = 'long', choices = {1768116272: 'PciPdoExtensionType', 1768116273: 'PciFdoExtensionType', 1768116274: 'PciArb_Io', 1768116275: 'PciArb_Memory', 1768116276: 'PciArb_Interrupt', 1768116277: 'PciArb_BusNumber', 1768116278: 'PciTrans_Interrupt', 1768116279: 'PciInterface_BusHandler', 1768116280: 'PciInterface_IntRouteHandler', 1768116281: 'PciInterface_PciCb', 1768116282: 'PciInterface_LegacyDeviceDetection', 1768116283: 'PciInterface_PmeHandler', 1768116284: 'PciInterface_DevicePresent', 1768116285: 'PciInterface_NativeIde', 1768116286: 'PciInterface_Location', 1768116287: 'PciInterface_AgpTarget'})]],
'Destructor' : [ 0x10, ['pointer64', ['void']]],
} ],
'__unnamed_1842' : [ 0x30, {
'type0' : [ 0x0, ['_PCI_HEADER_TYPE_0']],
'type1' : [ 0x0, ['_PCI_HEADER_TYPE_1']],
'type2' : [ 0x0, ['_PCI_HEADER_TYPE_2']],
} ],
'_PCI_COMMON_CONFIG' : [ 0x100, {
'VendorID' : [ 0x0, ['unsigned short']],
'DeviceID' : [ 0x2, ['unsigned short']],
'Command' : [ 0x4, ['unsigned short']],
'Status' : [ 0x6, ['unsigned short']],
'RevisionID' : [ 0x8, ['unsigned char']],
'ProgIf' : [ 0x9, ['unsigned char']],
'SubClass' : [ 0xa, ['unsigned char']],
'BaseClass' : [ 0xb, ['unsigned char']],
'CacheLineSize' : [ 0xc, ['unsigned char']],
'LatencyTimer' : [ 0xd, ['unsigned char']],
'HeaderType' : [ 0xe, ['unsigned char']],
'BIST' : [ 0xf, ['unsigned char']],
'u' : [ 0x10, ['__unnamed_1842']],
'DeviceSpecific' : [ 0x40, ['array', 192, ['unsigned char']]],
} ],
'_HEAP_FREE_ENTRY_EXTRA' : [ 0x4, {
'TagIndex' : [ 0x0, ['unsigned short']],
'FreeBackTraceIndex' : [ 0x2, ['unsigned short']],
} ],
'_SECTION_IMAGE_INFORMATION' : [ 0x40, {
'TransferAddress' : [ 0x0, ['pointer64', ['void']]],
'ZeroBits' : [ 0x8, ['unsigned long']],
'MaximumStackSize' : [ 0x10, ['unsigned long long']],
'CommittedStackSize' : [ 0x18, ['unsigned long long']],
'SubSystemType' : [ 0x20, ['unsigned long']],
'SubSystemMinorVersion' : [ 0x24, ['unsigned short']],
'SubSystemMajorVersion' : [ 0x26, ['unsigned short']],
'SubSystemVersion' : [ 0x24, ['unsigned long']],
'GpValue' : [ 0x28, ['unsigned long']],
'ImageCharacteristics' : [ 0x2c, ['unsigned short']],
'DllCharacteristics' : [ 0x2e, ['unsigned short']],
'Machine' : [ 0x30, ['unsigned short']],
'ImageContainsCode' : [ 0x32, ['unsigned char']],
'Spare1' : [ 0x33, ['unsigned char']],
'LoaderFlags' : [ 0x34, ['unsigned long']],
'ImageFileSize' : [ 0x38, ['unsigned long']],
'Reserved' : [ 0x3c, ['array', 1, ['unsigned long']]],
} ],
'_POOL_TRACKER_TABLE' : [ 0x28, {
'Key' : [ 0x0, ['unsigned long']],
'NonPagedAllocs' : [ 0x4, ['unsigned long']],
'NonPagedFrees' : [ 0x8, ['unsigned long']],
'NonPagedBytes' : [ 0x10, ['unsigned long long']],
'PagedAllocs' : [ 0x18, ['unsigned long']],
'PagedFrees' : [ 0x1c, ['unsigned long']],
'PagedBytes' : [ 0x20, ['unsigned long long']],
} ],
'_KNODE' : [ 0x40, {
'DeadStackList' : [ 0x0, ['_SLIST_HEADER']],
'PfnDereferenceSListHead' : [ 0x10, ['_SLIST_HEADER']],
'Alignment' : [ 0x10, ['unsigned long long']],
'ProcessorMask' : [ 0x18, ['unsigned long long']],
'Color' : [ 0x20, ['unsigned char']],
'Seed' : [ 0x21, ['unsigned char']],
'NodeNumber' : [ 0x22, ['unsigned char']],
'Flags' : [ 0x23, ['_flags']],
'MmShiftedColor' : [ 0x24, ['unsigned long']],
'FreeCount' : [ 0x28, ['array', 2, ['unsigned long long']]],
'PfnDeferredList' : [ 0x38, ['pointer64', ['_SLIST_ENTRY']]],
} ],
'_PHYSICAL_MEMORY_DESCRIPTOR' : [ 0x20, {
'NumberOfRuns' : [ 0x0, ['unsigned long']],
'NumberOfPages' : [ 0x8, ['unsigned long long']],
'Run' : [ 0x10, ['array', 1, ['_PHYSICAL_MEMORY_RUN']]],
} ],
'_SEGMENT_FLAGS' : [ 0x8, {
'TotalNumberOfPtes4132' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 10, native_type='unsigned long long')]],
'ExtraSharedWowSubsections' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long long')]],
'LargePages' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned long long')]],
'Spare' : [ 0x0, ['BitField', dict(start_bit = 12, end_bit = 64, native_type='unsigned long long')]],
} ],
'_PI_BUS_EXTENSION' : [ 0x70, {
'Flags' : [ 0x0, ['unsigned long']],
'NumberCSNs' : [ 0x4, ['unsigned char']],
'ReadDataPort' : [ 0x8, ['pointer64', ['unsigned char']]],
'DataPortMapped' : [ 0x10, ['unsigned char']],
'AddressPort' : [ 0x18, ['pointer64', ['unsigned char']]],
'AddrPortMapped' : [ 0x20, ['unsigned char']],
'CommandPort' : [ 0x28, ['pointer64', ['unsigned char']]],
'CmdPortMapped' : [ 0x30, ['unsigned char']],
'NextSlotNumber' : [ 0x34, ['unsigned long']],
'DeviceList' : [ 0x38, ['_SINGLE_LIST_ENTRY']],
'CardList' : [ 0x40, ['_SINGLE_LIST_ENTRY']],
'PhysicalBusDevice' : [ 0x48, ['pointer64', ['_DEVICE_OBJECT']]],
'FunctionalBusDevice' : [ 0x50, ['pointer64', ['_DEVICE_OBJECT']]],
'AttachedDevice' : [ 0x58, ['pointer64', ['_DEVICE_OBJECT']]],
'BusNumber' : [ 0x60, ['unsigned long']],
'SystemPowerState' : [ 0x64, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'DevicePowerState' : [ 0x68, ['Enumeration', dict(target = 'long', choices = {0: 'PowerDeviceUnspecified', 1: 'PowerDeviceD0', 2: 'PowerDeviceD1', 3: 'PowerDeviceD2', 4: 'PowerDeviceD3', 5: 'PowerDeviceMaximum'})]],
} ],
'_CLIENT_ID32' : [ 0x8, {
'UniqueProcess' : [ 0x0, ['unsigned long']],
'UniqueThread' : [ 0x4, ['unsigned long']],
} ],
'_VI_DEADLOCK_THREAD' : [ 0x30, {
'Thread' : [ 0x0, ['pointer64', ['_KTHREAD']]],
'CurrentSpinNode' : [ 0x8, ['pointer64', ['_VI_DEADLOCK_NODE']]],
'CurrentOtherNode' : [ 0x10, ['pointer64', ['_VI_DEADLOCK_NODE']]],
'ListEntry' : [ 0x18, ['_LIST_ENTRY']],
'FreeListEntry' : [ 0x18, ['_LIST_ENTRY']],
'NodeCount' : [ 0x28, ['unsigned long']],
'PagingCount' : [ 0x2c, ['unsigned long']],
} ],
'_MMEXTEND_INFO' : [ 0x10, {
'CommittedSize' : [ 0x0, ['unsigned long long']],
'ReferenceCount' : [ 0x8, ['unsigned long']],
} ],
'_GDI_TEB_BATCH64' : [ 0x4e8, {
'Offset' : [ 0x0, ['unsigned long']],
'HDC' : [ 0x8, ['unsigned long long']],
'Buffer' : [ 0x10, ['array', 310, ['unsigned long']]],
} ],
'_IMAGE_DEBUG_DIRECTORY' : [ 0x1c, {
'Characteristics' : [ 0x0, ['unsigned long']],
'TimeDateStamp' : [ 0x4, ['unsigned long']],
'MajorVersion' : [ 0x8, ['unsigned short']],
'MinorVersion' : [ 0xa, ['unsigned short']],
'Type' : [ 0xc, ['unsigned long']],
'SizeOfData' : [ 0x10, ['unsigned long']],
'AddressOfRawData' : [ 0x14, ['unsigned long']],
'PointerToRawData' : [ 0x18, ['unsigned long']],
} ],
'_PCI_INTERFACE' : [ 0x28, {
'InterfaceType' : [ 0x0, ['pointer64', ['_GUID']]],
'MinSize' : [ 0x8, ['unsigned short']],
'MinVersion' : [ 0xa, ['unsigned short']],
'MaxVersion' : [ 0xc, ['unsigned short']],
'Flags' : [ 0xe, ['unsigned short']],
'ReferenceCount' : [ 0x10, ['long']],
'Signature' : [ 0x14, ['Enumeration', dict(target = 'long', choices = {1768116272: 'PciPdoExtensionType', 1768116273: 'PciFdoExtensionType', 1768116274: 'PciArb_Io', 1768116275: 'PciArb_Memory', 1768116276: 'PciArb_Interrupt', 1768116277: 'PciArb_BusNumber', 1768116278: 'PciTrans_Interrupt', 1768116279: 'PciInterface_BusHandler', 1768116280: 'PciInterface_IntRouteHandler', 1768116281: 'PciInterface_PciCb', 1768116282: 'PciInterface_LegacyDeviceDetection', 1768116283: 'PciInterface_PmeHandler', 1768116284: 'PciInterface_DevicePresent', 1768116285: 'PciInterface_NativeIde', 1768116286: 'PciInterface_Location', 1768116287: 'PciInterface_AgpTarget'})]],
'Constructor' : [ 0x18, ['pointer64', ['void']]],
'Initializer' : [ 0x20, ['pointer64', ['void']]],
} ],
'_POP_POWER_ACTION' : [ 0x50, {
'Updates' : [ 0x0, ['unsigned char']],
'State' : [ 0x1, ['unsigned char']],
'Shutdown' : [ 0x2, ['unsigned char']],
'Action' : [ 0x4, ['Enumeration', dict(target = 'long', choices = {0: 'PowerActionNone', 1: 'PowerActionReserved', 2: 'PowerActionSleep', 3: 'PowerActionHibernate', 4: 'PowerActionShutdown', 5: 'PowerActionShutdownReset', 6: 'PowerActionShutdownOff', 7: 'PowerActionWarmEject'})]],
'LightestState' : [ 0x8, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'Flags' : [ 0xc, ['unsigned long']],
'Status' : [ 0x10, ['long']],
'IrpMinor' : [ 0x14, ['unsigned char']],
'SystemState' : [ 0x18, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'NextSystemState' : [ 0x1c, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'ShutdownBugCode' : [ 0x20, ['pointer64', ['_POP_SHUTDOWN_BUG_CHECK']]],
'DevState' : [ 0x28, ['pointer64', ['_POP_DEVICE_SYS_STATE']]],
'HiberContext' : [ 0x30, ['pointer64', ['_POP_HIBER_CONTEXT']]],
'LastWakeState' : [ 0x38, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'WakeTime' : [ 0x40, ['unsigned long long']],
'SleepTime' : [ 0x48, ['unsigned long long']],
} ],
'_LPCP_MESSAGE' : [ 0x50, {
'Entry' : [ 0x0, ['_LIST_ENTRY']],
'FreeEntry' : [ 0x0, ['_SINGLE_LIST_ENTRY']],
'Reserved0' : [ 0x8, ['unsigned long']],
'SenderPort' : [ 0x10, ['pointer64', ['void']]],
'RepliedToThread' : [ 0x18, ['pointer64', ['_ETHREAD']]],
'PortContext' : [ 0x20, ['pointer64', ['void']]],
'Request' : [ 0x28, ['_PORT_MESSAGE']],
} ],
'_MMVAD_SHORT' : [ 0x30, {
'u1' : [ 0x0, ['__unnamed_1180']],
'LeftChild' : [ 0x8, ['pointer64', ['_MMVAD']]],
'RightChild' : [ 0x10, ['pointer64', ['_MMVAD']]],
'StartingVpn' : [ 0x18, ['unsigned long long']],
'EndingVpn' : [ 0x20, ['unsigned long long']],
'u' : [ 0x28, ['__unnamed_1183']],
} ],
'__unnamed_188b' : [ 0x2c, {
'InitialPrivilegeSet' : [ 0x0, ['_INITIAL_PRIVILEGE_SET']],
'PrivilegeSet' : [ 0x0, ['_PRIVILEGE_SET']],
} ],
'_ACCESS_STATE' : [ 0xa0, {
'OperationID' : [ 0x0, ['_LUID']],
'SecurityEvaluated' : [ 0x8, ['unsigned char']],
'GenerateAudit' : [ 0x9, ['unsigned char']],
'GenerateOnClose' : [ 0xa, ['unsigned char']],
'PrivilegesAllocated' : [ 0xb, ['unsigned char']],
'Flags' : [ 0xc, ['unsigned long']],
'RemainingDesiredAccess' : [ 0x10, ['unsigned long']],
'PreviouslyGrantedAccess' : [ 0x14, ['unsigned long']],
'OriginalDesiredAccess' : [ 0x18, ['unsigned long']],
'SubjectSecurityContext' : [ 0x20, ['_SECURITY_SUBJECT_CONTEXT']],
'SecurityDescriptor' : [ 0x40, ['pointer64', ['void']]],
'AuxData' : [ 0x48, ['pointer64', ['void']]],
'Privileges' : [ 0x50, ['__unnamed_188b']],
'AuditPrivileges' : [ 0x7c, ['unsigned char']],
'ObjectName' : [ 0x80, ['_UNICODE_STRING']],
'ObjectTypeName' : [ 0x90, ['_UNICODE_STRING']],
} ],
'_PNP_DEVICE_EVENT_ENTRY' : [ 0x88, {
'ListEntry' : [ 0x0, ['_LIST_ENTRY']],
'Argument' : [ 0x10, ['unsigned long']],
'CallerEvent' : [ 0x18, ['pointer64', ['_KEVENT']]],
'Callback' : [ 0x20, ['pointer64', ['void']]],
'Context' : [ 0x28, ['pointer64', ['void']]],
'VetoType' : [ 0x30, ['pointer64', ['Enumeration', dict(target = 'long', choices = {0: 'PNP_VetoTypeUnknown', 1: 'PNP_VetoLegacyDevice', 2: 'PNP_VetoPendingClose', 3: 'PNP_VetoWindowsApp', 4: 'PNP_VetoWindowsService', 5: 'PNP_VetoOutstandingOpen', 6: 'PNP_VetoDevice', 7: 'PNP_VetoDriver', 8: 'PNP_VetoIllegalDeviceRequest', 9: 'PNP_VetoInsufficientPower', 10: 'PNP_VetoNonDisableable', 11: 'PNP_VetoLegacyDriver', 12: 'PNP_VetoInsufficientRights'})]]],
'VetoName' : [ 0x38, ['pointer64', ['_UNICODE_STRING']]],
'Data' : [ 0x40, ['_PLUGPLAY_EVENT_BLOCK']],
} ],
'_PRIVATE_CACHE_MAP_FLAGS' : [ 0x4, {
'DontUse' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 16, native_type='unsigned long')]],
'ReadAheadActive' : [ 0x0, ['BitField', dict(start_bit = 16, end_bit = 17, native_type='unsigned long')]],
'ReadAheadEnabled' : [ 0x0, ['BitField', dict(start_bit = 17, end_bit = 18, native_type='unsigned long')]],
'Available' : [ 0x0, ['BitField', dict(start_bit = 18, end_bit = 32, native_type='unsigned long')]],
} ],
'_PNP_DEVICE_EVENT_LIST' : [ 0x88, {
'Status' : [ 0x0, ['long']],
'EventQueueMutex' : [ 0x8, ['_KMUTANT']],
'Lock' : [ 0x40, ['_KGUARDED_MUTEX']],
'List' : [ 0x78, ['_LIST_ENTRY']],
} ],
'_MMPTE_TRANSITION' : [ 0x8, {
'Valid' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long long')]],
'Write' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long long')]],
'Owner' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long long')]],
'WriteThrough' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long long')]],
'CacheDisable' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long long')]],
'Protection' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 10, native_type='unsigned long long')]],
'Prototype' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long long')]],
'Transition' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned long long')]],
'PageFrameNumber' : [ 0x0, ['BitField', dict(start_bit = 12, end_bit = 40, native_type='unsigned long long')]],
'Unused' : [ 0x0, ['BitField', dict(start_bit = 40, end_bit = 64, native_type='unsigned long long')]],
} ],
'_KREQUEST_PACKET' : [ 0x20, {
'CurrentPacket' : [ 0x0, ['array', 3, ['pointer64', ['void']]]],
'WorkerRoutine' : [ 0x18, ['pointer64', ['void']]],
} ],
'_STRING' : [ 0x10, {
'Length' : [ 0x0, ['unsigned short']],
'MaximumLength' : [ 0x2, ['unsigned short']],
'Buffer' : [ 0x8, ['pointer64', ['unsigned char']]],
} ],
'_flags' : [ 0x1, {
'Removable' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]],
'Fill' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 8, native_type='unsigned char')]],
} ],
'_CM_KEY_SECURITY_CACHE' : [ 0x38, {
'Cell' : [ 0x0, ['unsigned long']],
'ConvKey' : [ 0x4, ['unsigned long']],
'List' : [ 0x8, ['_LIST_ENTRY']],
'DescriptorLength' : [ 0x18, ['unsigned long']],
'RealRefCount' : [ 0x1c, ['unsigned long']],
'Descriptor' : [ 0x20, ['_SECURITY_DESCRIPTOR_RELATIVE']],
} ],
'_PROCESSOR_POWER_POLICY_INFO' : [ 0x14, {
'TimeCheck' : [ 0x0, ['unsigned long']],
'DemoteLimit' : [ 0x4, ['unsigned long']],
'PromoteLimit' : [ 0x8, ['unsigned long']],
'DemotePercent' : [ 0xc, ['unsigned char']],
'PromotePercent' : [ 0xd, ['unsigned char']],
'Spare' : [ 0xe, ['array', 2, ['unsigned char']]],
'AllowDemotion' : [ 0x10, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'AllowPromotion' : [ 0x10, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]],
'Reserved' : [ 0x10, ['BitField', dict(start_bit = 2, end_bit = 32, native_type='unsigned long')]],
} ],
'_ARBITER_INSTANCE' : [ 0x138, {
'Signature' : [ 0x0, ['unsigned long']],
'MutexEvent' : [ 0x8, ['pointer64', ['_KEVENT']]],
'Name' : [ 0x10, ['pointer64', ['unsigned short']]],
'ResourceType' : [ 0x18, ['long']],
'Allocation' : [ 0x20, ['pointer64', ['_RTL_RANGE_LIST']]],
'PossibleAllocation' : [ 0x28, ['pointer64', ['_RTL_RANGE_LIST']]],
'OrderingList' : [ 0x30, ['_ARBITER_ORDERING_LIST']],
'ReservedList' : [ 0x40, ['_ARBITER_ORDERING_LIST']],
'ReferenceCount' : [ 0x50, ['long']],
'Interface' : [ 0x58, ['pointer64', ['_ARBITER_INTERFACE']]],
'AllocationStackMaxSize' : [ 0x60, ['unsigned long']],
'AllocationStack' : [ 0x68, ['pointer64', ['_ARBITER_ALLOCATION_STATE']]],
'UnpackRequirement' : [ 0x70, ['pointer64', ['void']]],
'PackResource' : [ 0x78, ['pointer64', ['void']]],
'UnpackResource' : [ 0x80, ['pointer64', ['void']]],
'ScoreRequirement' : [ 0x88, ['pointer64', ['void']]],
'TestAllocation' : [ 0x90, ['pointer64', ['void']]],
'RetestAllocation' : [ 0x98, ['pointer64', ['void']]],
'CommitAllocation' : [ 0xa0, ['pointer64', ['void']]],
'RollbackAllocation' : [ 0xa8, ['pointer64', ['void']]],
'BootAllocation' : [ 0xb0, ['pointer64', ['void']]],
'QueryArbitrate' : [ 0xb8, ['pointer64', ['void']]],
'QueryConflict' : [ 0xc0, ['pointer64', ['void']]],
'AddReserved' : [ 0xc8, ['pointer64', ['void']]],
'StartArbiter' : [ 0xd0, ['pointer64', ['void']]],
'PreprocessEntry' : [ 0xd8, ['pointer64', ['void']]],
'AllocateEntry' : [ 0xe0, ['pointer64', ['void']]],
'GetNextAllocationRange' : [ 0xe8, ['pointer64', ['void']]],
'FindSuitableRange' : [ 0xf0, ['pointer64', ['void']]],
'AddAllocation' : [ 0xf8, ['pointer64', ['void']]],
'BacktrackAllocation' : [ 0x100, ['pointer64', ['void']]],
'OverrideConflict' : [ 0x108, ['pointer64', ['void']]],
'TransactionInProgress' : [ 0x110, ['unsigned char']],
'Extension' : [ 0x118, ['pointer64', ['void']]],
'BusDeviceObject' : [ 0x120, ['pointer64', ['_DEVICE_OBJECT']]],
'ConflictCallbackContext' : [ 0x128, ['pointer64', ['void']]],
'ConflictCallback' : [ 0x130, ['pointer64', ['void']]],
} ],
'_BUS_HANDLER' : [ 0xb8, {
'Version' : [ 0x0, ['unsigned long']],
'InterfaceType' : [ 0x4, ['Enumeration', dict(target = 'long', choices = {0: 'Internal', 1: 'Isa', 2: 'Eisa', 3: 'MicroChannel', 4: 'TurboChannel', 5: 'PCIBus', 6: 'VMEBus', 7: 'NuBus', 8: 'PCMCIABus', 9: 'CBus', 10: 'MPIBus', 11: 'MPSABus', 12: 'ProcessorInternal', 13: 'InternalPowerBus', 14: 'PNPISABus', 15: 'PNPBus', 16: 'MaximumInterfaceType', -1: 'InterfaceTypeUndefined'})]],
'ConfigurationType' : [ 0x8, ['Enumeration', dict(target = 'long', choices = {0: 'Cmos', 1: 'EisaConfiguration', 2: 'Pos', 3: 'CbusConfiguration', 4: 'PCIConfiguration', 5: 'VMEConfiguration', 6: 'NuBusConfiguration', 7: 'PCMCIAConfiguration', 8: 'MPIConfiguration', 9: 'MPSAConfiguration', 10: 'PNPISAConfiguration', 11: 'SgiInternalConfiguration', 12: 'MaximumBusDataType', -1: 'ConfigurationSpaceUndefined'})]],
'BusNumber' : [ 0xc, ['unsigned long']],
'DeviceObject' : [ 0x10, ['pointer64', ['_DEVICE_OBJECT']]],
'ParentHandler' : [ 0x18, ['pointer64', ['_BUS_HANDLER']]],
'BusData' : [ 0x20, ['pointer64', ['void']]],
'DeviceControlExtensionSize' : [ 0x28, ['unsigned long']],
'BusAddresses' : [ 0x30, ['pointer64', ['_SUPPORTED_RANGES']]],
'Reserved' : [ 0x38, ['array', 4, ['unsigned long']]],
'GetBusData' : [ 0x48, ['pointer64', ['void']]],
'SetBusData' : [ 0x50, ['pointer64', ['void']]],
'AdjustResourceList' : [ 0x58, ['pointer64', ['void']]],
'AssignSlotResources' : [ 0x60, ['pointer64', ['void']]],
'GetInterruptVector' : [ 0x68, ['pointer64', ['void']]],
'TranslateBusAddress' : [ 0x70, ['pointer64', ['void']]],
'Spare1' : [ 0x78, ['pointer64', ['void']]],
'Spare2' : [ 0x80, ['pointer64', ['void']]],
'Spare3' : [ 0x88, ['pointer64', ['void']]],
'Spare4' : [ 0x90, ['pointer64', ['void']]],
'Spare5' : [ 0x98, ['pointer64', ['void']]],
'Spare6' : [ 0xa0, ['pointer64', ['void']]],
'Spare7' : [ 0xa8, ['pointer64', ['void']]],
'Spare8' : [ 0xb0, ['pointer64', ['void']]],
} ],
'SYSTEM_POWER_LEVEL' : [ 0x18, {
'Enable' : [ 0x0, ['unsigned char']],
'Spare' : [ 0x1, ['array', 3, ['unsigned char']]],
'BatteryLevel' : [ 0x4, ['unsigned long']],
'PowerPolicy' : [ 0x8, ['POWER_ACTION_POLICY']],
'MinSystemState' : [ 0x14, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
} ],
'_PCI_MN_DISPATCH_TABLE' : [ 0x10, {
'DispatchStyle' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'IRP_COMPLETE', 1: 'IRP_DOWNWARD', 2: 'IRP_UPWARD', 3: 'IRP_DISPATCH'})]],
'DispatchFunction' : [ 0x8, ['pointer64', ['void']]],
} ],
'_POP_DEVICE_SYS_STATE' : [ 0xba8, {
'IrpMinor' : [ 0x0, ['unsigned char']],
'SystemState' : [ 0x4, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'Event' : [ 0x8, ['_KEVENT']],
'SpinLock' : [ 0x20, ['unsigned long long']],
'Thread' : [ 0x28, ['pointer64', ['_KTHREAD']]],
'GetNewDeviceList' : [ 0x30, ['unsigned char']],
'Order' : [ 0x38, ['_PO_DEVICE_NOTIFY_ORDER']],
'Status' : [ 0x448, ['long']],
'FailedDevice' : [ 0x450, ['pointer64', ['_DEVICE_OBJECT']]],
'Waking' : [ 0x458, ['unsigned char']],
'Cancelled' : [ 0x459, ['unsigned char']],
'IgnoreErrors' : [ 0x45a, ['unsigned char']],
'IgnoreNotImplemented' : [ 0x45b, ['unsigned char']],
'WaitAny' : [ 0x45c, ['unsigned char']],
'WaitAll' : [ 0x45d, ['unsigned char']],
'PresentIrpQueue' : [ 0x460, ['_LIST_ENTRY']],
'Head' : [ 0x470, ['_POP_DEVICE_POWER_IRP']],
'PowerIrpState' : [ 0x4c8, ['array', 20, ['_POP_DEVICE_POWER_IRP']]],
} ],
'_OBJECT_DUMP_CONTROL' : [ 0x10, {
'Stream' : [ 0x0, ['pointer64', ['void']]],
'Detail' : [ 0x8, ['unsigned long']],
} ],
'_SECURITY_SUBJECT_CONTEXT' : [ 0x20, {
'ClientToken' : [ 0x0, ['pointer64', ['void']]],
'ImpersonationLevel' : [ 0x8, ['Enumeration', dict(target = 'long', choices = {0: 'SecurityAnonymous', 1: 'SecurityIdentification', 2: 'SecurityImpersonation', 3: 'SecurityDelegation'})]],
'PrimaryToken' : [ 0x10, ['pointer64', ['void']]],
'ProcessAuditId' : [ 0x18, ['pointer64', ['void']]],
} ],
'_HEAP_STOP_ON_TAG' : [ 0x4, {
'HeapAndTagIndex' : [ 0x0, ['unsigned long']],
'TagIndex' : [ 0x0, ['unsigned short']],
'HeapIndex' : [ 0x2, ['unsigned short']],
} ],
'_MMWSLE_HASH' : [ 0x10, {
'Key' : [ 0x0, ['pointer64', ['void']]],
'Index' : [ 0x8, ['unsigned long']],
} ],
'_CM_NAME_CONTROL_BLOCK' : [ 0x20, {
'Compressed' : [ 0x0, ['unsigned char']],
'RefCount' : [ 0x2, ['unsigned short']],
'NameHash' : [ 0x8, ['_CM_NAME_HASH']],
'ConvKey' : [ 0x8, ['unsigned long']],
'NextHash' : [ 0x10, ['pointer64', ['_CM_KEY_HASH']]],
'NameLength' : [ 0x18, ['unsigned short']],
'Name' : [ 0x1a, ['array', 1, ['unsigned short']]],
} ],
'_CM_KEY_BODY' : [ 0x30, {
'Type' : [ 0x0, ['unsigned long']],
'KeyControlBlock' : [ 0x8, ['pointer64', ['_CM_KEY_CONTROL_BLOCK']]],
'NotifyBlock' : [ 0x10, ['pointer64', ['_CM_NOTIFY_BLOCK']]],
'ProcessID' : [ 0x18, ['pointer64', ['void']]],
'KeyBodyList' : [ 0x20, ['_LIST_ENTRY']],
} ],
'_HANDLE_TABLE_ENTRY' : [ 0x10, {
'Object' : [ 0x0, ['pointer64', ['void']]],
'ObAttributes' : [ 0x0, ['unsigned long']],
'InfoTable' : [ 0x0, ['pointer64', ['_HANDLE_TABLE_ENTRY_INFO']]],
'Value' : [ 0x0, ['unsigned long long']],
'GrantedAccess' : [ 0x8, ['unsigned long']],
'GrantedAccessIndex' : [ 0x8, ['unsigned short']],
'CreatorBackTraceIndex' : [ 0xa, ['unsigned short']],
'NextFreeTableEntry' : [ 0x8, ['long']],
} ],
'_HEAP_USERDATA_HEADER' : [ 0x20, {
'SFreeListEntry' : [ 0x0, ['_SINGLE_LIST_ENTRY']],
'SubSegment' : [ 0x0, ['pointer64', ['_HEAP_SUBSEGMENT']]],
'HeapHandle' : [ 0x8, ['pointer64', ['void']]],
'SizeIndex' : [ 0x10, ['unsigned long long']],
'Signature' : [ 0x18, ['unsigned long long']],
} ],
'_LPCP_PORT_OBJECT' : [ 0x100, {
'ConnectionPort' : [ 0x0, ['pointer64', ['_LPCP_PORT_OBJECT']]],
'ConnectedPort' : [ 0x8, ['pointer64', ['_LPCP_PORT_OBJECT']]],
'MsgQueue' : [ 0x10, ['_LPCP_PORT_QUEUE']],
'Creator' : [ 0x30, ['_CLIENT_ID']],
'ClientSectionBase' : [ 0x40, ['pointer64', ['void']]],
'ServerSectionBase' : [ 0x48, ['pointer64', ['void']]],
'PortContext' : [ 0x50, ['pointer64', ['void']]],
'ClientThread' : [ 0x58, ['pointer64', ['_ETHREAD']]],
'SecurityQos' : [ 0x60, ['_SECURITY_QUALITY_OF_SERVICE']],
'StaticSecurity' : [ 0x70, ['_SECURITY_CLIENT_CONTEXT']],
'LpcReplyChainHead' : [ 0xb8, ['_LIST_ENTRY']],
'LpcDataInfoChainHead' : [ 0xc8, ['_LIST_ENTRY']],
'ServerProcess' : [ 0xd8, ['pointer64', ['_EPROCESS']]],
'MappingProcess' : [ 0xd8, ['pointer64', ['_EPROCESS']]],
'MaxMessageLength' : [ 0xe0, ['unsigned short']],
'MaxConnectionInfoLength' : [ 0xe2, ['unsigned short']],
'Flags' : [ 0xe4, ['unsigned long']],
'WaitEvent' : [ 0xe8, ['_KEVENT']],
} ],
'PCI_POWER_STATE' : [ 0x50, {
'CurrentSystemState' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'CurrentDeviceState' : [ 0x4, ['Enumeration', dict(target = 'long', choices = {0: 'PowerDeviceUnspecified', 1: 'PowerDeviceD0', 2: 'PowerDeviceD1', 3: 'PowerDeviceD2', 4: 'PowerDeviceD3', 5: 'PowerDeviceMaximum'})]],
'SystemWakeLevel' : [ 0x8, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'DeviceWakeLevel' : [ 0xc, ['Enumeration', dict(target = 'long', choices = {0: 'PowerDeviceUnspecified', 1: 'PowerDeviceD0', 2: 'PowerDeviceD1', 3: 'PowerDeviceD2', 4: 'PowerDeviceD3', 5: 'PowerDeviceMaximum'})]],
'SystemStateMapping' : [ 0x10, ['array', -28, ['Enumeration', dict(target = 'long', choices = {0: 'PowerDeviceUnspecified', 1: 'PowerDeviceD0', 2: 'PowerDeviceD1', 3: 'PowerDeviceD2', 4: 'PowerDeviceD3', 5: 'PowerDeviceMaximum'})]]],
'WaitWakeIrp' : [ 0x30, ['pointer64', ['_IRP']]],
'SavedCancelRoutine' : [ 0x38, ['pointer64', ['void']]],
'Paging' : [ 0x40, ['long']],
'Hibernate' : [ 0x44, ['long']],
'CrashDump' : [ 0x48, ['long']],
} ],
'_STRING64' : [ 0x10, {
'Length' : [ 0x0, ['unsigned short']],
'MaximumLength' : [ 0x2, ['unsigned short']],
'Buffer' : [ 0x8, ['unsigned long long']],
} ],
'_POOL_HACKER' : [ 0x30, {
'Header' : [ 0x0, ['_POOL_HEADER']],
'Contents' : [ 0x10, ['array', 8, ['unsigned long']]],
} ],
'_CM_INDEX_HINT_BLOCK' : [ 0x8, {
'Count' : [ 0x0, ['unsigned long']],
'HashKey' : [ 0x4, ['array', 1, ['unsigned long']]],
} ],
'_TOKEN_CONTROL' : [ 0x28, {
'TokenId' : [ 0x0, ['_LUID']],
'AuthenticationId' : [ 0x8, ['_LUID']],
'ModifiedId' : [ 0x10, ['_LUID']],
'TokenSource' : [ 0x18, ['_TOKEN_SOURCE']],
} ],
'__unnamed_1930' : [ 0x20, {
'SecurityContext' : [ 0x0, ['pointer64', ['_IO_SECURITY_CONTEXT']]],
'Options' : [ 0x8, ['unsigned long']],
'FileAttributes' : [ 0x10, ['unsigned short']],
'ShareAccess' : [ 0x12, ['unsigned short']],
'EaLength' : [ 0x18, ['unsigned long']],
} ],
'__unnamed_1934' : [ 0x20, {
'SecurityContext' : [ 0x0, ['pointer64', ['_IO_SECURITY_CONTEXT']]],
'Options' : [ 0x8, ['unsigned long']],
'Reserved' : [ 0x10, ['unsigned short']],
'ShareAccess' : [ 0x12, ['unsigned short']],
'Parameters' : [ 0x18, ['pointer64', ['_NAMED_PIPE_CREATE_PARAMETERS']]],
} ],
'__unnamed_1938' : [ 0x20, {
'SecurityContext' : [ 0x0, ['pointer64', ['_IO_SECURITY_CONTEXT']]],
'Options' : [ 0x8, ['unsigned long']],
'Reserved' : [ 0x10, ['unsigned short']],
'ShareAccess' : [ 0x12, ['unsigned short']],
'Parameters' : [ 0x18, ['pointer64', ['_MAILSLOT_CREATE_PARAMETERS']]],
} ],
'__unnamed_193a' : [ 0x18, {
'Length' : [ 0x0, ['unsigned long']],
'Key' : [ 0x8, ['unsigned long']],
'ByteOffset' : [ 0x10, ['_LARGE_INTEGER']],
} ],
'__unnamed_193e' : [ 0x20, {
'Length' : [ 0x0, ['unsigned long']],
'FileName' : [ 0x8, ['pointer64', ['_UNICODE_STRING']]],
'FileInformationClass' : [ 0x10, ['Enumeration', dict(target = 'long', choices = {1: 'FileDirectoryInformation', 2: 'FileFullDirectoryInformation', 3: 'FileBothDirectoryInformation', 4: 'FileBasicInformation', 5: 'FileStandardInformation', 6: 'FileInternalInformation', 7: 'FileEaInformation', 8: 'FileAccessInformation', 9: 'FileNameInformation', 10: 'FileRenameInformation', 11: 'FileLinkInformation', 12: 'FileNamesInformation', 13: 'FileDispositionInformation', 14: 'FilePositionInformation', 15: 'FileFullEaInformation', 16: 'FileModeInformation', 17: 'FileAlignmentInformation', 18: 'FileAllInformation', 19: 'FileAllocationInformation', 20: 'FileEndOfFileInformation', 21: 'FileAlternateNameInformation', 22: 'FileStreamInformation', 23: 'FilePipeInformation', 24: 'FilePipeLocalInformation', 25: 'FilePipeRemoteInformation', 26: 'FileMailslotQueryInformation', 27: 'FileMailslotSetInformation', 28: 'FileCompressionInformation', 29: 'FileObjectIdInformation', 30: 'FileCompletionInformation', 31: 'FileMoveClusterInformation', 32: 'FileQuotaInformation', 33: 'FileReparsePointInformation', 34: 'FileNetworkOpenInformation', 35: 'FileAttributeTagInformation', 36: 'FileTrackingInformation', 37: 'FileIdBothDirectoryInformation', 38: 'FileIdFullDirectoryInformation', 39: 'FileValidDataLengthInformation', 40: 'FileShortNameInformation', 41: 'FileIoCompletionNotificationInformation', 42: 'FileMaximumInformation'})]],
'FileIndex' : [ 0x18, ['unsigned long']],
} ],
'__unnamed_1940' : [ 0x10, {
'Length' : [ 0x0, ['unsigned long']],
'CompletionFilter' : [ 0x8, ['unsigned long']],
} ],
'__unnamed_1942' : [ 0x10, {
'Length' : [ 0x0, ['unsigned long']],
'FileInformationClass' : [ 0x8, ['Enumeration', dict(target = 'long', choices = {1: 'FileDirectoryInformation', 2: 'FileFullDirectoryInformation', 3: 'FileBothDirectoryInformation', 4: 'FileBasicInformation', 5: 'FileStandardInformation', 6: 'FileInternalInformation', 7: 'FileEaInformation', 8: 'FileAccessInformation', 9: 'FileNameInformation', 10: 'FileRenameInformation', 11: 'FileLinkInformation', 12: 'FileNamesInformation', 13: 'FileDispositionInformation', 14: 'FilePositionInformation', 15: 'FileFullEaInformation', 16: 'FileModeInformation', 17: 'FileAlignmentInformation', 18: 'FileAllInformation', 19: 'FileAllocationInformation', 20: 'FileEndOfFileInformation', 21: 'FileAlternateNameInformation', 22: 'FileStreamInformation', 23: 'FilePipeInformation', 24: 'FilePipeLocalInformation', 25: 'FilePipeRemoteInformation', 26: 'FileMailslotQueryInformation', 27: 'FileMailslotSetInformation', 28: 'FileCompressionInformation', 29: 'FileObjectIdInformation', 30: 'FileCompletionInformation', 31: 'FileMoveClusterInformation', 32: 'FileQuotaInformation', 33: 'FileReparsePointInformation', 34: 'FileNetworkOpenInformation', 35: 'FileAttributeTagInformation', 36: 'FileTrackingInformation', 37: 'FileIdBothDirectoryInformation', 38: 'FileIdFullDirectoryInformation', 39: 'FileValidDataLengthInformation', 40: 'FileShortNameInformation', 41: 'FileIoCompletionNotificationInformation', 42: 'FileMaximumInformation'})]],
} ],
'__unnamed_1944' : [ 0x20, {
'Length' : [ 0x0, ['unsigned long']],
'FileInformationClass' : [ 0x8, ['Enumeration', dict(target = 'long', choices = {1: 'FileDirectoryInformation', 2: 'FileFullDirectoryInformation', 3: 'FileBothDirectoryInformation', 4: 'FileBasicInformation', 5: 'FileStandardInformation', 6: 'FileInternalInformation', 7: 'FileEaInformation', 8: 'FileAccessInformation', 9: 'FileNameInformation', 10: 'FileRenameInformation', 11: 'FileLinkInformation', 12: 'FileNamesInformation', 13: 'FileDispositionInformation', 14: 'FilePositionInformation', 15: 'FileFullEaInformation', 16: 'FileModeInformation', 17: 'FileAlignmentInformation', 18: 'FileAllInformation', 19: 'FileAllocationInformation', 20: 'FileEndOfFileInformation', 21: 'FileAlternateNameInformation', 22: 'FileStreamInformation', 23: 'FilePipeInformation', 24: 'FilePipeLocalInformation', 25: 'FilePipeRemoteInformation', 26: 'FileMailslotQueryInformation', 27: 'FileMailslotSetInformation', 28: 'FileCompressionInformation', 29: 'FileObjectIdInformation', 30: 'FileCompletionInformation', 31: 'FileMoveClusterInformation', 32: 'FileQuotaInformation', 33: 'FileReparsePointInformation', 34: 'FileNetworkOpenInformation', 35: 'FileAttributeTagInformation', 36: 'FileTrackingInformation', 37: 'FileIdBothDirectoryInformation', 38: 'FileIdFullDirectoryInformation', 39: 'FileValidDataLengthInformation', 40: 'FileShortNameInformation', 41: 'FileIoCompletionNotificationInformation', 42: 'FileMaximumInformation'})]],
'FileObject' : [ 0x10, ['pointer64', ['_FILE_OBJECT']]],
'ReplaceIfExists' : [ 0x18, ['unsigned char']],
'AdvanceOnly' : [ 0x19, ['unsigned char']],
'ClusterCount' : [ 0x18, ['unsigned long']],
'DeleteHandle' : [ 0x18, ['pointer64', ['void']]],
} ],
'__unnamed_1946' : [ 0x20, {
'Length' : [ 0x0, ['unsigned long']],
'EaList' : [ 0x8, ['pointer64', ['void']]],
'EaListLength' : [ 0x10, ['unsigned long']],
'EaIndex' : [ 0x18, ['unsigned long']],
} ],
'__unnamed_1948' : [ 0x4, {
'Length' : [ 0x0, ['unsigned long']],
} ],
'__unnamed_194c' : [ 0x10, {
'Length' : [ 0x0, ['unsigned long']],
'FsInformationClass' : [ 0x8, ['Enumeration', dict(target = 'long', choices = {1: 'FileFsVolumeInformation', 2: 'FileFsLabelInformation', 3: 'FileFsSizeInformation', 4: 'FileFsDeviceInformation', 5: 'FileFsAttributeInformation', 6: 'FileFsControlInformation', 7: 'FileFsFullSizeInformation', 8: 'FileFsObjectIdInformation', 9: 'FileFsDriverPathInformation', 10: 'FileFsMaximumInformation'})]],
} ],
'__unnamed_194e' : [ 0x20, {
'OutputBufferLength' : [ 0x0, ['unsigned long']],
'InputBufferLength' : [ 0x8, ['unsigned long']],
'FsControlCode' : [ 0x10, ['unsigned long']],
'Type3InputBuffer' : [ 0x18, ['pointer64', ['void']]],
} ],
'__unnamed_1950' : [ 0x18, {
'Length' : [ 0x0, ['pointer64', ['_LARGE_INTEGER']]],
'Key' : [ 0x8, ['unsigned long']],
'ByteOffset' : [ 0x10, ['_LARGE_INTEGER']],
} ],
'__unnamed_1952' : [ 0x20, {
'OutputBufferLength' : [ 0x0, ['unsigned long']],
'InputBufferLength' : [ 0x8, ['unsigned long']],
'IoControlCode' : [ 0x10, ['unsigned long']],
'Type3InputBuffer' : [ 0x18, ['pointer64', ['void']]],
} ],
'__unnamed_1954' : [ 0x10, {
'SecurityInformation' : [ 0x0, ['unsigned long']],
'Length' : [ 0x8, ['unsigned long']],
} ],
'__unnamed_1956' : [ 0x10, {
'SecurityInformation' : [ 0x0, ['unsigned long']],
'SecurityDescriptor' : [ 0x8, ['pointer64', ['void']]],
} ],
'__unnamed_1958' : [ 0x10, {
'Vpb' : [ 0x0, ['pointer64', ['_VPB']]],
'DeviceObject' : [ 0x8, ['pointer64', ['_DEVICE_OBJECT']]],
} ],
'__unnamed_195c' : [ 0x8, {
'Srb' : [ 0x0, ['pointer64', ['_SCSI_REQUEST_BLOCK']]],
} ],
'__unnamed_1960' : [ 0x20, {
'Length' : [ 0x0, ['unsigned long']],
'StartSid' : [ 0x8, ['pointer64', ['void']]],
'SidList' : [ 0x10, ['pointer64', ['_FILE_GET_QUOTA_INFORMATION']]],
'SidListLength' : [ 0x18, ['unsigned long']],
} ],
'__unnamed_1964' : [ 0x4, {
'Type' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'BusRelations', 1: 'EjectionRelations', 2: 'PowerRelations', 3: 'RemovalRelations', 4: 'TargetDeviceRelation', 5: 'SingleBusRelations'})]],
} ],
'__unnamed_1966' : [ 0x20, {
'InterfaceType' : [ 0x0, ['pointer64', ['_GUID']]],
'Size' : [ 0x8, ['unsigned short']],
'Version' : [ 0xa, ['unsigned short']],
'Interface' : [ 0x10, ['pointer64', ['_INTERFACE']]],
'InterfaceSpecificData' : [ 0x18, ['pointer64', ['void']]],
} ],
'__unnamed_196a' : [ 0x8, {
'Capabilities' : [ 0x0, ['pointer64', ['_DEVICE_CAPABILITIES']]],
} ],
'__unnamed_196c' : [ 0x8, {
'IoResourceRequirementList' : [ 0x0, ['pointer64', ['_IO_RESOURCE_REQUIREMENTS_LIST']]],
} ],
'__unnamed_196e' : [ 0x20, {
'WhichSpace' : [ 0x0, ['unsigned long']],
'Buffer' : [ 0x8, ['pointer64', ['void']]],
'Offset' : [ 0x10, ['unsigned long']],
'Length' : [ 0x18, ['unsigned long']],
} ],
'__unnamed_1970' : [ 0x1, {
'Lock' : [ 0x0, ['unsigned char']],
} ],
'__unnamed_1974' : [ 0x4, {
'IdType' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'BusQueryDeviceID', 1: 'BusQueryHardwareIDs', 2: 'BusQueryCompatibleIDs', 3: 'BusQueryInstanceID', 4: 'BusQueryDeviceSerialNumber'})]],
} ],
'__unnamed_1978' : [ 0x10, {
'DeviceTextType' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'DeviceTextDescription', 1: 'DeviceTextLocationInformation'})]],
'LocaleId' : [ 0x8, ['unsigned long']],
} ],
'__unnamed_197c' : [ 0x10, {
'InPath' : [ 0x0, ['unsigned char']],
'Reserved' : [ 0x1, ['array', 3, ['unsigned char']]],
'Type' : [ 0x8, ['Enumeration', dict(target = 'long', choices = {0: 'DeviceUsageTypeUndefined', 1: 'DeviceUsageTypePaging', 2: 'DeviceUsageTypeHibernation', 3: 'DeviceUsageTypeDumpFile'})]],
} ],
'__unnamed_197e' : [ 0x4, {
'PowerState' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
} ],
'__unnamed_1982' : [ 0x8, {
'PowerSequence' : [ 0x0, ['pointer64', ['_POWER_SEQUENCE']]],
} ],
'__unnamed_1986' : [ 0x20, {
'SystemContext' : [ 0x0, ['unsigned long']],
'Type' : [ 0x8, ['Enumeration', dict(target = 'long', choices = {0: 'SystemPowerState', 1: 'DevicePowerState'})]],
'State' : [ 0x10, ['_POWER_STATE']],
'ShutdownType' : [ 0x18, ['Enumeration', dict(target = 'long', choices = {0: 'PowerActionNone', 1: 'PowerActionReserved', 2: 'PowerActionSleep', 3: 'PowerActionHibernate', 4: 'PowerActionShutdown', 5: 'PowerActionShutdownReset', 6: 'PowerActionShutdownOff', 7: 'PowerActionWarmEject'})]],
} ],
'__unnamed_1988' : [ 0x10, {
'AllocatedResources' : [ 0x0, ['pointer64', ['_CM_RESOURCE_LIST']]],
'AllocatedResourcesTranslated' : [ 0x8, ['pointer64', ['_CM_RESOURCE_LIST']]],
} ],
'__unnamed_198a' : [ 0x20, {
'ProviderId' : [ 0x0, ['unsigned long long']],
'DataPath' : [ 0x8, ['pointer64', ['void']]],
'BufferSize' : [ 0x10, ['unsigned long']],
'Buffer' : [ 0x18, ['pointer64', ['void']]],
} ],
'__unnamed_198c' : [ 0x20, {
'Argument1' : [ 0x0, ['pointer64', ['void']]],
'Argument2' : [ 0x8, ['pointer64', ['void']]],
'Argument3' : [ 0x10, ['pointer64', ['void']]],
'Argument4' : [ 0x18, ['pointer64', ['void']]],
} ],
'__unnamed_198e' : [ 0x20, {
'Create' : [ 0x0, ['__unnamed_1930']],
'CreatePipe' : [ 0x0, ['__unnamed_1934']],
'CreateMailslot' : [ 0x0, ['__unnamed_1938']],
'Read' : [ 0x0, ['__unnamed_193a']],
'Write' : [ 0x0, ['__unnamed_193a']],
'QueryDirectory' : [ 0x0, ['__unnamed_193e']],
'NotifyDirectory' : [ 0x0, ['__unnamed_1940']],
'QueryFile' : [ 0x0, ['__unnamed_1942']],
'SetFile' : [ 0x0, ['__unnamed_1944']],
'QueryEa' : [ 0x0, ['__unnamed_1946']],
'SetEa' : [ 0x0, ['__unnamed_1948']],
'QueryVolume' : [ 0x0, ['__unnamed_194c']],
'SetVolume' : [ 0x0, ['__unnamed_194c']],
'FileSystemControl' : [ 0x0, ['__unnamed_194e']],
'LockControl' : [ 0x0, ['__unnamed_1950']],
'DeviceIoControl' : [ 0x0, ['__unnamed_1952']],
'QuerySecurity' : [ 0x0, ['__unnamed_1954']],
'SetSecurity' : [ 0x0, ['__unnamed_1956']],
'MountVolume' : [ 0x0, ['__unnamed_1958']],
'VerifyVolume' : [ 0x0, ['__unnamed_1958']],
'Scsi' : [ 0x0, ['__unnamed_195c']],
'QueryQuota' : [ 0x0, ['__unnamed_1960']],
'SetQuota' : [ 0x0, ['__unnamed_1948']],
'QueryDeviceRelations' : [ 0x0, ['__unnamed_1964']],
'QueryInterface' : [ 0x0, ['__unnamed_1966']],
'DeviceCapabilities' : [ 0x0, ['__unnamed_196a']],
'FilterResourceRequirements' : [ 0x0, ['__unnamed_196c']],
'ReadWriteConfig' : [ 0x0, ['__unnamed_196e']],
'SetLock' : [ 0x0, ['__unnamed_1970']],
'QueryId' : [ 0x0, ['__unnamed_1974']],
'QueryDeviceText' : [ 0x0, ['__unnamed_1978']],
'UsageNotification' : [ 0x0, ['__unnamed_197c']],
'WaitWake' : [ 0x0, ['__unnamed_197e']],
'PowerSequence' : [ 0x0, ['__unnamed_1982']],
'Power' : [ 0x0, ['__unnamed_1986']],
'StartDevice' : [ 0x0, ['__unnamed_1988']],
'WMI' : [ 0x0, ['__unnamed_198a']],
'Others' : [ 0x0, ['__unnamed_198c']],
} ],
'_IO_STACK_LOCATION' : [ 0x48, {
'MajorFunction' : [ 0x0, ['unsigned char']],
'MinorFunction' : [ 0x1, ['unsigned char']],
'Flags' : [ 0x2, ['unsigned char']],
'Control' : [ 0x3, ['unsigned char']],
'Parameters' : [ 0x8, ['__unnamed_198e']],
'DeviceObject' : [ 0x28, ['pointer64', ['_DEVICE_OBJECT']]],
'FileObject' : [ 0x30, ['pointer64', ['_FILE_OBJECT']]],
'CompletionRoutine' : [ 0x38, ['pointer64', ['void']]],
'Context' : [ 0x40, ['pointer64', ['void']]],
} ],
'__unnamed_1995' : [ 0x18, {
'Length' : [ 0x0, ['unsigned long']],
'Alignment' : [ 0x4, ['unsigned long']],
'MinimumAddress' : [ 0x8, ['_LARGE_INTEGER']],
'MaximumAddress' : [ 0x10, ['_LARGE_INTEGER']],
} ],
'__unnamed_1997' : [ 0x8, {
'MinimumVector' : [ 0x0, ['unsigned long']],
'MaximumVector' : [ 0x4, ['unsigned long']],
} ],
'__unnamed_1999' : [ 0x8, {
'MinimumChannel' : [ 0x0, ['unsigned long']],
'MaximumChannel' : [ 0x4, ['unsigned long']],
} ],
'__unnamed_199b' : [ 0x10, {
'Length' : [ 0x0, ['unsigned long']],
'MinBusNumber' : [ 0x4, ['unsigned long']],
'MaxBusNumber' : [ 0x8, ['unsigned long']],
'Reserved' : [ 0xc, ['unsigned long']],
} ],
'__unnamed_199d' : [ 0xc, {
'Priority' : [ 0x0, ['unsigned long']],
'Reserved1' : [ 0x4, ['unsigned long']],
'Reserved2' : [ 0x8, ['unsigned long']],
} ],
'__unnamed_199f' : [ 0x18, {
'Port' : [ 0x0, ['__unnamed_1995']],
'Memory' : [ 0x0, ['__unnamed_1995']],
'Interrupt' : [ 0x0, ['__unnamed_1997']],
'Dma' : [ 0x0, ['__unnamed_1999']],
'Generic' : [ 0x0, ['__unnamed_1995']],
'DevicePrivate' : [ 0x0, ['__unnamed_16dc']],
'BusNumber' : [ 0x0, ['__unnamed_199b']],
'ConfigData' : [ 0x0, ['__unnamed_199d']],
} ],
'_IO_RESOURCE_DESCRIPTOR' : [ 0x20, {
'Option' : [ 0x0, ['unsigned char']],
'Type' : [ 0x1, ['unsigned char']],
'ShareDisposition' : [ 0x2, ['unsigned char']],
'Spare1' : [ 0x3, ['unsigned char']],
'Flags' : [ 0x4, ['unsigned short']],
'Spare2' : [ 0x6, ['unsigned short']],
'u' : [ 0x8, ['__unnamed_199f']],
} ],
'_MI_VERIFIER_POOL_HEADER' : [ 0x8, {
'VerifierPoolEntry' : [ 0x0, ['pointer64', ['_VI_POOL_ENTRY']]],
} ],
'__unnamed_19a8' : [ 0x4, {
'DataLength' : [ 0x0, ['short']],
'TotalLength' : [ 0x2, ['short']],
} ],
'__unnamed_19aa' : [ 0x4, {
's1' : [ 0x0, ['__unnamed_19a8']],
'Length' : [ 0x0, ['unsigned long']],
} ],
'__unnamed_19ac' : [ 0x4, {
'Type' : [ 0x0, ['short']],
'DataInfoOffset' : [ 0x2, ['short']],
} ],
'__unnamed_19ae' : [ 0x4, {
's2' : [ 0x0, ['__unnamed_19ac']],
'ZeroInit' : [ 0x0, ['unsigned long']],
} ],
'_PORT_MESSAGE' : [ 0x28, {
'u1' : [ 0x0, ['__unnamed_19aa']],
'u2' : [ 0x4, ['__unnamed_19ae']],
'ClientId' : [ 0x8, ['_CLIENT_ID']],
'DoNotUseThisField' : [ 0x8, ['double']],
'MessageId' : [ 0x18, ['unsigned long']],
'ClientViewSize' : [ 0x20, ['unsigned long long']],
'CallbackId' : [ 0x20, ['unsigned long']],
} ],
'_DBGKD_ANY_CONTROL_SET' : [ 0x1c, {
'X86ControlSet' : [ 0x0, ['_X86_DBGKD_CONTROL_SET']],
'AlphaControlSet' : [ 0x0, ['unsigned long']],
'IA64ControlSet' : [ 0x0, ['_IA64_DBGKD_CONTROL_SET']],
'Amd64ControlSet' : [ 0x0, ['_AMD64_DBGKD_CONTROL_SET']],
} ],
'_ARBITER_ORDERING_LIST' : [ 0x10, {
'Count' : [ 0x0, ['unsigned short']],
'Maximum' : [ 0x2, ['unsigned short']],
'Orderings' : [ 0x8, ['pointer64', ['_ARBITER_ORDERING']]],
} ],
'_HBASE_BLOCK' : [ 0x1000, {
'Signature' : [ 0x0, ['unsigned long']],
'Sequence1' : [ 0x4, ['unsigned long']],
'Sequence2' : [ 0x8, ['unsigned long']],
'TimeStamp' : [ 0xc, ['_LARGE_INTEGER']],
'Major' : [ 0x14, ['unsigned long']],
'Minor' : [ 0x18, ['unsigned long']],
'Type' : [ 0x1c, ['unsigned long']],
'Format' : [ 0x20, ['unsigned long']],
'RootCell' : [ 0x24, ['unsigned long']],
'Length' : [ 0x28, ['unsigned long']],
'Cluster' : [ 0x2c, ['unsigned long']],
'FileName' : [ 0x30, ['array', 64, ['unsigned char']]],
'Reserved1' : [ 0x70, ['array', 99, ['unsigned long']]],
'CheckSum' : [ 0x1fc, ['unsigned long']],
'Reserved2' : [ 0x200, ['array', 894, ['unsigned long']]],
'BootType' : [ 0xff8, ['unsigned long']],
'BootRecover' : [ 0xffc, ['unsigned long']],
} ],
'_DUAL' : [ 0x278, {
'Length' : [ 0x0, ['unsigned long']],
'Map' : [ 0x8, ['pointer64', ['_HMAP_DIRECTORY']]],
'SmallDir' : [ 0x10, ['pointer64', ['_HMAP_TABLE']]],
'Guard' : [ 0x18, ['unsigned long']],
'FreeDisplay' : [ 0x20, ['array', 24, ['_FREE_DISPLAY']]],
'FreeSummary' : [ 0x260, ['unsigned long']],
'FreeBins' : [ 0x268, ['_LIST_ENTRY']],
} ],
'_VI_POOL_ENTRY' : [ 0x20, {
'PageHeader' : [ 0x0, ['_VI_POOL_PAGE_HEADER']],
'InUse' : [ 0x0, ['_VI_POOL_ENTRY_INUSE']],
'NextFree' : [ 0x0, ['pointer64', ['_SLIST_ENTRY']]],
} ],
'_LPCP_PORT_QUEUE' : [ 0x20, {
'NonPagedPortQueue' : [ 0x0, ['pointer64', ['_LPCP_NONPAGED_PORT_QUEUE']]],
'Semaphore' : [ 0x8, ['pointer64', ['_KSEMAPHORE']]],
'ReceiveHead' : [ 0x10, ['_LIST_ENTRY']],
} ],
'_INITIAL_PRIVILEGE_SET' : [ 0x2c, {
'PrivilegeCount' : [ 0x0, ['unsigned long']],
'Control' : [ 0x4, ['unsigned long']],
'Privilege' : [ 0x8, ['array', 3, ['_LUID_AND_ATTRIBUTES']]],
} ],
'_POP_HIBER_CONTEXT' : [ 0x150, {
'WriteToFile' : [ 0x0, ['unsigned char']],
'ReserveLoaderMemory' : [ 0x1, ['unsigned char']],
'ReserveFreeMemory' : [ 0x2, ['unsigned char']],
'VerifyOnWake' : [ 0x3, ['unsigned char']],
'Reset' : [ 0x4, ['unsigned char']],
'HiberFlags' : [ 0x5, ['unsigned char']],
'LinkFile' : [ 0x6, ['unsigned char']],
'LinkFileHandle' : [ 0x8, ['pointer64', ['void']]],
'Lock' : [ 0x10, ['unsigned long long']],
'MapFrozen' : [ 0x18, ['unsigned char']],
'MemoryMap' : [ 0x20, ['_RTL_BITMAP']],
'ClonedRanges' : [ 0x30, ['_LIST_ENTRY']],
'ClonedRangeCount' : [ 0x40, ['unsigned long']],
'NextCloneRange' : [ 0x48, ['pointer64', ['_LIST_ENTRY']]],
'NextPreserve' : [ 0x50, ['unsigned long long']],
'LoaderMdl' : [ 0x58, ['pointer64', ['_MDL']]],
'Clones' : [ 0x60, ['pointer64', ['_MDL']]],
'NextClone' : [ 0x68, ['pointer64', ['unsigned char']]],
'NoClones' : [ 0x70, ['unsigned long long']],
'Spares' : [ 0x78, ['pointer64', ['_MDL']]],
'PagesOut' : [ 0x80, ['unsigned long long']],
'IoPage' : [ 0x88, ['pointer64', ['void']]],
'CurrentMcb' : [ 0x90, ['pointer64', ['void']]],
'DumpStack' : [ 0x98, ['pointer64', ['_DUMP_STACK_CONTEXT']]],
'WakeState' : [ 0xa0, ['pointer64', ['_KPROCESSOR_STATE']]],
'NoRanges' : [ 0xa8, ['unsigned long']],
'HiberVa' : [ 0xb0, ['unsigned long long']],
'HiberPte' : [ 0xb8, ['_LARGE_INTEGER']],
'Status' : [ 0xc0, ['long']],
'MemoryImage' : [ 0xc8, ['pointer64', ['PO_MEMORY_IMAGE']]],
'TableHead' : [ 0xd0, ['pointer64', ['_PO_MEMORY_RANGE_ARRAY']]],
'CompressionWorkspace' : [ 0xd8, ['pointer64', ['unsigned char']]],
'CompressedWriteBuffer' : [ 0xe0, ['pointer64', ['unsigned char']]],
'PerformanceStats' : [ 0xe8, ['pointer64', ['unsigned long']]],
'CompressionBlock' : [ 0xf0, ['pointer64', ['void']]],
'DmaIO' : [ 0xf8, ['pointer64', ['void']]],
'TemporaryHeap' : [ 0x100, ['pointer64', ['void']]],
'PerfInfo' : [ 0x108, ['_PO_HIBER_PERF']],
} ],
'_FILE_GET_QUOTA_INFORMATION' : [ 0x14, {
'NextEntryOffset' : [ 0x0, ['unsigned long']],
'SidLength' : [ 0x4, ['unsigned long']],
'Sid' : [ 0x8, ['_SID']],
} ],
'_MMADDRESS_LIST' : [ 0x10, {
'StartVpn' : [ 0x0, ['unsigned long long']],
'EndVpn' : [ 0x8, ['unsigned long long']],
} ],
'_OBJECT_NAME_INFORMATION' : [ 0x10, {
'Name' : [ 0x0, ['_UNICODE_STRING']],
} ],
'_KDESCRIPTOR' : [ 0x10, {
'Pad' : [ 0x0, ['array', 3, ['unsigned short']]],
'Limit' : [ 0x6, ['unsigned short']],
'Base' : [ 0x8, ['pointer64', ['void']]],
} ],
'_DUMP_STACK_CONTEXT' : [ 0x110, {
'Init' : [ 0x0, ['_DUMP_INITIALIZATION_CONTEXT']],
'PartitionOffset' : [ 0xa0, ['_LARGE_INTEGER']],
'DumpPointers' : [ 0xa8, ['pointer64', ['void']]],
'PointersLength' : [ 0xb0, ['unsigned long']],
'ModulePrefix' : [ 0xb8, ['pointer64', ['unsigned short']]],
'DriverList' : [ 0xc0, ['_LIST_ENTRY']],
'InitMsg' : [ 0xd0, ['_STRING']],
'ProgMsg' : [ 0xe0, ['_STRING']],
'DoneMsg' : [ 0xf0, ['_STRING']],
'FileObject' : [ 0x100, ['pointer64', ['void']]],
'UsageType' : [ 0x108, ['Enumeration', dict(target = 'long', choices = {0: 'DeviceUsageTypeUndefined', 1: 'DeviceUsageTypePaging', 2: 'DeviceUsageTypeHibernation', 3: 'DeviceUsageTypeDumpFile'})]],
} ],
'_POP_SHUTDOWN_BUG_CHECK' : [ 0x28, {
'Code' : [ 0x0, ['unsigned long']],
'Parameter1' : [ 0x8, ['unsigned long long']],
'Parameter2' : [ 0x10, ['unsigned long long']],
'Parameter3' : [ 0x18, ['unsigned long long']],
'Parameter4' : [ 0x20, ['unsigned long long']],
} ],
'__unnamed_19e9' : [ 0x4, {
'DeviceNumber' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 5, native_type='unsigned long')]],
'FunctionNumber' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 8, native_type='unsigned long')]],
'Reserved' : [ 0x0, ['BitField', dict(start_bit = 8, end_bit = 32, native_type='unsigned long')]],
} ],
'__unnamed_19eb' : [ 0x4, {
'bits' : [ 0x0, ['__unnamed_19e9']],
'AsULONG' : [ 0x0, ['unsigned long']],
} ],
'_PCI_SLOT_NUMBER' : [ 0x4, {
'u' : [ 0x0, ['__unnamed_19eb']],
} ],
'_CM_NOTIFY_BLOCK' : [ 0x58, {
'HiveList' : [ 0x0, ['_LIST_ENTRY']],
'PostList' : [ 0x10, ['_LIST_ENTRY']],
'KeyControlBlock' : [ 0x20, ['pointer64', ['_CM_KEY_CONTROL_BLOCK']]],
'KeyBody' : [ 0x28, ['pointer64', ['_CM_KEY_BODY']]],
'Filter' : [ 0x30, ['BitField', dict(start_bit = 0, end_bit = 30, native_type='unsigned long')]],
'WatchTree' : [ 0x30, ['BitField', dict(start_bit = 30, end_bit = 31, native_type='unsigned long')]],
'NotifyPending' : [ 0x30, ['BitField', dict(start_bit = 31, end_bit = 32, native_type='unsigned long')]],
'SubjectContext' : [ 0x38, ['_SECURITY_SUBJECT_CONTEXT']],
} ],
'_SID' : [ 0xc, {
'Revision' : [ 0x0, ['unsigned char']],
'SubAuthorityCount' : [ 0x1, ['unsigned char']],
'IdentifierAuthority' : [ 0x2, ['_SID_IDENTIFIER_AUTHORITY']],
'SubAuthority' : [ 0x8, ['array', 1, ['unsigned long']]],
} ],
'_RTL_HANDLE_TABLE_ENTRY' : [ 0x8, {
'Flags' : [ 0x0, ['unsigned long']],
'NextFree' : [ 0x0, ['pointer64', ['_RTL_HANDLE_TABLE_ENTRY']]],
} ],
'_VI_POOL_ENTRY_INUSE' : [ 0x20, {
'VirtualAddress' : [ 0x0, ['pointer64', ['void']]],
'CallingAddress' : [ 0x8, ['pointer64', ['void']]],
'NumberOfBytes' : [ 0x10, ['unsigned long long']],
'Tag' : [ 0x18, ['unsigned long long']],
} ],
'_INTERFACE' : [ 0x20, {
'Size' : [ 0x0, ['unsigned short']],
'Version' : [ 0x2, ['unsigned short']],
'Context' : [ 0x8, ['pointer64', ['void']]],
'InterfaceReference' : [ 0x10, ['pointer64', ['void']]],
'InterfaceDereference' : [ 0x18, ['pointer64', ['void']]],
} ],
'_SUPPORTED_RANGES' : [ 0xc0, {
'Version' : [ 0x0, ['unsigned short']],
'Sorted' : [ 0x2, ['unsigned char']],
'Reserved' : [ 0x3, ['unsigned char']],
'NoIO' : [ 0x4, ['unsigned long']],
'IO' : [ 0x8, ['_SUPPORTED_RANGE']],
'NoMemory' : [ 0x30, ['unsigned long']],
'Memory' : [ 0x38, ['_SUPPORTED_RANGE']],
'NoPrefetchMemory' : [ 0x60, ['unsigned long']],
'PrefetchMemory' : [ 0x68, ['_SUPPORTED_RANGE']],
'NoDma' : [ 0x90, ['unsigned long']],
'Dma' : [ 0x98, ['_SUPPORTED_RANGE']],
} ],
'_DRIVER_OBJECT' : [ 0x150, {
'Type' : [ 0x0, ['short']],
'Size' : [ 0x2, ['short']],
'DeviceObject' : [ 0x8, ['pointer64', ['_DEVICE_OBJECT']]],
'Flags' : [ 0x10, ['unsigned long']],
'DriverStart' : [ 0x18, ['pointer64', ['void']]],
'DriverSize' : [ 0x20, ['unsigned long']],
'DriverSection' : [ 0x28, ['pointer64', ['void']]],
'DriverExtension' : [ 0x30, ['pointer64', ['_DRIVER_EXTENSION']]],
'DriverName' : [ 0x38, ['_UNICODE_STRING']],
'HardwareDatabase' : [ 0x48, ['pointer64', ['_UNICODE_STRING']]],
'FastIoDispatch' : [ 0x50, ['pointer64', ['_FAST_IO_DISPATCH']]],
'DriverInit' : [ 0x58, ['pointer64', ['void']]],
'DriverStartIo' : [ 0x60, ['pointer64', ['void']]],
'DriverUnload' : [ 0x68, ['pointer64', ['void']]],
'MajorFunction' : [ 0x70, ['array', 28, ['pointer64', ['void']]]],
} ],
'_SID_IDENTIFIER_AUTHORITY' : [ 0x6, {
'Value' : [ 0x0, ['array', 6, ['unsigned char']]],
} ],
'_SECURITY_DESCRIPTOR_RELATIVE' : [ 0x14, {
'Revision' : [ 0x0, ['unsigned char']],
'Sbz1' : [ 0x1, ['unsigned char']],
'Control' : [ 0x2, ['unsigned short']],
'Owner' : [ 0x4, ['unsigned long']],
'Group' : [ 0x8, ['unsigned long']],
'Sacl' : [ 0xc, ['unsigned long']],
'Dacl' : [ 0x10, ['unsigned long']],
} ],
'_DRIVER_EXTENSION' : [ 0x38, {
'DriverObject' : [ 0x0, ['pointer64', ['_DRIVER_OBJECT']]],
'AddDevice' : [ 0x8, ['pointer64', ['void']]],
'Count' : [ 0x10, ['unsigned long']],
'ServiceKeyName' : [ 0x18, ['_UNICODE_STRING']],
'ClientDriverExtension' : [ 0x28, ['pointer64', ['_IO_CLIENT_EXTENSION']]],
'FsFilterCallbacks' : [ 0x30, ['pointer64', ['_FS_FILTER_CALLBACKS']]],
} ],
'_PM_SUPPORT' : [ 0x1, {
'Rsvd2' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]],
'D1' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned char')]],
'D2' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned char')]],
'PMED0' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned char')]],
'PMED1' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned char')]],
'PMED2' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned char')]],
'PMED3Hot' : [ 0x0, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned char')]],
'PMED3Cold' : [ 0x0, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned char')]],
} ],
'__unnamed_1a1a' : [ 0x18, {
'ArbitrationList' : [ 0x0, ['pointer64', ['_LIST_ENTRY']]],
'AllocateFromCount' : [ 0x8, ['unsigned long']],
'AllocateFrom' : [ 0x10, ['pointer64', ['_CM_PARTIAL_RESOURCE_DESCRIPTOR']]],
} ],
'__unnamed_1a1c' : [ 0x8, {
'ArbitrationList' : [ 0x0, ['pointer64', ['_LIST_ENTRY']]],
} ],
'__unnamed_1a20' : [ 0x8, {
'AllocatedResources' : [ 0x0, ['pointer64', ['pointer64', ['_CM_PARTIAL_RESOURCE_LIST']]]],
} ],
'__unnamed_1a22' : [ 0x20, {
'PhysicalDeviceObject' : [ 0x0, ['pointer64', ['_DEVICE_OBJECT']]],
'ConflictingResource' : [ 0x8, ['pointer64', ['_IO_RESOURCE_DESCRIPTOR']]],
'ConflictCount' : [ 0x10, ['pointer64', ['unsigned long']]],
'Conflicts' : [ 0x18, ['pointer64', ['pointer64', ['_ARBITER_CONFLICT_INFO']]]],
} ],
'__unnamed_1a24' : [ 0x8, {
'ReserveDevice' : [ 0x0, ['pointer64', ['_DEVICE_OBJECT']]],
} ],
'__unnamed_1a26' : [ 0x20, {
'TestAllocation' : [ 0x0, ['__unnamed_1a1a']],
'RetestAllocation' : [ 0x0, ['__unnamed_1a1a']],
'BootAllocation' : [ 0x0, ['__unnamed_1a1c']],
'QueryAllocatedResources' : [ 0x0, ['__unnamed_1a20']],
'QueryConflict' : [ 0x0, ['__unnamed_1a22']],
'QueryArbitrate' : [ 0x0, ['__unnamed_1a1c']],
'AddReserved' : [ 0x0, ['__unnamed_1a24']],
} ],
'_ARBITER_PARAMETERS' : [ 0x20, {
'Parameters' : [ 0x0, ['__unnamed_1a26']],
} ],
'POWER_ACTION_POLICY' : [ 0xc, {
'Action' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'PowerActionNone', 1: 'PowerActionReserved', 2: 'PowerActionSleep', 3: 'PowerActionHibernate', 4: 'PowerActionShutdown', 5: 'PowerActionShutdownReset', 6: 'PowerActionShutdownOff', 7: 'PowerActionWarmEject'})]],
'Flags' : [ 0x4, ['unsigned long']],
'EventCode' : [ 0x8, ['unsigned long']],
} ],
'_HANDLE_TABLE_ENTRY_INFO' : [ 0x4, {
'AuditMask' : [ 0x0, ['unsigned long']],
} ],
'_POWER_SEQUENCE' : [ 0xc, {
'SequenceD1' : [ 0x0, ['unsigned long']],
'SequenceD2' : [ 0x4, ['unsigned long']],
'SequenceD3' : [ 0x8, ['unsigned long']],
} ],
'_IMAGE_DATA_DIRECTORY' : [ 0x8, {
'VirtualAddress' : [ 0x0, ['unsigned long']],
'Size' : [ 0x4, ['unsigned long']],
} ],
'PO_MEMORY_IMAGE' : [ 0xc0, {
'Signature' : [ 0x0, ['unsigned long']],
'Version' : [ 0x4, ['unsigned long']],
'CheckSum' : [ 0x8, ['unsigned long']],
'LengthSelf' : [ 0xc, ['unsigned long']],
'PageSelf' : [ 0x10, ['unsigned long long']],
'PageSize' : [ 0x18, ['unsigned long']],
'ImageType' : [ 0x1c, ['unsigned long']],
'SystemTime' : [ 0x20, ['_LARGE_INTEGER']],
'InterruptTime' : [ 0x28, ['unsigned long long']],
'FeatureFlags' : [ 0x30, ['unsigned long']],
'HiberFlags' : [ 0x34, ['unsigned char']],
'spare' : [ 0x35, ['array', 3, ['unsigned char']]],
'NoHiberPtes' : [ 0x38, ['unsigned long']],
'HiberVa' : [ 0x40, ['unsigned long long']],
'HiberPte' : [ 0x48, ['_LARGE_INTEGER']],
'NoFreePages' : [ 0x50, ['unsigned long']],
'FreeMapCheck' : [ 0x54, ['unsigned long']],
'WakeCheck' : [ 0x58, ['unsigned long']],
'TotalPages' : [ 0x60, ['unsigned long long']],
'FirstTablePage' : [ 0x68, ['unsigned long long']],
'LastFilePage' : [ 0x70, ['unsigned long long']],
'PerfInfo' : [ 0x78, ['_PO_HIBER_PERF']],
} ],
'BATTERY_REPORTING_SCALE' : [ 0x8, {
'Granularity' : [ 0x0, ['unsigned long']],
'Capacity' : [ 0x4, ['unsigned long']],
} ],
'_CURDIR' : [ 0x18, {
'DosPath' : [ 0x0, ['_UNICODE_STRING']],
'Handle' : [ 0x10, ['pointer64', ['void']]],
} ],
'_PO_HIBER_PERF' : [ 0x48, {
'IoTicks' : [ 0x0, ['unsigned long long']],
'InitTicks' : [ 0x8, ['unsigned long long']],
'CopyTicks' : [ 0x10, ['unsigned long long']],
'StartCount' : [ 0x18, ['unsigned long long']],
'ElapsedTime' : [ 0x20, ['unsigned long']],
'IoTime' : [ 0x24, ['unsigned long']],
'CopyTime' : [ 0x28, ['unsigned long']],
'InitTime' : [ 0x2c, ['unsigned long']],
'PagesWritten' : [ 0x30, ['unsigned long']],
'PagesProcessed' : [ 0x34, ['unsigned long']],
'BytesCopied' : [ 0x38, ['unsigned long']],
'DumpCount' : [ 0x3c, ['unsigned long']],
'FileRuns' : [ 0x40, ['unsigned long']],
} ],
'_FREE_DISPLAY' : [ 0x18, {
'RealVectorSize' : [ 0x0, ['unsigned long']],
'Display' : [ 0x8, ['_RTL_BITMAP']],
} ],
'_KDEVICE_QUEUE_ENTRY' : [ 0x18, {
'DeviceListEntry' : [ 0x0, ['_LIST_ENTRY']],
'SortKey' : [ 0x10, ['unsigned long']],
'Inserted' : [ 0x14, ['unsigned char']],
} ],
'_DEVICE_CAPABILITIES' : [ 0x40, {
'Size' : [ 0x0, ['unsigned short']],
'Version' : [ 0x2, ['unsigned short']],
'DeviceD1' : [ 0x4, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'DeviceD2' : [ 0x4, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]],
'LockSupported' : [ 0x4, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]],
'EjectSupported' : [ 0x4, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]],
'Removable' : [ 0x4, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long')]],
'DockDevice' : [ 0x4, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long')]],
'UniqueID' : [ 0x4, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned long')]],
'SilentInstall' : [ 0x4, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned long')]],
'RawDeviceOK' : [ 0x4, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long')]],
'SurpriseRemovalOK' : [ 0x4, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long')]],
'WakeFromD0' : [ 0x4, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long')]],
'WakeFromD1' : [ 0x4, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned long')]],
'WakeFromD2' : [ 0x4, ['BitField', dict(start_bit = 12, end_bit = 13, native_type='unsigned long')]],
'WakeFromD3' : [ 0x4, ['BitField', dict(start_bit = 13, end_bit = 14, native_type='unsigned long')]],
'HardwareDisabled' : [ 0x4, ['BitField', dict(start_bit = 14, end_bit = 15, native_type='unsigned long')]],
'NonDynamic' : [ 0x4, ['BitField', dict(start_bit = 15, end_bit = 16, native_type='unsigned long')]],
'WarmEjectSupported' : [ 0x4, ['BitField', dict(start_bit = 16, end_bit = 17, native_type='unsigned long')]],
'NoDisplayInUI' : [ 0x4, ['BitField', dict(start_bit = 17, end_bit = 18, native_type='unsigned long')]],
'Reserved' : [ 0x4, ['BitField', dict(start_bit = 18, end_bit = 32, native_type='unsigned long')]],
'Address' : [ 0x8, ['unsigned long']],
'UINumber' : [ 0xc, ['unsigned long']],
'DeviceState' : [ 0x10, ['array', -28, ['Enumeration', dict(target = 'long', choices = {0: 'PowerDeviceUnspecified', 1: 'PowerDeviceD0', 2: 'PowerDeviceD1', 3: 'PowerDeviceD2', 4: 'PowerDeviceD3', 5: 'PowerDeviceMaximum'})]]],
'SystemWake' : [ 0x2c, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'DeviceWake' : [ 0x30, ['Enumeration', dict(target = 'long', choices = {0: 'PowerDeviceUnspecified', 1: 'PowerDeviceD0', 2: 'PowerDeviceD1', 3: 'PowerDeviceD2', 4: 'PowerDeviceD3', 5: 'PowerDeviceMaximum'})]],
'D1Latency' : [ 0x34, ['unsigned long']],
'D2Latency' : [ 0x38, ['unsigned long']],
'D3Latency' : [ 0x3c, ['unsigned long']],
} ],
'_VI_POOL_PAGE_HEADER' : [ 0x18, {
'NextPage' : [ 0x0, ['pointer64', ['_SLIST_ENTRY']]],
'VerifierEntry' : [ 0x8, ['pointer64', ['void']]],
'Signature' : [ 0x10, ['unsigned long long']],
} ],
'_RTL_RANGE_LIST' : [ 0x20, {
'ListHead' : [ 0x0, ['_LIST_ENTRY']],
'Flags' : [ 0x10, ['unsigned long']],
'Count' : [ 0x14, ['unsigned long']],
'Stamp' : [ 0x18, ['unsigned long']],
} ],
'_RTL_CRITICAL_SECTION_DEBUG' : [ 0x30, {
'Type' : [ 0x0, ['unsigned short']],
'CreatorBackTraceIndex' : [ 0x2, ['unsigned short']],
'CriticalSection' : [ 0x8, ['pointer64', ['_RTL_CRITICAL_SECTION']]],
'ProcessLocksList' : [ 0x10, ['_LIST_ENTRY']],
'EntryCount' : [ 0x20, ['unsigned long']],
'ContentionCount' : [ 0x24, ['unsigned long']],
'Spare' : [ 0x28, ['array', 2, ['unsigned long']]],
} ],
'__unnamed_1a48' : [ 0x14, {
'ClassGuid' : [ 0x0, ['_GUID']],
'SymbolicLinkName' : [ 0x10, ['array', 1, ['unsigned short']]],
} ],
'__unnamed_1a4a' : [ 0x2, {
'DeviceIds' : [ 0x0, ['array', 1, ['unsigned short']]],
} ],
'__unnamed_1a4c' : [ 0x2, {
'DeviceId' : [ 0x0, ['array', 1, ['unsigned short']]],
} ],
'__unnamed_1a4e' : [ 0x10, {
'NotificationStructure' : [ 0x0, ['pointer64', ['void']]],
'DeviceIds' : [ 0x8, ['array', 1, ['unsigned short']]],
} ],
'__unnamed_1a50' : [ 0x8, {
'Notification' : [ 0x0, ['pointer64', ['void']]],
} ],
'__unnamed_1a52' : [ 0x8, {
'NotificationCode' : [ 0x0, ['unsigned long']],
'NotificationData' : [ 0x4, ['unsigned long']],
} ],
'__unnamed_1a54' : [ 0x8, {
'VetoType' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'PNP_VetoTypeUnknown', 1: 'PNP_VetoLegacyDevice', 2: 'PNP_VetoPendingClose', 3: 'PNP_VetoWindowsApp', 4: 'PNP_VetoWindowsService', 5: 'PNP_VetoOutstandingOpen', 6: 'PNP_VetoDevice', 7: 'PNP_VetoDriver', 8: 'PNP_VetoIllegalDeviceRequest', 9: 'PNP_VetoInsufficientPower', 10: 'PNP_VetoNonDisableable', 11: 'PNP_VetoLegacyDriver', 12: 'PNP_VetoInsufficientRights'})]],
'DeviceIdVetoNameBuffer' : [ 0x4, ['array', 1, ['unsigned short']]],
} ],
'__unnamed_1a56' : [ 0x10, {
'BlockedDriverGuid' : [ 0x0, ['_GUID']],
} ],
'__unnamed_1a58' : [ 0x2, {
'ParentId' : [ 0x0, ['array', 1, ['unsigned short']]],
} ],
'__unnamed_1a5a' : [ 0x18, {
'DeviceClass' : [ 0x0, ['__unnamed_1a48']],
'TargetDevice' : [ 0x0, ['__unnamed_1a4a']],
'InstallDevice' : [ 0x0, ['__unnamed_1a4c']],
'CustomNotification' : [ 0x0, ['__unnamed_1a4e']],
'ProfileNotification' : [ 0x0, ['__unnamed_1a50']],
'PowerNotification' : [ 0x0, ['__unnamed_1a52']],
'VetoNotification' : [ 0x0, ['__unnamed_1a54']],
'BlockedDriverNotification' : [ 0x0, ['__unnamed_1a56']],
'InvalidIDNotification' : [ 0x0, ['__unnamed_1a58']],
} ],
'_PLUGPLAY_EVENT_BLOCK' : [ 0x48, {
'EventGuid' : [ 0x0, ['_GUID']],
'EventCategory' : [ 0x10, ['Enumeration', dict(target = 'long', choices = {0: 'HardwareProfileChangeEvent', 1: 'TargetDeviceChangeEvent', 2: 'DeviceClassChangeEvent', 3: 'CustomDeviceEvent', 4: 'DeviceInstallEvent', 5: 'DeviceArrivalEvent', 6: 'PowerEvent', 7: 'VetoEvent', 8: 'BlockedDriverEvent', 9: 'InvalidIDEvent', 10: 'MaxPlugEventCategory'})]],
'Result' : [ 0x18, ['pointer64', ['unsigned long']]],
'Flags' : [ 0x20, ['unsigned long']],
'TotalSize' : [ 0x24, ['unsigned long']],
'DeviceObject' : [ 0x28, ['pointer64', ['void']]],
'u' : [ 0x30, ['__unnamed_1a5a']],
} ],
'_CACHED_CHILD_LIST' : [ 0x10, {
'Count' : [ 0x0, ['unsigned long']],
'ValueList' : [ 0x8, ['unsigned long long']],
'RealKcb' : [ 0x8, ['pointer64', ['_CM_KEY_CONTROL_BLOCK']]],
} ],
'_PO_MEMORY_RANGE_ARRAY' : [ 0x20, {
'Range' : [ 0x0, ['_PO_MEMORY_RANGE_ARRAY_RANGE']],
'Link' : [ 0x0, ['_PO_MEMORY_RANGE_ARRAY_LINK']],
} ],
'__unnamed_1a71' : [ 0x8, {
'Signature' : [ 0x0, ['unsigned long']],
'CheckSum' : [ 0x4, ['unsigned long']],
} ],
'__unnamed_1a73' : [ 0x10, {
'DiskId' : [ 0x0, ['_GUID']],
} ],
'__unnamed_1a75' : [ 0x10, {
'Mbr' : [ 0x0, ['__unnamed_1a71']],
'Gpt' : [ 0x0, ['__unnamed_1a73']],
} ],
'_DUMP_INITIALIZATION_CONTEXT' : [ 0xa0, {
'Length' : [ 0x0, ['unsigned long']],
'Reserved' : [ 0x4, ['unsigned long']],
'MemoryBlock' : [ 0x8, ['pointer64', ['void']]],
'CommonBuffer' : [ 0x10, ['array', 2, ['pointer64', ['void']]]],
'PhysicalAddress' : [ 0x20, ['array', 2, ['_LARGE_INTEGER']]],
'StallRoutine' : [ 0x30, ['pointer64', ['void']]],
'OpenRoutine' : [ 0x38, ['pointer64', ['void']]],
'WriteRoutine' : [ 0x40, ['pointer64', ['void']]],
'FinishRoutine' : [ 0x48, ['pointer64', ['void']]],
'AdapterObject' : [ 0x50, ['pointer64', ['_ADAPTER_OBJECT']]],
'MappedRegisterBase' : [ 0x58, ['pointer64', ['void']]],
'PortConfiguration' : [ 0x60, ['pointer64', ['void']]],
'CrashDump' : [ 0x68, ['unsigned char']],
'MaximumTransferSize' : [ 0x6c, ['unsigned long']],
'CommonBufferSize' : [ 0x70, ['unsigned long']],
'TargetAddress' : [ 0x78, ['pointer64', ['void']]],
'WritePendingRoutine' : [ 0x80, ['pointer64', ['void']]],
'PartitionStyle' : [ 0x88, ['unsigned long']],
'DiskInfo' : [ 0x8c, ['__unnamed_1a75']],
} ],
'_IO_CLIENT_EXTENSION' : [ 0x10, {
'NextExtension' : [ 0x0, ['pointer64', ['_IO_CLIENT_EXTENSION']]],
'ClientIdentificationAddress' : [ 0x8, ['pointer64', ['void']]],
} ],
'_CM_NAME_HASH' : [ 0x18, {
'ConvKey' : [ 0x0, ['unsigned long']],
'NextHash' : [ 0x8, ['pointer64', ['_CM_NAME_HASH']]],
'NameLength' : [ 0x10, ['unsigned short']],
'Name' : [ 0x12, ['array', 1, ['unsigned short']]],
} ],
'_ARBITER_ALLOCATION_STATE' : [ 0x50, {
'Start' : [ 0x0, ['unsigned long long']],
'End' : [ 0x8, ['unsigned long long']],
'CurrentMinimum' : [ 0x10, ['unsigned long long']],
'CurrentMaximum' : [ 0x18, ['unsigned long long']],
'Entry' : [ 0x20, ['pointer64', ['_ARBITER_LIST_ENTRY']]],
'CurrentAlternative' : [ 0x28, ['pointer64', ['_ARBITER_ALTERNATIVE']]],
'AlternativeCount' : [ 0x30, ['unsigned long']],
'Alternatives' : [ 0x38, ['pointer64', ['_ARBITER_ALTERNATIVE']]],
'Flags' : [ 0x40, ['unsigned short']],
'RangeAttributes' : [ 0x42, ['unsigned char']],
'RangeAvailableAttributes' : [ 0x43, ['unsigned char']],
'WorkSpace' : [ 0x48, ['unsigned long long']],
} ],
'_PCI_HEADER_TYPE_0' : [ 0x30, {
'BaseAddresses' : [ 0x0, ['array', 6, ['unsigned long']]],
'CIS' : [ 0x18, ['unsigned long']],
'SubVendorID' : [ 0x1c, ['unsigned short']],
'SubSystemID' : [ 0x1e, ['unsigned short']],
'ROMBaseAddress' : [ 0x20, ['unsigned long']],
'CapabilitiesPtr' : [ 0x24, ['unsigned char']],
'Reserved1' : [ 0x25, ['array', 3, ['unsigned char']]],
'Reserved2' : [ 0x28, ['unsigned long']],
'InterruptLine' : [ 0x2c, ['unsigned char']],
'InterruptPin' : [ 0x2d, ['unsigned char']],
'MinimumGrant' : [ 0x2e, ['unsigned char']],
'MaximumLatency' : [ 0x2f, ['unsigned char']],
} ],
'_PO_DEVICE_NOTIFY_ORDER' : [ 0x410, {
'DevNodeSequence' : [ 0x0, ['unsigned long']],
'WarmEjectPdoPointer' : [ 0x8, ['pointer64', ['pointer64', ['_DEVICE_OBJECT']]]],
'OrderLevel' : [ 0x10, ['array', 8, ['_PO_NOTIFY_ORDER_LEVEL']]],
} ],
'_FS_FILTER_CALLBACKS' : [ 0x68, {
'SizeOfFsFilterCallbacks' : [ 0x0, ['unsigned long']],
'Reserved' : [ 0x4, ['unsigned long']],
'PreAcquireForSectionSynchronization' : [ 0x8, ['pointer64', ['void']]],
'PostAcquireForSectionSynchronization' : [ 0x10, ['pointer64', ['void']]],
'PreReleaseForSectionSynchronization' : [ 0x18, ['pointer64', ['void']]],
'PostReleaseForSectionSynchronization' : [ 0x20, ['pointer64', ['void']]],
'PreAcquireForCcFlush' : [ 0x28, ['pointer64', ['void']]],
'PostAcquireForCcFlush' : [ 0x30, ['pointer64', ['void']]],
'PreReleaseForCcFlush' : [ 0x38, ['pointer64', ['void']]],
'PostReleaseForCcFlush' : [ 0x40, ['pointer64', ['void']]],
'PreAcquireForModifiedPageWriter' : [ 0x48, ['pointer64', ['void']]],
'PostAcquireForModifiedPageWriter' : [ 0x50, ['pointer64', ['void']]],
'PreReleaseForModifiedPageWriter' : [ 0x58, ['pointer64', ['void']]],
'PostReleaseForModifiedPageWriter' : [ 0x60, ['pointer64', ['void']]],
} ],
'_IA64_DBGKD_CONTROL_SET' : [ 0x14, {
'Continue' : [ 0x0, ['unsigned long']],
'CurrentSymbolStart' : [ 0x4, ['unsigned long long']],
'CurrentSymbolEnd' : [ 0xc, ['unsigned long long']],
} ],
'_PO_MEMORY_RANGE_ARRAY_RANGE' : [ 0x20, {
'PageNo' : [ 0x0, ['unsigned long long']],
'StartPage' : [ 0x8, ['unsigned long long']],
'EndPage' : [ 0x10, ['unsigned long long']],
'CheckSum' : [ 0x18, ['unsigned long']],
} ],
'_u' : [ 0x50, {
'KeyNode' : [ 0x0, ['_CM_KEY_NODE']],
'KeyValue' : [ 0x0, ['_CM_KEY_VALUE']],
'KeySecurity' : [ 0x0, ['_CM_KEY_SECURITY']],
'KeyIndex' : [ 0x0, ['_CM_KEY_INDEX']],
'ValueData' : [ 0x0, ['_CM_BIG_DATA']],
'KeyList' : [ 0x0, ['array', 1, ['unsigned long']]],
'KeyString' : [ 0x0, ['array', 1, ['unsigned short']]],
} ],
'_ARBITER_CONFLICT_INFO' : [ 0x18, {
'OwningObject' : [ 0x0, ['pointer64', ['_DEVICE_OBJECT']]],
'Start' : [ 0x8, ['unsigned long long']],
'End' : [ 0x10, ['unsigned long long']],
} ],
'_PO_NOTIFY_ORDER_LEVEL' : [ 0x80, {
'LevelReady' : [ 0x0, ['_KEVENT']],
'DeviceCount' : [ 0x18, ['unsigned long']],
'ActiveCount' : [ 0x1c, ['unsigned long']],
'WaitSleep' : [ 0x20, ['_LIST_ENTRY']],
'ReadySleep' : [ 0x30, ['_LIST_ENTRY']],
'Pending' : [ 0x40, ['_LIST_ENTRY']],
'Complete' : [ 0x50, ['_LIST_ENTRY']],
'ReadyS0' : [ 0x60, ['_LIST_ENTRY']],
'WaitS0' : [ 0x70, ['_LIST_ENTRY']],
} ],
'__unnamed_1aa5' : [ 0x8, {
'Base' : [ 0x0, ['unsigned long']],
'Limit' : [ 0x4, ['unsigned long']],
} ],
'_PCI_HEADER_TYPE_2' : [ 0x30, {
'SocketRegistersBaseAddress' : [ 0x0, ['unsigned long']],
'CapabilitiesPtr' : [ 0x4, ['unsigned char']],
'Reserved' : [ 0x5, ['unsigned char']],
'SecondaryStatus' : [ 0x6, ['unsigned short']],
'PrimaryBus' : [ 0x8, ['unsigned char']],
'SecondaryBus' : [ 0x9, ['unsigned char']],
'SubordinateBus' : [ 0xa, ['unsigned char']],
'SecondaryLatency' : [ 0xb, ['unsigned char']],
'Range' : [ 0xc, ['array', 4, ['__unnamed_1aa5']]],
'InterruptLine' : [ 0x2c, ['unsigned char']],
'InterruptPin' : [ 0x2d, ['unsigned char']],
'BridgeControl' : [ 0x2e, ['unsigned short']],
} ],
'_CM_KEY_VALUE' : [ 0x18, {
'Signature' : [ 0x0, ['unsigned short']],
'NameLength' : [ 0x2, ['unsigned short']],
'DataLength' : [ 0x4, ['unsigned long']],
'Data' : [ 0x8, ['unsigned long']],
'Type' : [ 0xc, ['unsigned long']],
'Flags' : [ 0x10, ['unsigned short']],
'Spare' : [ 0x12, ['unsigned short']],
'Name' : [ 0x14, ['array', 1, ['unsigned short']]],
} ],
'_FS_FILTER_CALLBACK_DATA' : [ 0x40, {
'SizeOfFsFilterCallbackData' : [ 0x0, ['unsigned long']],
'Operation' : [ 0x4, ['unsigned char']],
'Reserved' : [ 0x5, ['unsigned char']],
'DeviceObject' : [ 0x8, ['pointer64', ['_DEVICE_OBJECT']]],
'FileObject' : [ 0x10, ['pointer64', ['_FILE_OBJECT']]],
'Parameters' : [ 0x18, ['_FS_FILTER_PARAMETERS']],
} ],
'_PO_MEMORY_RANGE_ARRAY_LINK' : [ 0x18, {
'Next' : [ 0x0, ['pointer64', ['_PO_MEMORY_RANGE_ARRAY']]],
'NextTable' : [ 0x8, ['unsigned long long']],
'CheckSum' : [ 0x10, ['unsigned long']],
'EntryCount' : [ 0x14, ['unsigned long']],
} ],
'_FAST_IO_DISPATCH' : [ 0xe0, {
'SizeOfFastIoDispatch' : [ 0x0, ['unsigned long']],
'FastIoCheckIfPossible' : [ 0x8, ['pointer64', ['void']]],
'FastIoRead' : [ 0x10, ['pointer64', ['void']]],
'FastIoWrite' : [ 0x18, ['pointer64', ['void']]],
'FastIoQueryBasicInfo' : [ 0x20, ['pointer64', ['void']]],
'FastIoQueryStandardInfo' : [ 0x28, ['pointer64', ['void']]],
'FastIoLock' : [ 0x30, ['pointer64', ['void']]],
'FastIoUnlockSingle' : [ 0x38, ['pointer64', ['void']]],
'FastIoUnlockAll' : [ 0x40, ['pointer64', ['void']]],
'FastIoUnlockAllByKey' : [ 0x48, ['pointer64', ['void']]],
'FastIoDeviceControl' : [ 0x50, ['pointer64', ['void']]],
'AcquireFileForNtCreateSection' : [ 0x58, ['pointer64', ['void']]],
'ReleaseFileForNtCreateSection' : [ 0x60, ['pointer64', ['void']]],
'FastIoDetachDevice' : [ 0x68, ['pointer64', ['void']]],
'FastIoQueryNetworkOpenInfo' : [ 0x70, ['pointer64', ['void']]],
'AcquireForModWrite' : [ 0x78, ['pointer64', ['void']]],
'MdlRead' : [ 0x80, ['pointer64', ['void']]],
'MdlReadComplete' : [ 0x88, ['pointer64', ['void']]],
'PrepareMdlWrite' : [ 0x90, ['pointer64', ['void']]],
'MdlWriteComplete' : [ 0x98, ['pointer64', ['void']]],
'FastIoReadCompressed' : [ 0xa0, ['pointer64', ['void']]],
'FastIoWriteCompressed' : [ 0xa8, ['pointer64', ['void']]],
'MdlReadCompleteCompressed' : [ 0xb0, ['pointer64', ['void']]],
'MdlWriteCompleteCompressed' : [ 0xb8, ['pointer64', ['void']]],
'FastIoQueryOpen' : [ 0xc0, ['pointer64', ['void']]],
'ReleaseForModWrite' : [ 0xc8, ['pointer64', ['void']]],
'AcquireForCcFlush' : [ 0xd0, ['pointer64', ['void']]],
'ReleaseForCcFlush' : [ 0xd8, ['pointer64', ['void']]],
} ],
'_OBJECT_DIRECTORY_ENTRY' : [ 0x18, {
'ChainLink' : [ 0x0, ['pointer64', ['_OBJECT_DIRECTORY_ENTRY']]],
'Object' : [ 0x8, ['pointer64', ['void']]],
'HashValue' : [ 0x10, ['unsigned long']],
} ],
'_POP_DEVICE_POWER_IRP' : [ 0x58, {
'Free' : [ 0x0, ['_SINGLE_LIST_ENTRY']],
'Irp' : [ 0x8, ['pointer64', ['_IRP']]],
'Notify' : [ 0x10, ['pointer64', ['_PO_DEVICE_NOTIFY']]],
'Pending' : [ 0x18, ['_LIST_ENTRY']],
'Complete' : [ 0x28, ['_LIST_ENTRY']],
'Abort' : [ 0x38, ['_LIST_ENTRY']],
'Failed' : [ 0x48, ['_LIST_ENTRY']],
} ],
'_FILE_BASIC_INFORMATION' : [ 0x28, {
'CreationTime' : [ 0x0, ['_LARGE_INTEGER']],
'LastAccessTime' : [ 0x8, ['_LARGE_INTEGER']],
'LastWriteTime' : [ 0x10, ['_LARGE_INTEGER']],
'ChangeTime' : [ 0x18, ['_LARGE_INTEGER']],
'FileAttributes' : [ 0x20, ['unsigned long']],
} ],
'_RTL_RANGE' : [ 0x28, {
'Start' : [ 0x0, ['unsigned long long']],
'End' : [ 0x8, ['unsigned long long']],
'UserData' : [ 0x10, ['pointer64', ['void']]],
'Owner' : [ 0x18, ['pointer64', ['void']]],
'Attributes' : [ 0x20, ['unsigned char']],
'Flags' : [ 0x21, ['unsigned char']],
} ],
'_PCI_HEADER_TYPE_1' : [ 0x30, {
'BaseAddresses' : [ 0x0, ['array', 2, ['unsigned long']]],
'PrimaryBus' : [ 0x8, ['unsigned char']],
'SecondaryBus' : [ 0x9, ['unsigned char']],
'SubordinateBus' : [ 0xa, ['unsigned char']],
'SecondaryLatency' : [ 0xb, ['unsigned char']],
'IOBase' : [ 0xc, ['unsigned char']],
'IOLimit' : [ 0xd, ['unsigned char']],
'SecondaryStatus' : [ 0xe, ['unsigned short']],
'MemoryBase' : [ 0x10, ['unsigned short']],
'MemoryLimit' : [ 0x12, ['unsigned short']],
'PrefetchBase' : [ 0x14, ['unsigned short']],
'PrefetchLimit' : [ 0x16, ['unsigned short']],
'PrefetchBaseUpper32' : [ 0x18, ['unsigned long']],
'PrefetchLimitUpper32' : [ 0x1c, ['unsigned long']],
'IOBaseUpper16' : [ 0x20, ['unsigned short']],
'IOLimitUpper16' : [ 0x22, ['unsigned short']],
'CapabilitiesPtr' : [ 0x24, ['unsigned char']],
'Reserved1' : [ 0x25, ['array', 3, ['unsigned char']]],
'ROMBaseAddress' : [ 0x28, ['unsigned long']],
'InterruptLine' : [ 0x2c, ['unsigned char']],
'InterruptPin' : [ 0x2d, ['unsigned char']],
'BridgeControl' : [ 0x2e, ['unsigned short']],
} ],
'_PRIVILEGE_SET' : [ 0x14, {
'PrivilegeCount' : [ 0x0, ['unsigned long']],
'Control' : [ 0x4, ['unsigned long']],
'Privilege' : [ 0x8, ['array', 1, ['_LUID_AND_ATTRIBUTES']]],
} ],
'_IO_SECURITY_CONTEXT' : [ 0x18, {
'SecurityQos' : [ 0x0, ['pointer64', ['_SECURITY_QUALITY_OF_SERVICE']]],
'AccessState' : [ 0x8, ['pointer64', ['_ACCESS_STATE']]],
'DesiredAccess' : [ 0x10, ['unsigned long']],
'FullCreateOptions' : [ 0x14, ['unsigned long']],
} ],
'_X86_DBGKD_CONTROL_SET' : [ 0x10, {
'TraceFlag' : [ 0x0, ['unsigned long']],
'Dr7' : [ 0x4, ['unsigned long']],
'CurrentSymbolStart' : [ 0x8, ['unsigned long']],
'CurrentSymbolEnd' : [ 0xc, ['unsigned long']],
} ],
'_RTL_ACTIVATION_CONTEXT_STACK_FRAME' : [ 0x18, {
'Previous' : [ 0x0, ['pointer64', ['_RTL_ACTIVATION_CONTEXT_STACK_FRAME']]],
'ActivationContext' : [ 0x8, ['pointer64', ['_ACTIVATION_CONTEXT']]],
'Flags' : [ 0x10, ['unsigned long']],
} ],
'_MAILSLOT_CREATE_PARAMETERS' : [ 0x18, {
'MailslotQuota' : [ 0x0, ['unsigned long']],
'MaximumMessageSize' : [ 0x4, ['unsigned long']],
'ReadTimeout' : [ 0x8, ['_LARGE_INTEGER']],
'TimeoutSpecified' : [ 0x10, ['unsigned char']],
} ],
'_NAMED_PIPE_CREATE_PARAMETERS' : [ 0x28, {
'NamedPipeType' : [ 0x0, ['unsigned long']],
'ReadMode' : [ 0x4, ['unsigned long']],
'CompletionMode' : [ 0x8, ['unsigned long']],
'MaximumInstances' : [ 0xc, ['unsigned long']],
'InboundQuota' : [ 0x10, ['unsigned long']],
'OutboundQuota' : [ 0x14, ['unsigned long']],
'DefaultTimeout' : [ 0x18, ['_LARGE_INTEGER']],
'TimeoutSpecified' : [ 0x20, ['unsigned char']],
} ],
'_CM_BIG_DATA' : [ 0x8, {
'Signature' : [ 0x0, ['unsigned short']],
'Count' : [ 0x2, ['unsigned short']],
'List' : [ 0x4, ['unsigned long']],
} ],
'_SUPPORTED_RANGE' : [ 0x28, {
'Next' : [ 0x0, ['pointer64', ['_SUPPORTED_RANGE']]],
'SystemAddressSpace' : [ 0x8, ['unsigned long']],
'SystemBase' : [ 0x10, ['long long']],
'Base' : [ 0x18, ['long long']],
'Limit' : [ 0x20, ['long long']],
} ],
'_CM_KEY_NODE' : [ 0x50, {
'Signature' : [ 0x0, ['unsigned short']],
'Flags' : [ 0x2, ['unsigned short']],
'LastWriteTime' : [ 0x4, ['_LARGE_INTEGER']],
'Spare' : [ 0xc, ['unsigned long']],
'Parent' : [ 0x10, ['unsigned long']],
'SubKeyCounts' : [ 0x14, ['array', 2, ['unsigned long']]],
'SubKeyLists' : [ 0x1c, ['array', 2, ['unsigned long']]],
'ValueList' : [ 0x24, ['_CHILD_LIST']],
'ChildHiveReference' : [ 0x1c, ['_CM_KEY_REFERENCE']],
'Security' : [ 0x2c, ['unsigned long']],
'Class' : [ 0x30, ['unsigned long']],
'MaxNameLen' : [ 0x34, ['BitField', dict(start_bit = 0, end_bit = 16, native_type='unsigned long')]],
'UserFlags' : [ 0x34, ['BitField', dict(start_bit = 16, end_bit = 20, native_type='unsigned long')]],
'VirtControlFlags' : [ 0x34, ['BitField', dict(start_bit = 20, end_bit = 24, native_type='unsigned long')]],
'Debug' : [ 0x34, ['BitField', dict(start_bit = 24, end_bit = 32, native_type='unsigned long')]],
'MaxClassLen' : [ 0x38, ['unsigned long']],
'MaxValueNameLen' : [ 0x3c, ['unsigned long']],
'MaxValueDataLen' : [ 0x40, ['unsigned long']],
'WorkVar' : [ 0x44, ['unsigned long']],
'NameLength' : [ 0x48, ['unsigned short']],
'ClassLength' : [ 0x4a, ['unsigned short']],
'Name' : [ 0x4c, ['array', 1, ['unsigned short']]],
} ],
'_ARBITER_ORDERING' : [ 0x10, {
'Start' : [ 0x0, ['unsigned long long']],
'End' : [ 0x8, ['unsigned long long']],
} ],
'_ARBITER_LIST_ENTRY' : [ 0x60, {
'ListEntry' : [ 0x0, ['_LIST_ENTRY']],
'AlternativeCount' : [ 0x10, ['unsigned long']],
'Alternatives' : [ 0x18, ['pointer64', ['_IO_RESOURCE_DESCRIPTOR']]],
'PhysicalDeviceObject' : [ 0x20, ['pointer64', ['_DEVICE_OBJECT']]],
'RequestSource' : [ 0x28, ['Enumeration', dict(target = 'long', choices = {0: 'ArbiterRequestLegacyReported', 1: 'ArbiterRequestHalReported', 2: 'ArbiterRequestLegacyAssigned', 3: 'ArbiterRequestPnpDetected', 4: 'ArbiterRequestPnpEnumerated', -1: 'ArbiterRequestUndefined'})]],
'Flags' : [ 0x2c, ['unsigned long']],
'WorkSpace' : [ 0x30, ['long long']],
'InterfaceType' : [ 0x38, ['Enumeration', dict(target = 'long', choices = {0: 'Internal', 1: 'Isa', 2: 'Eisa', 3: 'MicroChannel', 4: 'TurboChannel', 5: 'PCIBus', 6: 'VMEBus', 7: 'NuBus', 8: 'PCMCIABus', 9: 'CBus', 10: 'MPIBus', 11: 'MPSABus', 12: 'ProcessorInternal', 13: 'InternalPowerBus', 14: 'PNPISABus', 15: 'PNPBus', 16: 'MaximumInterfaceType', -1: 'InterfaceTypeUndefined'})]],
'SlotNumber' : [ 0x3c, ['unsigned long']],
'BusNumber' : [ 0x40, ['unsigned long']],
'Assignment' : [ 0x48, ['pointer64', ['_CM_PARTIAL_RESOURCE_DESCRIPTOR']]],
'SelectedAlternative' : [ 0x50, ['pointer64', ['_IO_RESOURCE_DESCRIPTOR']]],
'Result' : [ 0x58, ['Enumeration', dict(target = 'long', choices = {0: 'ArbiterResultSuccess', 1: 'ArbiterResultExternalConflict', 2: 'ArbiterResultNullRequest', -1: 'ArbiterResultUndefined'})]],
} ],
'_LPCP_NONPAGED_PORT_QUEUE' : [ 0x28, {
'Semaphore' : [ 0x0, ['_KSEMAPHORE']],
'BackPointer' : [ 0x20, ['pointer64', ['_LPCP_PORT_OBJECT']]],
} ],
'_CM_KEY_INDEX' : [ 0x8, {
'Signature' : [ 0x0, ['unsigned short']],
'Count' : [ 0x2, ['unsigned short']],
'List' : [ 0x4, ['array', 1, ['unsigned long']]],
} ],
'_FILE_NETWORK_OPEN_INFORMATION' : [ 0x38, {
'CreationTime' : [ 0x0, ['_LARGE_INTEGER']],
'LastAccessTime' : [ 0x8, ['_LARGE_INTEGER']],
'LastWriteTime' : [ 0x10, ['_LARGE_INTEGER']],
'ChangeTime' : [ 0x18, ['_LARGE_INTEGER']],
'AllocationSize' : [ 0x20, ['_LARGE_INTEGER']],
'EndOfFile' : [ 0x28, ['_LARGE_INTEGER']],
'FileAttributes' : [ 0x30, ['unsigned long']],
} ],
'_CM_KEY_REFERENCE' : [ 0x10, {
'KeyCell' : [ 0x0, ['unsigned long']],
'KeyHive' : [ 0x8, ['pointer64', ['_HHIVE']]],
} ],
'_ARBITER_ALTERNATIVE' : [ 0x38, {
'Minimum' : [ 0x0, ['unsigned long long']],
'Maximum' : [ 0x8, ['unsigned long long']],
'Length' : [ 0x10, ['unsigned long']],
'Alignment' : [ 0x14, ['unsigned long']],
'Priority' : [ 0x18, ['long']],
'Flags' : [ 0x1c, ['unsigned long']],
'Descriptor' : [ 0x20, ['pointer64', ['_IO_RESOURCE_DESCRIPTOR']]],
'Reserved' : [ 0x28, ['array', 3, ['unsigned long']]],
} ],
'__unnamed_1b2b' : [ 0x10, {
'EndingOffset' : [ 0x0, ['pointer64', ['_LARGE_INTEGER']]],
'ResourceToRelease' : [ 0x8, ['pointer64', ['pointer64', ['_ERESOURCE']]]],
} ],
'__unnamed_1b2d' : [ 0x8, {
'ResourceToRelease' : [ 0x0, ['pointer64', ['_ERESOURCE']]],
} ],
'__unnamed_1b31' : [ 0x8, {
'SyncType' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'SyncTypeOther', 1: 'SyncTypeCreateSection'})]],
'PageProtection' : [ 0x4, ['unsigned long']],
} ],
'__unnamed_1b33' : [ 0x28, {
'Argument1' : [ 0x0, ['pointer64', ['void']]],
'Argument2' : [ 0x8, ['pointer64', ['void']]],
'Argument3' : [ 0x10, ['pointer64', ['void']]],
'Argument4' : [ 0x18, ['pointer64', ['void']]],
'Argument5' : [ 0x20, ['pointer64', ['void']]],
} ],
'_FS_FILTER_PARAMETERS' : [ 0x28, {
'AcquireForModifiedPageWriter' : [ 0x0, ['__unnamed_1b2b']],
'ReleaseForModifiedPageWriter' : [ 0x0, ['__unnamed_1b2d']],
'AcquireForSectionSynchronization' : [ 0x0, ['__unnamed_1b31']],
'Others' : [ 0x0, ['__unnamed_1b33']],
} ],
'_COMPRESSED_DATA_INFO' : [ 0xc, {
'CompressionFormatAndEngine' : [ 0x0, ['unsigned short']],
'CompressionUnitShift' : [ 0x2, ['unsigned char']],
'ChunkShift' : [ 0x3, ['unsigned char']],
'ClusterShift' : [ 0x4, ['unsigned char']],
'Reserved' : [ 0x5, ['unsigned char']],
'NumberOfChunks' : [ 0x6, ['unsigned short']],
'CompressedChunkSizes' : [ 0x8, ['array', 1, ['unsigned long']]],
} ],
'_FILE_STANDARD_INFORMATION' : [ 0x18, {
'AllocationSize' : [ 0x0, ['_LARGE_INTEGER']],
'EndOfFile' : [ 0x8, ['_LARGE_INTEGER']],
'NumberOfLinks' : [ 0x10, ['unsigned long']],
'DeletePending' : [ 0x14, ['unsigned char']],
'Directory' : [ 0x15, ['unsigned char']],
} ],
'_CHILD_LIST' : [ 0x8, {
'Count' : [ 0x0, ['unsigned long']],
'List' : [ 0x4, ['unsigned long']],
} ],
'_CM_KEY_SECURITY' : [ 0x28, {
'Signature' : [ 0x0, ['unsigned short']],
'Reserved' : [ 0x2, ['unsigned short']],
'Flink' : [ 0x4, ['unsigned long']],
'Blink' : [ 0x8, ['unsigned long']],
'ReferenceCount' : [ 0xc, ['unsigned long']],
'DescriptorLength' : [ 0x10, ['unsigned long']],
'Descriptor' : [ 0x14, ['_SECURITY_DESCRIPTOR_RELATIVE']],
} ],
}
|
gpl-2.0
|
codelv/enaml-native
|
src/enamlnative/android/android_toggle_button.py
|
1
|
1623
|
"""
Copyright (c) 2017, Jairus Martin.
Distributed under the terms of the MIT License.
The full license is in the file LICENSE, distributed with this software.
Created on June 7, 2017
@author: jrm
"""
from atom.api import Typed, set_default
from enamlnative.widgets.toggle_button import ProxyToggleButton
from .android_compound_button import AndroidCompoundButton, CompoundButton
from .bridge import JavaMethod
class ToggleButton(CompoundButton):
__nativeclass__ = set_default('android.widget.ToggleButton')
setTextOff = JavaMethod('java.lang.CharSequence')
setTextOn = JavaMethod('java.lang.CharSequence')
class AndroidToggleButton(AndroidCompoundButton, ProxyToggleButton):
""" An Android implementation of an Enaml ProxyToggleButton.
"""
#: A reference to the widget created by the proxy.
widget = Typed(ToggleButton)
# -------------------------------------------------------------------------
# Initialization API
# -------------------------------------------------------------------------
def create_widget(self):
""" Create the underlying widget.
"""
d = self.declaration
self.widget = ToggleButton(self.get_context(), None,
d.style or "@attr/buttonStyleToggle")
# -------------------------------------------------------------------------
# ProxyToggleButton API
# -------------------------------------------------------------------------
def set_text_off(self, text):
self.widget.setTextOff(text)
def set_text_on(self, text):
self.widget.setTextOn(text)
|
mit
|
dbertha/odoo
|
addons/account/wizard/account_move_line_unreconcile_select.py
|
385
|
1864
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import fields, osv
class account_move_line_unreconcile_select(osv.osv_memory):
_name = "account.move.line.unreconcile.select"
_description = "Unreconciliation"
_columns ={
'account_id': fields.many2one('account.account','Account',required=True),
}
def action_open_window(self, cr, uid, ids, context=None):
data = self.read(cr, uid, ids, context=context)[0]
return {
'domain': "[('account_id','=',%d),('reconcile_id','<>',False),('state','<>','draft')]" % data['account_id'],
'name': 'Unreconciliation',
'view_type': 'form',
'view_mode': 'tree,form',
'view_id': False,
'res_model': 'account.move.line',
'type': 'ir.actions.act_window'
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
agpl-3.0
|
LeartS/odoo
|
addons/stock/res_config.py
|
61
|
8107
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Business Applications
# Copyright (C) 2004-2012 OpenERP S.A. (<http://openerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import fields, osv
from openerp.tools.translate import _
class res_company(osv.osv):
_inherit = "res.company"
_columns = {
'propagation_minimum_delta': fields.integer('Minimum Delta for Propagation of a Date Change on moves linked together'),
'internal_transit_location_id': fields.many2one('stock.location', 'Internal Transit Location', help="Technical field used for resupply routes between warehouses that belong to this company", on_delete="restrict"),
}
def create_transit_location(self, cr, uid, company_id, company_name, context=None):
'''Create a transit location with company_id being the given company_id. This is needed
in case of resuply routes between warehouses belonging to the same company, because
we don't want to create accounting entries at that time.
'''
data_obj = self.pool.get('ir.model.data')
try:
parent_loc = data_obj.get_object_reference(cr, uid, 'stock', 'stock_location_locations')[1]
except:
parent_loc = False
location_vals = {
'name': _('%s: Transit Location') % company_name,
'usage': 'transit',
'company_id': company_id,
'location_id': parent_loc,
}
location_id = self.pool.get('stock.location').create(cr, uid, location_vals, context=context)
self.write(cr, uid, [company_id], {'internal_transit_location_id': location_id}, context=context)
def create(self, cr, uid, vals, context=None):
company_id = super(res_company, self).create(cr, uid, vals, context=context)
self.create_transit_location(cr, uid, company_id, vals['name'], context=context)
return company_id
_defaults = {
'propagation_minimum_delta': 1,
}
class stock_config_settings(osv.osv_memory):
_name = 'stock.config.settings'
_inherit = 'res.config.settings'
_columns = {
'company_id': fields.many2one('res.company', 'Company', required=True),
'module_procurement_jit': fields.boolean("Generate procurement in real time",
help="""This allows Just In Time computation of procurement orders.
All procurement orders will be processed immediately, which could in some
cases entail a small performance impact.
This installs the module procurement_jit."""),
'module_claim_from_delivery': fields.boolean("Allow claim on deliveries",
help='Adds a Claim link to the delivery order.\n'
'-This installs the module claim_from_delivery.'),
'module_product_expiry': fields.boolean("Expiry date on serial numbers",
help="""Track different dates on products and serial numbers.
The following dates can be tracked:
- end of life
- best before date
- removal date
- alert date.
This installs the module product_expiry."""),
'group_uom': fields.boolean("Manage different units of measure for products",
implied_group='product.group_uom',
help="""Allows you to select and maintain different units of measure for products."""),
'group_uos': fields.boolean("Invoice products in a different unit of measure than the sales order",
implied_group='product.group_uos',
help='Allows you to sell units of a product, but invoice based on a different unit of measure.\n'
'For instance, you can sell pieces of meat that you invoice based on their weight.'),
'group_stock_packaging': fields.boolean("Allow to define several packaging methods on products",
implied_group='product.group_stock_packaging',
help="""Allows you to create and manage your packaging dimensions and types you want to be maintained in your system."""),
'group_stock_production_lot': fields.boolean("Track lots or serial numbers",
implied_group='stock.group_production_lot',
help="""This allows you to assign a lot (or serial number) to the pickings and moves. This can make it possible to know which production lot was sent to a certain client, ..."""),
'group_stock_tracking_lot': fields.boolean("Use packages: pallets, boxes, ...",
implied_group='stock.group_tracking_lot',
help="""This allows you to manage products by using serial numbers. When you select a serial number on product moves, you can get the traceability of that product."""),
'group_stock_tracking_owner': fields.boolean("Manage owner on stock",
implied_group='stock.group_tracking_owner',
help="""This way you can receive products attributed to a certain owner. """),
'group_stock_multiple_locations': fields.boolean("Manage multiple locations and warehouses",
implied_group='stock.group_locations',
help="""This will show you the locations and allows you to define multiple picking types and warehouses."""),
'group_stock_adv_location': fields.boolean("Manage advanced routes for your warehouse",
implied_group='stock.group_adv_location',
help="""This option supplements the warehouse application by effectively implementing Push and Pull inventory flows through Routes."""),
'decimal_precision': fields.integer('Decimal precision on weight', help="As an example, a decimal precision of 2 will allow weights like: 9.99 kg, whereas a decimal precision of 4 will allow weights like: 0.0231 kg."),
'propagation_minimum_delta': fields.related('company_id', 'propagation_minimum_delta', type='integer', string="Minimum days to trigger a propagation of date change in pushed/pull flows."),
'module_stock_dropshipping': fields.boolean("Manage dropshipping",
help='\nCreates the dropship route and add more complex tests'
'-This installs the module stock_dropshipping.'),
'module_stock_picking_wave': fields.boolean('Manage picking wave', help='Install the picking wave module which will help you grouping your pickings and processing them in batch'),
}
def onchange_adv_location(self, cr, uid, ids, group_stock_adv_location, context=None):
if group_stock_adv_location:
return {'value': {'group_stock_multiple_locations': True}}
return {}
def _default_company(self, cr, uid, context=None):
user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
return user.company_id.id
def get_default_dp(self, cr, uid, fields, context=None):
dp = self.pool.get('ir.model.data').get_object(cr, uid, 'product', 'decimal_stock_weight')
return {'decimal_precision': dp.digits}
def set_default_dp(self, cr, uid, ids, context=None):
config = self.browse(cr, uid, ids[0], context)
dp = self.pool.get('ir.model.data').get_object(cr, uid, 'product', 'decimal_stock_weight')
dp.write({'digits': config.decimal_precision})
_defaults = {
'company_id': _default_company,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
agpl-3.0
|
MyAOSP/external_chromium_org
|
chrome/test/pyautolib/pyauto.py
|
27
|
194924
|
#!/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.
"""PyAuto: Python Interface to Chromium's Automation Proxy.
PyAuto uses swig to expose Automation Proxy interfaces to Python.
For complete documentation on the functionality available,
run pydoc on this file.
Ref: http://dev.chromium.org/developers/testing/pyauto
Include the following in your PyAuto test script to make it run standalone.
from pyauto import Main
if __name__ == '__main__':
Main()
This script can be used as an executable to fire off other scripts, similar
to unittest.py
python pyauto.py test_script
"""
import cStringIO
import copy
import functools
import hashlib
import inspect
import logging
import optparse
import os
import pickle
import pprint
import re
import shutil
import signal
import socket
import stat
import string
import subprocess
import sys
import tempfile
import time
import types
import unittest
import urllib
import pyauto_paths
def _LocateBinDirs():
"""Setup a few dirs where we expect to find dependency libraries."""
deps_dirs = [
os.path.dirname(__file__),
pyauto_paths.GetThirdPartyDir(),
os.path.join(pyauto_paths.GetThirdPartyDir(), 'webdriver', 'pylib'),
]
sys.path += map(os.path.normpath, pyauto_paths.GetBuildDirs() + deps_dirs)
_LocateBinDirs()
_PYAUTO_DOC_URL = 'http://dev.chromium.org/developers/testing/pyauto'
try:
import pyautolib
# Needed so that all additional classes (like: FilePath, GURL) exposed by
# swig interface get available in this module.
from pyautolib import *
except ImportError:
print >>sys.stderr, 'Could not locate pyautolib shared libraries. ' \
'Did you build?\n Documentation: %s' % _PYAUTO_DOC_URL
# Mac requires python2.5 even when not the default 'python' (e.g. 10.6)
if 'darwin' == sys.platform and sys.version_info[:2] != (2,5):
print >>sys.stderr, '*\n* Perhaps use "python2.5", not "python" ?\n*'
raise
# Should go after sys.path is set appropriately
import bookmark_model
import download_info
import history_info
import omnibox_info
import plugins_info
import prefs_info
from pyauto_errors import AutomationCommandFail
from pyauto_errors import AutomationCommandTimeout
from pyauto_errors import JavascriptRuntimeError
from pyauto_errors import JSONInterfaceError
from pyauto_errors import NTPThumbnailNotShownError
import pyauto_utils
import simplejson as json # found in third_party
_CHROME_DRIVER_FACTORY = None
_DEFAULT_AUTOMATION_TIMEOUT = 45
_HTTP_SERVER = None
_REMOTE_PROXY = None
_OPTIONS = None
_BROWSER_PID = None
class PyUITest(pyautolib.PyUITestBase, unittest.TestCase):
"""Base class for UI Test Cases in Python.
A browser is created before executing each test, and is destroyed after
each test irrespective of whether the test passed or failed.
You should derive from this class and create methods with 'test' prefix,
and use methods inherited from PyUITestBase (the C++ side).
Example:
class MyTest(PyUITest):
def testNavigation(self):
self.NavigateToURL("http://www.google.com")
self.assertEqual("Google", self.GetActiveTabTitle())
"""
def __init__(self, methodName='runTest', **kwargs):
"""Initialize PyUITest.
When redefining __init__ in a derived class, make sure that:
o you make a call this __init__
o __init__ takes methodName as an arg. this is mandated by unittest module
Args:
methodName: the default method name. Internal use by unittest module
(The rest of the args can be in any order. They can even be skipped in
which case the defaults will be used.)
clear_profile: If True, clean the profile dir before use. Defaults to True
homepage: the home page. Defaults to "about:blank"
"""
# Fetch provided keyword args, or fill in defaults.
clear_profile = kwargs.get('clear_profile', True)
homepage = kwargs.get('homepage', 'about:blank')
self._automation_timeout = _DEFAULT_AUTOMATION_TIMEOUT * 1000
pyautolib.PyUITestBase.__init__(self, clear_profile, homepage)
self.Initialize(pyautolib.FilePath(self.BrowserPath()))
unittest.TestCase.__init__(self, methodName)
# Give all pyauto tests easy access to pprint.PrettyPrinter functions.
self.pprint = pprint.pprint
self.pformat = pprint.pformat
# Set up remote proxies, if they were requested.
self.remotes = []
self.remote = None
global _REMOTE_PROXY
if _REMOTE_PROXY:
self.remotes = _REMOTE_PROXY
self.remote = _REMOTE_PROXY[0]
def __del__(self):
pyautolib.PyUITestBase.__del__(self)
def _SetExtraChromeFlags(self):
"""Prepares the browser to launch with the specified extra Chrome flags.
This function is called right before the browser is launched for the first
time.
"""
for flag in self.ExtraChromeFlags():
if flag.startswith('--'):
flag = flag[2:]
split_pos = flag.find('=')
if split_pos >= 0:
flag_name = flag[:split_pos]
flag_val = flag[split_pos + 1:]
self.AppendBrowserLaunchSwitch(flag_name, flag_val)
else:
self.AppendBrowserLaunchSwitch(flag)
def __SetUp(self):
named_channel_id = None
if _OPTIONS:
named_channel_id = _OPTIONS.channel_id
if self.IsChromeOS(): # Enable testing interface on ChromeOS.
if self.get_clear_profile():
self.CleanupBrowserProfileOnChromeOS()
self.EnableCrashReportingOnChromeOS()
if not named_channel_id:
named_channel_id = self.EnableChromeTestingOnChromeOS()
else:
self._SetExtraChromeFlags() # Flags already previously set for ChromeOS.
if named_channel_id:
self._named_channel_id = named_channel_id
self.UseNamedChannelID(named_channel_id)
# Initialize automation and fire the browser (does not fire the browser
# on ChromeOS).
self.SetUp()
global _BROWSER_PID
try:
_BROWSER_PID = self.GetBrowserInfo()['browser_pid']
except JSONInterfaceError:
raise JSONInterfaceError('Unable to get browser_pid over automation '
'channel on first attempt. Something went very '
'wrong. Chrome probably did not launch.')
# Forcibly trigger all plugins to get registered. crbug.com/94123
# Sometimes flash files loaded too quickly after firing browser
# ends up getting downloaded, which seems to indicate that the plugin
# hasn't been registered yet.
if not self.IsChromeOS():
self.GetPluginsInfo()
if (self.IsChromeOS() and not self.GetLoginInfo()['is_logged_in'] and
self.ShouldOOBESkipToLogin()):
if self.GetOOBEScreenInfo()['screen_name'] != 'login':
self.SkipToLogin()
if self.ShouldAutoLogin():
# Login with default creds.
sys.path.append('/usr/local') # to import autotest libs
from autotest.cros import constants
creds = constants.CREDENTIALS['$default']
self.Login(creds[0], creds[1])
assert self.GetLoginInfo()['is_logged_in']
logging.info('Logged in as %s.' % creds[0])
# If we are connected to any RemoteHosts, create PyAuto
# instances on the remote sides and set them up too.
for remote in self.remotes:
remote.CreateTarget(self)
remote.setUp()
def setUp(self):
"""Override this method to launch browser differently.
Can be used to prevent launching the browser window by default in case a
test wants to do some additional setup before firing browser.
When using the named interface, it connects to an existing browser
instance.
On ChromeOS, a browser showing the login window is started. Tests can
initiate a user session by calling Login() or LoginAsGuest(). Cryptohome
vaults or flimflam profiles left over by previous tests can be cleared by
calling RemoveAllCryptohomeVaults() respectively CleanFlimflamDirs() before
logging in to improve isolation. Note that clearing flimflam profiles
requires a flimflam restart, briefly taking down network connectivity and
slowing down the test. This should be done for tests that use flimflam only.
"""
self.__SetUp()
def tearDown(self):
for remote in self.remotes:
remote.tearDown()
self.TearDown() # Destroy browser
# Method required by the Python standard library unittest.TestCase.
def runTest(self):
pass
@staticmethod
def BrowserPath():
"""Returns the path to Chromium binaries.
Expects the browser binaries to be in the
same location as the pyautolib binaries.
"""
return os.path.normpath(os.path.dirname(pyautolib.__file__))
def ExtraChromeFlags(self):
"""Return a list of extra chrome flags to use with Chrome for testing.
These are flags needed to facilitate testing. Override this function to
use a custom set of Chrome flags.
"""
auth_ext_path = ('/usr/local/autotest/deps/pyauto_dep/' +
'test_src/chrome/browser/resources/gaia_auth')
if self.IsChromeOS():
return [
'--homepage=about:blank',
'--allow-file-access',
'--allow-file-access-from-files',
'--enable-file-cookies',
'--disable-default-apps',
'--dom-automation',
'--skip-oauth-login',
# Enables injection of test content script for webui login automation
'--auth-ext-path=%s' % auth_ext_path,
# Enable automation provider, chromeos net and chromeos login logs
'--vmodule=*/browser/automation/*=2,*/chromeos/net/*=2,' +
'*/chromeos/login/*=2',
]
else:
return []
def ShouldOOBESkipToLogin(self):
"""Determine if we should skip the OOBE flow on ChromeOS.
This makes automation skip the OOBE flow during setUp() and land directly
to the login screen. Applies only if not logged in already.
Override and return False if OOBE flow is required, for OOBE tests, for
example. Calling this function directly will have no effect.
Returns:
True, if the OOBE should be skipped and automation should
go to the 'Add user' login screen directly
False, if the OOBE should not be skipped.
"""
assert self.IsChromeOS()
return True
def ShouldAutoLogin(self):
"""Determine if we should auto-login on ChromeOS at browser startup.
To be used for tests that expect user to be logged in before running test,
without caring which user. ShouldOOBESkipToLogin() should return True
for this to take effect.
Override and return False to not auto login, for tests where login is part
of the use case.
Returns:
True, if chrome should auto login after startup.
False, otherwise.
"""
assert self.IsChromeOS()
return True
def CloseChromeOnChromeOS(self):
"""Gracefully exit chrome on ChromeOS."""
def _GetListOfChromePids():
"""Retrieves the list of currently-running Chrome process IDs.
Returns:
A list of strings, where each string represents a currently-running
'chrome' process ID.
"""
proc = subprocess.Popen(['pgrep', '^chrome$'], stdout=subprocess.PIPE)
proc.wait()
return [x.strip() for x in proc.stdout.readlines()]
orig_pids = _GetListOfChromePids()
subprocess.call(['pkill', '^chrome$'])
def _AreOrigPidsDead(orig_pids):
"""Determines whether all originally-running 'chrome' processes are dead.
Args:
orig_pids: A list of strings, where each string represents the PID for
an originally-running 'chrome' process.
Returns:
True, if all originally-running 'chrome' processes have been killed, or
False otherwise.
"""
for new_pid in _GetListOfChromePids():
if new_pid in orig_pids:
return False
return True
self.WaitUntil(lambda: _AreOrigPidsDead(orig_pids))
@staticmethod
def _IsRootSuid(path):
"""Determine if |path| is a suid-root file."""
return os.path.isfile(path) and (os.stat(path).st_mode & stat.S_ISUID)
@staticmethod
def SuidPythonPath():
"""Path to suid_python binary on ChromeOS.
This is typically in the same directory as pyautolib.py
"""
return os.path.join(PyUITest.BrowserPath(), 'suid-python')
@staticmethod
def RunSuperuserActionOnChromeOS(action):
"""Run the given action with superuser privs (on ChromeOS).
Uses the suid_actions.py script.
Args:
action: An action to perform.
See suid_actions.py for available options.
Returns:
(stdout, stderr)
"""
assert PyUITest._IsRootSuid(PyUITest.SuidPythonPath()), \
'Did not find suid-root python at %s' % PyUITest.SuidPythonPath()
file_path = os.path.join(os.path.dirname(__file__), 'chromeos',
'suid_actions.py')
args = [PyUITest.SuidPythonPath(), file_path, '--action=%s' % action]
proc = subprocess.Popen(
args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()
return (stdout, stderr)
def EnableChromeTestingOnChromeOS(self):
"""Enables the named automation interface on chromeos.
Restarts chrome so that you get a fresh instance.
Also sets some testing-friendly flags for chrome.
Expects suid python to be present in the same dir as pyautolib.py
"""
assert PyUITest._IsRootSuid(self.SuidPythonPath()), \
'Did not find suid-root python at %s' % self.SuidPythonPath()
file_path = os.path.join(os.path.dirname(__file__), 'chromeos',
'enable_testing.py')
args = [self.SuidPythonPath(), file_path]
# Pass extra chrome flags for testing
for flag in self.ExtraChromeFlags():
args.append('--extra-chrome-flags=%s' % flag)
assert self.WaitUntil(lambda: self._IsSessionManagerReady(0))
proc = subprocess.Popen(args, stdout=subprocess.PIPE)
automation_channel_path = proc.communicate()[0].strip()
assert len(automation_channel_path), 'Could not enable testing interface'
return automation_channel_path
@staticmethod
def EnableCrashReportingOnChromeOS():
"""Enables crash reporting on ChromeOS.
Writes the "/home/chronos/Consent To Send Stats" file with a 32-char
readable string. See comment in session_manager_setup.sh which does this
too.
Note that crash reporting will work only if breakpad is built in, ie in a
'Google Chrome' build (not Chromium).
"""
consent_file = '/home/chronos/Consent To Send Stats'
def _HasValidConsentFile():
if not os.path.isfile(consent_file):
return False
stat = os.stat(consent_file)
return (len(open(consent_file).read()) and
(1000, 1000) == (stat.st_uid, stat.st_gid))
if not _HasValidConsentFile():
client_id = hashlib.md5('abcdefgh').hexdigest()
# Consent file creation and chown to chronos needs to be atomic
# to avoid races with the session_manager. crosbug.com/18413
# Therefore, create a temp file, chown, then rename it as consent file.
temp_file = consent_file + '.tmp'
open(temp_file, 'w').write(client_id)
# This file must be owned by chronos:chronos!
os.chown(temp_file, 1000, 1000);
shutil.move(temp_file, consent_file)
assert _HasValidConsentFile(), 'Could not create %s' % consent_file
@staticmethod
def _IsSessionManagerReady(old_pid):
"""Is the ChromeOS session_manager running and ready to accept DBus calls?
Called after session_manager is killed to know when it has restarted.
Args:
old_pid: The pid that session_manager had before it was killed,
to ensure that we don't look at the DBus interface
of an old session_manager process.
"""
pgrep_process = subprocess.Popen(['pgrep', 'session_manager'],
stdout=subprocess.PIPE)
new_pid = pgrep_process.communicate()[0].strip()
if not new_pid or old_pid == new_pid:
return False
import dbus
try:
bus = dbus.SystemBus()
proxy = bus.get_object('org.chromium.SessionManager',
'/org/chromium/SessionManager')
dbus.Interface(proxy, 'org.chromium.SessionManagerInterface')
except dbus.DBusException:
return False
return True
@staticmethod
def CleanupBrowserProfileOnChromeOS():
"""Cleanup browser profile dir on ChromeOS.
This does not clear cryptohome.
Browser should not be running, or else there will be locked files.
"""
profile_dir = '/home/chronos/user'
for item in os.listdir(profile_dir):
# Deleting .pki causes stateful partition to get erased.
if item not in ['log', 'flimflam'] and not item.startswith('.'):
pyauto_utils.RemovePath(os.path.join(profile_dir, item))
chronos_dir = '/home/chronos'
for item in os.listdir(chronos_dir):
if item != 'user' and not item.startswith('.'):
pyauto_utils.RemovePath(os.path.join(chronos_dir, item))
@staticmethod
def CleanupFlimflamDirsOnChromeOS():
"""Clean the contents of flimflam profiles and restart flimflam."""
PyUITest.RunSuperuserActionOnChromeOS('CleanFlimflamDirs')
@staticmethod
def RemoveAllCryptohomeVaultsOnChromeOS():
"""Remove any existing cryptohome vaults."""
PyUITest.RunSuperuserActionOnChromeOS('RemoveAllCryptohomeVaults')
@staticmethod
def _IsInodeNew(path, old_inode):
"""Determine whether an inode has changed. POSIX only.
Args:
path: The file path to check for changes.
old_inode: The old inode number.
Returns:
True if the path exists and its inode number is different from old_inode.
False otherwise.
"""
try:
stat_result = os.stat(path)
except OSError:
return False
if not stat_result:
return False
return stat_result.st_ino != old_inode
def RestartBrowser(self, clear_profile=True, pre_launch_hook=None):
"""Restart the browser.
For use with tests that require to restart the browser.
Args:
clear_profile: If True, the browser profile is cleared before restart.
Defaults to True, that is restarts browser with a clean
profile.
pre_launch_hook: If specified, must be a callable that is invoked before
the browser is started again. Not supported in ChromeOS.
"""
if self.IsChromeOS():
assert pre_launch_hook is None, 'Not supported in ChromeOS'
self.TearDown()
if clear_profile:
self.CleanupBrowserProfileOnChromeOS()
self.CloseChromeOnChromeOS()
self.EnableChromeTestingOnChromeOS()
self.SetUp()
return
# Not chromeos
orig_clear_state = self.get_clear_profile()
self.CloseBrowserAndServer()
self.set_clear_profile(clear_profile)
if pre_launch_hook:
pre_launch_hook()
logging.debug('Restarting browser with clear_profile=%s',
self.get_clear_profile())
self.LaunchBrowserAndServer()
self.set_clear_profile(orig_clear_state) # Reset to original state.
@staticmethod
def DataDir():
"""Returns the path to the data dir chrome/test/data."""
return os.path.normpath(
os.path.join(os.path.dirname(__file__), os.pardir, "data"))
@staticmethod
def ChromeOSDataDir():
"""Returns the path to the data dir chromeos/test/data."""
return os.path.normpath(
os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir,
"chromeos", "test", "data"))
@staticmethod
def GetFileURLForPath(*path):
"""Get file:// url for the given path.
Also quotes the url using urllib.quote().
Args:
path: Variable number of strings that can be joined.
"""
path_str = os.path.join(*path)
abs_path = os.path.abspath(path_str)
if sys.platform == 'win32':
# Don't quote the ':' in drive letter ( say, C: ) on win.
# Also, replace '\' with '/' as expected in a file:/// url.
drive, rest = os.path.splitdrive(abs_path)
quoted_path = drive.upper() + urllib.quote((rest.replace('\\', '/')))
return 'file:///' + quoted_path
else:
quoted_path = urllib.quote(abs_path)
return 'file://' + quoted_path
@staticmethod
def GetFileURLForDataPath(*relative_path):
"""Get file:// url for the given path relative to the chrome test data dir.
Also quotes the url using urllib.quote().
Args:
relative_path: Variable number of strings that can be joined.
"""
return PyUITest.GetFileURLForPath(PyUITest.DataDir(), *relative_path)
@staticmethod
def GetHttpURLForDataPath(*relative_path):
"""Get http:// url for the given path in the data dir.
The URL will be usable only after starting the http server.
"""
global _HTTP_SERVER
assert _HTTP_SERVER, 'HTTP Server not yet started'
return _HTTP_SERVER.GetURL(os.path.join('files', *relative_path)).spec()
@staticmethod
def ContentDataDir():
"""Get path to content/test/data."""
return os.path.join(PyUITest.DataDir(), os.pardir, os.pardir, os.pardir,
'content', 'test', 'data')
@staticmethod
def GetFileURLForContentDataPath(*relative_path):
"""Get file:// url for the given path relative to content test data dir.
Also quotes the url using urllib.quote().
Args:
relative_path: Variable number of strings that can be joined.
"""
return PyUITest.GetFileURLForPath(PyUITest.ContentDataDir(), *relative_path)
@staticmethod
def GetFtpURLForDataPath(ftp_server, *relative_path):
"""Get ftp:// url for the given path in the data dir.
Args:
ftp_server: handle to ftp server, an instance of SpawnedTestServer
relative_path: any number of path elements
The URL will be usable only after starting the ftp server.
"""
assert ftp_server, 'FTP Server not yet started'
return ftp_server.GetURL(os.path.join(*relative_path)).spec()
@staticmethod
def IsMac():
"""Are we on Mac?"""
return 'darwin' == sys.platform
@staticmethod
def IsLinux():
"""Are we on Linux? ChromeOS is linux too."""
return sys.platform.startswith('linux')
@staticmethod
def IsWin():
"""Are we on Win?"""
return 'win32' == sys.platform
@staticmethod
def IsWin7():
"""Are we on Windows 7?"""
if not PyUITest.IsWin():
return False
ver = sys.getwindowsversion()
return (ver[3], ver[0], ver[1]) == (2, 6, 1)
@staticmethod
def IsWinVista():
"""Are we on Windows Vista?"""
if not PyUITest.IsWin():
return False
ver = sys.getwindowsversion()
return (ver[3], ver[0], ver[1]) == (2, 6, 0)
@staticmethod
def IsWinXP():
"""Are we on Windows XP?"""
if not PyUITest.IsWin():
return False
ver = sys.getwindowsversion()
return (ver[3], ver[0], ver[1]) == (2, 5, 1)
@staticmethod
def IsChromeOS():
"""Are we on ChromeOS (or Chromium OS)?
Checks for "CHROMEOS_RELEASE_NAME=" in /etc/lsb-release.
"""
lsb_release = '/etc/lsb-release'
if not PyUITest.IsLinux() or not os.path.isfile(lsb_release):
return False
for line in open(lsb_release).readlines():
if line.startswith('CHROMEOS_RELEASE_NAME='):
return True
return False
@staticmethod
def IsPosix():
"""Are we on Mac/Linux?"""
return PyUITest.IsMac() or PyUITest.IsLinux()
@staticmethod
def IsEnUS():
"""Are we en-US?"""
# TODO: figure out the machine's langugage.
return True
@staticmethod
def GetPlatform():
"""Return the platform name."""
# Since ChromeOS is also Linux, we check for it first.
if PyUITest.IsChromeOS():
return 'chromeos'
elif PyUITest.IsLinux():
return 'linux'
elif PyUITest.IsMac():
return 'mac'
elif PyUITest.IsWin():
return 'win'
else:
return 'unknown'
@staticmethod
def EvalDataFrom(filename):
"""Return eval of python code from given file.
The datastructure used in the file will be preserved.
"""
data_file = os.path.join(filename)
contents = open(data_file).read()
try:
ret = eval(contents)
except:
print >>sys.stderr, '%s is an invalid data file.' % data_file
raise
return ret
@staticmethod
def ChromeOSBoard():
"""What is the ChromeOS board name"""
if PyUITest.IsChromeOS():
for line in open('/etc/lsb-release'):
line = line.strip()
if line.startswith('CHROMEOS_RELEASE_BOARD='):
return line.split('=')[1]
return None
@staticmethod
def Kill(pid):
"""Terminate the given pid.
If the pid refers to a renderer, use KillRendererProcess instead.
"""
if PyUITest.IsWin():
subprocess.call(['taskkill.exe', '/T', '/F', '/PID', str(pid)])
else:
os.kill(pid, signal.SIGTERM)
@staticmethod
def GetPrivateInfo():
"""Fetch info from private_tests_info.txt in private dir.
Returns:
a dictionary of items from private_tests_info.txt
"""
private_file = os.path.join(
PyUITest.DataDir(), 'pyauto_private', 'private_tests_info.txt')
assert os.path.exists(private_file), '%s missing' % private_file
return PyUITest.EvalDataFrom(private_file)
def WaitUntil(self, function, timeout=-1, retry_sleep=0.25, args=[],
expect_retval=None, return_retval=False, debug=True):
"""Poll on a condition until timeout.
Waits until the |function| evalues to |expect_retval| or until |timeout|
secs, whichever occurs earlier.
This is better than using a sleep, since it waits (almost) only as much
as needed.
WARNING: This method call should be avoided as far as possible in favor
of a real wait from chromium (like wait-until-page-loaded).
Only use in case there's really no better option.
EXAMPLES:-
Wait for "file.txt" to get created:
WaitUntil(os.path.exists, args=["file.txt"])
Same as above, but using lambda:
WaitUntil(lambda: os.path.exists("file.txt"))
Args:
function: the function whose truth value is to be evaluated
timeout: the max timeout (in secs) for which to wait. The default
action is to wait for kWaitForActionMaxMsec, as set in
ui_test.cc
Use None to wait indefinitely.
retry_sleep: the sleep interval (in secs) before retrying |function|.
Defaults to 0.25 secs.
args: the args to pass to |function|
expect_retval: the expected return value for |function|. This forms the
exit criteria. In case this is None (the default),
|function|'s return value is checked for truth,
so 'non-empty-string' should match with True
return_retval: If True, return the value returned by the last call to
|function()|
debug: if True, displays debug info at each retry.
Returns:
The return value of the |function| (when return_retval == True)
True, if returning when |function| evaluated to True (when
return_retval == False)
False, when returning due to timeout
"""
if timeout == -1: # Default
timeout = self._automation_timeout / 1000.0
assert callable(function), "function should be a callable"
begin = time.time()
debug_begin = begin
retval = None
while timeout is None or time.time() - begin <= timeout:
retval = function(*args)
if (expect_retval is None and retval) or \
(expect_retval is not None and expect_retval == retval):
return retval if return_retval else True
if debug and time.time() - debug_begin > 5:
debug_begin += 5
if function.func_name == (lambda: True).func_name:
function_info = inspect.getsource(function).strip()
else:
function_info = '%s()' % function.func_name
logging.debug('WaitUntil(%s:%d %s) still waiting. '
'Expecting %s. Last returned %s.',
os.path.basename(inspect.getsourcefile(function)),
inspect.getsourcelines(function)[1],
function_info,
True if expect_retval is None else expect_retval,
retval)
time.sleep(retry_sleep)
return retval if return_retval else False
def StartFTPServer(self, data_dir):
"""Start a local file server hosting data files over ftp://
Args:
data_dir: path where ftp files should be served
Returns:
handle to FTP Server, an instance of SpawnedTestServer
"""
ftp_server = pyautolib.SpawnedTestServer(
pyautolib.SpawnedTestServer.TYPE_FTP,
'127.0.0.1',
pyautolib.FilePath(data_dir))
assert ftp_server.Start(), 'Could not start ftp server'
logging.debug('Started ftp server at "%s".', data_dir)
return ftp_server
def StopFTPServer(self, ftp_server):
"""Stop the local ftp server."""
assert ftp_server, 'FTP Server not yet started'
assert ftp_server.Stop(), 'Could not stop ftp server'
logging.debug('Stopped ftp server.')
def StartHTTPServer(self, data_dir):
"""Starts a local HTTP SpawnedTestServer serving files from |data_dir|.
Args:
data_dir: path where the SpawnedTestServer should serve files from.
This will be appended to the source dir to get the final document root.
Returns:
handle to the HTTP SpawnedTestServer
"""
http_server = pyautolib.SpawnedTestServer(
pyautolib.SpawnedTestServer.TYPE_HTTP,
'127.0.0.1',
pyautolib.FilePath(data_dir))
assert http_server.Start(), 'Could not start HTTP server'
logging.debug('Started HTTP server at "%s".', data_dir)
return http_server
def StopHTTPServer(self, http_server):
assert http_server, 'HTTP server not yet started'
assert http_server.Stop(), 'Cloud not stop the HTTP server'
logging.debug('Stopped HTTP server.')
def StartHttpsServer(self, cert_type, data_dir):
"""Starts a local HTTPS SpawnedTestServer serving files from |data_dir|.
Args:
cert_type: An instance of SSLOptions.ServerCertificate for three
certificate types: ok, expired, or mismatch.
data_dir: The path where SpawnedTestServer should serve files from.
This is appended to the source dir to get the final
document root.
Returns:
Handle to the HTTPS SpawnedTestServer
"""
https_server = pyautolib.SpawnedTestServer(
pyautolib.SpawnedTestServer.TYPE_HTTPS,
pyautolib.SSLOptions(cert_type),
pyautolib.FilePath(data_dir))
assert https_server.Start(), 'Could not start HTTPS server.'
logging.debug('Start HTTPS server at "%s".' % data_dir)
return https_server
def StopHttpsServer(self, https_server):
assert https_server, 'HTTPS server not yet started.'
assert https_server.Stop(), 'Could not stop the HTTPS server.'
logging.debug('Stopped HTTPS server.')
class ActionTimeoutChanger(object):
"""Facilitate temporary changes to PyAuto command timeout.
Automatically resets to original timeout when object is destroyed.
"""
_saved_timeout = -1 # Saved timeout value
def __init__(self, ui_test, new_timeout):
"""Initialize.
Args:
ui_test: a PyUITest object
new_timeout: new timeout to use (in milli secs)
"""
self._saved_timeout = ui_test._automation_timeout
ui_test._automation_timeout = new_timeout
self._ui_test = ui_test
def __del__(self):
"""Reset command_execution_timeout_ms to original value."""
self._ui_test._automation_timeout = self._saved_timeout
class JavascriptExecutor(object):
"""Abstract base class for JavaScript injection.
Derived classes should override Execute method."""
def Execute(self, script):
pass
class JavascriptExecutorInTab(JavascriptExecutor):
"""Wrapper for injecting JavaScript in a tab."""
def __init__(self, ui_test, tab_index=0, windex=0, frame_xpath=''):
"""Initialize.
Refer to ExecuteJavascript() for the complete argument list
description.
Args:
ui_test: a PyUITest object
"""
self._ui_test = ui_test
self.windex = windex
self.tab_index = tab_index
self.frame_xpath = frame_xpath
def Execute(self, script):
"""Execute script in the tab."""
return self._ui_test.ExecuteJavascript(script,
self.tab_index,
self.windex,
self.frame_xpath)
class JavascriptExecutorInRenderView(JavascriptExecutor):
"""Wrapper for injecting JavaScript in an extension view."""
def __init__(self, ui_test, view, frame_xpath=''):
"""Initialize.
Refer to ExecuteJavascriptInRenderView() for the complete argument list
description.
Args:
ui_test: a PyUITest object
"""
self._ui_test = ui_test
self.view = view
self.frame_xpath = frame_xpath
def Execute(self, script):
"""Execute script in the render view."""
return self._ui_test.ExecuteJavascriptInRenderView(script,
self.view,
self.frame_xpath)
def _GetResultFromJSONRequestDiagnostics(self):
"""Same as _GetResultFromJSONRequest without throwing a timeout exception.
This method is used to diagnose if a command returns without causing a
timout exception to be thrown. This should be used for debugging purposes
only.
Returns:
True if the request returned; False if it timed out.
"""
result = self._SendJSONRequest(-1,
json.dumps({'command': 'GetBrowserInfo',}),
self._automation_timeout)
if not result:
# The diagnostic command did not complete, Chrome is probably in a bad
# state
return False
return True
def _GetResultFromJSONRequest(self, cmd_dict, windex=0, timeout=-1):
"""Issue call over the JSON automation channel and fetch output.
This method packages the given dictionary into a json string, sends it
over the JSON automation channel, loads the json output string returned,
and returns it back as a dictionary.
Args:
cmd_dict: the command dictionary. It must have a 'command' key
Sample:
{
'command': 'SetOmniboxText',
'text': text,
}
windex: 0-based window index on which to work. Default: 0 (first window)
Use -ve windex or None if the automation command does not apply
to a browser window. Example: for chromeos login
timeout: request timeout (in milliseconds)
Returns:
a dictionary for the output returned by the automation channel.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
if timeout == -1: # Default
timeout = self._automation_timeout
if windex is None: # Do not target any window
windex = -1
result = self._SendJSONRequest(windex, json.dumps(cmd_dict), timeout)
if not result:
additional_info = 'No information available.'
# Windows does not support os.kill until Python 2.7.
if not self.IsWin() and _BROWSER_PID:
browser_pid_exists = True
# Does the browser PID exist?
try:
# Does not actually kill the process
os.kill(int(_BROWSER_PID), 0)
except OSError:
browser_pid_exists = False
if browser_pid_exists:
if self._GetResultFromJSONRequestDiagnostics():
# Browser info, worked, that means this hook had a problem
additional_info = ('The browser process ID %d still exists. '
'PyAuto was able to obtain browser info. It '
'is possible this hook is broken.'
% _BROWSER_PID)
else:
additional_info = ('The browser process ID %d still exists. '
'PyAuto was not able to obtain browser info. '
'It is possible the browser is hung.'
% _BROWSER_PID)
else:
additional_info = ('The browser process ID %d no longer exists. '
'Perhaps the browser crashed.' % _BROWSER_PID)
elif not _BROWSER_PID:
additional_info = ('The browser PID was not obtained. Does this test '
'have a unique startup configuration?')
# Mask private data if it is in the JSON dictionary
cmd_dict_copy = copy.copy(cmd_dict)
if 'password' in cmd_dict_copy.keys():
cmd_dict_copy['password'] = '**********'
if 'username' in cmd_dict_copy.keys():
cmd_dict_copy['username'] = 'removed_username'
raise JSONInterfaceError('Automation call %s received empty response. '
'Additional information:\n%s' % (cmd_dict_copy,
additional_info))
ret_dict = json.loads(result)
if ret_dict.has_key('error'):
if ret_dict.get('is_interface_timeout'):
raise AutomationCommandTimeout(ret_dict['error'])
elif ret_dict.get('is_interface_error'):
raise JSONInterfaceError(ret_dict['error'])
else:
raise AutomationCommandFail(ret_dict['error'])
return ret_dict
def NavigateToURL(self, url, windex=0, tab_index=None, navigation_count=1):
"""Navigate the given tab to the given URL.
Note that this method also activates the corresponding tab/window if it's
not active already. Blocks until |navigation_count| navigations have
completed.
Args:
url: The URL to which to navigate, can be a string or GURL object.
windex: The index of the browser window to work on. Defaults to the first
window.
tab_index: The index of the tab to work on. Defaults to the active tab.
navigation_count: the number of navigations to wait for. Defaults to 1.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
if isinstance(url, GURL):
url = url.spec()
if tab_index is None:
tab_index = self.GetActiveTabIndex(windex)
cmd_dict = {
'command': 'NavigateToURL',
'url': url,
'windex': windex,
'tab_index': tab_index,
'navigation_count': navigation_count,
}
self._GetResultFromJSONRequest(cmd_dict, windex=None)
def NavigateToURLAsync(self, url, windex=0, tab_index=None):
"""Initiate a URL navigation.
A wrapper for NavigateToURL with navigation_count set to 0.
"""
self.NavigateToURL(url, windex, tab_index, 0)
def ApplyAccelerator(self, accelerator, windex=0):
"""Apply the accelerator with the given id.
Note that this method schedules the accelerator, but does not wait for it to
actually finish doing anything.
Args:
accelerator: The accelerator id, IDC_BACK, IDC_NEWTAB, etc. The list of
ids can be found at chrome/app/chrome_command_ids.h.
windex: The index of the browser window to work on. Defaults to the first
window.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'ApplyAccelerator',
'accelerator': accelerator,
'windex': windex,
}
self._GetResultFromJSONRequest(cmd_dict, windex=None)
def RunCommand(self, accelerator, windex=0):
"""Apply the accelerator with the given id and wait for it to finish.
This is like ApplyAccelerator except that it waits for the command to finish
executing.
Args:
accelerator: The accelerator id. The list of ids can be found at
chrome/app/chrome_command_ids.h.
windex: The index of the browser window to work on. Defaults to the first
window.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'RunCommand',
'accelerator': accelerator,
'windex': windex,
}
self._GetResultFromJSONRequest(cmd_dict, windex=None)
def IsMenuCommandEnabled(self, accelerator, windex=0):
"""Check if a command is enabled for a window.
Returns true if the command with the given accelerator id is enabled on the
given window.
Args:
accelerator: The accelerator id. The list of ids can be found at
chrome/app/chrome_command_ids.h.
windex: The index of the browser window to work on. Defaults to the first
window.
Returns:
True if the command is enabled for the given window.
"""
cmd_dict = {
'command': 'IsMenuCommandEnabled',
'accelerator': accelerator,
'windex': windex,
}
return self._GetResultFromJSONRequest(cmd_dict, windex=None).get('enabled')
def TabGoForward(self, tab_index=0, windex=0):
"""Navigate a tab forward in history.
Equivalent to clicking the Forward button in the UI. Activates the tab as a
side effect.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
self.ActivateTab(tab_index, windex)
self.RunCommand(IDC_FORWARD, windex)
def TabGoBack(self, tab_index=0, windex=0):
"""Navigate a tab backwards in history.
Equivalent to clicking the Back button in the UI. Activates the tab as a
side effect.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
self.ActivateTab(tab_index, windex)
self.RunCommand(IDC_BACK, windex)
def ReloadTab(self, tab_index=0, windex=0):
"""Reload the given tab.
Blocks until the page has reloaded.
Args:
tab_index: The index of the tab to reload. Defaults to 0.
windex: The index of the browser window to work on. Defaults to the first
window.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
self.ActivateTab(tab_index, windex)
self.RunCommand(IDC_RELOAD, windex)
def CloseTab(self, tab_index=0, windex=0, wait_until_closed=True):
"""Close the given tab.
Note: Be careful closing the last tab in a window as it may close the
browser.
Args:
tab_index: The index of the tab to reload. Defaults to 0.
windex: The index of the browser window to work on. Defaults to the first
window.
wait_until_closed: Whether to block until the tab finishes closing.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'CloseTab',
'tab_index': tab_index,
'windex': windex,
'wait_until_closed': wait_until_closed,
}
self._GetResultFromJSONRequest(cmd_dict, windex=None)
def WaitForTabToBeRestored(self, tab_index=0, windex=0, timeout=-1):
"""Wait for the given tab to be restored.
Args:
tab_index: The index of the tab to reload. Defaults to 0.
windex: The index of the browser window to work on. Defaults to the first
window.
timeout: Timeout in milliseconds.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'CloseTab',
'tab_index': tab_index,
'windex': windex,
}
self._GetResultFromJSONRequest(cmd_dict, windex=None, timeout=timeout)
def ReloadActiveTab(self, windex=0):
"""Reload an active tab.
Warning: Depending on the concept of an active tab is dangerous as it can
change during the test. Use ReloadTab and supply a tab_index explicitly.
Args:
windex: The index of the browser window to work on. Defaults to the first
window.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
self.ReloadTab(self.GetActiveTabIndex(windex), windex)
def GetActiveTabIndex(self, windex=0):
"""Get the index of the currently active tab in the given browser window.
Warning: Depending on the concept of an active tab is dangerous as it can
change during the test. Supply the tab_index explicitly, if possible.
Args:
windex: The index of the browser window to work on. Defaults to the first
window.
Returns:
An integer index for the currently active tab.
"""
cmd_dict = {
'command': 'GetActiveTabIndex',
'windex': windex,
}
return self._GetResultFromJSONRequest(cmd_dict,
windex=None).get('tab_index')
def ActivateTab(self, tab_index=0, windex=0):
"""Activates the given tab in the specified window.
Warning: Depending on the concept of an active tab is dangerous as it can
change during the test. Instead use functions that accept a tab_index
explicitly.
Args:
tab_index: Integer index of the tab to activate; defaults to 0.
windex: Integer index of the browser window to use; defaults to the first
window.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'ActivateTab',
'tab_index': tab_index,
'windex': windex,
}
self.BringBrowserToFront(windex)
self._GetResultFromJSONRequest(cmd_dict, windex=None)
def BringBrowserToFront(self, windex=0):
"""Activate the browser's window and bring it to front.
Args:
windex: Integer index of the browser window to use; defaults to the first
window.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'BringBrowserToFront',
'windex': windex,
}
self._GetResultFromJSONRequest(cmd_dict, windex=None)
def GetBrowserWindowCount(self):
"""Get the browser window count.
Args:
None.
Returns:
Integer count of the number of browser windows. Includes popups.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {'command': 'GetBrowserWindowCount'}
return self._GetResultFromJSONRequest(cmd_dict, windex=None)['count']
def OpenNewBrowserWindow(self, show):
"""Create a new browser window.
Args:
show: Boolean indicating whether to show the window.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'OpenNewBrowserWindow',
'show': show,
}
self._GetResultFromJSONRequest(cmd_dict, windex=None)
def CloseBrowserWindow(self, windex=0):
"""Create a new browser window.
Args:
windex: Index of the browser window to close; defaults to 0.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'CloseBrowserWindow',
'windex': windex,
}
self._GetResultFromJSONRequest(cmd_dict, windex=None)
def AppendTab(self, url, windex=0):
"""Append a new tab.
Creates a new tab at the end of given browser window and activates
it. Blocks until the specified |url| is loaded.
Args:
url: The url to load, can be string or a GURL object.
windex: The index of the browser window to work on. Defaults to the first
window.
Returns:
True if the url loads successfully in the new tab. False otherwise.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
if isinstance(url, GURL):
url = url.spec()
cmd_dict = {
'command': 'AppendTab',
'url': url,
'windex': windex,
}
return self._GetResultFromJSONRequest(cmd_dict, windex=None).get('result')
def GetTabCount(self, windex=0):
"""Gets the number of tab in the given browser window.
Args:
windex: Integer index of the browser window to use; defaults to the first
window.
Returns:
The tab count.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'GetTabCount',
'windex': windex,
}
return self._GetResultFromJSONRequest(cmd_dict, windex=None)['tab_count']
def GetTabInfo(self, tab_index=0, windex=0):
"""Gets information about the specified tab.
Args:
tab_index: Integer index of the tab to activate; defaults to 0.
windex: Integer index of the browser window to use; defaults to the first
window.
Returns:
A dictionary containing information about the tab.
Example:
{ u'title': "Hello World",
u'url': "http://foo.bar", }
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'GetTabInfo',
'tab_index': tab_index,
'windex': windex,
}
return self._GetResultFromJSONRequest(cmd_dict, windex=None)
def GetActiveTabTitle(self, windex=0):
"""Gets the title of the active tab.
Warning: Depending on the concept of an active tab is dangerous as it can
change during the test. Use GetTabInfo and supply a tab_index explicitly.
Args:
windex: Integer index of the browser window to use; defaults to the first
window.
Returns:
The tab title as a string.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
return self.GetTabInfo(self.GetActiveTabIndex(windex), windex)['title']
def GetActiveTabURL(self, windex=0):
"""Gets the URL of the active tab.
Warning: Depending on the concept of an active tab is dangerous as it can
change during the test. Use GetTabInfo and supply a tab_index explicitly.
Args:
windex: Integer index of the browser window to use; defaults to the first
window.
Returns:
The tab URL as a GURL object.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
return GURL(str(self.GetTabInfo(self.GetActiveTabIndex(windex),
windex)['url']))
def ActionOnSSLBlockingPage(self, tab_index=0, windex=0, proceed=True):
"""Take action on an interstitial page.
Calling this when an interstitial page is not showing is an error.
Args:
tab_index: Integer index of the tab to activate; defaults to 0.
windex: Integer index of the browser window to use; defaults to the first
window.
proceed: Whether to proceed to the URL or not.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'ActionOnSSLBlockingPage',
'tab_index': tab_index,
'windex': windex,
'proceed': proceed,
}
return self._GetResultFromJSONRequest(cmd_dict, windex=None)
def GetBookmarkModel(self, windex=0):
"""Return the bookmark model as a BookmarkModel object.
This is a snapshot of the bookmark model; it is not a proxy and
does not get updated as the bookmark model changes.
"""
bookmarks_as_json = self._GetBookmarksAsJSON(windex)
if not bookmarks_as_json:
raise JSONInterfaceError('Could not resolve browser proxy.')
return bookmark_model.BookmarkModel(bookmarks_as_json)
def _GetBookmarksAsJSON(self, windex=0):
"""Get bookmarks as a JSON dictionary; used by GetBookmarkModel()."""
cmd_dict = {
'command': 'GetBookmarksAsJSON',
'windex': windex,
}
self.WaitForBookmarkModelToLoad(windex)
return self._GetResultFromJSONRequest(cmd_dict,
windex=None)['bookmarks_as_json']
def WaitForBookmarkModelToLoad(self, windex=0):
"""Gets the status of the bookmark bar as a dictionary.
Args:
windex: Integer index of the browser window to use; defaults to the first
window.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'WaitForBookmarkModelToLoad',
'windex': windex,
}
return self._GetResultFromJSONRequest(cmd_dict, windex=None)
def GetBookmarkBarStatus(self, windex=0):
"""Gets the status of the bookmark bar as a dictionary.
Args:
windex: Integer index of the browser window to use; defaults to the first
window.
Returns:
A dictionary.
Example:
{ u'visible': True,
u'animating': False,
u'detached': False, }
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'GetBookmarkBarStatus',
'windex': windex,
}
return self._GetResultFromJSONRequest(cmd_dict, windex=None)
def GetBookmarkBarStatus(self, windex=0):
"""Gets the status of the bookmark bar as a dictionary.
Args:
windex: Integer index of the browser window to use; defaults to the first
window.
Returns:
A dictionary.
Example:
{ u'visible': True,
u'animating': False,
u'detached': False, }
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'GetBookmarkBarStatus',
'windex': windex,
}
return self._GetResultFromJSONRequest(cmd_dict, windex=None)
def GetBookmarkBarStatus(self, windex=0):
"""Gets the status of the bookmark bar as a dictionary.
Args:
windex: Integer index of the browser window to use; defaults to the first
window.
Returns:
A dictionary.
Example:
{ u'visible': True,
u'animating': False,
u'detached': False, }
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'GetBookmarkBarStatus',
'windex': windex,
}
return self._GetResultFromJSONRequest(cmd_dict, windex=None)
def GetBookmarkBarVisibility(self, windex=0):
"""Returns the visibility of the bookmark bar.
Args:
windex: Integer index of the browser window to use; defaults to the first
window.
Returns:
True if the bookmark bar is visible, false otherwise.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
return self.GetBookmarkBarStatus(windex)['visible']
def AddBookmarkGroup(self, parent_id, index, title, windex=0):
"""Adds a bookmark folder.
Args:
parent_id: The parent bookmark folder.
index: The location in the parent's list to insert this bookmark folder.
title: The name of the bookmark folder.
windex: Integer index of the browser window to use; defaults to the first
window.
Returns:
True if the bookmark bar is detached, false otherwise.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
if isinstance(parent_id, basestring):
parent_id = int(parent_id)
cmd_dict = {
'command': 'AddBookmark',
'parent_id': parent_id,
'index': index,
'title': title,
'is_folder': True,
'windex': windex,
}
self.WaitForBookmarkModelToLoad(windex)
self._GetResultFromJSONRequest(cmd_dict, windex=None)
def AddBookmarkURL(self, parent_id, index, title, url, windex=0):
"""Add a bookmark URL.
Args:
parent_id: The parent bookmark folder.
index: The location in the parent's list to insert this bookmark.
title: The name of the bookmark.
url: The url of the bookmark.
windex: Integer index of the browser window to use; defaults to the first
window.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
if isinstance(parent_id, basestring):
parent_id = int(parent_id)
cmd_dict = {
'command': 'AddBookmark',
'parent_id': parent_id,
'index': index,
'title': title,
'url': url,
'is_folder': False,
'windex': windex,
}
self.WaitForBookmarkModelToLoad(windex)
self._GetResultFromJSONRequest(cmd_dict, windex=None)
def ReparentBookmark(self, id, new_parent_id, index, windex=0):
"""Move a bookmark.
Args:
id: The bookmark to move.
new_parent_id: The new parent bookmark folder.
index: The location in the parent's list to insert this bookmark.
windex: Integer index of the browser window to use; defaults to the first
window.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
if isinstance(id, basestring):
id = int(id)
if isinstance(new_parent_id, basestring):
new_parent_id = int(new_parent_id)
cmd_dict = {
'command': 'ReparentBookmark',
'id': id,
'new_parent_id': new_parent_id,
'index': index,
'windex': windex,
}
self.WaitForBookmarkModelToLoad(windex)
self._GetResultFromJSONRequest(cmd_dict, windex=None)
def SetBookmarkTitle(self, id, title, windex=0):
"""Change the title of a bookmark.
Args:
id: The bookmark to rename.
title: The new title for the bookmark.
windex: Integer index of the browser window to use; defaults to the first
window.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
if isinstance(id, basestring):
id = int(id)
cmd_dict = {
'command': 'SetBookmarkTitle',
'id': id,
'title': title,
'windex': windex,
}
self.WaitForBookmarkModelToLoad(windex)
self._GetResultFromJSONRequest(cmd_dict, windex=None)
def SetBookmarkURL(self, id, url, windex=0):
"""Change the URL of a bookmark.
Args:
id: The bookmark to change.
url: The new url for the bookmark.
windex: Integer index of the browser window to use; defaults to the first
window.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
if isinstance(id, basestring):
id = int(id)
cmd_dict = {
'command': 'SetBookmarkURL',
'id': id,
'url': url,
'windex': windex,
}
self.WaitForBookmarkModelToLoad(windex)
self._GetResultFromJSONRequest(cmd_dict, windex=None)
def RemoveBookmark(self, id, windex=0):
"""Remove a bookmark.
Args:
id: The bookmark to remove.
windex: Integer index of the browser window to use; defaults to the first
window.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
if isinstance(id, basestring):
id = int(id)
cmd_dict = {
'command': 'RemoveBookmark',
'id': id,
'windex': windex,
}
self.WaitForBookmarkModelToLoad(windex)
self._GetResultFromJSONRequest(cmd_dict, windex=None)
def GetDownloadsInfo(self, windex=0):
"""Return info about downloads.
This includes all the downloads recognized by the history system.
Returns:
an instance of downloads_info.DownloadInfo
"""
return download_info.DownloadInfo(
self._GetResultFromJSONRequest({'command': 'GetDownloadsInfo'},
windex=windex))
def GetOmniboxInfo(self, windex=0):
"""Return info about Omnibox.
This represents a snapshot of the omnibox. If you expect changes
you need to call this method again to get a fresh snapshot.
Note that this DOES NOT shift focus to the omnibox; you've to ensure that
the omnibox is in focus or else you won't get any interesting info.
It's OK to call this even when the omnibox popup is not showing. In this
case however, there won't be any matches, but other properties (like the
current text in the omnibox) will still be fetched.
Due to the nature of the omnibox, this function is sensitive to mouse
focus. DO NOT HOVER MOUSE OVER OMNIBOX OR CHANGE WINDOW FOCUS WHEN USING
THIS METHOD.
Args:
windex: the index of the browser window to work on.
Default: 0 (first window)
Returns:
an instance of omnibox_info.OmniboxInfo
"""
return omnibox_info.OmniboxInfo(
self._GetResultFromJSONRequest({'command': 'GetOmniboxInfo'},
windex=windex))
def SetOmniboxText(self, text, windex=0):
"""Enter text into the omnibox. This shifts focus to the omnibox.
Args:
text: the text to be set.
windex: the index of the browser window to work on.
Default: 0 (first window)
"""
# Ensure that keyword data is loaded from the profile.
# This would normally be triggered by the user inputting this text.
self._GetResultFromJSONRequest({'command': 'LoadSearchEngineInfo'})
cmd_dict = {
'command': 'SetOmniboxText',
'text': text,
}
self._GetResultFromJSONRequest(cmd_dict, windex=windex)
# TODO(ace): Remove this hack, update bug 62783.
def WaitUntilOmniboxReadyHack(self, windex=0):
"""Wait until the omnibox is ready for input.
This is a hack workaround for linux platform, which returns from
synchronous window creation methods before the omnibox is fully functional.
No-op on non-linux platforms.
Args:
windex: the index of the browser to work on.
"""
if self.IsLinux():
return self.WaitUntil(
lambda : self.GetOmniboxInfo(windex).Properties('has_focus'))
def WaitUntilOmniboxQueryDone(self, windex=0):
"""Wait until omnibox has finished populating results.
Uses WaitUntil() so the wait duration is capped by the timeout values
used by automation, which WaitUntil() uses.
Args:
windex: the index of the browser window to work on.
Default: 0 (first window)
"""
return self.WaitUntil(
lambda : not self.GetOmniboxInfo(windex).IsQueryInProgress())
def OmniboxMovePopupSelection(self, count, windex=0):
"""Move omnibox popup selection up or down.
Args:
count: number of rows by which to move.
-ve implies down, +ve implies up
windex: the index of the browser window to work on.
Default: 0 (first window)
"""
cmd_dict = {
'command': 'OmniboxMovePopupSelection',
'count': count,
}
self._GetResultFromJSONRequest(cmd_dict, windex=windex)
def OmniboxAcceptInput(self, windex=0):
"""Accepts the current string of text in the omnibox.
This is equivalent to clicking or hiting enter on a popup selection.
Blocks until the page loads.
Args:
windex: the index of the browser window to work on.
Default: 0 (first window)
"""
cmd_dict = {
'command': 'OmniboxAcceptInput',
}
self._GetResultFromJSONRequest(cmd_dict, windex=windex)
def GetCookie(self, url, windex=0):
"""Get the value of the cookie at url in context of the specified browser.
Args:
url: Either a GURL object or url string specifing the cookie url.
windex: The index of the browser window to work on. Defaults to the first
window.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
if isinstance(url, GURL):
url = url.spec()
cmd_dict = {
'command': 'GetCookiesInBrowserContext',
'url': url,
'windex': windex,
}
return self._GetResultFromJSONRequest(cmd_dict, windex=None)['cookies']
def DeleteCookie(self, url, cookie_name, windex=0):
"""Delete the cookie at url with name cookie_name.
Args:
url: Either a GURL object or url string specifing the cookie url.
cookie_name: The name of the cookie to delete as a string.
windex: The index of the browser window to work on. Defaults to the first
window.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
if isinstance(url, GURL):
url = url.spec()
cmd_dict = {
'command': 'DeleteCookieInBrowserContext',
'url': url,
'cookie_name': cookie_name,
'windex': windex,
}
self._GetResultFromJSONRequest(cmd_dict, windex=None)
def SetCookie(self, url, value, windex=0):
"""Set the value of the cookie at url to value in the context of a browser.
Args:
url: Either a GURL object or url string specifing the cookie url.
value: A string to set as the cookie's value.
windex: The index of the browser window to work on. Defaults to the first
window.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
if isinstance(url, GURL):
url = url.spec()
cmd_dict = {
'command': 'SetCookieInBrowserContext',
'url': url,
'value': value,
'windex': windex,
}
self._GetResultFromJSONRequest(cmd_dict, windex=None)
def GetSearchEngineInfo(self, windex=0):
"""Return info about search engines.
Args:
windex: The window index, default is 0.
Returns:
An ordered list of dictionaries describing info about each search engine.
Example:
[ { u'display_url': u'{google:baseURL}search?q=%s',
u'host': u'www.google.com',
u'in_default_list': True,
u'is_default': True,
u'is_valid': True,
u'keyword': u'google.com',
u'path': u'/search',
u'short_name': u'Google',
u'supports_replacement': True,
u'url': u'{google:baseURL}search?q={searchTerms}'},
{ u'display_url': u'http://search.yahoo.com/search?p=%s',
u'host': u'search.yahoo.com',
u'in_default_list': True,
u'is_default': False,
u'is_valid': True,
u'keyword': u'yahoo.com',
u'path': u'/search',
u'short_name': u'Yahoo!',
u'supports_replacement': True,
u'url': u'http://search.yahoo.com/search?p={searchTerms}'},
"""
# Ensure that the search engine profile is loaded into data model.
self._GetResultFromJSONRequest({'command': 'LoadSearchEngineInfo'},
windex=windex)
cmd_dict = {'command': 'GetSearchEngineInfo'}
return self._GetResultFromJSONRequest(
cmd_dict, windex=windex)['search_engines']
def AddSearchEngine(self, title, keyword, url, windex=0):
"""Add a search engine, as done through the search engines UI.
Args:
title: name for search engine.
keyword: keyword, used to initiate a custom search from omnibox.
url: url template for this search engine's query.
'%s' is replaced by search query string when used to search.
windex: The window index, default is 0.
"""
# Ensure that the search engine profile is loaded into data model.
self._GetResultFromJSONRequest({'command': 'LoadSearchEngineInfo'},
windex=windex)
cmd_dict = {'command': 'AddOrEditSearchEngine',
'new_title': title,
'new_keyword': keyword,
'new_url': url}
self._GetResultFromJSONRequest(cmd_dict, windex=windex)
def EditSearchEngine(self, keyword, new_title, new_keyword, new_url,
windex=0):
"""Edit info for existing search engine.
Args:
keyword: existing search engine keyword.
new_title: new name for this search engine.
new_keyword: new keyword for this search engine.
new_url: new url for this search engine.
windex: The window index, default is 0.
"""
# Ensure that the search engine profile is loaded into data model.
self._GetResultFromJSONRequest({'command': 'LoadSearchEngineInfo'},
windex=windex)
cmd_dict = {'command': 'AddOrEditSearchEngine',
'keyword': keyword,
'new_title': new_title,
'new_keyword': new_keyword,
'new_url': new_url}
self._GetResultFromJSONRequest(cmd_dict, windex=windex)
def DeleteSearchEngine(self, keyword, windex=0):
"""Delete search engine with given keyword.
Args:
keyword: the keyword string of the search engine to delete.
windex: The window index, default is 0.
"""
# Ensure that the search engine profile is loaded into data model.
self._GetResultFromJSONRequest({'command': 'LoadSearchEngineInfo'},
windex=windex)
cmd_dict = {'command': 'PerformActionOnSearchEngine', 'keyword': keyword,
'action': 'delete'}
self._GetResultFromJSONRequest(cmd_dict, windex=windex)
def MakeSearchEngineDefault(self, keyword, windex=0):
"""Make search engine with given keyword the default search.
Args:
keyword: the keyword string of the search engine to make default.
windex: The window index, default is 0.
"""
# Ensure that the search engine profile is loaded into data model.
self._GetResultFromJSONRequest({'command': 'LoadSearchEngineInfo'},
windex=windex)
cmd_dict = {'command': 'PerformActionOnSearchEngine', 'keyword': keyword,
'action': 'default'}
self._GetResultFromJSONRequest(cmd_dict, windex=windex)
def GetLocalStatePrefsInfo(self):
"""Return info about preferences.
This represents a snapshot of the local state preferences. If you expect
local state preferences to have changed, you need to call this method again
to get a fresh snapshot.
Returns:
an instance of prefs_info.PrefsInfo
"""
return prefs_info.PrefsInfo(
self._GetResultFromJSONRequest({'command': 'GetLocalStatePrefsInfo'},
windex=None))
def SetLocalStatePrefs(self, path, value):
"""Set local state preference for the given path.
Preferences are stored by Chromium as a hierarchical dictionary.
dot-separated paths can be used to refer to a particular preference.
example: "session.restore_on_startup"
Some preferences are managed, that is, they cannot be changed by the
user. It's up to the user to know which ones can be changed. Typically,
the options available via Chromium preferences can be changed.
Args:
path: the path the preference key that needs to be changed
example: "session.restore_on_startup"
One of the equivalent names in chrome/common/pref_names.h could
also be used.
value: the value to be set. It could be plain values like int, bool,
string or complex ones like list.
The user has to ensure that the right value is specified for the
right key. It's useful to dump the preferences first to determine
what type is expected for a particular preference path.
"""
cmd_dict = {
'command': 'SetLocalStatePrefs',
'windex': 0,
'path': path,
'value': value,
}
self._GetResultFromJSONRequest(cmd_dict, windex=None)
def GetPrefsInfo(self, windex=0):
"""Return info about preferences.
This represents a snapshot of the preferences. If you expect preferences
to have changed, you need to call this method again to get a fresh
snapshot.
Args:
windex: The window index, default is 0.
Returns:
an instance of prefs_info.PrefsInfo
"""
cmd_dict = {
'command': 'GetPrefsInfo',
'windex': windex,
}
return prefs_info.PrefsInfo(
self._GetResultFromJSONRequest(cmd_dict, windex=None))
def SetPrefs(self, path, value, windex=0):
"""Set preference for the given path.
Preferences are stored by Chromium as a hierarchical dictionary.
dot-separated paths can be used to refer to a particular preference.
example: "session.restore_on_startup"
Some preferences are managed, that is, they cannot be changed by the
user. It's up to the user to know which ones can be changed. Typically,
the options available via Chromium preferences can be changed.
Args:
path: the path the preference key that needs to be changed
example: "session.restore_on_startup"
One of the equivalent names in chrome/common/pref_names.h could
also be used.
value: the value to be set. It could be plain values like int, bool,
string or complex ones like list.
The user has to ensure that the right value is specified for the
right key. It's useful to dump the preferences first to determine
what type is expected for a particular preference path.
windex: window index to work on. Defaults to 0 (first window).
"""
cmd_dict = {
'command': 'SetPrefs',
'windex': windex,
'path': path,
'value': value,
}
self._GetResultFromJSONRequest(cmd_dict, windex=None)
def SendWebkitKeyEvent(self, key_type, key_code, tab_index=0, windex=0):
"""Send a webkit key event to the browser.
Args:
key_type: the raw key type such as 0 for up and 3 for down.
key_code: the hex value associated with the keypress (virtual key code).
tab_index: tab index to work on. Defaults to 0 (first tab).
windex: window index to work on. Defaults to 0 (first window).
"""
cmd_dict = {
'command': 'SendWebkitKeyEvent',
'type': key_type,
'text': '',
'isSystemKey': False,
'unmodifiedText': '',
'nativeKeyCode': 0,
'windowsKeyCode': key_code,
'modifiers': 0,
'windex': windex,
'tab_index': tab_index,
}
# Sending request for key event.
self._GetResultFromJSONRequest(cmd_dict, windex=None)
def SendWebkitCharEvent(self, char, tab_index=0, windex=0):
"""Send a webkit char to the browser.
Args:
char: the char value to be sent to the browser.
tab_index: tab index to work on. Defaults to 0 (first tab).
windex: window index to work on. Defaults to 0 (first window).
"""
cmd_dict = {
'command': 'SendWebkitKeyEvent',
'type': 2, # kCharType
'text': char,
'isSystemKey': False,
'unmodifiedText': char,
'nativeKeyCode': 0,
'windowsKeyCode': ord((char).upper()),
'modifiers': 0,
'windex': windex,
'tab_index': tab_index,
}
# Sending request for a char.
self._GetResultFromJSONRequest(cmd_dict, windex=None)
def SetDownloadShelfVisible(self, is_visible, windex=0):
"""Set download shelf visibility for the specified browser window.
Args:
is_visible: A boolean indicating the desired shelf visibility.
windex: The window index, defaults to 0 (the first window).
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'SetDownloadShelfVisible',
'is_visible': is_visible,
'windex': windex,
}
self._GetResultFromJSONRequest(cmd_dict, windex=None)
def IsDownloadShelfVisible(self, windex=0):
"""Determine whether the download shelf is visible in the given window.
Args:
windex: The window index, defaults to 0 (the first window).
Returns:
A boolean indicating the shelf visibility.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'IsDownloadShelfVisible',
'windex': windex,
}
return self._GetResultFromJSONRequest(cmd_dict, windex=None)['is_visible']
def GetDownloadDirectory(self, tab_index=None, windex=0):
"""Get the path to the download directory.
Warning: Depending on the concept of an active tab is dangerous as it can
change during the test. Always supply a tab_index explicitly.
Args:
tab_index: The index of the tab to work on. Defaults to the active tab.
windex: The index of the browser window to work on. Defaults to 0.
Returns:
The path to the download directory as a FilePath object.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
if tab_index is None:
tab_index = self.GetActiveTabIndex(windex)
cmd_dict = {
'command': 'GetDownloadDirectory',
'tab_index': tab_index,
'windex': windex,
}
return FilePath(str(self._GetResultFromJSONRequest(cmd_dict,
windex=None)['path']))
def WaitForAllDownloadsToComplete(self, pre_download_ids=[], windex=0,
timeout=-1):
"""Wait for all pending downloads to complete.
This function assumes that any downloads to wait for have already been
triggered and have started (it is ok if those downloads complete before this
function is called).
Args:
pre_download_ids: A list of numbers representing the IDs of downloads that
exist *before* downloads to wait for have been
triggered. Defaults to []; use GetDownloadsInfo() to get
these IDs (only necessary if a test previously
downloaded files).
windex: The window index, defaults to 0 (the first window).
timeout: The maximum amount of time (in milliseconds) to wait for
downloads to complete.
"""
cmd_dict = {
'command': 'WaitForAllDownloadsToComplete',
'pre_download_ids': pre_download_ids,
}
self._GetResultFromJSONRequest(cmd_dict, windex=windex, timeout=timeout)
def PerformActionOnDownload(self, id, action, window_index=0):
"""Perform the given action on the download with the given id.
Args:
id: The id of the download.
action: The action to perform on the download.
Possible actions:
'open': Opens the download (waits until it has completed first).
'toggle_open_files_like_this': Toggles the 'Always Open Files
Of This Type' option.
'remove': Removes the file from downloads (not from disk).
'decline_dangerous_download': Equivalent to 'Discard' option
after downloading a dangerous download (ex. an executable).
'save_dangerous_download': Equivalent to 'Save' option after
downloading a dangerous file.
'pause': Pause the download. If the download completed before
this call or is already paused, it's a no-op.
'resume': Resume the download. If the download completed before
this call or was not paused, it's a no-op.
'cancel': Cancel the download.
window_index: The window index, default is 0.
Returns:
A dictionary representing the updated download item (except in the case
of 'decline_dangerous_download', 'toggle_open_files_like_this', and
'remove', which return an empty dict).
Example dictionary:
{ u'PercentComplete': 100,
u'file_name': u'file.txt',
u'full_path': u'/path/to/file.txt',
u'id': 0,
u'is_otr': False,
u'is_paused': False,
u'is_temporary': False,
u'open_when_complete': False,
u'referrer_url': u'',
u'state': u'COMPLETE',
u'danger_type': u'DANGEROUS_FILE',
u'url': u'file://url/to/file.txt'
}
"""
cmd_dict = { # Prepare command for the json interface
'command': 'PerformActionOnDownload',
'id': id,
'action': action
}
return self._GetResultFromJSONRequest(cmd_dict, windex=window_index)
def DownloadAndWaitForStart(self, file_url, windex=0):
"""Trigger download for the given url and wait for downloads to start.
It waits for download by looking at the download info from Chrome, so
anything which isn't registered by the history service won't be noticed.
This is not thread-safe, but it's fine to call this method to start
downloading multiple files in parallel. That is after starting a
download, it's fine to start another one even if the first one hasn't
completed.
"""
try:
num_downloads = len(self.GetDownloadsInfo(windex).Downloads())
except JSONInterfaceError:
num_downloads = 0
self.NavigateToURL(file_url, windex) # Trigger download.
# It might take a while for the download to kick in, hold on until then.
self.assertTrue(self.WaitUntil(
lambda: len(self.GetDownloadsInfo(windex).Downloads()) >
num_downloads))
def SetWindowDimensions(
self, x=None, y=None, width=None, height=None, windex=0):
"""Set window dimensions.
All args are optional and current values will be preserved.
Arbitrarily large values will be handled gracefully by the browser.
Args:
x: window origin x
y: window origin y
width: window width
height: window height
windex: window index to work on. Defaults to 0 (first window)
"""
cmd_dict = { # Prepare command for the json interface
'command': 'SetWindowDimensions',
}
if x:
cmd_dict['x'] = x
if y:
cmd_dict['y'] = y
if width:
cmd_dict['width'] = width
if height:
cmd_dict['height'] = height
self._GetResultFromJSONRequest(cmd_dict, windex=windex)
def WaitForInfobarCount(self, count, windex=0, tab_index=0):
"""Wait until infobar count becomes |count|.
Note: Wait duration is capped by the automation timeout.
Args:
count: requested number of infobars
windex: window index. Defaults to 0 (first window)
tab_index: tab index Defaults to 0 (first tab)
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
# TODO(phajdan.jr): We need a solid automation infrastructure to handle
# these cases. See crbug.com/53647.
def _InfobarCount():
windows = self.GetBrowserInfo()['windows']
if windex >= len(windows): # not enough windows
return -1
tabs = windows[windex]['tabs']
if tab_index >= len(tabs): # not enough tabs
return -1
return len(tabs[tab_index]['infobars'])
return self.WaitUntil(_InfobarCount, expect_retval=count)
def PerformActionOnInfobar(
self, action, infobar_index, windex=0, tab_index=0):
"""Perform actions on an infobar.
Args:
action: the action to be performed.
Actions depend on the type of the infobar. The user needs to
call the right action for the right infobar.
Valid inputs are:
- "dismiss": closes the infobar (for all infobars)
- "accept", "cancel": click accept / cancel (for confirm infobars)
- "allow", "deny": click allow / deny (for media stream infobars)
infobar_index: 0-based index of the infobar on which to perform the action
windex: 0-based window index Defaults to 0 (first window)
tab_index: 0-based tab index. Defaults to 0 (first tab)
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'PerformActionOnInfobar',
'action': action,
'infobar_index': infobar_index,
'tab_index': tab_index,
}
if action not in ('dismiss', 'accept', 'allow', 'deny', 'cancel'):
raise JSONInterfaceError('Invalid action %s' % action)
self._GetResultFromJSONRequest(cmd_dict, windex=windex)
def GetBrowserInfo(self):
"""Return info about the browser.
This includes things like the version number, the executable name,
executable path, pid info about the renderer/plugin/extension processes,
window dimensions. (See sample below)
For notification pid info, see 'GetActiveNotifications'.
Returns:
a dictionary
Sample:
{ u'browser_pid': 93737,
# Child processes are the processes for plugins and other workers.
u'child_process_path': u'.../Chromium.app/Contents/'
'Versions/6.0.412.0/Chromium Helper.app/'
'Contents/MacOS/Chromium Helper',
u'child_processes': [ { u'name': u'Shockwave Flash',
u'pid': 93766,
u'type': u'Plug-in'}],
u'extension_views': [ {
u'name': u'Webpage Screenshot',
u'pid': 93938,
u'extension_id': u'dgcoklnmbeljaehamekjpeidmbicddfj',
u'url': u'chrome-extension://dgcoklnmbeljaehamekjpeidmbicddfj/'
'bg.html',
u'loaded': True,
u'view': {
u'render_process_id': 2,
u'render_view_id': 1},
u'view_type': u'EXTENSION_BACKGROUND_PAGE'}]
u'properties': {
u'BrowserProcessExecutableName': u'Chromium',
u'BrowserProcessExecutablePath': u'Chromium.app/Contents/MacOS/'
'Chromium',
u'ChromeVersion': u'6.0.412.0',
u'HelperProcessExecutableName': u'Chromium Helper',
u'HelperProcessExecutablePath': u'Chromium Helper.app/Contents/'
'MacOS/Chromium Helper',
u'command_line_string': "COMMAND_LINE_STRING --WITH-FLAGS",
u'branding': 'Chromium',
u'is_official': False,}
# The order of the windows and tabs listed here will be the same as
# what shows up on screen.
u'windows': [ { u'index': 0,
u'height': 1134,
u'incognito': False,
u'profile_path': u'Default',
u'fullscreen': False,
u'visible_page_actions':
[u'dgcoklnmbeljaehamekjpeidmbicddfj',
u'osfcklnfasdofpcldmalwpicslasdfgd']
u'selected_tab': 0,
u'tabs': [ {
u'index': 0,
u'infobars': [],
u'pinned': True,
u'renderer_pid': 93747,
u'url': u'http://www.google.com/' }, {
u'index': 1,
u'infobars': [],
u'pinned': False,
u'renderer_pid': 93919,
u'url': u'https://chrome.google.com/'}, {
u'index': 2,
u'infobars': [ {
u'buttons': [u'Allow', u'Deny'],
u'link_text': u'Learn more',
u'text': u'slides.html5rocks.com wants to track '
'your physical location',
u'type': u'confirm_infobar'}],
u'pinned': False,
u'renderer_pid': 93929,
u'url': u'http://slides.html5rocks.com/#slide14'},
],
u'type': u'tabbed',
u'width': 925,
u'x': 26,
u'y': 44}]}
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = { # Prepare command for the json interface
'command': 'GetBrowserInfo',
}
return self._GetResultFromJSONRequest(cmd_dict, windex=None)
def IsAura(self):
"""Is this Aura?"""
return self.GetBrowserInfo()['properties']['aura']
def GetProcessInfo(self):
"""Returns information about browser-related processes that currently exist.
This will also return information about other currently-running browsers
besides just Chrome.
Returns:
A dictionary containing browser-related process information as identified
by class MemoryDetails in src/chrome/browser/memory_details.h. The
dictionary contains a single key 'browsers', mapped to a list of
dictionaries containing information about each browser process name.
Each of those dictionaries contains a key 'processes', mapped to a list
of dictionaries containing the specific information for each process
with the given process name.
The memory values given in |committed_mem| and |working_set_mem| are in
KBytes.
Sample:
{ 'browsers': [ { 'name': 'Chromium',
'process_name': 'chrome',
'processes': [ { 'child_process_type': 'Browser',
'committed_mem': { 'image': 0,
'mapped': 0,
'priv': 0},
'is_diagnostics': False,
'num_processes': 1,
'pid': 7770,
'product_name': '',
'renderer_type': 'Unknown',
'titles': [],
'version': '',
'working_set_mem': { 'priv': 43672,
'shareable': 0,
'shared': 59251}},
{ 'child_process_type': 'Tab',
'committed_mem': { 'image': 0,
'mapped': 0,
'priv': 0},
'is_diagnostics': False,
'num_processes': 1,
'pid': 7791,
'product_name': '',
'renderer_type': 'Tab',
'titles': ['about:blank'],
'version': '',
'working_set_mem': { 'priv': 16768,
'shareable': 0,
'shared': 26256}},
...<more processes>...]}]}
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = { # Prepare command for the json interface.
'command': 'GetProcessInfo',
}
return self._GetResultFromJSONRequest(cmd_dict, windex=None)
def GetNavigationInfo(self, tab_index=0, windex=0):
"""Get info about the navigation state of a given tab.
Args:
tab_index: The tab index, default is 0.
window_index: The window index, default is 0.
Returns:
a dictionary.
Sample:
{ u'favicon_url': u'https://www.google.com/favicon.ico',
u'page_type': u'NORMAL_PAGE',
u'ssl': { u'displayed_insecure_content': False,
u'ran_insecure_content': False,
u'security_style': u'SECURITY_STYLE_AUTHENTICATED'}}
Values for security_style can be:
SECURITY_STYLE_UNKNOWN
SECURITY_STYLE_UNAUTHENTICATED
SECURITY_STYLE_AUTHENTICATION_BROKEN
SECURITY_STYLE_AUTHENTICATED
Values for page_type can be:
NORMAL_PAGE
ERROR_PAGE
INTERSTITIAL_PAGE
"""
cmd_dict = { # Prepare command for the json interface
'command': 'GetNavigationInfo',
'tab_index': tab_index,
}
return self._GetResultFromJSONRequest(cmd_dict, windex=windex)
def GetSecurityState(self, tab_index=0, windex=0):
"""Get security details for a given tab.
Args:
tab_index: The tab index, default is 0.
window_index: The window index, default is 0.
Returns:
a dictionary.
Sample:
{ "security_style": SECURITY_STYLE_AUTHENTICATED,
"ssl_cert_status": 3, // bitmask of status flags
"insecure_content_status": 1, // bitmask of status flags
}
"""
cmd_dict = { # Prepare command for the json interface
'command': 'GetSecurityState',
'tab_index': tab_index,
'windex': windex,
}
return self._GetResultFromJSONRequest(cmd_dict, windex=None)
def GetHistoryInfo(self, search_text='', windex=0):
"""Return info about browsing history.
Args:
search_text: the string to search in history. Defaults to empty string
which means that all history would be returned. This is
functionally equivalent to searching for a text in the
chrome://history UI. So partial matches work too.
When non-empty, the history items returned will contain a
"snippet" field corresponding to the snippet visible in
the chrome://history/ UI.
windex: index of the browser window, defaults to 0.
Returns:
an instance of history_info.HistoryInfo
"""
cmd_dict = { # Prepare command for the json interface
'command': 'GetHistoryInfo',
'search_text': search_text,
}
return history_info.HistoryInfo(
self._GetResultFromJSONRequest(cmd_dict, windex=windex))
def InstallExtension(self, extension_path, with_ui=False, from_webstore=None,
windex=0, tab_index=0):
"""Installs an extension from the given path.
The path must be absolute and may be a crx file or an unpacked extension
directory. Returns the extension ID if successfully installed and loaded.
Otherwise, throws an exception. The extension must not already be installed.
Args:
extension_path: The absolute path to the extension to install. If the
extension is packed, it must have a .crx extension.
with_ui: Whether the extension install confirmation UI should be shown.
from_webstore: If True, forces a .crx extension to be recognized as one
from the webstore. Can be used to force install an extension with
'experimental' permissions.
windex: Integer index of the browser window to use; defaults to 0
(first window).
Returns:
The ID of the installed extension.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'InstallExtension',
'path': extension_path,
'with_ui': with_ui,
'windex': windex,
'tab_index': tab_index,
}
if from_webstore:
cmd_dict['from_webstore'] = True
return self._GetResultFromJSONRequest(cmd_dict, windex=None)['id']
def GetExtensionsInfo(self, windex=0):
"""Returns information about all installed extensions.
Args:
windex: Integer index of the browser window to use; defaults to 0
(first window).
Returns:
A list of dictionaries representing each of the installed extensions.
Example:
[ { u'api_permissions': [u'bookmarks', u'experimental', u'tabs'],
u'background_url': u'',
u'description': u'Bookmark Manager',
u'effective_host_permissions': [u'chrome://favicon/*',
u'chrome://resources/*'],
u'host_permissions': [u'chrome://favicon/*', u'chrome://resources/*'],
u'id': u'eemcgdkfndhakfknompkggombfjjjeno',
u'is_component': True,
u'is_internal': False,
u'name': u'Bookmark Manager',
u'options_url': u'',
u'public_key': u'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDQcByy+eN9jza\
zWF/DPn7NW47sW7lgmpk6eKc0BQM18q8hvEM3zNm2n7HkJv/R6f\
U+X5mtqkDuKvq5skF6qqUF4oEyaleWDFhd1xFwV7JV+/DU7bZ00\
w2+6gzqsabkerFpoP33ZRIw7OviJenP0c0uWqDWF8EGSyMhB3tx\
qhOtiQIDAQAB',
u'version': u'0.1' },
{ u'api_permissions': [...],
u'background_url': u'chrome-extension://\
lkdedmbpkaiahjjibfdmpoefffnbdkli/\
background.html',
u'description': u'Extension which lets you read your Facebook news \
feed and wall. You can also post status updates.',
u'effective_host_permissions': [...],
u'host_permissions': [...],
u'id': u'lkdedmbpkaiahjjibfdmpoefffnbdkli',
u'name': u'Facebook for Google Chrome',
u'options_url': u'',
u'public_key': u'...',
u'version': u'2.0.9'
u'is_enabled': True,
u'allowed_in_incognito': True} ]
"""
cmd_dict = { # Prepare command for the json interface
'command': 'GetExtensionsInfo',
'windex': windex,
}
return self._GetResultFromJSONRequest(cmd_dict, windex=None)['extensions']
def UninstallExtensionById(self, id, windex=0):
"""Uninstall the extension with the given id.
Args:
id: The string id of the extension.
windex: Integer index of the browser window to use; defaults to 0
(first window).
Returns:
True, if the extension was successfully uninstalled, or
False, otherwise.
"""
cmd_dict = { # Prepare command for the json interface
'command': 'UninstallExtensionById',
'id': id,
'windex': windex,
}
return self._GetResultFromJSONRequest(cmd_dict, windex=None)['success']
def SetExtensionStateById(self, id, enable, allow_in_incognito, windex=0):
"""Set extension state: enable/disable, allow/disallow in incognito mode.
Args:
id: The string id of the extension.
enable: A boolean, enable extension.
allow_in_incognito: A boolean, allow extension in incognito.
windex: Integer index of the browser window to use; defaults to 0
(first window).
"""
cmd_dict = { # Prepare command for the json interface
'command': 'SetExtensionStateById',
'id': id,
'enable': enable,
'allow_in_incognito': allow_in_incognito,
'windex': windex,
}
self._GetResultFromJSONRequest(cmd_dict, windex=None)
def TriggerPageActionById(self, id, tab_index=0, windex=0):
"""Trigger page action asynchronously in the active tab.
The page action icon must be displayed before invoking this function.
Args:
id: The string id of the extension.
tab_index: Integer index of the tab to use; defaults to 0 (first tab).
windex: Integer index of the browser window to use; defaults to 0
(first window).
"""
cmd_dict = { # Prepare command for the json interface
'command': 'TriggerPageActionById',
'id': id,
'windex': windex,
'tab_index': tab_index,
}
self._GetResultFromJSONRequest(cmd_dict, windex=None)
def TriggerBrowserActionById(self, id, tab_index=0, windex=0):
"""Trigger browser action asynchronously in the active tab.
Args:
id: The string id of the extension.
tab_index: Integer index of the tab to use; defaults to 0 (first tab).
windex: Integer index of the browser window to use; defaults to 0
(first window).
"""
cmd_dict = { # Prepare command for the json interface
'command': 'TriggerBrowserActionById',
'id': id,
'windex': windex,
'tab_index': tab_index,
}
self._GetResultFromJSONRequest(cmd_dict, windex=None)
def UpdateExtensionsNow(self, windex=0):
"""Auto-updates installed extensions.
Waits until all extensions are updated, loaded, and ready for use.
This is equivalent to clicking the "Update extensions now" button on the
chrome://extensions page.
Args:
windex: Integer index of the browser window to use; defaults to 0
(first window).
Raises:
pyauto_errors.JSONInterfaceError if the automation returns an error.
"""
cmd_dict = { # Prepare command for the json interface.
'command': 'UpdateExtensionsNow',
'windex': windex,
}
self._GetResultFromJSONRequest(cmd_dict, windex=None)
def WaitUntilExtensionViewLoaded(self, name=None, extension_id=None,
url=None, view_type=None):
"""Wait for a loaded extension view matching all the given properties.
If no matching extension views are found, wait for one to be loaded.
If there are more than one matching extension view, return one at random.
Uses WaitUntil so timeout is capped by automation timeout.
Refer to extension_view dictionary returned in GetBrowserInfo()
for sample input/output values.
Args:
name: (optional) Name of the extension.
extension_id: (optional) ID of the extension.
url: (optional) URL of the extension view.
view_type: (optional) Type of the extension view.
['EXTENSION_BACKGROUND_PAGE'|'EXTENSION_POPUP'|'EXTENSION_INFOBAR'|
'EXTENSION_DIALOG']
Returns:
The 'view' property of the extension view.
None, if no view loaded.
Raises:
pyauto_errors.JSONInterfaceError if the automation returns an error.
"""
def _GetExtensionViewLoaded():
extension_views = self.GetBrowserInfo()['extension_views']
for extension_view in extension_views:
if ((name and name != extension_view['name']) or
(extension_id and extension_id != extension_view['extension_id']) or
(url and url != extension_view['url']) or
(view_type and view_type != extension_view['view_type'])):
continue
if extension_view['loaded']:
return extension_view['view']
return False
if self.WaitUntil(lambda: _GetExtensionViewLoaded()):
return _GetExtensionViewLoaded()
return None
def WaitUntilExtensionViewClosed(self, view):
"""Wait for the given extension view to to be closed.
Uses WaitUntil so timeout is capped by automation timeout.
Refer to extension_view dictionary returned by GetBrowserInfo()
for sample input value.
Args:
view: 'view' property of extension view.
Raises:
pyauto_errors.JSONInterfaceError if the automation returns an error.
"""
def _IsExtensionViewClosed():
extension_views = self.GetBrowserInfo()['extension_views']
for extension_view in extension_views:
if view == extension_view['view']:
return False
return True
return self.WaitUntil(lambda: _IsExtensionViewClosed())
def GetPluginsInfo(self, windex=0):
"""Return info about plugins.
This is the info available from about:plugins
Returns:
an instance of plugins_info.PluginsInfo
"""
return plugins_info.PluginsInfo(
self._GetResultFromJSONRequest({'command': 'GetPluginsInfo'},
windex=windex))
def EnablePlugin(self, path):
"""Enable the plugin at the given path.
Use GetPluginsInfo() to fetch path info about a plugin.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'EnablePlugin',
'path': path,
}
self._GetResultFromJSONRequest(cmd_dict)
def DisablePlugin(self, path):
"""Disable the plugin at the given path.
Use GetPluginsInfo() to fetch path info about a plugin.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'DisablePlugin',
'path': path,
}
self._GetResultFromJSONRequest(cmd_dict)
def GetTabContents(self, tab_index=0, window_index=0):
"""Get the html contents of a tab (a la "view source").
As an implementation detail, this saves the html in a file, reads
the file into a buffer, then deletes it.
Args:
tab_index: tab index, defaults to 0.
window_index: window index, defaults to 0.
Returns:
html content of a page as a string.
"""
tempdir = tempfile.mkdtemp()
# Make it writable by chronos on chromeos
os.chmod(tempdir, 0777)
filename = os.path.join(tempdir, 'content.html')
cmd_dict = { # Prepare command for the json interface
'command': 'SaveTabContents',
'tab_index': tab_index,
'filename': filename
}
self._GetResultFromJSONRequest(cmd_dict, windex=window_index)
try:
f = open(filename)
all_data = f.read()
f.close()
return all_data
finally:
shutil.rmtree(tempdir, ignore_errors=True)
def AddSavedPassword(self, password_dict, windex=0):
"""Adds the given username-password combination to the saved passwords.
Args:
password_dict: a dictionary that represents a password. Example:
{ 'username_value': '[email protected]', # Required
'password_value': 'test.password', # Required
'signon_realm': 'https://www.example.com/', # Required
'time': 1279317810.0, # Can get from time.time()
'origin_url': 'https://www.example.com/login',
'username_element': 'username', # The HTML element
'password_element': 'password', # The HTML element
'submit_element': 'submit', # The HTML element
'action_target': 'https://www.example.com/login/',
'blacklist': False }
windex: window index; defaults to 0 (first window).
*Blacklist notes* To blacklist a site, add a blacklist password with the
following dictionary items: origin_url, signon_realm, username_element,
password_element, action_target, and 'blacklist': True. Then all sites that
have password forms matching those are blacklisted.
Returns:
True if adding the password succeeded, false otherwise. In incognito
mode, adding the password should fail.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = { # Prepare command for the json interface
'command': 'AddSavedPassword',
'password': password_dict
}
return self._GetResultFromJSONRequest(
cmd_dict, windex=windex)['password_added']
def RemoveSavedPassword(self, password_dict, windex=0):
"""Removes the password matching the provided password dictionary.
Args:
password_dict: A dictionary that represents a password.
For an example, see the dictionary in AddSavedPassword.
windex: The window index, default is 0 (first window).
"""
cmd_dict = { # Prepare command for the json interface
'command': 'RemoveSavedPassword',
'password': password_dict
}
self._GetResultFromJSONRequest(cmd_dict, windex=windex)
def GetSavedPasswords(self):
"""Return the passwords currently saved.
Returns:
A list of dictionaries representing each password. For an example
dictionary see AddSavedPassword documentation. The overall structure will
be:
[ {password1 dictionary}, {password2 dictionary} ]
"""
cmd_dict = { # Prepare command for the json interface
'command': 'GetSavedPasswords'
}
return self._GetResultFromJSONRequest(cmd_dict)['passwords']
def SetTheme(self, crx_file_path, windex=0):
"""Installs the given theme synchronously.
A theme file is a file with a .crx suffix, like an extension. The theme
file must be specified with an absolute path. This method call waits until
the theme is installed and will trigger the "theme installed" infobar.
If the install is unsuccessful, will throw an exception.
Uses InstallExtension().
Returns:
The ID of the installed theme.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
return self.InstallExtension(crx_file_path, True, windex)
def GetActiveNotifications(self):
"""Gets a list of the currently active/shown HTML5 notifications.
Returns:
a list containing info about each active notification, with the
first item in the list being the notification on the bottom of the
notification stack. The 'content_url' key can refer to a URL or a data
URI. The 'pid' key-value pair may be invalid if the notification is
closing.
SAMPLE:
[ { u'content_url': u'data:text/html;charset=utf-8,%3C!DOCTYPE%l%3E%0Atm...'
u'display_source': 'www.corp.google.com',
u'origin_url': 'http://www.corp.google.com/',
u'pid': 8505},
{ u'content_url': 'http://www.gmail.com/special_notification.html',
u'display_source': 'www.gmail.com',
u'origin_url': 'http://www.gmail.com/',
u'pid': 9291}]
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
return [x for x in self.GetAllNotifications() if 'pid' in x]
def GetAllNotifications(self):
"""Gets a list of all active and queued HTML5 notifications.
An active notification is one that is currently shown to the user. Chrome's
notification system will limit the number of notifications shown (currently
by only allowing a certain percentage of the screen to be taken up by them).
A notification will be queued if there are too many active notifications.
Once other notifications are closed, another will be shown from the queue.
Returns:
a list containing info about each notification, with the first
item in the list being the notification on the bottom of the
notification stack. The 'content_url' key can refer to a URL or a data
URI. The 'pid' key-value pair will only be present for active
notifications.
SAMPLE:
[ { u'content_url': u'data:text/html;charset=utf-8,%3C!DOCTYPE%l%3E%0Atm...'
u'display_source': 'www.corp.google.com',
u'origin_url': 'http://www.corp.google.com/',
u'pid': 8505},
{ u'content_url': 'http://www.gmail.com/special_notification.html',
u'display_source': 'www.gmail.com',
u'origin_url': 'http://www.gmail.com/'}]
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'GetAllNotifications',
}
return self._GetResultFromJSONRequest(cmd_dict)['notifications']
def CloseNotification(self, index):
"""Closes the active HTML5 notification at the given index.
Args:
index: the index of the notification to close. 0 refers to the
notification on the bottom of the notification stack.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'CloseNotification',
'index': index,
}
return self._GetResultFromJSONRequest(cmd_dict)
def WaitForNotificationCount(self, count):
"""Waits for the number of active HTML5 notifications to reach the given
count.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'WaitForNotificationCount',
'count': count,
}
self._GetResultFromJSONRequest(cmd_dict)
def FindInPage(self, search_string, forward=True,
match_case=False, find_next=False,
tab_index=0, windex=0, timeout=-1):
"""Find the match count for the given search string and search parameters.
This is equivalent to using the find box.
Args:
search_string: The string to find on the page.
forward: Boolean to set if the search direction is forward or backwards
match_case: Boolean to set for case sensitive search.
find_next: Boolean to set to continue the search or start from beginning.
tab_index: The tab index, default is 0.
windex: The window index, default is 0.
timeout: request timeout (in milliseconds), default is -1.
Returns:
number of matches found for the given search string and parameters
SAMPLE:
{ u'match_count': 10,
u'match_left': 100,
u'match_top': 100,
u'match_right': 200,
u'match_bottom': 200}
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'FindInPage',
'tab_index' : tab_index,
'search_string' : search_string,
'forward' : forward,
'match_case' : match_case,
'find_next' : find_next,
}
return self._GetResultFromJSONRequest(cmd_dict, windex=windex,
timeout=timeout)
def OpenFindInPage(self, windex=0):
"""Opens the "Find in Page" box.
Args:
windex: Index of the window; defaults to 0.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'OpenFindInPage',
'windex' : windex,
}
self._GetResultFromJSONRequest(cmd_dict, windex=None)
def IsFindInPageVisible(self, windex=0):
"""Returns the visibility of the "Find in Page" box.
Args:
windex: Index of the window; defaults to 0.
Returns:
A boolean indicating the visibility state of the "Find in Page" box.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'IsFindInPageVisible',
'windex' : windex,
}
return self._GetResultFromJSONRequest(cmd_dict, windex=None)['is_visible']
def AddDomEventObserver(self, event_name='', automation_id=-1,
recurring=False):
"""Adds a DomEventObserver associated with the AutomationEventQueue.
An app raises a matching event in Javascript by calling:
window.domAutomationController.sendWithId(automation_id, event_name)
Args:
event_name: The event name to watch for. By default an event is raised
for any message.
automation_id: The Automation Id of the sent message. By default all
messages sent from the window.domAutomationController are
observed. Note that other PyAuto functions also send
messages through window.domAutomationController with
arbirary Automation Ids and they will be observed.
recurring: If False the observer will be removed after it generates one
event, otherwise it will continue observing and generating
events until explicity removed with RemoveEventObserver(id).
Returns:
The id of the created observer, which can be used with GetNextEvent(id)
and RemoveEventObserver(id).
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'AddDomEventObserver',
'event_name': event_name,
'automation_id': automation_id,
'recurring': recurring,
}
return self._GetResultFromJSONRequest(cmd_dict, windex=None)['observer_id']
def AddDomMutationObserver(self, mutation_type, xpath,
attribute='textContent', expected_value=None,
automation_id=44444,
exec_js=None, **kwargs):
"""Sets up an event observer watching for a specific DOM mutation.
Creates an observer that raises an event when a mutation of the given type
occurs on a DOM node specified by |selector|.
Args:
mutation_type: One of 'add', 'remove', 'change', or 'exists'.
xpath: An xpath specifying the DOM node to watch. The node must already
exist if |mutation_type| is 'change'.
attribute: Attribute to match |expected_value| against, if given. Defaults
to 'textContent'.
expected_value: Optional regular expression to match against the node's
textContent attribute after the mutation. Defaults to None.
automation_id: The automation_id used to route the observer javascript
messages. Defaults to 44444.
exec_js: A callable of the form f(self, js, **kwargs) used to inject the
MutationObserver javascript. Defaults to None, which uses
PyUITest.ExecuteJavascript.
Any additional keyword arguments are passed on to ExecuteJavascript and
can be used to select the tab where the DOM MutationObserver is created.
Returns:
The id of the created observer, which can be used with GetNextEvent(id)
and RemoveEventObserver(id).
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
pyauto_errors.JavascriptRuntimeError if the injected javascript
MutationObserver returns an error.
"""
assert mutation_type in ('add', 'remove', 'change', 'exists'), \
'Unexpected value "%s" for mutation_type.' % mutation_type
cmd_dict = {
'command': 'AddDomEventObserver',
'event_name': '__dom_mutation_observer__:$(id)',
'automation_id': automation_id,
'recurring': False,
}
observer_id = (
self._GetResultFromJSONRequest(cmd_dict, windex=None)['observer_id'])
expected_string = ('null' if expected_value is None else '"%s"' %
expected_value.replace('"', r'\"'))
jsfile = os.path.join(os.path.abspath(os.path.dirname(__file__)),
'dom_mutation_observer.js')
with open(jsfile, 'r') as f:
js = ('(' + f.read() + ')(%d, %d, "%s", "%s", "%s", %s);' %
(automation_id, observer_id, mutation_type,
xpath.replace('"', r'\"'), attribute, expected_string))
exec_js = exec_js or PyUITest.ExecuteJavascript
try:
jsreturn = exec_js(self, js, **kwargs)
except JSONInterfaceError:
raise JSONInterfaceError('Failed to inject DOM mutation observer.')
if jsreturn != 'success':
self.RemoveEventObserver(observer_id)
raise JavascriptRuntimeError(jsreturn)
return observer_id
def WaitForDomNode(self, xpath, attribute='textContent',
expected_value=None, exec_js=None, timeout=-1,
msg='Expected DOM node failed to appear.', **kwargs):
"""Waits until a node specified by an xpath exists in the DOM.
NOTE: This does NOT poll. It returns as soon as the node appears, or
immediately if the node already exists.
Args:
xpath: An xpath specifying the DOM node to watch.
attribute: Attribute to match |expected_value| against, if given. Defaults
to 'textContent'.
expected_value: Optional regular expression to match against the node's
textContent attribute. Defaults to None.
exec_js: A callable of the form f(self, js, **kwargs) used to inject the
MutationObserver javascript. Defaults to None, which uses
PyUITest.ExecuteJavascript.
msg: An optional error message used if a JSONInterfaceError is caught
while waiting for the DOM node to appear.
timeout: Time to wait for the node to exist before raising an exception,
defaults to the default automation timeout.
Any additional keyword arguments are passed on to ExecuteJavascript and
can be used to select the tab where the DOM MutationObserver is created.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
pyauto_errors.JavascriptRuntimeError if the injected javascript
MutationObserver returns an error.
"""
observer_id = self.AddDomMutationObserver('exists', xpath, attribute,
expected_value, exec_js=exec_js,
**kwargs)
try:
self.GetNextEvent(observer_id, timeout=timeout)
except JSONInterfaceError:
raise JSONInterfaceError(msg)
def GetNextEvent(self, observer_id=-1, blocking=True, timeout=-1):
"""Waits for an observed event to occur.
The returned event is removed from the Event Queue. If there is already a
matching event in the queue it is returned immediately, otherwise the call
blocks until a matching event occurs. If blocking is disabled and no
matching event is in the queue this function will immediately return None.
Args:
observer_id: The id of the observer to wait for, matches any event by
default.
blocking: If True waits until there is a matching event in the queue,
if False and there is no event waiting in the queue returns None
immediately.
timeout: Time to wait for a matching event, defaults to the default
automation timeout.
Returns:
Event response dictionary, or None if blocking is disabled and there is no
matching event in the queue.
SAMPLE:
{ 'observer_id': 1,
'name': 'login completed',
'type': 'raised_event'}
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'GetNextEvent',
'observer_id' : observer_id,
'blocking' : blocking,
}
return self._GetResultFromJSONRequest(cmd_dict, windex=None,
timeout=timeout)
def RemoveEventObserver(self, observer_id):
"""Removes an Event Observer from the AutomationEventQueue.
Expects a valid observer_id.
Args:
observer_id: The id of the observer to remove.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'RemoveEventObserver',
'observer_id' : observer_id,
}
return self._GetResultFromJSONRequest(cmd_dict, windex=None)
def ClearEventQueue(self):
"""Removes all events currently in the AutomationEventQueue.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'ClearEventQueue',
}
return self._GetResultFromJSONRequest(cmd_dict, windex=None)
def WaitUntilNavigationCompletes(self, tab_index=0, windex=0):
"""Wait until the specified tab is done navigating.
It is safe to call ExecuteJavascript() as soon as the call returns. If
there is no outstanding navigation the call will return immediately.
Args:
tab_index: index of the tab.
windex: index of the window.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'WaitUntilNavigationCompletes',
'tab_index': tab_index,
'windex': windex,
}
return self._GetResultFromJSONRequest(cmd_dict)
def ExecuteJavascript(self, js, tab_index=0, windex=0, frame_xpath=''):
"""Executes a script in the specified frame of a tab.
By default, execute the script in the top frame of the first tab in the
first window. The invoked javascript function must send a result back via
the domAutomationController.send function, or this function will never
return.
Args:
js: script to be executed.
windex: index of the window.
tab_index: index of the tab.
frame_xpath: XPath of the frame to execute the script. Default is no
frame. Example: '//frames[1]'.
Returns:
a value that was sent back via the domAutomationController.send method
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'ExecuteJavascript',
'javascript' : js,
'windex' : windex,
'tab_index' : tab_index,
'frame_xpath' : frame_xpath,
}
result = self._GetResultFromJSONRequest(cmd_dict)['result']
# Wrap result in an array before deserializing because valid JSON has an
# array or an object as the root.
json_string = '[' + result + ']'
return json.loads(json_string)[0]
def ExecuteJavascriptInRenderView(self, js, view, frame_xpath=''):
"""Executes a script in the specified frame of an render view.
The invoked javascript function must send a result back via the
domAutomationController.send function, or this function will never return.
Args:
js: script to be executed.
view: A dictionary representing a unique id for the render view as
returned for example by.
self.GetBrowserInfo()['extension_views'][]['view'].
Example:
{ 'render_process_id': 1,
'render_view_id' : 2}
frame_xpath: XPath of the frame to execute the script. Default is no
frame. Example:
'//frames[1]'
Returns:
a value that was sent back via the domAutomationController.send method
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'ExecuteJavascriptInRenderView',
'javascript' : js,
'view' : view,
'frame_xpath' : frame_xpath,
}
result = self._GetResultFromJSONRequest(cmd_dict, windex=None)['result']
# Wrap result in an array before deserializing because valid JSON has an
# array or an object as the root.
json_string = '[' + result + ']'
return json.loads(json_string)[0]
def ExecuteJavascriptInOOBEWebUI(self, js, frame_xpath=''):
"""Executes a script in the specified frame of the OOBE WebUI.
By default, execute the script in the top frame of the OOBE window. This
also works for all OOBE pages, including the enterprise enrollment
screen and login page. The invoked javascript function must send a result
back via the domAutomationController.send function, or this function will
never return.
Args:
js: Script to be executed.
frame_xpath: XPath of the frame to execute the script. Default is no
frame. Example: '//frames[1]'
Returns:
A value that was sent back via the domAutomationController.send method.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'ExecuteJavascriptInOOBEWebUI',
'javascript': js,
'frame_xpath': frame_xpath,
}
result = self._GetResultFromJSONRequest(cmd_dict, windex=None)['result']
# Wrap result in an array before deserializing because valid JSON has an
# array or an object as the root.
return json.loads('[' + result + ']')[0]
def GetDOMValue(self, expr, tab_index=0, windex=0, frame_xpath=''):
"""Executes a Javascript expression and returns the value.
This is a wrapper for ExecuteJavascript, eliminating the need to
explicitly call domAutomationController.send function.
Args:
expr: expression value to be returned.
tab_index: index of the tab.
windex: index of the window.
frame_xpath: XPath of the frame to execute the script. Default is no
frame. Example: '//frames[1]'.
Returns:
a string that was sent back via the domAutomationController.send method.
"""
js = 'window.domAutomationController.send(%s);' % expr
return self.ExecuteJavascript(js, tab_index, windex, frame_xpath)
def CallJavascriptFunc(self, function, args=[], tab_index=0, windex=0):
"""Executes a script which calls a given javascript function.
The invoked javascript function must send a result back via the
domAutomationController.send function, or this function will never return.
Defaults to first tab in first window.
Args:
function: name of the function.
args: list of all the arguments to pass into the called function. These
should be able to be converted to a string using the |str| function.
tab_index: index of the tab within the given window.
windex: index of the window.
Returns:
a string that was sent back via the domAutomationController.send method
"""
converted_args = map(lambda arg: json.dumps(arg), args)
js = '%s(%s)' % (function, ', '.join(converted_args))
logging.debug('Executing javascript: %s', js)
return self.ExecuteJavascript(js, tab_index, windex)
def HeapProfilerDump(self, process_type, reason, tab_index=0, windex=0):
"""Dumps a heap profile. It works only on Linux and ChromeOS.
We need an environment variable "HEAPPROFILE" set to a directory and a
filename prefix, for example, "/tmp/prof". In a case of this example,
heap profiles will be dumped into "/tmp/prof.(pid).0002.heap",
"/tmp/prof.(pid).0003.heap", and so on. Nothing happens when this
function is called without the env.
Also, this requires the --enable-memory-benchmarking command line flag.
Args:
process_type: A string which is one of 'browser' or 'renderer'.
reason: A string which describes the reason for dumping a heap profile.
The reason will be included in the logged message.
Examples:
'To check memory leaking'
'For PyAuto tests'
tab_index: tab index to work on if 'process_type' == 'renderer'.
Defaults to 0 (first tab).
windex: window index to work on if 'process_type' == 'renderer'.
Defaults to 0 (first window).
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
assert process_type in ('browser', 'renderer')
if self.IsLinux(): # IsLinux() also implies IsChromeOS().
js = """
if (!chrome.memoryBenchmarking ||
!chrome.memoryBenchmarking.isHeapProfilerRunning()) {
domAutomationController.send('memory benchmarking disabled');
} else {
chrome.memoryBenchmarking.heapProfilerDump("%s", "%s");
domAutomationController.send('success');
}
""" % (process_type, reason.replace('"', '\\"'))
result = self.ExecuteJavascript(js, tab_index, windex)
if result != 'success':
raise JSONInterfaceError('Heap profiler dump failed: ' + result)
else:
logging.warn('Heap-profiling is not supported in this OS.')
def GetNTPThumbnails(self):
"""Return a list of info about the sites in the NTP most visited section.
SAMPLE:
[{ u'title': u'Google',
u'url': u'http://www.google.com'},
{
u'title': u'Yahoo',
u'url': u'http://www.yahoo.com'}]
"""
return self._GetNTPInfo()['most_visited']
def GetNTPThumbnailIndex(self, thumbnail):
"""Returns the index of the given NTP thumbnail, or -1 if it is not shown.
Args:
thumbnail: a thumbnail dict received from |GetNTPThumbnails|
"""
thumbnails = self.GetNTPThumbnails()
for i in range(len(thumbnails)):
if thumbnails[i]['url'] == thumbnail['url']:
return i
return -1
def RemoveNTPThumbnail(self, thumbnail):
"""Removes the NTP thumbnail and returns true on success.
Args:
thumbnail: a thumbnail dict received from |GetNTPThumbnails|
"""
self._CheckNTPThumbnailShown(thumbnail)
cmd_dict = {
'command': 'RemoveNTPMostVisitedThumbnail',
'url': thumbnail['url']
}
self._GetResultFromJSONRequest(cmd_dict)
def RestoreAllNTPThumbnails(self):
"""Restores all the removed NTP thumbnails.
Note:
the default thumbnails may come back into the Most Visited sites
section after doing this
"""
cmd_dict = {
'command': 'RestoreAllNTPMostVisitedThumbnails'
}
self._GetResultFromJSONRequest(cmd_dict)
def GetNTPDefaultSites(self):
"""Returns a list of URLs for all the default NTP sites, regardless of
whether they are showing or not.
These sites are the ones present in the NTP on a fresh install of Chrome.
"""
return self._GetNTPInfo()['default_sites']
def RemoveNTPDefaultThumbnails(self):
"""Removes all thumbnails for default NTP sites, regardless of whether they
are showing or not."""
cmd_dict = { 'command': 'RemoveNTPMostVisitedThumbnail' }
for site in self.GetNTPDefaultSites():
cmd_dict['url'] = site
self._GetResultFromJSONRequest(cmd_dict)
def GetNTPRecentlyClosed(self):
"""Return a list of info about the items in the NTP recently closed section.
SAMPLE:
[{
u'type': u'tab',
u'url': u'http://www.bing.com',
u'title': u'Bing',
u'timestamp': 2139082.03912, # Seconds since epoch (Jan 1, 1970)
u'direction': u'ltr'},
{
u'type': u'window',
u'timestamp': 2130821.90812,
u'tabs': [
{
u'type': u'tab',
u'url': u'http://www.cnn.com',
u'title': u'CNN',
u'timestamp': 2129082.12098,
u'direction': u'ltr'}]},
{
u'type': u'tab',
u'url': u'http://www.altavista.com',
u'title': u'Altavista',
u'timestamp': 21390820.12903,
u'direction': u'rtl'}]
"""
return self._GetNTPInfo()['recently_closed']
def GetNTPApps(self):
"""Retrieves information about the apps listed on the NTP.
In the sample data below, the "launch_type" will be one of the following
strings: "pinned", "regular", "fullscreen", "window", or "unknown".
SAMPLE:
[
{
u'app_launch_index': 2,
u'description': u'Web Store',
u'icon_big': u'chrome://theme/IDR_APP_DEFAULT_ICON',
u'icon_small': u'chrome://favicon/https://chrome.google.com/webstore',
u'id': u'ahfgeienlihckogmohjhadlkjgocpleb',
u'is_component_extension': True,
u'is_disabled': False,
u'launch_container': 2,
u'launch_type': u'regular',
u'launch_url': u'https://chrome.google.com/webstore',
u'name': u'Chrome Web Store',
u'options_url': u'',
},
{
u'app_launch_index': 1,
u'description': u'A countdown app',
u'icon_big': (u'chrome-extension://aeabikdlfbfeihglecobdkdflahfgcpd/'
u'countdown128.png'),
u'icon_small': (u'chrome://favicon/chrome-extension://'
u'aeabikdlfbfeihglecobdkdflahfgcpd/'
u'launchLocalPath.html'),
u'id': u'aeabikdlfbfeihglecobdkdflahfgcpd',
u'is_component_extension': False,
u'is_disabled': False,
u'launch_container': 2,
u'launch_type': u'regular',
u'launch_url': (u'chrome-extension://aeabikdlfbfeihglecobdkdflahfgcpd/'
u'launchLocalPath.html'),
u'name': u'Countdown',
u'options_url': u'',
}
]
Returns:
A list of dictionaries in which each dictionary contains the information
for a single app that appears in the "Apps" section of the NTP.
"""
return self._GetNTPInfo()['apps']
def _GetNTPInfo(self):
"""Get info about the New Tab Page (NTP).
This does not retrieve the actual info displayed in a particular NTP; it
retrieves the current state of internal data that would be used to display
an NTP. This includes info about the apps, the most visited sites,
the recently closed tabs and windows, and the default NTP sites.
SAMPLE:
{
u'apps': [ ... ],
u'most_visited': [ ... ],
u'recently_closed': [ ... ],
u'default_sites': [ ... ]
}
Returns:
A dictionary containing all the NTP info. See details about the different
sections in their respective methods: GetNTPApps(), GetNTPThumbnails(),
GetNTPRecentlyClosed(), and GetNTPDefaultSites().
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'GetNTPInfo',
}
return self._GetResultFromJSONRequest(cmd_dict)
def _CheckNTPThumbnailShown(self, thumbnail):
if self.GetNTPThumbnailIndex(thumbnail) == -1:
raise NTPThumbnailNotShownError()
def LaunchApp(self, app_id, windex=0):
"""Opens the New Tab Page and launches the specified app from it.
This method will not return until after the contents of a new tab for the
launched app have stopped loading.
Args:
app_id: The string ID of the app to launch.
windex: The index of the browser window to work on. Defaults to 0 (the
first window).
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
self.AppendTab(GURL('chrome://newtab'), windex) # Also activates this tab.
cmd_dict = {
'command': 'LaunchApp',
'id': app_id,
}
return self._GetResultFromJSONRequest(cmd_dict, windex=windex)
def SetAppLaunchType(self, app_id, launch_type, windex=0):
"""Sets the launch type for the specified app.
Args:
app_id: The string ID of the app whose launch type should be set.
launch_type: The string launch type, which must be one of the following:
'pinned': Launch in a pinned tab.
'regular': Launch in a regular tab.
'fullscreen': Launch in a fullscreen tab.
'window': Launch in a new browser window.
windex: The index of the browser window to work on. Defaults to 0 (the
first window).
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
self.assertTrue(launch_type in ('pinned', 'regular', 'fullscreen',
'window'),
msg='Unexpected launch type value: "%s"' % launch_type)
cmd_dict = {
'command': 'SetAppLaunchType',
'id': app_id,
'launch_type': launch_type,
}
return self._GetResultFromJSONRequest(cmd_dict, windex=windex)
def GetV8HeapStats(self, tab_index=0, windex=0):
"""Returns statistics about the v8 heap in the renderer process for a tab.
Args:
tab_index: The tab index, default is 0.
window_index: The window index, default is 0.
Returns:
A dictionary containing v8 heap statistics. Memory values are in bytes.
Example:
{ 'renderer_id': 6223,
'v8_memory_allocated': 21803776,
'v8_memory_used': 10565392 }
"""
cmd_dict = { # Prepare command for the json interface.
'command': 'GetV8HeapStats',
'tab_index': tab_index,
}
return self._GetResultFromJSONRequest(cmd_dict, windex=windex)
def GetFPS(self, tab_index=0, windex=0):
"""Returns the current FPS associated with the renderer process for a tab.
FPS is the rendered frames per second.
Args:
tab_index: The tab index, default is 0.
window_index: The window index, default is 0.
Returns:
A dictionary containing FPS info.
Example:
{ 'renderer_id': 23567,
'routing_id': 1,
'fps': 29.404298782348633 }
"""
cmd_dict = { # Prepare command for the json interface.
'command': 'GetFPS',
'tab_index': tab_index,
}
return self._GetResultFromJSONRequest(cmd_dict, windex=windex)
def IsFullscreenForBrowser(self, windex=0):
"""Returns true if the window is currently fullscreen and was initially
transitioned to fullscreen by a browser (vs tab) mode transition."""
return self._GetResultFromJSONRequest(
{ 'command': 'IsFullscreenForBrowser' },
windex=windex).get('result')
def IsFullscreenForTab(self, windex=0):
"""Returns true if fullscreen has been caused by a tab."""
return self._GetResultFromJSONRequest(
{ 'command': 'IsFullscreenForTab' },
windex=windex).get('result')
def IsMouseLocked(self, windex=0):
"""Returns true if the mouse is currently locked."""
return self._GetResultFromJSONRequest(
{ 'command': 'IsMouseLocked' },
windex=windex).get('result')
def IsMouseLockPermissionRequested(self, windex=0):
"""Returns true if the user is currently prompted to give permision for
mouse lock."""
return self._GetResultFromJSONRequest(
{ 'command': 'IsMouseLockPermissionRequested' },
windex=windex).get('result')
def IsFullscreenPermissionRequested(self, windex=0):
"""Returns true if the user is currently prompted to give permision for
fullscreen."""
return self._GetResultFromJSONRequest(
{ 'command': 'IsFullscreenPermissionRequested' },
windex=windex).get('result')
def IsFullscreenBubbleDisplayed(self, windex=0):
"""Returns true if the fullscreen and mouse lock bubble is currently
displayed."""
return self._GetResultFromJSONRequest(
{ 'command': 'IsFullscreenBubbleDisplayed' },
windex=windex).get('result')
def IsFullscreenBubbleDisplayingButtons(self, windex=0):
"""Returns true if the fullscreen and mouse lock bubble is currently
displayed and presenting buttons."""
return self._GetResultFromJSONRequest(
{ 'command': 'IsFullscreenBubbleDisplayingButtons' },
windex=windex).get('result')
def AcceptCurrentFullscreenOrMouseLockRequest(self, windex=0):
"""Activate the accept button on the fullscreen and mouse lock bubble."""
return self._GetResultFromJSONRequest(
{ 'command': 'AcceptCurrentFullscreenOrMouseLockRequest' },
windex=windex)
def DenyCurrentFullscreenOrMouseLockRequest(self, windex=0):
"""Activate the deny button on the fullscreen and mouse lock bubble."""
return self._GetResultFromJSONRequest(
{ 'command': 'DenyCurrentFullscreenOrMouseLockRequest' },
windex=windex)
def KillRendererProcess(self, pid):
"""Kills the given renderer process.
This will return only after the browser has received notice of the renderer
close.
Args:
pid: the process id of the renderer to kill
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'KillRendererProcess',
'pid': pid
}
return self._GetResultFromJSONRequest(cmd_dict)
def NewWebDriver(self, port=0):
"""Returns a new remote WebDriver instance.
Args:
port: The port to start WebDriver on; by default the service selects an
open port. It is an error to request a port number and request a
different port later.
Returns:
selenium.webdriver.remote.webdriver.WebDriver instance
"""
from chrome_driver_factory import ChromeDriverFactory
global _CHROME_DRIVER_FACTORY
if _CHROME_DRIVER_FACTORY is None:
_CHROME_DRIVER_FACTORY = ChromeDriverFactory(port=port)
self.assertTrue(_CHROME_DRIVER_FACTORY.GetPort() == port or port == 0,
msg='Requested a WebDriver on a specific port while already'
' running on a different port.')
return _CHROME_DRIVER_FACTORY.NewChromeDriver(self)
def CreateNewAutomationProvider(self, channel_id):
"""Creates a new automation provider.
The provider will open a named channel in server mode.
Args:
channel_id: the channel_id to open the server channel with
"""
cmd_dict = {
'command': 'CreateNewAutomationProvider',
'channel_id': channel_id
}
self._GetResultFromJSONRequest(cmd_dict)
def OpenNewBrowserWindowWithNewProfile(self):
"""Creates a new multi-profiles user, and then opens and shows a new
tabbed browser window with the new profile.
This is equivalent to 'Add new user' action with multi-profiles.
To account for crbug.com/108761 on Win XP, this call polls until the
profile count increments by 1.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
num_profiles = len(self.GetMultiProfileInfo()['profiles'])
cmd_dict = { # Prepare command for the json interface
'command': 'OpenNewBrowserWindowWithNewProfile'
}
self._GetResultFromJSONRequest(cmd_dict, windex=None)
# TODO(nirnimesh): Remove when crbug.com/108761 is fixed
self.WaitUntil(
lambda: len(self.GetMultiProfileInfo()['profiles']),
expect_retval=(num_profiles + 1))
def OpenProfileWindow(self, path, num_loads=1):
"""Open browser window for an existing profile.
This is equivalent to picking a profile from the multi-profile menu.
Multi-profile should be enabled and the requested profile should already
exist. Creates a new window for the given profile. Use
OpenNewBrowserWindowWithNewProfile() to create a new profile.
Args:
path: profile path of the profile to be opened.
num_loads: the number of loads to wait for, when a new browser window
is created. Useful when restoring a window with many tabs.
"""
cmd_dict = { # Prepare command for the json interface
'command': 'OpenProfileWindow',
'path': path,
'num_loads': num_loads,
}
return self._GetResultFromJSONRequest(cmd_dict, windex=None)
def GetMultiProfileInfo(self):
"""Fetch info about all multi-profile users.
Returns:
A dictionary.
Sample:
{
'enabled': True,
'profiles': [{'name': 'First user',
'path': '/tmp/.org.chromium.Chromium.Tyx17X/Default'},
{'name': 'User 1',
'path': '/tmp/.org.chromium.Chromium.Tyx17X/profile_1'}],
}
Profiles will be listed in the same order as visible in preferences.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = { # Prepare command for the json interface
'command': 'GetMultiProfileInfo'
}
return self._GetResultFromJSONRequest(cmd_dict, windex=None)
def RefreshPolicies(self):
"""Refreshes all the available policy providers.
Each policy provider will reload its policy source and push the updated
policies. This call waits for the new policies to be applied; any policies
installed before this call is issued are guaranteed to be ready after it
returns.
"""
# TODO(craigdh): Determine the root cause of RefreshPolicies' flakiness.
# See crosbug.com/30221
timeout = PyUITest.ActionTimeoutChanger(self, 3 * 60 * 1000)
cmd_dict = { 'command': 'RefreshPolicies' }
self._GetResultFromJSONRequest(cmd_dict, windex=None)
def SubmitForm(self, form_id, tab_index=0, windex=0, frame_xpath=''):
"""Submits the given form ID, and returns after it has been submitted.
Args:
form_id: the id attribute of the form to submit.
Returns: true on success.
"""
js = """
document.getElementById("%s").submit();
window.addEventListener("unload", function() {
window.domAutomationController.send("done");
});
""" % form_id
if self.ExecuteJavascript(js, tab_index, windex, frame_xpath) != 'done':
return False
# Wait until the form is submitted and the page completes loading.
return self.WaitUntil(
lambda: self.GetDOMValue('document.readyState',
tab_index, windex, frame_xpath),
expect_retval='complete')
def SimulateAsanMemoryBug(self):
"""Simulates a memory bug for Address Sanitizer to catch.
Address Sanitizer (if it was built it) will catch the bug and abort
the process.
This method returns immediately before it actually causes a crash.
"""
cmd_dict = { 'command': 'SimulateAsanMemoryBug' }
self._GetResultFromJSONRequest(cmd_dict, windex=None)
## ChromeOS section
def GetLoginInfo(self):
"""Returns information about login and screen locker state.
This includes things like whether a user is logged in, the username
of the logged in user, and whether the screen is locked.
Returns:
A dictionary.
Sample:
{ u'is_guest': False,
u'is_owner': True,
u'email': u'[email protected]',
u'user_image': 2, # non-negative int, 'profile', 'file'
u'is_screen_locked': False,
u'login_ui_type': 'nativeui', # or 'webui'
u'is_logged_in': True}
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = { 'command': 'GetLoginInfo' }
return self._GetResultFromJSONRequest(cmd_dict, windex=None)
def WaitForSessionManagerRestart(self, function):
"""Call a function and wait for the ChromeOS session_manager to restart.
Args:
function: The function to call.
"""
assert callable(function)
pgrep_process = subprocess.Popen(['pgrep', 'session_manager'],
stdout=subprocess.PIPE)
old_pid = pgrep_process.communicate()[0].strip()
function()
return self.WaitUntil(lambda: self._IsSessionManagerReady(old_pid))
def _WaitForInodeChange(self, path, function):
"""Call a function and wait for the specified file path to change.
Args:
path: The file path to check for changes.
function: The function to call.
"""
assert callable(function)
old_inode = os.stat(path).st_ino
function()
return self.WaitUntil(lambda: self._IsInodeNew(path, old_inode))
def ShowCreateAccountUI(self):
"""Go to the account creation page.
This is the same as clicking the "Create Account" link on the
ChromeOS login screen. Does not actually create a new account.
Should be displaying the login screen to work.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = { 'command': 'ShowCreateAccountUI' }
# See note below under LoginAsGuest(). ShowCreateAccountUI() logs
# the user in as guest in order to access the account creation page.
assert self._WaitForInodeChange(
self._named_channel_id,
lambda: self._GetResultFromJSONRequest(cmd_dict, windex=None)), \
'Chrome did not reopen the testing channel after login as guest.'
self.SetUp()
def SkipToLogin(self, skip_image_selection=True):
"""Skips OOBE to the login screen.
Assumes that we're at the beginning of OOBE.
Args:
skip_image_selection: Boolean indicating whether the user image selection
screen should also be skipped.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = { 'command': 'SkipToLogin',
'skip_image_selection': skip_image_selection }
result = self._GetResultFromJSONRequest(cmd_dict, windex=None)
assert result['next_screen'] == 'login', 'Unexpected wizard transition'
def GetOOBEScreenInfo(self):
"""Queries info about the current OOBE screen.
Returns:
A dictionary with the following keys:
'screen_name': The title of the current OOBE screen as a string.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = { 'command': 'GetOOBEScreenInfo' }
return self._GetResultFromJSONRequest(cmd_dict, windex=None)
def AcceptOOBENetworkScreen(self):
"""Accepts OOBE network screen and advances to the next one.
Assumes that we're already at the OOBE network screen.
Returns:
A dictionary with the following keys:
'next_screen': The title of the next OOBE screen as a string.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = { 'command': 'AcceptOOBENetworkScreen' }
return self._GetResultFromJSONRequest(cmd_dict, windex=None)
def AcceptOOBEEula(self, accepted, usage_stats_reporting=False):
"""Accepts OOBE EULA and advances to the next screen.
Assumes that we're already at the OOBE EULA screen.
Args:
accepted: Boolean indicating whether the EULA should be accepted.
usage_stats_reporting: Boolean indicating whether UMA should be enabled.
Returns:
A dictionary with the following keys:
'next_screen': The title of the next OOBE screen as a string.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = { 'command': 'AcceptOOBEEula',
'accepted': accepted,
'usage_stats_reporting': usage_stats_reporting }
return self._GetResultFromJSONRequest(cmd_dict, windex=None)
def CancelOOBEUpdate(self):
"""Skips update on OOBE and advances to the next screen.
Returns:
A dictionary with the following keys:
'next_screen': The title of the next OOBE screen as a string.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = { 'command': 'CancelOOBEUpdate' }
return self._GetResultFromJSONRequest(cmd_dict, windex=None)
def PickUserImage(self, image):
"""Chooses image for the newly created user.
Should be called immediately after login.
Args:
image_type: type of user image to choose. Possible values:
- "profile": Google profile image
- non-negative int: one of the default images
Returns:
A dictionary with the following keys:
'next_screen': The title of the next OOBE screen as a string.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = { 'command': 'PickUserImage',
'image': image }
return self._GetResultFromJSONRequest(cmd_dict, windex=None)
def LoginAsGuest(self):
"""Login to chromeos as a guest user.
Waits until logged in.
Should be displaying the login screen to work.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = { 'command': 'LoginAsGuest' }
# Currently, logging in as guest causes session_manager to
# restart Chrome, which will close the testing channel.
# We need to call SetUp() again to reconnect to the new channel.
assert self._WaitForInodeChange(
self._named_channel_id,
lambda: self._GetResultFromJSONRequest(cmd_dict, windex=None)), \
'Chrome did not reopen the testing channel after login as guest.'
self.SetUp()
def Login(self, username, password, timeout=120 * 1000):
"""Login to chromeos.
Waits until logged in and browser is ready.
Should be displaying the login screen to work.
Note that in case of webui auth-extension-based login, gaia auth errors
will not be noticed here, because the browser has no knowledge of it. In
this case the GetNextEvent automation command will always time out.
Args:
username: the username to log in as.
password: the user's password.
timeout: timeout in ms; defaults to two minutes.
Returns:
An error string if an error occured.
None otherwise.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
self._GetResultFromJSONRequest({'command': 'AddLoginEventObserver'},
windex=None)
cmd_dict = {
'command': 'SubmitLoginForm',
'username': username,
'password': password,
}
self._GetResultFromJSONRequest(cmd_dict, windex=None)
self.AddDomEventObserver('loginfail', automation_id=4444)
try:
if self.GetNextEvent(timeout=timeout).get('name') == 'loginfail':
raise JSONInterfaceError('Login denied by auth server.')
except JSONInterfaceError as e:
raise JSONInterfaceError('Login failed. Perhaps Chrome crashed, '
'failed to start, or the login flow is '
'broken? Error message: %s' % str(e))
def Logout(self):
"""Log out from ChromeOS and wait for session_manager to come up.
This is equivalent to pressing the 'Sign out' button from the
aura shell tray when logged in.
Should be logged in to work. Re-initializes the automation channel
after logout.
"""
clear_profile_orig = self.get_clear_profile()
self.set_clear_profile(False)
assert self.GetLoginInfo()['is_logged_in'], \
'Trying to log out when already logged out.'
def _SignOut():
cmd_dict = { 'command': 'SignOut' }
self._GetResultFromJSONRequest(cmd_dict, windex=None)
assert self.WaitForSessionManagerRestart(_SignOut), \
'Session manager did not restart after logout.'
self.__SetUp()
self.set_clear_profile(clear_profile_orig)
def LockScreen(self):
"""Locks the screen on chromeos.
Waits until screen is locked.
Should be logged in and screen should not be locked to work.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = { 'command': 'LockScreen' }
self._GetResultFromJSONRequest(cmd_dict, windex=None)
def UnlockScreen(self, password):
"""Unlocks the screen on chromeos, authenticating the user's password first.
Waits until screen is unlocked.
Screen locker should be active for this to work.
Returns:
An error string if an error occured.
None otherwise.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'UnlockScreen',
'password': password,
}
result = self._GetResultFromJSONRequest(cmd_dict, windex=None)
return result.get('error_string')
def SignoutInScreenLocker(self):
"""Signs out of chromeos using the screen locker's "Sign out" feature.
Effectively the same as clicking the "Sign out" link on the screen locker.
Screen should be locked for this to work.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = { 'command': 'SignoutInScreenLocker' }
assert self.WaitForSessionManagerRestart(
lambda: self._GetResultFromJSONRequest(cmd_dict, windex=None)), \
'Session manager did not restart after logout.'
self.__SetUp()
def GetBatteryInfo(self):
"""Get details about battery state.
Returns:
A dictionary with the following keys:
'battery_is_present': bool
'line_power_on': bool
if 'battery_is_present':
'battery_percentage': float (0 ~ 100)
'battery_fully_charged': bool
if 'line_power_on':
'battery_time_to_full': int (seconds)
else:
'battery_time_to_empty': int (seconds)
If it is still calculating the time left, 'battery_time_to_full'
and 'battery_time_to_empty' will be absent.
Use 'battery_fully_charged' instead of 'battery_percentage'
or 'battery_time_to_full' to determine whether the battery
is fully charged, since the percentage is only approximate.
Sample:
{ u'battery_is_present': True,
u'line_power_on': False,
u'battery_time_to_empty': 29617,
u'battery_percentage': 100.0,
u'battery_fully_charged': False }
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = { 'command': 'GetBatteryInfo' }
return self._GetResultFromJSONRequest(cmd_dict, windex=None)
def GetPanelInfo(self):
"""Get details about open ChromeOS panels.
A panel is actually a type of browser window, so all of
this information is also available using GetBrowserInfo().
Returns:
A dictionary.
Sample:
[{ 'incognito': False,
'renderer_pid': 4820,
'title': u'Downloads',
'url': u'chrome://active-downloads/'}]
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
panels = []
for browser in self.GetBrowserInfo()['windows']:
if browser['type'] != 'panel':
continue
panel = {}
panels.append(panel)
tab = browser['tabs'][0]
panel['incognito'] = browser['incognito']
panel['renderer_pid'] = tab['renderer_pid']
panel['title'] = self.GetActiveTabTitle(browser['index'])
panel['url'] = tab['url']
return panels
def EnableSpokenFeedback(self, enabled):
"""Enables or disables spoken feedback accessibility mode.
Args:
enabled: Boolean value indicating the desired state of spoken feedback.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'EnableSpokenFeedback',
'enabled': enabled,
}
return self._GetResultFromJSONRequest(cmd_dict, windex=None)
def IsSpokenFeedbackEnabled(self):
"""Check whether spoken feedback accessibility mode is enabled.
Returns:
True if spoken feedback is enabled, False otherwise.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = { 'command': 'IsSpokenFeedbackEnabled', }
result = self._GetResultFromJSONRequest(cmd_dict, windex=None)
return result.get('spoken_feedback')
def GetTimeInfo(self, windex=0):
"""Gets info about the ChromeOS status bar clock.
Set the 24-hour clock by using:
self.SetPrefs('settings.clock.use_24hour_clock', True)
Returns:
a dictionary.
Sample:
{u'display_date': u'Tuesday, July 26, 2011',
u'display_time': u'4:30',
u'timezone': u'America/Los_Angeles'}
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = { 'command': 'GetTimeInfo' }
if self.GetLoginInfo()['is_logged_in']:
return self._GetResultFromJSONRequest(cmd_dict, windex=windex)
else:
return self._GetResultFromJSONRequest(cmd_dict, windex=None)
def SetTimezone(self, timezone):
"""Sets the timezone on ChromeOS. A user must be logged in.
The timezone is the relative path to the timezone file in
/usr/share/zoneinfo. For example, /usr/share/zoneinfo/America/Los_Angeles is
'America/Los_Angeles'. For a list of valid timezones see
'chromeos/settings/timezone_settings.cc'.
This method does not return indication of success or failure.
If the timezone is it falls back to a valid timezone.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = {
'command': 'SetTimezone',
'timezone': timezone,
}
self._GetResultFromJSONRequest(cmd_dict, windex=None)
def UpdateCheck(self):
"""Checks for a ChromeOS update. Blocks until finished updating.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = { 'command': 'UpdateCheck' }
self._GetResultFromJSONRequest(cmd_dict, windex=None)
def GetVolumeInfo(self):
"""Gets the volume and whether the device is muted.
Returns:
a tuple.
Sample:
(47.763456790123456, False)
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = { 'command': 'GetVolumeInfo' }
return self._GetResultFromJSONRequest(cmd_dict, windex=None)
def SetVolume(self, volume):
"""Sets the volume on ChromeOS. Only valid if not muted.
Args:
volume: The desired volume level as a percent from 0 to 100.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
assert volume >= 0 and volume <= 100
cmd_dict = {
'command': 'SetVolume',
'volume': float(volume),
}
return self._GetResultFromJSONRequest(cmd_dict, windex=None)
def SetMute(self, mute):
"""Sets whether ChromeOS is muted or not.
Args:
mute: True to mute, False to unmute.
Raises:
pyauto_errors.JSONInterfaceError if the automation call returns an error.
"""
cmd_dict = { 'command': 'SetMute' }
cmd_dict = {
'command': 'SetMute',
'mute': mute,
}
return self._GetResultFromJSONRequest(cmd_dict, windex=None)
# HTML Terminal
def OpenCrosh(self):
"""Open crosh.
Equivalent to pressing Ctrl-Alt-t.
Opens in the last active (non-incognito) window.
Waits long enough for crosh to load, but does not wait for the crosh
prompt. Use WaitForHtermText() for that.
"""
cmd_dict = { 'command': 'OpenCrosh' }
self._GetResultFromJSONRequest(cmd_dict, windex=None)
def WaitForHtermText(self, text, msg=None, tab_index=0, windex=0):
"""Waits for the given text in a hterm tab.
Can be used to wait for the crosh> prompt or ssh prompt.
This does not poll. It uses dom mutation observers to wait
for the given text to show up.
Args:
text: the text to wait for. Can be a regex.
msg: the failure message to emit if the text could not be found.
tab_index: the tab for the hterm tab. Default: 0.
windex: the window index for the hterm tab. Default: 0.
"""
self.WaitForDomNode(
xpath='//*[contains(text(), "%s")]' % text, frame_xpath='//iframe',
msg=msg, tab_index=tab_index, windex=windex)
def GetHtermRowsText(self, start, end, tab_index=0, windex=0):
"""Fetch rows from a html terminal tab.
Works for both crosh and ssh tab.
Uses term_.getRowsText(start, end) javascript call.
Args:
start: start line number (0-based).
end: the end line (one beyond the line of interest).
tab_index: the tab for the hterm tab. Default: 0.
windex: the window index for the hterm tab. Default: 0.
"""
return self.ExecuteJavascript(
'domAutomationController.send(term_.getRowsText(%d, %d))' % (
start, end),
tab_index=tab_index, windex=windex)
def SendKeysToHterm(self, text, tab_index=0, windex=0):
"""Send keys to a html terminal tab.
Works for both crosh and ssh tab.
Uses term_.onVTKeystroke(str) javascript call.
Args:
text: the text to send.
tab_index: the tab for the hterm tab. Default: 0.
windex: the window index for the hterm tab. Default: 0.
"""
return self.ExecuteJavascript(
'term_.onVTKeystroke("%s");'
'domAutomationController.send("done")' % text,
tab_index=tab_index, windex=windex)
def GetMemoryStatsChromeOS(self, duration):
"""Identifies and returns different kinds of current memory usage stats.
This function samples values each second for |duration| seconds, then
outputs the min, max, and ending values for each measurement type.
Args:
duration: The number of seconds to sample data before outputting the
minimum, maximum, and ending values for each measurement type.
Returns:
A dictionary containing memory usage information. Each measurement type
is associated with the min, max, and ending values from among all
sampled values. Values are specified in KB.
{
'gem_obj': { # GPU memory usage.
'min': ...,
'max': ...,
'end': ...,
},
'gtt': { ... }, # GPU memory usage (graphics translation table).
'mem_free': { ... }, # CPU free memory.
'mem_available': { ... }, # CPU available memory.
'mem_shared': { ... }, # CPU shared memory.
'mem_cached': { ... }, # CPU cached memory.
'mem_anon': { ... }, # CPU anon memory (active + inactive).
'mem_file': { ... }, # CPU file memory (active + inactive).
'mem_slab': { ... }, # CPU slab memory.
'browser_priv': { ... }, # Chrome browser private memory.
'browser_shared': { ... }, # Chrome browser shared memory.
'gpu_priv': { ... }, # Chrome GPU private memory.
'gpu_shared': { ... }, # Chrome GPU shared memory.
'renderer_priv': { ... }, # Total private memory of all renderers.
'renderer_shared': { ... }, # Total shared memory of all renderers.
}
"""
logging.debug('Sampling memory information for %d seconds...' % duration)
stats = {}
for _ in xrange(duration):
# GPU memory.
gem_obj_path = '/sys/kernel/debug/dri/0/i915_gem_objects'
if os.path.exists(gem_obj_path):
p = subprocess.Popen('grep bytes %s' % gem_obj_path,
stdout=subprocess.PIPE, shell=True)
stdout = p.communicate()[0]
gem_obj = re.search(
'\d+ objects, (\d+) bytes\n', stdout).group(1)
if 'gem_obj' not in stats:
stats['gem_obj'] = []
stats['gem_obj'].append(int(gem_obj) / 1024.0)
gtt_path = '/sys/kernel/debug/dri/0/i915_gem_gtt'
if os.path.exists(gtt_path):
p = subprocess.Popen('grep bytes %s' % gtt_path,
stdout=subprocess.PIPE, shell=True)
stdout = p.communicate()[0]
gtt = re.search(
'Total [\d]+ objects, ([\d]+) bytes', stdout).group(1)
if 'gtt' not in stats:
stats['gtt'] = []
stats['gtt'].append(int(gtt) / 1024.0)
# CPU memory.
stdout = ''
with open('/proc/meminfo') as f:
stdout = f.read()
mem_free = re.search('MemFree:\s*([\d]+) kB', stdout).group(1)
if 'mem_free' not in stats:
stats['mem_free'] = []
stats['mem_free'].append(int(mem_free))
mem_dirty = re.search('Dirty:\s*([\d]+) kB', stdout).group(1)
mem_active_file = re.search(
'Active\(file\):\s*([\d]+) kB', stdout).group(1)
mem_inactive_file = re.search(
'Inactive\(file\):\s*([\d]+) kB', stdout).group(1)
with open('/proc/sys/vm/min_filelist_kbytes') as f:
mem_min_file = f.read()
# Available memory =
# MemFree + ActiveFile + InactiveFile - DirtyMem - MinFileMem
if 'mem_available' not in stats:
stats['mem_available'] = []
stats['mem_available'].append(
int(mem_free) + int(mem_active_file) + int(mem_inactive_file) -
int(mem_dirty) - int(mem_min_file))
mem_shared = re.search('Shmem:\s*([\d]+) kB', stdout).group(1)
if 'mem_shared' not in stats:
stats['mem_shared'] = []
stats['mem_shared'].append(int(mem_shared))
mem_cached = re.search('Cached:\s*([\d]+) kB', stdout).group(1)
if 'mem_cached' not in stats:
stats['mem_cached'] = []
stats['mem_cached'].append(int(mem_cached))
mem_anon_active = re.search('Active\(anon\):\s*([\d]+) kB',
stdout).group(1)
mem_anon_inactive = re.search('Inactive\(anon\):\s*([\d]+) kB',
stdout).group(1)
if 'mem_anon' not in stats:
stats['mem_anon'] = []
stats['mem_anon'].append(int(mem_anon_active) + int(mem_anon_inactive))
mem_file_active = re.search('Active\(file\):\s*([\d]+) kB',
stdout).group(1)
mem_file_inactive = re.search('Inactive\(file\):\s*([\d]+) kB',
stdout).group(1)
if 'mem_file' not in stats:
stats['mem_file'] = []
stats['mem_file'].append(int(mem_file_active) + int(mem_file_inactive))
mem_slab = re.search('Slab:\s*([\d]+) kB', stdout).group(1)
if 'mem_slab' not in stats:
stats['mem_slab'] = []
stats['mem_slab'].append(int(mem_slab))
# Chrome process memory.
pinfo = self.GetProcessInfo()['browsers'][0]['processes']
total_renderer_priv = 0
total_renderer_shared = 0
for process in pinfo:
mem_priv = process['working_set_mem']['priv']
mem_shared = process['working_set_mem']['shared']
if process['child_process_type'] == 'Browser':
if 'browser_priv' not in stats:
stats['browser_priv'] = []
stats['browser_priv'].append(int(mem_priv))
if 'browser_shared' not in stats:
stats['browser_shared'] = []
stats['browser_shared'].append(int(mem_shared))
elif process['child_process_type'] == 'GPU':
if 'gpu_priv' not in stats:
stats['gpu_priv'] = []
stats['gpu_priv'].append(int(mem_priv))
if 'gpu_shared' not in stats:
stats['gpu_shared'] = []
stats['gpu_shared'].append(int(mem_shared))
elif process['child_process_type'] == 'Tab':
# Sum the memory of all renderer processes.
total_renderer_priv += int(mem_priv)
total_renderer_shared += int(mem_shared)
if 'renderer_priv' not in stats:
stats['renderer_priv'] = []
stats['renderer_priv'].append(int(total_renderer_priv))
if 'renderer_shared' not in stats:
stats['renderer_shared'] = []
stats['renderer_shared'].append(int(total_renderer_shared))
time.sleep(1)
# Compute min, max, and ending values to return.
result = {}
for measurement_type in stats:
values = stats[measurement_type]
result[measurement_type] = {
'min': min(values),
'max': max(values),
'end': values[-1],
}
return result
## ChromeOS section -- end
class ExtraBrowser(PyUITest):
"""Launches a new browser with some extra flags.
The new browser is launched with its own fresh profile.
This class does not apply to ChromeOS.
"""
def __init__(self, chrome_flags=[], methodName='runTest', **kwargs):
"""Accepts extra chrome flags for launching a new browser instance.
Args:
chrome_flags: list of extra flags when launching a new browser.
"""
assert not PyUITest.IsChromeOS(), \
'This function cannot be used to launch a new browser in ChromeOS.'
PyUITest.__init__(self, methodName=methodName, **kwargs)
self._chrome_flags = chrome_flags
PyUITest.setUp(self)
def __del__(self):
"""Tears down the browser and then calls super class's destructor"""
PyUITest.tearDown(self)
PyUITest.__del__(self)
def ExtraChromeFlags(self):
"""Prepares the browser to launch with specified Chrome flags."""
return PyUITest.ExtraChromeFlags(self) + self._chrome_flags
class _RemoteProxy():
"""Class for PyAuto remote method calls.
Use this class along with RemoteHost.testRemoteHost to establish a PyAuto
connection with another machine and make remote PyAuto calls. The RemoteProxy
mimics a PyAuto object, so all json-style PyAuto calls can be made on it.
The remote host acts as a dumb executor that receives method call requests,
executes them, and sends all of the results back to the RemoteProxy, including
the return value, thrown exceptions, and console output.
The remote host should be running the same version of PyAuto as the proxy.
A mismatch could lead to undefined behavior.
Example usage:
class MyTest(pyauto.PyUITest):
def testRemoteExample(self):
remote = pyauto._RemoteProxy(('127.0.0.1', 7410))
remote.NavigateToURL('http://www.google.com')
title = remote.GetActiveTabTitle()
self.assertEqual(title, 'Google')
"""
class RemoteException(Exception):
pass
def __init__(self, host):
self.RemoteConnect(host)
def RemoteConnect(self, host):
begin = time.time()
while time.time() - begin < 50:
self._socket = socket.socket()
if not self._socket.connect_ex(host):
break
time.sleep(0.25)
else:
# Make one last attempt, but raise a socket error on failure.
self._socket = socket.socket()
self._socket.connect(host)
def RemoteDisconnect(self):
if self._socket:
self._socket.shutdown(socket.SHUT_RDWR)
self._socket.close()
self._socket = None
def CreateTarget(self, target):
"""Registers the methods and creates a remote instance of a target.
Any RPC calls will then be made on the remote target instance. Note that the
remote instance will be a brand new instance and will have none of the state
of the local instance. The target's class should have a constructor that
takes no arguments.
"""
self._Call('CreateTarget', target.__class__)
self._RegisterClassMethods(target)
def _RegisterClassMethods(self, remote_class):
# Make remote-call versions of all remote_class methods.
for method_name, _ in inspect.getmembers(remote_class, inspect.ismethod):
# Ignore private methods and duplicates.
if method_name[0] in string.letters and \
getattr(self, method_name, None) is None:
setattr(self, method_name, functools.partial(self._Call, method_name))
def _Call(self, method_name, *args, **kwargs):
# Send request.
request = pickle.dumps((method_name, args, kwargs))
if self._socket.send(request) != len(request):
raise self.RemoteException('Error sending remote method call request.')
# Receive response.
response = self._socket.recv(4096)
if not response:
raise self.RemoteException('Client disconnected during method call.')
result, stdout, stderr, exception = pickle.loads(response)
# Print any output the client captured, throw any exceptions, and return.
sys.stdout.write(stdout)
sys.stderr.write(stderr)
if exception:
raise self.RemoteException('%s raised by remote client: %s' %
(exception[0], exception[1]))
return result
class PyUITestSuite(pyautolib.PyUITestSuiteBase, unittest.TestSuite):
"""Base TestSuite for PyAuto UI tests."""
def __init__(self, args):
pyautolib.PyUITestSuiteBase.__init__(self, args)
# Figure out path to chromium binaries
browser_dir = os.path.normpath(os.path.dirname(pyautolib.__file__))
logging.debug('Loading pyauto libs from %s', browser_dir)
self.InitializeWithPath(pyautolib.FilePath(browser_dir))
os.environ['PATH'] = browser_dir + os.pathsep + os.environ['PATH']
unittest.TestSuite.__init__(self)
cr_source_root = os.path.normpath(os.path.join(
os.path.dirname(__file__), os.pardir, os.pardir, os.pardir))
self.SetCrSourceRoot(pyautolib.FilePath(cr_source_root))
# Start http server, if needed.
global _OPTIONS
if _OPTIONS and not _OPTIONS.no_http_server:
self._StartHTTPServer()
if _OPTIONS and _OPTIONS.remote_host:
self._ConnectToRemoteHosts(_OPTIONS.remote_host.split(','))
def __del__(self):
# python unittest module is setup such that the suite gets deleted before
# the test cases, which is odd because our test cases depend on
# initializtions like exitmanager, autorelease pool provided by the
# suite. Forcibly delete the test cases before the suite.
del self._tests
pyautolib.PyUITestSuiteBase.__del__(self)
global _HTTP_SERVER
if _HTTP_SERVER:
self._StopHTTPServer()
global _CHROME_DRIVER_FACTORY
if _CHROME_DRIVER_FACTORY is not None:
_CHROME_DRIVER_FACTORY.Stop()
def _StartHTTPServer(self):
"""Start a local file server hosting data files over http://"""
global _HTTP_SERVER
assert not _HTTP_SERVER, 'HTTP Server already started'
http_data_dir = _OPTIONS.http_data_dir
http_server = pyautolib.SpawnedTestServer(
pyautolib.SpawnedTestServer.TYPE_HTTP,
'127.0.0.1',
pyautolib.FilePath(http_data_dir))
assert http_server.Start(), 'Could not start http server'
_HTTP_SERVER = http_server
logging.debug('Started http server at "%s".', http_data_dir)
def _StopHTTPServer(self):
"""Stop the local http server."""
global _HTTP_SERVER
assert _HTTP_SERVER, 'HTTP Server not yet started'
assert _HTTP_SERVER.Stop(), 'Could not stop http server'
_HTTP_SERVER = None
logging.debug('Stopped http server.')
def _ConnectToRemoteHosts(self, addresses):
"""Connect to remote PyAuto instances using a RemoteProxy.
The RemoteHost instances must already be running."""
global _REMOTE_PROXY
assert not _REMOTE_PROXY, 'Already connected to a remote host.'
_REMOTE_PROXY = []
for address in addresses:
if address == 'localhost' or address == '127.0.0.1':
self._StartLocalRemoteHost()
_REMOTE_PROXY.append(_RemoteProxy((address, 7410)))
def _StartLocalRemoteHost(self):
"""Start a remote PyAuto instance on the local machine."""
# Add the path to our main class to the RemoteHost's
# environment, so it can load that class at runtime.
import __main__
main_path = os.path.dirname(__main__.__file__)
env = os.environ
if env.get('PYTHONPATH', None):
env['PYTHONPATH'] += ':' + main_path
else:
env['PYTHONPATH'] = main_path
# Run it!
subprocess.Popen([sys.executable, os.path.join(os.path.dirname(__file__),
'remote_host.py')], env=env)
class _GTestTextTestResult(unittest._TextTestResult):
"""A test result class that can print formatted text results to a stream.
Results printed in conformance with gtest output format, like:
[ RUN ] autofill.AutofillTest.testAutofillInvalid: "test desc."
[ OK ] autofill.AutofillTest.testAutofillInvalid
[ RUN ] autofill.AutofillTest.testFillProfile: "test desc."
[ OK ] autofill.AutofillTest.testFillProfile
[ RUN ] autofill.AutofillTest.testFillProfileCrazyCharacters: "Test."
[ OK ] autofill.AutofillTest.testFillProfileCrazyCharacters
"""
def __init__(self, stream, descriptions, verbosity):
unittest._TextTestResult.__init__(self, stream, descriptions, verbosity)
def _GetTestURI(self, test):
if sys.version_info[:2] <= (2, 4):
return '%s.%s' % (unittest._strclass(test.__class__),
test._TestCase__testMethodName)
return '%s.%s.%s' % (test.__class__.__module__,
test.__class__.__name__,
test._testMethodName)
def getDescription(self, test):
return '%s: "%s"' % (self._GetTestURI(test), test.shortDescription())
def startTest(self, test):
unittest.TestResult.startTest(self, test)
self.stream.writeln('[ RUN ] %s' % self.getDescription(test))
def addSuccess(self, test):
unittest.TestResult.addSuccess(self, test)
self.stream.writeln('[ OK ] %s' % self._GetTestURI(test))
def addError(self, test, err):
unittest.TestResult.addError(self, test, err)
self.stream.writeln('[ ERROR ] %s' % self._GetTestURI(test))
def addFailure(self, test, err):
unittest.TestResult.addFailure(self, test, err)
self.stream.writeln('[ FAILED ] %s' % self._GetTestURI(test))
class PyAutoTextTestRunner(unittest.TextTestRunner):
"""Test Runner for PyAuto tests that displays results in textual format.
Results are displayed in conformance with gtest output.
"""
def __init__(self, verbosity=1):
unittest.TextTestRunner.__init__(self,
stream=sys.stderr,
verbosity=verbosity)
def _makeResult(self):
return _GTestTextTestResult(self.stream, self.descriptions, self.verbosity)
# Implementation inspired from unittest.main()
class Main(object):
"""Main program for running PyAuto tests."""
_options, _args = None, None
_tests_filename = 'PYAUTO_TESTS'
_platform_map = {
'win32': 'win',
'darwin': 'mac',
'linux2': 'linux',
'linux3': 'linux',
'chromeos': 'chromeos',
}
def __init__(self):
self._ParseArgs()
self._Run()
def _ParseArgs(self):
"""Parse command line args."""
parser = optparse.OptionParser()
parser.add_option(
'', '--channel-id', type='string', default='',
help='Name of channel id, if using named interface.')
parser.add_option(
'', '--chrome-flags', type='string', default='',
help='Flags passed to Chrome. This is in addition to the usual flags '
'like suppressing first-run dialogs, enabling automation. '
'See chrome/common/chrome_switches.cc for the list of flags '
'chrome understands.')
parser.add_option(
'', '--http-data-dir', type='string',
default=os.path.join('chrome', 'test', 'data'),
help='Relative path from which http server should serve files.')
parser.add_option(
'-L', '--list-tests', action='store_true', default=False,
help='List all tests, and exit.')
parser.add_option(
'--shard',
help='Specify sharding params. Example: 1/3 implies split the list of '
'tests into 3 groups of which this is the 1st.')
parser.add_option(
'', '--log-file', type='string', default=None,
help='Provide a path to a file to which the logger will log')
parser.add_option(
'', '--no-http-server', action='store_true', default=False,
help='Do not start an http server to serve files in data dir.')
parser.add_option(
'', '--remote-host', type='string', default=None,
help='Connect to remote hosts for remote automation. If "localhost" '
'"127.0.0.1" is specified, a remote host will be launched '
'automatically on the local machine.')
parser.add_option(
'', '--repeat', type='int', default=1,
help='Number of times to repeat the tests. Useful to determine '
'flakiness. Defaults to 1.')
parser.add_option(
'-S', '--suite', type='string', default='FULL',
help='Name of the suite to load. Defaults to "FULL".')
parser.add_option(
'-v', '--verbose', action='store_true', default=False,
help='Make PyAuto verbose.')
parser.add_option(
'-D', '--wait-for-debugger', action='store_true', default=False,
help='Block PyAuto on startup for attaching debugger.')
self._options, self._args = parser.parse_args()
global _OPTIONS
_OPTIONS = self._options # Export options so other classes can access.
# Set up logging. All log messages will be prepended with a timestamp.
format = '%(asctime)s %(levelname)-8s %(message)s'
level = logging.INFO
if self._options.verbose:
level=logging.DEBUG
logging.basicConfig(level=level, format=format,
filename=self._options.log_file)
def TestsDir(self):
"""Returns the path to dir containing tests.
This is typically the dir containing the tests description file.
This method should be overridden by derived class to point to other dirs
if needed.
"""
return os.path.dirname(__file__)
@staticmethod
def _ImportTestsFromName(name):
"""Get a list of all test names from the given string.
Args:
name: dot-separated string for a module, a test case or a test method.
Examples: omnibox (a module)
omnibox.OmniboxTest (a test case)
omnibox.OmniboxTest.testA (a test method)
Returns:
[omnibox.OmniboxTest.testA, omnibox.OmniboxTest.testB, ...]
"""
def _GetTestsFromTestCase(class_obj):
"""Return all test method names from given class object."""
return [class_obj.__name__ + '.' + x for x in dir(class_obj) if
x.startswith('test')]
def _GetTestsFromModule(module):
"""Return all test method names from the given module object."""
tests = []
for name in dir(module):
obj = getattr(module, name)
if (isinstance(obj, (type, types.ClassType)) and
issubclass(obj, PyUITest) and obj != PyUITest):
tests.extend([module.__name__ + '.' + x for x in
_GetTestsFromTestCase(obj)])
return tests
module = None
# Locate the module
parts = name.split('.')
parts_copy = parts[:]
while parts_copy:
try:
module = __import__('.'.join(parts_copy))
break
except ImportError:
del parts_copy[-1]
if not parts_copy: raise
# We have the module. Pick the exact test method or class asked for.
parts = parts[1:]
obj = module
for part in parts:
obj = getattr(obj, part)
if type(obj) == types.ModuleType:
return _GetTestsFromModule(obj)
elif (isinstance(obj, (type, types.ClassType)) and
issubclass(obj, PyUITest) and obj != PyUITest):
return [module.__name__ + '.' + x for x in _GetTestsFromTestCase(obj)]
elif type(obj) == types.UnboundMethodType:
return [name]
else:
logging.warn('No tests in "%s"', name)
return []
def _HasTestCases(self, module_string):
"""Determines if we have any PyUITest test case classes in the module
identified by |module_string|."""
module = __import__(module_string)
for name in dir(module):
obj = getattr(module, name)
if (isinstance(obj, (type, types.ClassType)) and
issubclass(obj, PyUITest)):
return True
return False
def _ExpandTestNames(self, args):
"""Returns a list of tests loaded from the given args.
The given args can be either a module (ex: module1) or a testcase
(ex: module2.MyTestCase) or a test (ex: module1.MyTestCase.testX)
or a suite name (ex: @FULL). If empty, the tests in the already imported
modules are loaded.
Args:
args: [module1, module2, module3.testcase, module4.testcase.testX]
These modules or test cases or tests should be importable.
Suites can be specified by prefixing @. Example: @FULL
Returns:
a list of expanded test names. Example:
[
'module1.TestCase1.testA',
'module1.TestCase1.testB',
'module2.TestCase2.testX',
'module3.testcase.testY',
'module4.testcase.testX'
]
"""
def _TestsFromDescriptionFile(suite):
pyauto_tests_file = os.path.join(self.TestsDir(), self._tests_filename)
if suite:
logging.debug("Reading %s (@%s)", pyauto_tests_file, suite)
else:
logging.debug("Reading %s", pyauto_tests_file)
if not os.path.exists(pyauto_tests_file):
logging.warn("%s missing. Cannot load tests.", pyauto_tests_file)
return []
else:
return self._ExpandTestNamesFrom(pyauto_tests_file, suite)
if not args: # Load tests ourselves
if self._HasTestCases('__main__'): # we are running a test script
module_name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
args.append(module_name) # run the test cases found in it
else: # run tests from the test description file
args = _TestsFromDescriptionFile(self._options.suite)
else: # Check args with @ prefix for suites
out_args = []
for arg in args:
if arg.startswith('@'):
suite = arg[1:]
out_args += _TestsFromDescriptionFile(suite)
else:
out_args.append(arg)
args = out_args
return args
def _ExpandTestNamesFrom(self, filename, suite):
"""Load test names from the given file.
Args:
filename: the file to read the tests from
suite: the name of the suite to load from |filename|.
Returns:
a list of test names
[module.testcase.testX, module.testcase.testY, ..]
"""
suites = PyUITest.EvalDataFrom(filename)
platform = sys.platform
if PyUITest.IsChromeOS(): # check if it's chromeos
platform = 'chromeos'
assert platform in self._platform_map, '%s unsupported' % platform
def _NamesInSuite(suite_name):
logging.debug('Expanding suite %s', suite_name)
platforms = suites.get(suite_name)
names = platforms.get('all', []) + \
platforms.get(self._platform_map[platform], [])
ret = []
# Recursively include suites if any. Suites begin with @.
for name in names:
if name.startswith('@'): # Include another suite
ret.extend(_NamesInSuite(name[1:]))
else:
ret.append(name)
return ret
assert suite in suites, '%s: No such suite in %s' % (suite, filename)
all_names = _NamesInSuite(suite)
args = []
excluded = []
# Find all excluded tests. Excluded tests begin with '-'.
for name in all_names:
if name.startswith('-'): # Exclude
excluded.extend(self._ImportTestsFromName(name[1:]))
else:
args.extend(self._ImportTestsFromName(name))
for name in excluded:
if name in args:
args.remove(name)
else:
logging.warn('Cannot exclude %s. Not included. Ignoring', name)
if excluded:
logging.debug('Excluded %d test(s): %s', len(excluded), excluded)
return args
def _Run(self):
"""Run the tests."""
if self._options.wait_for_debugger:
raw_input('Attach debugger to process %s and hit <enter> ' % os.getpid())
suite_args = [sys.argv[0]]
chrome_flags = self._options.chrome_flags
# Set CHROME_HEADLESS. It enables crash reporter on posix.
os.environ['CHROME_HEADLESS'] = '1'
os.environ['EXTRA_CHROME_FLAGS'] = chrome_flags
test_names = self._ExpandTestNames(self._args)
# Shard, if requested (--shard).
if self._options.shard:
matched = re.match('(\d+)/(\d+)', self._options.shard)
if not matched:
print >>sys.stderr, 'Invalid sharding params: %s' % self._options.shard
sys.exit(1)
shard_index = int(matched.group(1)) - 1
num_shards = int(matched.group(2))
if shard_index < 0 or shard_index >= num_shards:
print >>sys.stderr, 'Invalid sharding params: %s' % self._options.shard
sys.exit(1)
test_names = pyauto_utils.Shard(test_names, shard_index, num_shards)
test_names *= self._options.repeat
logging.debug("Loading %d tests from %s", len(test_names), test_names)
if self._options.list_tests: # List tests and exit
for name in test_names:
print name
sys.exit(0)
pyauto_suite = PyUITestSuite(suite_args)
loaded_tests = unittest.defaultTestLoader.loadTestsFromNames(test_names)
pyauto_suite.addTests(loaded_tests)
verbosity = 1
if self._options.verbose:
verbosity = 2
result = PyAutoTextTestRunner(verbosity=verbosity).run(pyauto_suite)
del loaded_tests # Need to destroy test cases before the suite
del pyauto_suite
successful = result.wasSuccessful()
if not successful:
pyauto_tests_file = os.path.join(self.TestsDir(), self._tests_filename)
print >>sys.stderr, 'Tests can be disabled by editing %s. ' \
'Ref: %s' % (pyauto_tests_file, _PYAUTO_DOC_URL)
sys.exit(not successful)
if __name__ == '__main__':
Main()
|
bsd-3-clause
|
GbalsaC/bitnamiP
|
venv/lib/python2.7/site-packages/rest_framework/tests/test_renderers.py
|
6
|
24350
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from decimal import Decimal
from django.core.cache import cache
from django.db import models
from django.test import TestCase
from django.utils import unittest
from django.utils.translation import ugettext_lazy as _
from rest_framework import status, permissions
from rest_framework.compat import yaml, etree, patterns, url, include, six, StringIO
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.renderers import BaseRenderer, JSONRenderer, YAMLRenderer, \
XMLRenderer, JSONPRenderer, BrowsableAPIRenderer, UnicodeJSONRenderer, UnicodeYAMLRenderer
from rest_framework.parsers import YAMLParser, XMLParser
from rest_framework.settings import api_settings
from rest_framework.test import APIRequestFactory
from collections import MutableMapping
import datetime
import json
import pickle
import re
DUMMYSTATUS = status.HTTP_200_OK
DUMMYCONTENT = 'dummycontent'
RENDERER_A_SERIALIZER = lambda x: ('Renderer A: %s' % x).encode('ascii')
RENDERER_B_SERIALIZER = lambda x: ('Renderer B: %s' % x).encode('ascii')
expected_results = [
((elem for elem in [1, 2, 3]), JSONRenderer, b'[1, 2, 3]') # Generator
]
class DummyTestModel(models.Model):
name = models.CharField(max_length=42, default='')
class BasicRendererTests(TestCase):
def test_expected_results(self):
for value, renderer_cls, expected in expected_results:
output = renderer_cls().render(value)
self.assertEqual(output, expected)
class RendererA(BaseRenderer):
media_type = 'mock/renderera'
format = "formata"
def render(self, data, media_type=None, renderer_context=None):
return RENDERER_A_SERIALIZER(data)
class RendererB(BaseRenderer):
media_type = 'mock/rendererb'
format = "formatb"
def render(self, data, media_type=None, renderer_context=None):
return RENDERER_B_SERIALIZER(data)
class MockView(APIView):
renderer_classes = (RendererA, RendererB)
def get(self, request, **kwargs):
response = Response(DUMMYCONTENT, status=DUMMYSTATUS)
return response
class MockGETView(APIView):
def get(self, request, **kwargs):
return Response({'foo': ['bar', 'baz']})
class MockPOSTView(APIView):
def post(self, request, **kwargs):
return Response({'foo': request.DATA})
class EmptyGETView(APIView):
renderer_classes = (JSONRenderer,)
def get(self, request, **kwargs):
return Response(status=status.HTTP_204_NO_CONTENT)
class HTMLView(APIView):
renderer_classes = (BrowsableAPIRenderer, )
def get(self, request, **kwargs):
return Response('text')
class HTMLView1(APIView):
renderer_classes = (BrowsableAPIRenderer, JSONRenderer)
def get(self, request, **kwargs):
return Response('text')
urlpatterns = patterns('',
url(r'^.*\.(?P<format>.+)$', MockView.as_view(renderer_classes=[RendererA, RendererB])),
url(r'^$', MockView.as_view(renderer_classes=[RendererA, RendererB])),
url(r'^cache$', MockGETView.as_view()),
url(r'^jsonp/jsonrenderer$', MockGETView.as_view(renderer_classes=[JSONRenderer, JSONPRenderer])),
url(r'^jsonp/nojsonrenderer$', MockGETView.as_view(renderer_classes=[JSONPRenderer])),
url(r'^parseerror$', MockPOSTView.as_view(renderer_classes=[JSONRenderer, BrowsableAPIRenderer])),
url(r'^html$', HTMLView.as_view()),
url(r'^html1$', HTMLView1.as_view()),
url(r'^empty$', EmptyGETView.as_view()),
url(r'^api', include('rest_framework.urls', namespace='rest_framework'))
)
class POSTDeniedPermission(permissions.BasePermission):
def has_permission(self, request, view):
return request.method != 'POST'
class POSTDeniedView(APIView):
renderer_classes = (BrowsableAPIRenderer,)
permission_classes = (POSTDeniedPermission,)
def get(self, request):
return Response()
def post(self, request):
return Response()
def put(self, request):
return Response()
def patch(self, request):
return Response()
class DocumentingRendererTests(TestCase):
def test_only_permitted_forms_are_displayed(self):
view = POSTDeniedView.as_view()
request = APIRequestFactory().get('/')
response = view(request).render()
self.assertNotContains(response, '>POST<')
self.assertContains(response, '>PUT<')
self.assertContains(response, '>PATCH<')
class RendererEndToEndTests(TestCase):
"""
End-to-end testing of renderers using an RendererMixin on a generic view.
"""
urls = 'rest_framework.tests.test_renderers'
def test_default_renderer_serializes_content(self):
"""If the Accept header is not set the default renderer should serialize the response."""
resp = self.client.get('/')
self.assertEqual(resp['Content-Type'], RendererA.media_type + '; charset=utf-8')
self.assertEqual(resp.content, RENDERER_A_SERIALIZER(DUMMYCONTENT))
self.assertEqual(resp.status_code, DUMMYSTATUS)
def test_head_method_serializes_no_content(self):
"""No response must be included in HEAD requests."""
resp = self.client.head('/')
self.assertEqual(resp.status_code, DUMMYSTATUS)
self.assertEqual(resp['Content-Type'], RendererA.media_type + '; charset=utf-8')
self.assertEqual(resp.content, six.b(''))
def test_default_renderer_serializes_content_on_accept_any(self):
"""If the Accept header is set to */* the default renderer should serialize the response."""
resp = self.client.get('/', HTTP_ACCEPT='*/*')
self.assertEqual(resp['Content-Type'], RendererA.media_type + '; charset=utf-8')
self.assertEqual(resp.content, RENDERER_A_SERIALIZER(DUMMYCONTENT))
self.assertEqual(resp.status_code, DUMMYSTATUS)
def test_specified_renderer_serializes_content_default_case(self):
"""If the Accept header is set the specified renderer should serialize the response.
(In this case we check that works for the default renderer)"""
resp = self.client.get('/', HTTP_ACCEPT=RendererA.media_type)
self.assertEqual(resp['Content-Type'], RendererA.media_type + '; charset=utf-8')
self.assertEqual(resp.content, RENDERER_A_SERIALIZER(DUMMYCONTENT))
self.assertEqual(resp.status_code, DUMMYSTATUS)
def test_specified_renderer_serializes_content_non_default_case(self):
"""If the Accept header is set the specified renderer should serialize the response.
(In this case we check that works for a non-default renderer)"""
resp = self.client.get('/', HTTP_ACCEPT=RendererB.media_type)
self.assertEqual(resp['Content-Type'], RendererB.media_type + '; charset=utf-8')
self.assertEqual(resp.content, RENDERER_B_SERIALIZER(DUMMYCONTENT))
self.assertEqual(resp.status_code, DUMMYSTATUS)
def test_specified_renderer_serializes_content_on_accept_query(self):
"""The '_accept' query string should behave in the same way as the Accept header."""
param = '?%s=%s' % (
api_settings.URL_ACCEPT_OVERRIDE,
RendererB.media_type
)
resp = self.client.get('/' + param)
self.assertEqual(resp['Content-Type'], RendererB.media_type + '; charset=utf-8')
self.assertEqual(resp.content, RENDERER_B_SERIALIZER(DUMMYCONTENT))
self.assertEqual(resp.status_code, DUMMYSTATUS)
def test_unsatisfiable_accept_header_on_request_returns_406_status(self):
"""If the Accept header is unsatisfiable we should return a 406 Not Acceptable response."""
resp = self.client.get('/', HTTP_ACCEPT='foo/bar')
self.assertEqual(resp.status_code, status.HTTP_406_NOT_ACCEPTABLE)
def test_specified_renderer_serializes_content_on_format_query(self):
"""If a 'format' query is specified, the renderer with the matching
format attribute should serialize the response."""
param = '?%s=%s' % (
api_settings.URL_FORMAT_OVERRIDE,
RendererB.format
)
resp = self.client.get('/' + param)
self.assertEqual(resp['Content-Type'], RendererB.media_type + '; charset=utf-8')
self.assertEqual(resp.content, RENDERER_B_SERIALIZER(DUMMYCONTENT))
self.assertEqual(resp.status_code, DUMMYSTATUS)
def test_specified_renderer_serializes_content_on_format_kwargs(self):
"""If a 'format' keyword arg is specified, the renderer with the matching
format attribute should serialize the response."""
resp = self.client.get('/something.formatb')
self.assertEqual(resp['Content-Type'], RendererB.media_type + '; charset=utf-8')
self.assertEqual(resp.content, RENDERER_B_SERIALIZER(DUMMYCONTENT))
self.assertEqual(resp.status_code, DUMMYSTATUS)
def test_specified_renderer_is_used_on_format_query_with_matching_accept(self):
"""If both a 'format' query and a matching Accept header specified,
the renderer with the matching format attribute should serialize the response."""
param = '?%s=%s' % (
api_settings.URL_FORMAT_OVERRIDE,
RendererB.format
)
resp = self.client.get('/' + param,
HTTP_ACCEPT=RendererB.media_type)
self.assertEqual(resp['Content-Type'], RendererB.media_type + '; charset=utf-8')
self.assertEqual(resp.content, RENDERER_B_SERIALIZER(DUMMYCONTENT))
self.assertEqual(resp.status_code, DUMMYSTATUS)
def test_parse_error_renderers_browsable_api(self):
"""Invalid data should still render the browsable API correctly."""
resp = self.client.post('/parseerror', data='foobar', content_type='application/json', HTTP_ACCEPT='text/html')
self.assertEqual(resp['Content-Type'], 'text/html; charset=utf-8')
self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
def test_204_no_content_responses_have_no_content_type_set(self):
"""
Regression test for #1196
https://github.com/tomchristie/django-rest-framework/issues/1196
"""
resp = self.client.get('/empty')
self.assertEqual(resp.get('Content-Type', None), None)
self.assertEqual(resp.status_code, status.HTTP_204_NO_CONTENT)
def test_contains_headers_of_api_response(self):
"""
Issue #1437
Test we display the headers of the API response and not those from the
HTML response
"""
resp = self.client.get('/html1')
self.assertContains(resp, '>GET, HEAD, OPTIONS<')
self.assertContains(resp, '>application/json<')
self.assertNotContains(resp, '>text/html; charset=utf-8<')
_flat_repr = '{"foo": ["bar", "baz"]}'
_indented_repr = '{\n "foo": [\n "bar",\n "baz"\n ]\n}'
def strip_trailing_whitespace(content):
"""
Seems to be some inconsistencies re. trailing whitespace with
different versions of the json lib.
"""
return re.sub(' +\n', '\n', content)
class JSONRendererTests(TestCase):
"""
Tests specific to the JSON Renderer
"""
def test_render_lazy_strings(self):
"""
JSONRenderer should deal with lazy translated strings.
"""
ret = JSONRenderer().render(_('test'))
self.assertEqual(ret, b'"test"')
def test_render_queryset_values(self):
o = DummyTestModel.objects.create(name='dummy')
qs = DummyTestModel.objects.values('id', 'name')
ret = JSONRenderer().render(qs)
data = json.loads(ret.decode('utf-8'))
self.assertEquals(data, [{'id': o.id, 'name': o.name}])
def test_render_queryset_values_list(self):
o = DummyTestModel.objects.create(name='dummy')
qs = DummyTestModel.objects.values_list('id', 'name')
ret = JSONRenderer().render(qs)
data = json.loads(ret.decode('utf-8'))
self.assertEquals(data, [[o.id, o.name]])
def test_render_dict_abc_obj(self):
class Dict(MutableMapping):
def __init__(self):
self._dict = dict()
def __getitem__(self, key):
return self._dict.__getitem__(key)
def __setitem__(self, key, value):
return self._dict.__setitem__(key, value)
def __delitem__(self, key):
return self._dict.__delitem__(key)
def __iter__(self):
return self._dict.__iter__()
def __len__(self):
return self._dict.__len__()
def keys(self):
return self._dict.keys()
x = Dict()
x['key'] = 'string value'
x[2] = 3
ret = JSONRenderer().render(x)
data = json.loads(ret.decode('utf-8'))
self.assertEquals(data, {'key': 'string value', '2': 3})
def test_render_obj_with_getitem(self):
class DictLike(object):
def __init__(self):
self._dict = {}
def set(self, value):
self._dict = dict(value)
def __getitem__(self, key):
return self._dict[key]
x = DictLike()
x.set({'a': 1, 'b': 'string'})
with self.assertRaises(TypeError):
JSONRenderer().render(x)
def test_without_content_type_args(self):
"""
Test basic JSON rendering.
"""
obj = {'foo': ['bar', 'baz']}
renderer = JSONRenderer()
content = renderer.render(obj, 'application/json')
# Fix failing test case which depends on version of JSON library.
self.assertEqual(content.decode('utf-8'), _flat_repr)
def test_with_content_type_args(self):
"""
Test JSON rendering with additional content type arguments supplied.
"""
obj = {'foo': ['bar', 'baz']}
renderer = JSONRenderer()
content = renderer.render(obj, 'application/json; indent=2')
self.assertEqual(strip_trailing_whitespace(content.decode('utf-8')), _indented_repr)
def test_check_ascii(self):
obj = {'countries': ['United Kingdom', 'France', 'España']}
renderer = JSONRenderer()
content = renderer.render(obj, 'application/json')
self.assertEqual(content, '{"countries": ["United Kingdom", "France", "Espa\\u00f1a"]}'.encode('utf-8'))
class UnicodeJSONRendererTests(TestCase):
"""
Tests specific for the Unicode JSON Renderer
"""
def test_proper_encoding(self):
obj = {'countries': ['United Kingdom', 'France', 'España']}
renderer = UnicodeJSONRenderer()
content = renderer.render(obj, 'application/json')
self.assertEqual(content, '{"countries": ["United Kingdom", "France", "España"]}'.encode('utf-8'))
class JSONPRendererTests(TestCase):
"""
Tests specific to the JSONP Renderer
"""
urls = 'rest_framework.tests.test_renderers'
def test_without_callback_with_json_renderer(self):
"""
Test JSONP rendering with View JSON Renderer.
"""
resp = self.client.get('/jsonp/jsonrenderer',
HTTP_ACCEPT='application/javascript')
self.assertEqual(resp.status_code, status.HTTP_200_OK)
self.assertEqual(resp['Content-Type'], 'application/javascript; charset=utf-8')
self.assertEqual(resp.content,
('callback(%s);' % _flat_repr).encode('ascii'))
def test_without_callback_without_json_renderer(self):
"""
Test JSONP rendering without View JSON Renderer.
"""
resp = self.client.get('/jsonp/nojsonrenderer',
HTTP_ACCEPT='application/javascript')
self.assertEqual(resp.status_code, status.HTTP_200_OK)
self.assertEqual(resp['Content-Type'], 'application/javascript; charset=utf-8')
self.assertEqual(resp.content,
('callback(%s);' % _flat_repr).encode('ascii'))
def test_with_callback(self):
"""
Test JSONP rendering with callback function name.
"""
callback_func = 'myjsonpcallback'
resp = self.client.get('/jsonp/nojsonrenderer?callback=' + callback_func,
HTTP_ACCEPT='application/javascript')
self.assertEqual(resp.status_code, status.HTTP_200_OK)
self.assertEqual(resp['Content-Type'], 'application/javascript; charset=utf-8')
self.assertEqual(resp.content,
('%s(%s);' % (callback_func, _flat_repr)).encode('ascii'))
if yaml:
_yaml_repr = 'foo: [bar, baz]\n'
class YAMLRendererTests(TestCase):
"""
Tests specific to the YAML Renderer
"""
def test_render(self):
"""
Test basic YAML rendering.
"""
obj = {'foo': ['bar', 'baz']}
renderer = YAMLRenderer()
content = renderer.render(obj, 'application/yaml')
self.assertEqual(content, _yaml_repr)
def test_render_and_parse(self):
"""
Test rendering and then parsing returns the original object.
IE obj -> render -> parse -> obj.
"""
obj = {'foo': ['bar', 'baz']}
renderer = YAMLRenderer()
parser = YAMLParser()
content = renderer.render(obj, 'application/yaml')
data = parser.parse(StringIO(content))
self.assertEqual(obj, data)
def test_render_decimal(self):
"""
Test YAML decimal rendering.
"""
renderer = YAMLRenderer()
content = renderer.render({'field': Decimal('111.2')}, 'application/yaml')
self.assertYAMLContains(content, "field: '111.2'")
def assertYAMLContains(self, content, string):
self.assertTrue(string in content, '%r not in %r' % (string, content))
class UnicodeYAMLRendererTests(TestCase):
"""
Tests specific for the Unicode YAML Renderer
"""
def test_proper_encoding(self):
obj = {'countries': ['United Kingdom', 'France', 'España']}
renderer = UnicodeYAMLRenderer()
content = renderer.render(obj, 'application/yaml')
self.assertEqual(content.strip(), 'countries: [United Kingdom, France, España]'.encode('utf-8'))
class XMLRendererTestCase(TestCase):
"""
Tests specific to the XML Renderer
"""
_complex_data = {
"creation_date": datetime.datetime(2011, 12, 25, 12, 45, 00),
"name": "name",
"sub_data_list": [
{
"sub_id": 1,
"sub_name": "first"
},
{
"sub_id": 2,
"sub_name": "second"
}
]
}
def test_render_string(self):
"""
Test XML rendering.
"""
renderer = XMLRenderer()
content = renderer.render({'field': 'astring'}, 'application/xml')
self.assertXMLContains(content, '<field>astring</field>')
def test_render_integer(self):
"""
Test XML rendering.
"""
renderer = XMLRenderer()
content = renderer.render({'field': 111}, 'application/xml')
self.assertXMLContains(content, '<field>111</field>')
def test_render_datetime(self):
"""
Test XML rendering.
"""
renderer = XMLRenderer()
content = renderer.render({
'field': datetime.datetime(2011, 12, 25, 12, 45, 00)
}, 'application/xml')
self.assertXMLContains(content, '<field>2011-12-25 12:45:00</field>')
def test_render_float(self):
"""
Test XML rendering.
"""
renderer = XMLRenderer()
content = renderer.render({'field': 123.4}, 'application/xml')
self.assertXMLContains(content, '<field>123.4</field>')
def test_render_decimal(self):
"""
Test XML rendering.
"""
renderer = XMLRenderer()
content = renderer.render({'field': Decimal('111.2')}, 'application/xml')
self.assertXMLContains(content, '<field>111.2</field>')
def test_render_none(self):
"""
Test XML rendering.
"""
renderer = XMLRenderer()
content = renderer.render({'field': None}, 'application/xml')
self.assertXMLContains(content, '<field></field>')
def test_render_complex_data(self):
"""
Test XML rendering.
"""
renderer = XMLRenderer()
content = renderer.render(self._complex_data, 'application/xml')
self.assertXMLContains(content, '<sub_name>first</sub_name>')
self.assertXMLContains(content, '<sub_name>second</sub_name>')
@unittest.skipUnless(etree, 'defusedxml not installed')
def test_render_and_parse_complex_data(self):
"""
Test XML rendering.
"""
renderer = XMLRenderer()
content = StringIO(renderer.render(self._complex_data, 'application/xml'))
parser = XMLParser()
complex_data_out = parser.parse(content)
error_msg = "complex data differs!IN:\n %s \n\n OUT:\n %s" % (repr(self._complex_data), repr(complex_data_out))
self.assertEqual(self._complex_data, complex_data_out, error_msg)
def assertXMLContains(self, xml, string):
self.assertTrue(xml.startswith('<?xml version="1.0" encoding="utf-8"?>\n<root>'))
self.assertTrue(xml.endswith('</root>'))
self.assertTrue(string in xml, '%r not in %r' % (string, xml))
# Tests for caching issue, #346
class CacheRenderTest(TestCase):
"""
Tests specific to caching responses
"""
urls = 'rest_framework.tests.test_renderers'
cache_key = 'just_a_cache_key'
@classmethod
def _get_pickling_errors(cls, obj, seen=None):
""" Return any errors that would be raised if `obj' is pickled
Courtesy of koffie @ http://stackoverflow.com/a/7218986/109897
"""
if seen == None:
seen = []
try:
state = obj.__getstate__()
except AttributeError:
return
if state == None:
return
if isinstance(state, tuple):
if not isinstance(state[0], dict):
state = state[1]
else:
state = state[0].update(state[1])
result = {}
for i in state:
try:
pickle.dumps(state[i], protocol=2)
except pickle.PicklingError:
if not state[i] in seen:
seen.append(state[i])
result[i] = cls._get_pickling_errors(state[i], seen)
return result
def http_resp(self, http_method, url):
"""
Simple wrapper for Client http requests
Removes the `client' and `request' attributes from as they are
added by django.test.client.Client and not part of caching
responses outside of tests.
"""
method = getattr(self.client, http_method)
resp = method(url)
del resp.client, resp.request
try:
del resp.wsgi_request
except AttributeError:
pass
return resp
def test_obj_pickling(self):
"""
Test that responses are properly pickled
"""
resp = self.http_resp('get', '/cache')
# Make sure that no pickling errors occurred
self.assertEqual(self._get_pickling_errors(resp), {})
# Unfortunately LocMem backend doesn't raise PickleErrors but returns
# None instead.
cache.set(self.cache_key, resp)
self.assertTrue(cache.get(self.cache_key) is not None)
def test_head_caching(self):
"""
Test caching of HEAD requests
"""
resp = self.http_resp('head', '/cache')
cache.set(self.cache_key, resp)
cached_resp = cache.get(self.cache_key)
self.assertIsInstance(cached_resp, Response)
def test_get_caching(self):
"""
Test caching of GET requests
"""
resp = self.http_resp('get', '/cache')
cache.set(self.cache_key, resp)
cached_resp = cache.get(self.cache_key)
self.assertIsInstance(cached_resp, Response)
self.assertEqual(cached_resp.content, resp.content)
|
agpl-3.0
|
HackBulgaria/Odin
|
courses/views.py
|
1
|
4037
|
from datetime import date
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.http import HttpResponseForbidden, JsonResponse
from django.shortcuts import render, get_object_or_404
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from statistics.helpers import division_or_zero
from students.models import CourseAssignment, User, Solution
from .models import Course, Partner, Certificate, Task
def show_course(request, course_url):
course = get_object_or_404(Course, url=course_url)
enable_applications = date.today() <= course.application_until
return render(request, 'show_course.html', locals())
def show_all_courses(request):
date_today = date.today()
active_courses = Course.objects.filter(Q(start_time__lte=date_today, end_time__gt=date_today) | Q(end_time=None)).exclude(start_time=None)
upcoming_courses = Course.objects.filter(Q(start_time__gt=date_today) | Q(start_time=None))
ended_courses = Course.objects.filter(end_time__lte=date_today).exclude(start_time=None)
return render(request, 'show_all_courses.html', locals())
def show_all_partners(request):
partners = Partner.objects.filter(is_active=True)
return render(request, 'show_all_partners.html', locals())
@login_required
def show_course_students(request, course_url):
current_user = request.user
course = get_object_or_404(Course, url=course_url)
assignments = CourseAssignment.objects.only('id', 'user', 'course').filter(
course=course,
user__status=User.STUDENT
).select_related('user', 'certificate').prefetch_related('usernote_set', 'usernote_set__author').order_by('-is_attending', 'is_online')
is_teacher_or_hr = current_user.is_hr() or current_user.is_teacher()
if current_user.hr_of:
interested_in_me = CourseAssignment.objects.filter(
course=course,
favourite_partners=current_user.hr_of,
user__status=User.STUDENT
)
assignments = sorted(assignments, key = lambda x: (not x.is_attending, not x in interested_in_me))
return render(request, 'show_course_students.html', locals())
def show_certificate(request, assignment_id):
certificate = get_object_or_404(Certificate, assignment=assignment_id)
assignment = certificate.assignment
user = assignment.user
course = assignment.course
tasks = Task.objects.filter(course=course)
solutions = Solution.objects.filter(task__in=tasks, user=user)
website_url = "https://" + settings.DOMAIN
solutions_by_task = {}
for solution in solutions:
solutions_by_task[solution.task.id] = solution
for task in tasks:
if task.id in solutions_by_task:
task.solution = solutions_by_task[task.id]
percent = round(division_or_zero(solutions.count(), tasks.count()) * 100, 2)
return render(request, 'show_certificate.html', locals())
@login_required
def show_submitted_solutions(request, course_url):
current_user = request.user
if not current_user.is_teacher():
return HttpResponseForbidden()
course = get_object_or_404(Course, url=course_url)
tasks = Task.objects.filter(course=course).select_related('solution').order_by('name')
weeks = sorted(set(map(lambda task: task.week, tasks)))
solutions = Solution.objects.filter(task__in=tasks).select_related('task')
solutions_by_task = {}
for solution in solutions:
solutions_by_task[solution.task] = solution
for task in tasks:
if task in solutions_by_task:
task.solution = solutions_by_task[task]
return render(request, 'show_submitted_solutions.html', locals())
@csrf_exempt
@require_http_methods(['POST'])
def get_course_video(request):
course_id = request.POST['id']
course = get_object_or_404(Course, id=course_id)
needed_data = {"course_video": course.video}
return JsonResponse(needed_data)
|
agpl-3.0
|
douban/pygit2
|
pygit2/settings.py
|
3
|
2226
|
# -*- coding: utf-8 -*-
#
# Copyright 2010-2014 The pygit2 contributors
#
# This file is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2,
# as published by the Free Software Foundation.
#
# In addition to the permissions in the GNU General Public License,
# the authors give you unlimited permission to link the compiled
# version of this file into combinations with other programs,
# and to distribute those combinations without any restriction
# coming from the use of this file. (The General Public License
# restrictions do apply in other respects; for example, they cover
# modification of the file, and distribution when not linked into
# a combined executable.)
#
# This file 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; see the file COPYING. If not, write to
# the Free Software Foundation, 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301, USA.
from _pygit2 import option
from _pygit2 import GIT_OPT_GET_SEARCH_PATH, GIT_OPT_SET_SEARCH_PATH
from _pygit2 import GIT_OPT_GET_MWINDOW_SIZE, GIT_OPT_SET_MWINDOW_SIZE
class SearchPathList(object):
def __getitem__(self, key):
return option(GIT_OPT_GET_SEARCH_PATH, key)
def __setitem__(self, key, value):
option(GIT_OPT_SET_SEARCH_PATH, key, value)
class Settings(object):
"""Library-wide settings"""
__slots__ = []
_search_path = SearchPathList()
@property
def search_path(self):
"""Configuration file search path.
This behaves like an array whose indices correspond to the
GIT_CONFIG_LEVEL_* values. The local search path cannot be
changed.
"""
return self._search_path
@property
def mwindow_size(self):
"""Maximum mmap window size"""
return option(GIT_OPT_GET_MWINDOW_SIZE)
@mwindow_size.setter
def mwindow_size(self, value):
option(GIT_OPT_SET_MWINDOW_SIZE, value)
|
gpl-2.0
|
midnighteuler/BioBayesGraph
|
BioBayesGraph/examples/sifter/test_sifter_deaminase.py
|
1
|
7202
|
"""
Created on Jul 1, 2012
@author: msouza
"""
import unittest
import os
import sys
import sifter
import FunctionModels.Sifter2
from pprint import pprint
class Test_Sifter_Deaminase(unittest.TestCase):
"""
Tests SIFTER inference and leave one out on a toy family.
"""
def setUp(self):
"""
"""
self.sifter_inst = sifter.SIFTER()
self.t_path = os.path.dirname(os.path.realpath(__file__))
def tearDown(self):
"""
"""
def testSifter(self):
"""
"""
# Create Phylogenetic graphical model scaffold from phylogeny
stderr = sys.stderr
print >>stderr,"Loading Phylogeny"
self.sifter_inst.load_phylogeny(\
phylo_file = self.t_path + '/deaminase/deaminase.xml',
phylo_format = 'phyloxml')
# Evidence handling:
# Create GO annotation evidence processor
print >>stderr,"Loading evidence processing structure"
precomputed_go_graph = self.t_path + '/go_mf.bbg'
go_oboxml_file = self.t_path + '/go_daily-termdb.obo-xml.gz'
# Loads GO ontology from the GO OBO XML daily snapshot
# and stores to fast-loading biobayesgraph form
if not(os.path.exists(precomputed_go_graph)):
self.sifter_inst.load_evidence_processor(\
evidence_type='GO',
evidence_processor_class=FunctionModels.Sifter2.EvidenceProcessor,
processor_settings={'go_file':go_oboxml_file,
'go_format':'oboxml'})
self.sifter_inst.evidence_processors['GO'].export_as_graphml(precomputed_go_graph)
# Otherwise load precomputed BioBayesGraph object.
else:
self.sifter_inst.load_evidence_processor(\
evidence_type='GO',
evidence_processor_class=FunctionModels.Sifter2.EvidenceProcessor,
processor_settings={'go_file':precomputed_go_graph,
'go_format':'biobayesgraph'})
# Parse and then process evidence from a "pli" file:
print >>stderr,"Loading evidence"
evidence_file = self.t_path + '/deaminase/deaminase.pli'
evidence_constraints = {
# Experimental
'EXP': 0.9, # Experiment
'IDA': 0.9, # Direct Assay
'IPI': 0.8, # Physical Interaction
'IMP': 0.8, # Mutant Phenotype
'IGI': 0.8, # Genetic Interaction
'IEP': 0.4, # Expression Pattern
# Author Statements
'TAS': 0.9, # Traceable Author Statement
'NAS': -1.0, # Non-traceable Author Statement
# Computational Analysis Evidence Codes
'ISS': -1.0, # Sequence/Structural Similarity
'ISO': -1.0, # Sequence Orthology
'ISA': -1.0, # Sequence Alignment
'ISM': -1.0, # Sequence Model
'IGC': -1.0, # Genomic Context
'IBA': -1.0, # Biological aspect of ancestor
'IBD': -1.0, # Biological aspect of descendant
'IKR': -1.0, # Key Residues
'IRD': -1.0, # Rapid Divergence
'RCA': -1.0, # Reviews Computational Analysis
# Curator Statement
'IC' : -1.0, # Curator
'ND' : -1.0, # No biological data available
# Automatically assigned
'IEA': -1.0, # Electronic Annotation
# Obsolete
'NR' : -1.0, # Not recorded
# Mystery stuff Barbara included:
'P' : -1.0, # No clue what this is.
'GOR': -1.0, # "From reading papers"
'E' : -1.0 # No clue what this is.
}
go_ev_set = self.sifter_inst.parse_evidence(\
evidence_type='GO',
evidence_file=evidence_file,
evidence_constraints=evidence_constraints,
evidence_format='pli')
# SIFTER 2.0 style propagated evidence
processed_ev = self.sifter_inst.process_evidence(\
evidence_type='GO',
evidence_set=go_ev_set,
evidence_constraints=evidence_constraints)
# Store to be provided to likelihood function.
self.sifter_inst.phylo_graph.set_evidence_auxiliary_info(auxiliary_info=processed_ev)
print >>stderr,"Creating graphical model"
# Node setup
# Gives all nodes the same distribution function
num_fcns = len(processed_ev[processed_ev.keys()[0]].keys())
node_to_fcn_model_map = \
lambda v: { \
'auxiliary_info':{'num_functions':num_fcns,
'max_num_simul':2},
'prob_dist_class':FunctionModels.Sifter2.FunctionModel
}
print >>stderr,"Number of candidate functions:", num_fcns
print >>stderr,"Setting up node probability distributions..."
self.sifter_inst.setup_nodes(node_to_fcn_model_map=node_to_fcn_model_map)
# Now for each protein, add the virtual evidence for inference.
for p_name,aux_info in processed_ev.iteritems():
self.sifter_inst.phylo_graph.add_virtual_evidence(\
node_index=self.sifter_inst.phylo_graph.get_node_by_name(p_name),
observed_value=[1 for v in range(num_fcns)],
auxiliary_info=aux_info # info provided to likelihood function
)
print >>stderr,"Running inference for leave-one-out test"
# Test single node inference
query_nodes = [self.sifter_inst.phylo_graph.get_node_by_name( \
processed_ev.iterkeys().next())]
#q_results = self.sifter_inst.phylo_graph.inference_query(query_nodes=query_nodes)
q_results = self.sifter_inst.phylo_graph.inference_query_leave_one_out()
def marginalized_over_go_terms(loo_results):
for qn, left_out_results in q_results.iteritems():
left_out = [(k,v) for k,v in left_out_results['left_out']['auxiliary_info'].iteritems()]
res = [0 for i in range(len(left_out_results['left_out']['auxiliary_info']))]
for v, mar in left_out_results['marginals']:
res = map(sum, zip(res, [mar*i for i in v[0]]))
predictions = zip(left_out_results['left_out']['auxiliary_info'].iterkeys(), res)
yield qn, left_out, predictions
# Perform some computation on the results
for qn, left_out, predictions in marginalized_over_go_terms(q_results):
print "For node", self.sifter_inst.phylo_graph.get_name_by_node(qn)
for i in range(len(left_out)):
print predictions[i][0], left_out[i][0], (predictions[i][1], left_out[i][1])
raise Exception, "Manually inspect results."
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
|
gpl-3.0
|
wallrj/kubernetes
|
hack/boilerplate/boilerplate.py
|
300
|
6214
|
#!/usr/bin/env python
# Copyright 2015 The Kubernetes Authors.
#
# 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 print_function
import argparse
import difflib
import glob
import json
import mmap
import os
import re
import sys
parser = argparse.ArgumentParser()
parser.add_argument(
"filenames",
help="list of files to check, all files if unspecified",
nargs='*')
rootdir = os.path.dirname(__file__) + "/../../"
rootdir = os.path.abspath(rootdir)
parser.add_argument(
"--rootdir", default=rootdir, help="root directory to examine")
default_boilerplate_dir = os.path.join(rootdir, "hack/boilerplate")
parser.add_argument(
"--boilerplate-dir", default=default_boilerplate_dir)
parser.add_argument(
"-v", "--verbose",
help="give verbose output regarding why a file does not pass",
action="store_true")
args = parser.parse_args()
verbose_out = sys.stderr if args.verbose else open("/dev/null", "w")
def get_refs():
refs = {}
for path in glob.glob(os.path.join(args.boilerplate_dir, "boilerplate.*.txt")):
extension = os.path.basename(path).split(".")[1]
ref_file = open(path, 'r')
ref = ref_file.read().splitlines()
ref_file.close()
refs[extension] = ref
return refs
def file_passes(filename, refs, regexs):
try:
f = open(filename, 'r')
except Exception as exc:
print("Unable to open %s: %s" % (filename, exc), file=verbose_out)
return False
data = f.read()
f.close()
basename = os.path.basename(filename)
extension = file_extension(filename)
if extension != "":
ref = refs[extension]
else:
ref = refs[basename]
# remove build tags from the top of Go files
if extension == "go":
p = regexs["go_build_constraints"]
(data, found) = p.subn("", data, 1)
# remove shebang from the top of shell files
if extension == "sh":
p = regexs["shebang"]
(data, found) = p.subn("", data, 1)
data = data.splitlines()
# if our test file is smaller than the reference it surely fails!
if len(ref) > len(data):
print('File %s smaller than reference (%d < %d)' %
(filename, len(data), len(ref)),
file=verbose_out)
return False
# trim our file to the same number of lines as the reference file
data = data[:len(ref)]
p = regexs["year"]
for d in data:
if p.search(d):
print('File %s is missing the year' % filename, file=verbose_out)
return False
# Replace all occurrences of the regex "2017|2016|2015|2014" with "YEAR"
p = regexs["date"]
for i, d in enumerate(data):
(data[i], found) = p.subn('YEAR', d)
if found != 0:
break
# if we don't match the reference at this point, fail
if ref != data:
print("Header in %s does not match reference, diff:" % filename, file=verbose_out)
if args.verbose:
print(file=verbose_out)
for line in difflib.unified_diff(ref, data, 'reference', filename, lineterm=''):
print(line, file=verbose_out)
print(file=verbose_out)
return False
return True
def file_extension(filename):
return os.path.splitext(filename)[1].split(".")[-1].lower()
skipped_dirs = ['Godeps', 'third_party', '_gopath', '_output', '.git', 'cluster/env.sh',
"vendor", "test/e2e/generated/bindata.go", "hack/boilerplate/test",
"pkg/generated/bindata.go"]
def normalize_files(files):
newfiles = []
for pathname in files:
if any(x in pathname for x in skipped_dirs):
continue
newfiles.append(pathname)
for i, pathname in enumerate(newfiles):
if not os.path.isabs(pathname):
newfiles[i] = os.path.join(args.rootdir, pathname)
return newfiles
def get_files(extensions):
files = []
if len(args.filenames) > 0:
files = args.filenames
else:
for root, dirs, walkfiles in os.walk(args.rootdir):
# don't visit certain dirs. This is just a performance improvement
# as we would prune these later in normalize_files(). But doing it
# cuts down the amount of filesystem walking we do and cuts down
# the size of the file list
for d in skipped_dirs:
if d in dirs:
dirs.remove(d)
for name in walkfiles:
pathname = os.path.join(root, name)
files.append(pathname)
files = normalize_files(files)
outfiles = []
for pathname in files:
basename = os.path.basename(pathname)
extension = file_extension(pathname)
if extension in extensions or basename in extensions:
outfiles.append(pathname)
return outfiles
def get_regexs():
regexs = {}
# Search for "YEAR" which exists in the boilerplate, but shouldn't in the real thing
regexs["year"] = re.compile( 'YEAR' )
# dates can be 2014, 2015, 2016, or 2017; company holder names can be anything
regexs["date"] = re.compile( '(2014|2015|2016|2017)' )
# strip // +build \n\n build constraints
regexs["go_build_constraints"] = re.compile(r"^(// \+build.*\n)+\n", re.MULTILINE)
# strip #!.* from shell scripts
regexs["shebang"] = re.compile(r"^(#!.*\n)\n*", re.MULTILINE)
return regexs
def main():
regexs = get_regexs()
refs = get_refs()
filenames = get_files(refs.keys())
for filename in filenames:
if not file_passes(filename, refs, regexs):
print(filename, file=sys.stdout)
return 0
if __name__ == "__main__":
sys.exit(main())
|
apache-2.0
|
simonsdave/cloudfeaster-services
|
cloudfeaster_services/main.py
|
2
|
9992
|
"""This module contains an extensible mainline that's used
by all Cloudfeaster services.
"""
import logging
import optparse
import signal
import sys
import time
import tor_async_util
import tornado.httpclient
import tornado.httpserver
import tornado.web
from cloudfeaster_services import __version__
from config import Config
_logger = logging.getLogger(__name__)
class _CommandLineParser(optparse.OptionParser):
"""Used to parse a service's command line arguments."""
def __init__(self, description):
optparse.OptionParser.__init__(
self,
'usage: %prog [options]',
description=description)
default = '~/.clf/config'
help = 'config - default = %s' % default
self.add_option(
'--config',
action='store',
dest='config',
default=default,
type='string',
help=help)
class Main(object):
"""This class implements a standard mainline for all Cloudfeaster
services. Best way to understand how this class and the Config class
are expected to be used would be to look at the config and main
classes for an existing service.
"""
"""See _sigterm_handler() and process_targetted_for_termination()."""
_process_targetted_for_termination = False
@classmethod
def description(cls):
"""Derived classes are expected to override this method.
See this class' description for how this method is intended
to be used.
"""
return ''
@classmethod
def config_class(cls):
"""Derived classes are expected to override this method.
See this class' description for how this method is intended
to be used.
"""
return Config
@classmethod
def api_version(cls):
"""Derived classes are expected to override this method.
See this class' description for how this method is intended
to be used.
"""
return 'v1.0'
@classmethod
def handler_classes(cls):
"""Derived classes are expected to override this method.
See this class' description for how this method is intended
to be used.
"""
return []
@classmethod
def _sigint_handler(cls, signal_number, frame):
"""SIGINT generated when process is running on a developer's
desktop and CTRL+C is pressed. This is really here just only
to avoid a nasty stack trace which is the default handling
of SIGINT.
"""
assert signal_number == signal.SIGINT
_logger.info('Shutting down ...')
sys.exit(0)
@classmethod
def _sigterm_handler(cls, signal_number, frame):
"""SIGTERM generated by Kubernetes as an indication to the
process that the pod termination process has started.
"""
assert signal_number == signal.SIGTERM
_logger.info('Got SIGTERM - ignoring ...')
cls._process_targetted_for_termination = True
@classmethod
def run(cls):
"""Derived classes are expected to override this method.
See this class' description for how this method is intended
to be used.
"""
main = cls()
main.configure()
# in usual operation listen() does not return. during unit
# testing mocking the tornado IO loop may cause listen()
# to return.
main.listen()
# returning main is only done because it's super useful
# for unit testing
return main
@property
def config(self):
"""Motivated by desire to make code easier to read.
Allows mainline code to write code like
```self.config.something``` rather than
```tor_async_util.Config.instance.something```.
"""
return tor_async_util.Config.instance
@property
def process_targetted_for_termination(self):
"""Returns ```False``` until the process gets a SIGTERM
after which returns ```True``` indicating that Kubernetes
has determined that the process will be terminated and
the process should start preparing to exit.
"""
return type(self)._process_targetted_for_termination
def __init__(self, *args, **kwargs):
object.__init__(self, *args, **kwargs)
# app is a property mostly so that app.add_handlers() can be
# called in derived classes
self.app = None
def configure(self):
"""Perform all mainline configuration actions. configure() and
listen() are distinct methods to allow derived classes to be
created configure() be overridden to perform additional
configuration.
See this class' description for an example of how this method is
intended to be used.
"""
#
# parse command line args
#
clp = _CommandLineParser(type(self).description)
(clo, cla) = clp.parse_args()
#
# configure config:-)
#
tor_async_util.Config.instance = type(self).config_class()(clo.config)
#
# configure logging
#
logging.Formatter.converter = time.gmtime # remember gmt = utc
logging.basicConfig(
level=self.config.logging_level,
datefmt='%Y-%m-%dT%H:%M:%S',
format='%(asctime)s.%(msecs)03d+00:00 %(levelname)s %(module)s %(message)s')
#
# configure process' handling of signals which is critically
# important when considering "Termination of Pods" in Kubernetes.
# See https://kubernetes.io/docs/concepts/workloads/pods/pod/#termination-of-pods
# for additional details.
#
signal.signal(signal.SIGINT, type(self)._sigint_handler)
signal.signal(signal.SIGTERM, type(self)._sigterm_handler)
#
# configure tornado ...
#
async_http_client = 'tornado.curl_httpclient.CurlAsyncHTTPClient'
tornado.httpclient.AsyncHTTPClient.configure(
async_http_client,
max_clients=self.config.max_concurrent_executing_http_requests)
if not tor_async_util.is_libcurl_compiled_with_async_dns_resolver():
msg = (
'libcurl does not appear to have been '
'compiled with async dns resolve which '
'may result in timeouts on async requests'
)
_logger.warning(msg)
handlers = [(handler_class.url_spec, handler_class) for handler_class in type(self).handler_classes()]
settings = {
'default_handler_class': tor_async_util.DefaultRequestHandler,
}
self.app = tornado.web.Application(handlers=handlers, **settings)
def listen(self):
"""Start Tornado listening for inbound requests.
See this class' description for an example of how this method is
intended to be used.
"""
#
# log a startup message - note this is done before
# starting the http listener in case the listener
# throws an exception on startup in which case it
# can be very useful for debugging the exception
# to have this basic info available
#
fmt = (
'({package_version}/{api_version}) '
'read config from \'{config_file}[{config_section}]\' '
'and now listening on http://{address}:{port:d} '
'with logging level set to {logging_level}'
)
args = {
'package_version': __version__,
'api_version': type(self).api_version(),
'config_file': self.config.config_file,
'config_section': self.config.config_section,
'address': self.config.address,
'port': self.config.port,
'logging_level': logging.getLevelName(logging.getLogger().getEffectiveLevel()),
}
_logger.info(fmt.format(**args))
#
# start listening for and processing requests ...
#
http_server = tornado.httpserver.HTTPServer(self.app, xheaders=True)
http_server.listen(
self.config.port,
address=self.config.address)
mainloop = tornado.ioloop.IOLoop.instance()
mainloop.start()
def add_handlers(self, handler_classes):
"""A common pattern in services services is to override
listen() to perform some initialization task. For example,
a service may need to acquire a google cloud authorization
token so that request handlers can use the token when
servicing inbound requests. In this example, the request
handler should be available only after the token has
been acquired and hence the motivation for this method.
The example code below should help drive home the point.
def listen(self, *args, **kwargs):
self._generate_pubsub_access_token()
# this call to 'listen()' doesn't return
main.Main.listen(self, *args, **kwargs)
def _generate_pubsub_access_token(self):
credentials = self.config.google_cloud_pubsub_service_account_credentials
async_action = tor_async_google_pubsub.AsyncGeneratePubSubAccessToken(credentials)
async_action.generate(self._on_pubsub_access_token_generate_done)
def _on_pubsub_access_token_generate_done(self, access_token, _):
self.config.google_cloud_pubsub_access_token = access_token
self._finalize_handler_config()
def _finalize_handler_config(self):
handlers = [
request_handlers.CrawlsCollectionRequestHandler,
]
self.add_handlers(handlers)
"""
handlers = [(handler_class.url_spec, handler_class) for handler_class in handler_classes]
host_pattern = r'.*'
self.app.add_handlers(host_pattern, handlers)
|
mit
|
loli10K/linux-hardkernel
|
scripts/analyze_suspend.py
|
1537
|
120394
|
#!/usr/bin/python
#
# Tool for analyzing suspend/resume timing
# Copyright (c) 2013, Intel Corporation.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms and conditions of the GNU General Public License,
# version 2, as published by the Free Software Foundation.
#
# This program is distributed in the hope 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.
#
# Authors:
# Todd Brandt <[email protected]>
#
# Description:
# This tool is designed to assist kernel and OS developers in optimizing
# their linux stack's suspend/resume time. Using a kernel image built
# with a few extra options enabled, the tool will execute a suspend and
# will capture dmesg and ftrace data until resume is complete. This data
# is transformed into a device timeline and a callgraph to give a quick
# and detailed view of which devices and callbacks are taking the most
# time in suspend/resume. The output is a single html file which can be
# viewed in firefox or chrome.
#
# The following kernel build options are required:
# CONFIG_PM_DEBUG=y
# CONFIG_PM_SLEEP_DEBUG=y
# CONFIG_FTRACE=y
# CONFIG_FUNCTION_TRACER=y
# CONFIG_FUNCTION_GRAPH_TRACER=y
#
# For kernel versions older than 3.15:
# The following additional kernel parameters are required:
# (e.g. in file /etc/default/grub)
# GRUB_CMDLINE_LINUX_DEFAULT="... initcall_debug log_buf_len=16M ..."
#
# ----------------- LIBRARIES --------------------
import sys
import time
import os
import string
import re
import platform
from datetime import datetime
import struct
# ----------------- CLASSES --------------------
# Class: SystemValues
# Description:
# A global, single-instance container used to
# store system values and test parameters
class SystemValues:
version = 3.0
verbose = False
testdir = '.'
tpath = '/sys/kernel/debug/tracing/'
fpdtpath = '/sys/firmware/acpi/tables/FPDT'
epath = '/sys/kernel/debug/tracing/events/power/'
traceevents = [
'suspend_resume',
'device_pm_callback_end',
'device_pm_callback_start'
]
modename = {
'freeze': 'Suspend-To-Idle (S0)',
'standby': 'Power-On Suspend (S1)',
'mem': 'Suspend-to-RAM (S3)',
'disk': 'Suspend-to-disk (S4)'
}
mempath = '/dev/mem'
powerfile = '/sys/power/state'
suspendmode = 'mem'
hostname = 'localhost'
prefix = 'test'
teststamp = ''
dmesgfile = ''
ftracefile = ''
htmlfile = ''
rtcwake = False
rtcwaketime = 10
rtcpath = ''
android = False
adb = 'adb'
devicefilter = []
stamp = 0
execcount = 1
x2delay = 0
usecallgraph = False
usetraceevents = False
usetraceeventsonly = False
notestrun = False
altdevname = dict()
postresumetime = 0
tracertypefmt = '# tracer: (?P<t>.*)'
firmwarefmt = '# fwsuspend (?P<s>[0-9]*) fwresume (?P<r>[0-9]*)$'
postresumefmt = '# post resume time (?P<t>[0-9]*)$'
stampfmt = '# suspend-(?P<m>[0-9]{2})(?P<d>[0-9]{2})(?P<y>[0-9]{2})-'+\
'(?P<H>[0-9]{2})(?P<M>[0-9]{2})(?P<S>[0-9]{2})'+\
' (?P<host>.*) (?P<mode>.*) (?P<kernel>.*)$'
def __init__(self):
self.hostname = platform.node()
if(self.hostname == ''):
self.hostname = 'localhost'
rtc = "rtc0"
if os.path.exists('/dev/rtc'):
rtc = os.readlink('/dev/rtc')
rtc = '/sys/class/rtc/'+rtc
if os.path.exists(rtc) and os.path.exists(rtc+'/date') and \
os.path.exists(rtc+'/time') and os.path.exists(rtc+'/wakealarm'):
self.rtcpath = rtc
def setOutputFile(self):
if((self.htmlfile == '') and (self.dmesgfile != '')):
m = re.match('(?P<name>.*)_dmesg\.txt$', self.dmesgfile)
if(m):
self.htmlfile = m.group('name')+'.html'
if((self.htmlfile == '') and (self.ftracefile != '')):
m = re.match('(?P<name>.*)_ftrace\.txt$', self.ftracefile)
if(m):
self.htmlfile = m.group('name')+'.html'
if(self.htmlfile == ''):
self.htmlfile = 'output.html'
def initTestOutput(self, subdir):
if(not self.android):
self.prefix = self.hostname
v = open('/proc/version', 'r').read().strip()
kver = string.split(v)[2]
else:
self.prefix = 'android'
v = os.popen(self.adb+' shell cat /proc/version').read().strip()
kver = string.split(v)[2]
testtime = datetime.now().strftime('suspend-%m%d%y-%H%M%S')
if(subdir != "."):
self.testdir = subdir+"/"+testtime
else:
self.testdir = testtime
self.teststamp = \
'# '+testtime+' '+self.prefix+' '+self.suspendmode+' '+kver
self.dmesgfile = \
self.testdir+'/'+self.prefix+'_'+self.suspendmode+'_dmesg.txt'
self.ftracefile = \
self.testdir+'/'+self.prefix+'_'+self.suspendmode+'_ftrace.txt'
self.htmlfile = \
self.testdir+'/'+self.prefix+'_'+self.suspendmode+'.html'
os.mkdir(self.testdir)
def setDeviceFilter(self, devnames):
self.devicefilter = string.split(devnames)
def rtcWakeAlarm(self):
os.system('echo 0 > '+self.rtcpath+'/wakealarm')
outD = open(self.rtcpath+'/date', 'r').read().strip()
outT = open(self.rtcpath+'/time', 'r').read().strip()
mD = re.match('^(?P<y>[0-9]*)-(?P<m>[0-9]*)-(?P<d>[0-9]*)', outD)
mT = re.match('^(?P<h>[0-9]*):(?P<m>[0-9]*):(?P<s>[0-9]*)', outT)
if(mD and mT):
# get the current time from hardware
utcoffset = int((datetime.now() - datetime.utcnow()).total_seconds())
dt = datetime(\
int(mD.group('y')), int(mD.group('m')), int(mD.group('d')),
int(mT.group('h')), int(mT.group('m')), int(mT.group('s')))
nowtime = int(dt.strftime('%s')) + utcoffset
else:
# if hardware time fails, use the software time
nowtime = int(datetime.now().strftime('%s'))
alarm = nowtime + self.rtcwaketime
os.system('echo %d > %s/wakealarm' % (alarm, self.rtcpath))
sysvals = SystemValues()
# Class: DeviceNode
# Description:
# A container used to create a device hierachy, with a single root node
# and a tree of child nodes. Used by Data.deviceTopology()
class DeviceNode:
name = ''
children = 0
depth = 0
def __init__(self, nodename, nodedepth):
self.name = nodename
self.children = []
self.depth = nodedepth
# Class: Data
# Description:
# The primary container for suspend/resume test data. There is one for
# each test run. The data is organized into a cronological hierarchy:
# Data.dmesg {
# root structure, started as dmesg & ftrace, but now only ftrace
# contents: times for suspend start/end, resume start/end, fwdata
# phases {
# 10 sequential, non-overlapping phases of S/R
# contents: times for phase start/end, order/color data for html
# devlist {
# device callback or action list for this phase
# device {
# a single device callback or generic action
# contents: start/stop times, pid/cpu/driver info
# parents/children, html id for timeline/callgraph
# optionally includes an ftrace callgraph
# optionally includes intradev trace events
# }
# }
# }
# }
#
class Data:
dmesg = {} # root data structure
phases = [] # ordered list of phases
start = 0.0 # test start
end = 0.0 # test end
tSuspended = 0.0 # low-level suspend start
tResumed = 0.0 # low-level resume start
tLow = 0.0 # time spent in low-level suspend (standby/freeze)
fwValid = False # is firmware data available
fwSuspend = 0 # time spent in firmware suspend
fwResume = 0 # time spent in firmware resume
dmesgtext = [] # dmesg text file in memory
testnumber = 0
idstr = ''
html_device_id = 0
stamp = 0
outfile = ''
def __init__(self, num):
idchar = 'abcdefghijklmnopqrstuvwxyz'
self.testnumber = num
self.idstr = idchar[num]
self.dmesgtext = []
self.phases = []
self.dmesg = { # fixed list of 10 phases
'suspend_prepare': {'list': dict(), 'start': -1.0, 'end': -1.0,
'row': 0, 'color': '#CCFFCC', 'order': 0},
'suspend': {'list': dict(), 'start': -1.0, 'end': -1.0,
'row': 0, 'color': '#88FF88', 'order': 1},
'suspend_late': {'list': dict(), 'start': -1.0, 'end': -1.0,
'row': 0, 'color': '#00AA00', 'order': 2},
'suspend_noirq': {'list': dict(), 'start': -1.0, 'end': -1.0,
'row': 0, 'color': '#008888', 'order': 3},
'suspend_machine': {'list': dict(), 'start': -1.0, 'end': -1.0,
'row': 0, 'color': '#0000FF', 'order': 4},
'resume_machine': {'list': dict(), 'start': -1.0, 'end': -1.0,
'row': 0, 'color': '#FF0000', 'order': 5},
'resume_noirq': {'list': dict(), 'start': -1.0, 'end': -1.0,
'row': 0, 'color': '#FF9900', 'order': 6},
'resume_early': {'list': dict(), 'start': -1.0, 'end': -1.0,
'row': 0, 'color': '#FFCC00', 'order': 7},
'resume': {'list': dict(), 'start': -1.0, 'end': -1.0,
'row': 0, 'color': '#FFFF88', 'order': 8},
'resume_complete': {'list': dict(), 'start': -1.0, 'end': -1.0,
'row': 0, 'color': '#FFFFCC', 'order': 9}
}
self.phases = self.sortedPhases()
def getStart(self):
return self.dmesg[self.phases[0]]['start']
def setStart(self, time):
self.start = time
self.dmesg[self.phases[0]]['start'] = time
def getEnd(self):
return self.dmesg[self.phases[-1]]['end']
def setEnd(self, time):
self.end = time
self.dmesg[self.phases[-1]]['end'] = time
def isTraceEventOutsideDeviceCalls(self, pid, time):
for phase in self.phases:
list = self.dmesg[phase]['list']
for dev in list:
d = list[dev]
if(d['pid'] == pid and time >= d['start'] and
time <= d['end']):
return False
return True
def addIntraDevTraceEvent(self, action, name, pid, time):
if(action == 'mutex_lock_try'):
color = 'red'
elif(action == 'mutex_lock_pass'):
color = 'green'
elif(action == 'mutex_unlock'):
color = 'blue'
else:
# create separate colors based on the name
v1 = len(name)*10 % 256
v2 = string.count(name, 'e')*100 % 256
v3 = ord(name[0])*20 % 256
color = '#%06X' % ((v1*0x10000) + (v2*0x100) + v3)
for phase in self.phases:
list = self.dmesg[phase]['list']
for dev in list:
d = list[dev]
if(d['pid'] == pid and time >= d['start'] and
time <= d['end']):
e = TraceEvent(action, name, color, time)
if('traceevents' not in d):
d['traceevents'] = []
d['traceevents'].append(e)
return d
break
return 0
def capIntraDevTraceEvent(self, action, name, pid, time):
for phase in self.phases:
list = self.dmesg[phase]['list']
for dev in list:
d = list[dev]
if(d['pid'] == pid and time >= d['start'] and
time <= d['end']):
if('traceevents' not in d):
return
for e in d['traceevents']:
if(e.action == action and
e.name == name and not e.ready):
e.length = time - e.time
e.ready = True
break
return
def trimTimeVal(self, t, t0, dT, left):
if left:
if(t > t0):
if(t - dT < t0):
return t0
return t - dT
else:
return t
else:
if(t < t0 + dT):
if(t > t0):
return t0 + dT
return t + dT
else:
return t
def trimTime(self, t0, dT, left):
self.tSuspended = self.trimTimeVal(self.tSuspended, t0, dT, left)
self.tResumed = self.trimTimeVal(self.tResumed, t0, dT, left)
self.start = self.trimTimeVal(self.start, t0, dT, left)
self.end = self.trimTimeVal(self.end, t0, dT, left)
for phase in self.phases:
p = self.dmesg[phase]
p['start'] = self.trimTimeVal(p['start'], t0, dT, left)
p['end'] = self.trimTimeVal(p['end'], t0, dT, left)
list = p['list']
for name in list:
d = list[name]
d['start'] = self.trimTimeVal(d['start'], t0, dT, left)
d['end'] = self.trimTimeVal(d['end'], t0, dT, left)
if('ftrace' in d):
cg = d['ftrace']
cg.start = self.trimTimeVal(cg.start, t0, dT, left)
cg.end = self.trimTimeVal(cg.end, t0, dT, left)
for line in cg.list:
line.time = self.trimTimeVal(line.time, t0, dT, left)
if('traceevents' in d):
for e in d['traceevents']:
e.time = self.trimTimeVal(e.time, t0, dT, left)
def normalizeTime(self, tZero):
# first trim out any standby or freeze clock time
if(self.tSuspended != self.tResumed):
if(self.tResumed > tZero):
self.trimTime(self.tSuspended, \
self.tResumed-self.tSuspended, True)
else:
self.trimTime(self.tSuspended, \
self.tResumed-self.tSuspended, False)
# shift the timeline so that tZero is the new 0
self.tSuspended -= tZero
self.tResumed -= tZero
self.start -= tZero
self.end -= tZero
for phase in self.phases:
p = self.dmesg[phase]
p['start'] -= tZero
p['end'] -= tZero
list = p['list']
for name in list:
d = list[name]
d['start'] -= tZero
d['end'] -= tZero
if('ftrace' in d):
cg = d['ftrace']
cg.start -= tZero
cg.end -= tZero
for line in cg.list:
line.time -= tZero
if('traceevents' in d):
for e in d['traceevents']:
e.time -= tZero
def newPhaseWithSingleAction(self, phasename, devname, start, end, color):
for phase in self.phases:
self.dmesg[phase]['order'] += 1
self.html_device_id += 1
devid = '%s%d' % (self.idstr, self.html_device_id)
list = dict()
list[devname] = \
{'start': start, 'end': end, 'pid': 0, 'par': '',
'length': (end-start), 'row': 0, 'id': devid, 'drv': '' };
self.dmesg[phasename] = \
{'list': list, 'start': start, 'end': end,
'row': 0, 'color': color, 'order': 0}
self.phases = self.sortedPhases()
def newPhase(self, phasename, start, end, color, order):
if(order < 0):
order = len(self.phases)
for phase in self.phases[order:]:
self.dmesg[phase]['order'] += 1
if(order > 0):
p = self.phases[order-1]
self.dmesg[p]['end'] = start
if(order < len(self.phases)):
p = self.phases[order]
self.dmesg[p]['start'] = end
list = dict()
self.dmesg[phasename] = \
{'list': list, 'start': start, 'end': end,
'row': 0, 'color': color, 'order': order}
self.phases = self.sortedPhases()
def setPhase(self, phase, ktime, isbegin):
if(isbegin):
self.dmesg[phase]['start'] = ktime
else:
self.dmesg[phase]['end'] = ktime
def dmesgSortVal(self, phase):
return self.dmesg[phase]['order']
def sortedPhases(self):
return sorted(self.dmesg, key=self.dmesgSortVal)
def sortedDevices(self, phase):
list = self.dmesg[phase]['list']
slist = []
tmp = dict()
for devname in list:
dev = list[devname]
tmp[dev['start']] = devname
for t in sorted(tmp):
slist.append(tmp[t])
return slist
def fixupInitcalls(self, phase, end):
# if any calls never returned, clip them at system resume end
phaselist = self.dmesg[phase]['list']
for devname in phaselist:
dev = phaselist[devname]
if(dev['end'] < 0):
dev['end'] = end
vprint('%s (%s): callback didnt return' % (devname, phase))
def deviceFilter(self, devicefilter):
# remove all by the relatives of the filter devnames
filter = []
for phase in self.phases:
list = self.dmesg[phase]['list']
for name in devicefilter:
dev = name
while(dev in list):
if(dev not in filter):
filter.append(dev)
dev = list[dev]['par']
children = self.deviceDescendants(name, phase)
for dev in children:
if(dev not in filter):
filter.append(dev)
for phase in self.phases:
list = self.dmesg[phase]['list']
rmlist = []
for name in list:
pid = list[name]['pid']
if(name not in filter and pid >= 0):
rmlist.append(name)
for name in rmlist:
del list[name]
def fixupInitcallsThatDidntReturn(self):
# if any calls never returned, clip them at system resume end
for phase in self.phases:
self.fixupInitcalls(phase, self.getEnd())
def newActionGlobal(self, name, start, end):
# which phase is this device callback or action "in"
targetphase = "none"
overlap = 0.0
for phase in self.phases:
pstart = self.dmesg[phase]['start']
pend = self.dmesg[phase]['end']
o = max(0, min(end, pend) - max(start, pstart))
if(o > overlap):
targetphase = phase
overlap = o
if targetphase in self.phases:
self.newAction(targetphase, name, -1, '', start, end, '')
return True
return False
def newAction(self, phase, name, pid, parent, start, end, drv):
# new device callback for a specific phase
self.html_device_id += 1
devid = '%s%d' % (self.idstr, self.html_device_id)
list = self.dmesg[phase]['list']
length = -1.0
if(start >= 0 and end >= 0):
length = end - start
list[name] = {'start': start, 'end': end, 'pid': pid, 'par': parent,
'length': length, 'row': 0, 'id': devid, 'drv': drv }
def deviceIDs(self, devlist, phase):
idlist = []
list = self.dmesg[phase]['list']
for devname in list:
if devname in devlist:
idlist.append(list[devname]['id'])
return idlist
def deviceParentID(self, devname, phase):
pdev = ''
pdevid = ''
list = self.dmesg[phase]['list']
if devname in list:
pdev = list[devname]['par']
if pdev in list:
return list[pdev]['id']
return pdev
def deviceChildren(self, devname, phase):
devlist = []
list = self.dmesg[phase]['list']
for child in list:
if(list[child]['par'] == devname):
devlist.append(child)
return devlist
def deviceDescendants(self, devname, phase):
children = self.deviceChildren(devname, phase)
family = children
for child in children:
family += self.deviceDescendants(child, phase)
return family
def deviceChildrenIDs(self, devname, phase):
devlist = self.deviceChildren(devname, phase)
return self.deviceIDs(devlist, phase)
def printDetails(self):
vprint(' test start: %f' % self.start)
for phase in self.phases:
dc = len(self.dmesg[phase]['list'])
vprint(' %16s: %f - %f (%d devices)' % (phase, \
self.dmesg[phase]['start'], self.dmesg[phase]['end'], dc))
vprint(' test end: %f' % self.end)
def masterTopology(self, name, list, depth):
node = DeviceNode(name, depth)
for cname in list:
clist = self.deviceChildren(cname, 'resume')
cnode = self.masterTopology(cname, clist, depth+1)
node.children.append(cnode)
return node
def printTopology(self, node):
html = ''
if node.name:
info = ''
drv = ''
for phase in self.phases:
list = self.dmesg[phase]['list']
if node.name in list:
s = list[node.name]['start']
e = list[node.name]['end']
if list[node.name]['drv']:
drv = ' {'+list[node.name]['drv']+'}'
info += ('<li>%s: %.3fms</li>' % (phase, (e-s)*1000))
html += '<li><b>'+node.name+drv+'</b>'
if info:
html += '<ul>'+info+'</ul>'
html += '</li>'
if len(node.children) > 0:
html += '<ul>'
for cnode in node.children:
html += self.printTopology(cnode)
html += '</ul>'
return html
def rootDeviceList(self):
# list of devices graphed
real = []
for phase in self.dmesg:
list = self.dmesg[phase]['list']
for dev in list:
if list[dev]['pid'] >= 0 and dev not in real:
real.append(dev)
# list of top-most root devices
rootlist = []
for phase in self.dmesg:
list = self.dmesg[phase]['list']
for dev in list:
pdev = list[dev]['par']
if(re.match('[0-9]*-[0-9]*\.[0-9]*[\.0-9]*\:[\.0-9]*$', pdev)):
continue
if pdev and pdev not in real and pdev not in rootlist:
rootlist.append(pdev)
return rootlist
def deviceTopology(self):
rootlist = self.rootDeviceList()
master = self.masterTopology('', rootlist, 0)
return self.printTopology(master)
# Class: TraceEvent
# Description:
# A container for trace event data found in the ftrace file
class TraceEvent:
ready = False
name = ''
time = 0.0
color = '#FFFFFF'
length = 0.0
action = ''
def __init__(self, a, n, c, t):
self.action = a
self.name = n
self.color = c
self.time = t
# Class: FTraceLine
# Description:
# A container for a single line of ftrace data. There are six basic types:
# callgraph line:
# call: " dpm_run_callback() {"
# return: " }"
# leaf: " dpm_run_callback();"
# trace event:
# tracing_mark_write: SUSPEND START or RESUME COMPLETE
# suspend_resume: phase or custom exec block data
# device_pm_callback: device callback info
class FTraceLine:
time = 0.0
length = 0.0
fcall = False
freturn = False
fevent = False
depth = 0
name = ''
type = ''
def __init__(self, t, m, d):
self.time = float(t)
# is this a trace event
if(d == 'traceevent' or re.match('^ *\/\* *(?P<msg>.*) \*\/ *$', m)):
if(d == 'traceevent'):
# nop format trace event
msg = m
else:
# function_graph format trace event
em = re.match('^ *\/\* *(?P<msg>.*) \*\/ *$', m)
msg = em.group('msg')
emm = re.match('^(?P<call>.*?): (?P<msg>.*)', msg)
if(emm):
self.name = emm.group('msg')
self.type = emm.group('call')
else:
self.name = msg
self.fevent = True
return
# convert the duration to seconds
if(d):
self.length = float(d)/1000000
# the indentation determines the depth
match = re.match('^(?P<d> *)(?P<o>.*)$', m)
if(not match):
return
self.depth = self.getDepth(match.group('d'))
m = match.group('o')
# function return
if(m[0] == '}'):
self.freturn = True
if(len(m) > 1):
# includes comment with function name
match = re.match('^} *\/\* *(?P<n>.*) *\*\/$', m)
if(match):
self.name = match.group('n')
# function call
else:
self.fcall = True
# function call with children
if(m[-1] == '{'):
match = re.match('^(?P<n>.*) *\(.*', m)
if(match):
self.name = match.group('n')
# function call with no children (leaf)
elif(m[-1] == ';'):
self.freturn = True
match = re.match('^(?P<n>.*) *\(.*', m)
if(match):
self.name = match.group('n')
# something else (possibly a trace marker)
else:
self.name = m
def getDepth(self, str):
return len(str)/2
def debugPrint(self, dev):
if(self.freturn and self.fcall):
print('%s -- %f (%02d): %s(); (%.3f us)' % (dev, self.time, \
self.depth, self.name, self.length*1000000))
elif(self.freturn):
print('%s -- %f (%02d): %s} (%.3f us)' % (dev, self.time, \
self.depth, self.name, self.length*1000000))
else:
print('%s -- %f (%02d): %s() { (%.3f us)' % (dev, self.time, \
self.depth, self.name, self.length*1000000))
# Class: FTraceCallGraph
# Description:
# A container for the ftrace callgraph of a single recursive function.
# This can be a dpm_run_callback, dpm_prepare, or dpm_complete callgraph
# Each instance is tied to a single device in a single phase, and is
# comprised of an ordered list of FTraceLine objects
class FTraceCallGraph:
start = -1.0
end = -1.0
list = []
invalid = False
depth = 0
def __init__(self):
self.start = -1.0
self.end = -1.0
self.list = []
self.depth = 0
def setDepth(self, line):
if(line.fcall and not line.freturn):
line.depth = self.depth
self.depth += 1
elif(line.freturn and not line.fcall):
self.depth -= 1
line.depth = self.depth
else:
line.depth = self.depth
def addLine(self, line, match):
if(not self.invalid):
self.setDepth(line)
if(line.depth == 0 and line.freturn):
if(self.start < 0):
self.start = line.time
self.end = line.time
self.list.append(line)
return True
if(self.invalid):
return False
if(len(self.list) >= 1000000 or self.depth < 0):
if(len(self.list) > 0):
first = self.list[0]
self.list = []
self.list.append(first)
self.invalid = True
if(not match):
return False
id = 'task %s cpu %s' % (match.group('pid'), match.group('cpu'))
window = '(%f - %f)' % (self.start, line.time)
if(self.depth < 0):
print('Too much data for '+id+\
' (buffer overflow), ignoring this callback')
else:
print('Too much data for '+id+\
' '+window+', ignoring this callback')
return False
self.list.append(line)
if(self.start < 0):
self.start = line.time
return False
def slice(self, t0, tN):
minicg = FTraceCallGraph()
count = -1
firstdepth = 0
for l in self.list:
if(l.time < t0 or l.time > tN):
continue
if(count < 0):
if(not l.fcall or l.name == 'dev_driver_string'):
continue
firstdepth = l.depth
count = 0
l.depth -= firstdepth
minicg.addLine(l, 0)
if((count == 0 and l.freturn and l.fcall) or
(count > 0 and l.depth <= 0)):
break
count += 1
return minicg
def sanityCheck(self):
stack = dict()
cnt = 0
for l in self.list:
if(l.fcall and not l.freturn):
stack[l.depth] = l
cnt += 1
elif(l.freturn and not l.fcall):
if(l.depth not in stack):
return False
stack[l.depth].length = l.length
stack[l.depth] = 0
l.length = 0
cnt -= 1
if(cnt == 0):
return True
return False
def debugPrint(self, filename):
if(filename == 'stdout'):
print('[%f - %f]') % (self.start, self.end)
for l in self.list:
if(l.freturn and l.fcall):
print('%f (%02d): %s(); (%.3f us)' % (l.time, \
l.depth, l.name, l.length*1000000))
elif(l.freturn):
print('%f (%02d): %s} (%.3f us)' % (l.time, \
l.depth, l.name, l.length*1000000))
else:
print('%f (%02d): %s() { (%.3f us)' % (l.time, \
l.depth, l.name, l.length*1000000))
print(' ')
else:
fp = open(filename, 'w')
print(filename)
for l in self.list:
if(l.freturn and l.fcall):
fp.write('%f (%02d): %s(); (%.3f us)\n' % (l.time, \
l.depth, l.name, l.length*1000000))
elif(l.freturn):
fp.write('%f (%02d): %s} (%.3f us)\n' % (l.time, \
l.depth, l.name, l.length*1000000))
else:
fp.write('%f (%02d): %s() { (%.3f us)\n' % (l.time, \
l.depth, l.name, l.length*1000000))
fp.close()
# Class: Timeline
# Description:
# A container for a suspend/resume html timeline. In older versions
# of the script there were multiple timelines, but in the latest
# there is only one.
class Timeline:
html = {}
scaleH = 0.0 # height of the row as a percent of the timeline height
rowH = 0.0 # height of each row in percent of the timeline height
row_height_pixels = 30
maxrows = 0
height = 0
def __init__(self):
self.html = {
'timeline': '',
'legend': '',
'scale': ''
}
def setRows(self, rows):
self.maxrows = int(rows)
self.scaleH = 100.0/float(self.maxrows)
self.height = self.maxrows*self.row_height_pixels
r = float(self.maxrows - 1)
if(r < 1.0):
r = 1.0
self.rowH = (100.0 - self.scaleH)/r
# Class: TestRun
# Description:
# A container for a suspend/resume test run. This is necessary as
# there could be more than one, and they need to be separate.
class TestRun:
ftrace_line_fmt_fg = \
'^ *(?P<time>[0-9\.]*) *\| *(?P<cpu>[0-9]*)\)'+\
' *(?P<proc>.*)-(?P<pid>[0-9]*) *\|'+\
'[ +!]*(?P<dur>[0-9\.]*) .*\| (?P<msg>.*)'
ftrace_line_fmt_nop = \
' *(?P<proc>.*)-(?P<pid>[0-9]*) *\[(?P<cpu>[0-9]*)\] *'+\
'(?P<flags>.{4}) *(?P<time>[0-9\.]*): *'+\
'(?P<msg>.*)'
ftrace_line_fmt = ftrace_line_fmt_nop
cgformat = False
ftemp = dict()
ttemp = dict()
inthepipe = False
tracertype = ''
data = 0
def __init__(self, dataobj):
self.data = dataobj
self.ftemp = dict()
self.ttemp = dict()
def isReady(self):
if(tracertype == '' or not data):
return False
return True
def setTracerType(self, tracer):
self.tracertype = tracer
if(tracer == 'function_graph'):
self.cgformat = True
self.ftrace_line_fmt = self.ftrace_line_fmt_fg
elif(tracer == 'nop'):
self.ftrace_line_fmt = self.ftrace_line_fmt_nop
else:
doError('Invalid tracer format: [%s]' % tracer, False)
# ----------------- FUNCTIONS --------------------
# Function: vprint
# Description:
# verbose print (prints only with -verbose option)
# Arguments:
# msg: the debug/log message to print
def vprint(msg):
global sysvals
if(sysvals.verbose):
print(msg)
# Function: initFtrace
# Description:
# Configure ftrace to use trace events and/or a callgraph
def initFtrace():
global sysvals
tp = sysvals.tpath
cf = 'dpm_run_callback'
if(sysvals.usetraceeventsonly):
cf = '-e dpm_prepare -e dpm_complete -e dpm_run_callback'
if(sysvals.usecallgraph or sysvals.usetraceevents):
print('INITIALIZING FTRACE...')
# turn trace off
os.system('echo 0 > '+tp+'tracing_on')
# set the trace clock to global
os.system('echo global > '+tp+'trace_clock')
# set trace buffer to a huge value
os.system('echo nop > '+tp+'current_tracer')
os.system('echo 100000 > '+tp+'buffer_size_kb')
# initialize the callgraph trace, unless this is an x2 run
if(sysvals.usecallgraph and sysvals.execcount == 1):
# set trace type
os.system('echo function_graph > '+tp+'current_tracer')
os.system('echo "" > '+tp+'set_ftrace_filter')
# set trace format options
os.system('echo funcgraph-abstime > '+tp+'trace_options')
os.system('echo funcgraph-proc > '+tp+'trace_options')
# focus only on device suspend and resume
os.system('cat '+tp+'available_filter_functions | grep '+\
cf+' > '+tp+'set_graph_function')
if(sysvals.usetraceevents):
# turn trace events on
events = iter(sysvals.traceevents)
for e in events:
os.system('echo 1 > '+sysvals.epath+e+'/enable')
# clear the trace buffer
os.system('echo "" > '+tp+'trace')
# Function: initFtraceAndroid
# Description:
# Configure ftrace to capture trace events
def initFtraceAndroid():
global sysvals
tp = sysvals.tpath
if(sysvals.usetraceevents):
print('INITIALIZING FTRACE...')
# turn trace off
os.system(sysvals.adb+" shell 'echo 0 > "+tp+"tracing_on'")
# set the trace clock to global
os.system(sysvals.adb+" shell 'echo global > "+tp+"trace_clock'")
# set trace buffer to a huge value
os.system(sysvals.adb+" shell 'echo nop > "+tp+"current_tracer'")
os.system(sysvals.adb+" shell 'echo 10000 > "+tp+"buffer_size_kb'")
# turn trace events on
events = iter(sysvals.traceevents)
for e in events:
os.system(sysvals.adb+" shell 'echo 1 > "+\
sysvals.epath+e+"/enable'")
# clear the trace buffer
os.system(sysvals.adb+" shell 'echo \"\" > "+tp+"trace'")
# Function: verifyFtrace
# Description:
# Check that ftrace is working on the system
# Output:
# True or False
def verifyFtrace():
global sysvals
# files needed for any trace data
files = ['buffer_size_kb', 'current_tracer', 'trace', 'trace_clock',
'trace_marker', 'trace_options', 'tracing_on']
# files needed for callgraph trace data
tp = sysvals.tpath
if(sysvals.usecallgraph):
files += [
'available_filter_functions',
'set_ftrace_filter',
'set_graph_function'
]
for f in files:
if(sysvals.android):
out = os.popen(sysvals.adb+' shell ls '+tp+f).read().strip()
if(out != tp+f):
return False
else:
if(os.path.exists(tp+f) == False):
return False
return True
# Function: parseStamp
# Description:
# Pull in the stamp comment line from the data file(s),
# create the stamp, and add it to the global sysvals object
# Arguments:
# m: the valid re.match output for the stamp line
def parseStamp(m, data):
global sysvals
data.stamp = {'time': '', 'host': '', 'mode': ''}
dt = datetime(int(m.group('y'))+2000, int(m.group('m')),
int(m.group('d')), int(m.group('H')), int(m.group('M')),
int(m.group('S')))
data.stamp['time'] = dt.strftime('%B %d %Y, %I:%M:%S %p')
data.stamp['host'] = m.group('host')
data.stamp['mode'] = m.group('mode')
data.stamp['kernel'] = m.group('kernel')
sysvals.suspendmode = data.stamp['mode']
if not sysvals.stamp:
sysvals.stamp = data.stamp
# Function: diffStamp
# Description:
# compare the host, kernel, and mode fields in 3 stamps
# Arguments:
# stamp1: string array with mode, kernel, and host
# stamp2: string array with mode, kernel, and host
# Return:
# True if stamps differ, False if they're the same
def diffStamp(stamp1, stamp2):
if 'host' in stamp1 and 'host' in stamp2:
if stamp1['host'] != stamp2['host']:
return True
if 'kernel' in stamp1 and 'kernel' in stamp2:
if stamp1['kernel'] != stamp2['kernel']:
return True
if 'mode' in stamp1 and 'mode' in stamp2:
if stamp1['mode'] != stamp2['mode']:
return True
return False
# Function: doesTraceLogHaveTraceEvents
# Description:
# Quickly determine if the ftrace log has some or all of the trace events
# required for primary parsing. Set the usetraceevents and/or
# usetraceeventsonly flags in the global sysvals object
def doesTraceLogHaveTraceEvents():
global sysvals
sysvals.usetraceeventsonly = True
sysvals.usetraceevents = False
for e in sysvals.traceevents:
out = os.popen('cat '+sysvals.ftracefile+' | grep "'+e+': "').read()
if(not out):
sysvals.usetraceeventsonly = False
if(e == 'suspend_resume' and out):
sysvals.usetraceevents = True
# Function: appendIncompleteTraceLog
# Description:
# [deprecated for kernel 3.15 or newer]
# Legacy support of ftrace outputs that lack the device_pm_callback
# and/or suspend_resume trace events. The primary data should be
# taken from dmesg, and this ftrace is used only for callgraph data
# or custom actions in the timeline. The data is appended to the Data
# objects provided.
# Arguments:
# testruns: the array of Data objects obtained from parseKernelLog
def appendIncompleteTraceLog(testruns):
global sysvals
# create TestRun vessels for ftrace parsing
testcnt = len(testruns)
testidx = -1
testrun = []
for data in testruns:
testrun.append(TestRun(data))
# extract the callgraph and traceevent data
vprint('Analyzing the ftrace data...')
tf = open(sysvals.ftracefile, 'r')
for line in tf:
# remove any latent carriage returns
line = line.replace('\r\n', '')
# grab the time stamp first (signifies the start of the test run)
m = re.match(sysvals.stampfmt, line)
if(m):
testidx += 1
parseStamp(m, testrun[testidx].data)
continue
# pull out any firmware data
if(re.match(sysvals.firmwarefmt, line)):
continue
# if we havent found a test time stamp yet keep spinning til we do
if(testidx < 0):
continue
# determine the trace data type (required for further parsing)
m = re.match(sysvals.tracertypefmt, line)
if(m):
tracer = m.group('t')
testrun[testidx].setTracerType(tracer)
continue
# parse only valid lines, if this isnt one move on
m = re.match(testrun[testidx].ftrace_line_fmt, line)
if(not m):
continue
# gather the basic message data from the line
m_time = m.group('time')
m_pid = m.group('pid')
m_msg = m.group('msg')
if(testrun[testidx].cgformat):
m_param3 = m.group('dur')
else:
m_param3 = 'traceevent'
if(m_time and m_pid and m_msg):
t = FTraceLine(m_time, m_msg, m_param3)
pid = int(m_pid)
else:
continue
# the line should be a call, return, or event
if(not t.fcall and not t.freturn and not t.fevent):
continue
# only parse the ftrace data during suspend/resume
data = testrun[testidx].data
if(not testrun[testidx].inthepipe):
# look for the suspend start marker
if(t.fevent):
if(t.name == 'SUSPEND START'):
testrun[testidx].inthepipe = True
data.setStart(t.time)
continue
else:
# trace event processing
if(t.fevent):
if(t.name == 'RESUME COMPLETE'):
testrun[testidx].inthepipe = False
data.setEnd(t.time)
if(testidx == testcnt - 1):
break
continue
# general trace events have two types, begin and end
if(re.match('(?P<name>.*) begin$', t.name)):
isbegin = True
elif(re.match('(?P<name>.*) end$', t.name)):
isbegin = False
else:
continue
m = re.match('(?P<name>.*)\[(?P<val>[0-9]*)\] .*', t.name)
if(m):
val = m.group('val')
if val == '0':
name = m.group('name')
else:
name = m.group('name')+'['+val+']'
else:
m = re.match('(?P<name>.*) .*', t.name)
name = m.group('name')
# special processing for trace events
if re.match('dpm_prepare\[.*', name):
continue
elif re.match('machine_suspend.*', name):
continue
elif re.match('suspend_enter\[.*', name):
if(not isbegin):
data.dmesg['suspend_prepare']['end'] = t.time
continue
elif re.match('dpm_suspend\[.*', name):
if(not isbegin):
data.dmesg['suspend']['end'] = t.time
continue
elif re.match('dpm_suspend_late\[.*', name):
if(isbegin):
data.dmesg['suspend_late']['start'] = t.time
else:
data.dmesg['suspend_late']['end'] = t.time
continue
elif re.match('dpm_suspend_noirq\[.*', name):
if(isbegin):
data.dmesg['suspend_noirq']['start'] = t.time
else:
data.dmesg['suspend_noirq']['end'] = t.time
continue
elif re.match('dpm_resume_noirq\[.*', name):
if(isbegin):
data.dmesg['resume_machine']['end'] = t.time
data.dmesg['resume_noirq']['start'] = t.time
else:
data.dmesg['resume_noirq']['end'] = t.time
continue
elif re.match('dpm_resume_early\[.*', name):
if(isbegin):
data.dmesg['resume_early']['start'] = t.time
else:
data.dmesg['resume_early']['end'] = t.time
continue
elif re.match('dpm_resume\[.*', name):
if(isbegin):
data.dmesg['resume']['start'] = t.time
else:
data.dmesg['resume']['end'] = t.time
continue
elif re.match('dpm_complete\[.*', name):
if(isbegin):
data.dmesg['resume_complete']['start'] = t.time
else:
data.dmesg['resume_complete']['end'] = t.time
continue
# is this trace event outside of the devices calls
if(data.isTraceEventOutsideDeviceCalls(pid, t.time)):
# global events (outside device calls) are simply graphed
if(isbegin):
# store each trace event in ttemp
if(name not in testrun[testidx].ttemp):
testrun[testidx].ttemp[name] = []
testrun[testidx].ttemp[name].append(\
{'begin': t.time, 'end': t.time})
else:
# finish off matching trace event in ttemp
if(name in testrun[testidx].ttemp):
testrun[testidx].ttemp[name][-1]['end'] = t.time
else:
if(isbegin):
data.addIntraDevTraceEvent('', name, pid, t.time)
else:
data.capIntraDevTraceEvent('', name, pid, t.time)
# call/return processing
elif sysvals.usecallgraph:
# create a callgraph object for the data
if(pid not in testrun[testidx].ftemp):
testrun[testidx].ftemp[pid] = []
testrun[testidx].ftemp[pid].append(FTraceCallGraph())
# when the call is finished, see which device matches it
cg = testrun[testidx].ftemp[pid][-1]
if(cg.addLine(t, m)):
testrun[testidx].ftemp[pid].append(FTraceCallGraph())
tf.close()
for test in testrun:
# add the traceevent data to the device hierarchy
if(sysvals.usetraceevents):
for name in test.ttemp:
for event in test.ttemp[name]:
begin = event['begin']
end = event['end']
# if event starts before timeline start, expand timeline
if(begin < test.data.start):
test.data.setStart(begin)
# if event ends after timeline end, expand the timeline
if(end > test.data.end):
test.data.setEnd(end)
test.data.newActionGlobal(name, begin, end)
# add the callgraph data to the device hierarchy
for pid in test.ftemp:
for cg in test.ftemp[pid]:
if(not cg.sanityCheck()):
id = 'task %s cpu %s' % (pid, m.group('cpu'))
vprint('Sanity check failed for '+\
id+', ignoring this callback')
continue
callstart = cg.start
callend = cg.end
for p in test.data.phases:
if(test.data.dmesg[p]['start'] <= callstart and
callstart <= test.data.dmesg[p]['end']):
list = test.data.dmesg[p]['list']
for devname in list:
dev = list[devname]
if(pid == dev['pid'] and
callstart <= dev['start'] and
callend >= dev['end']):
dev['ftrace'] = cg
break
if(sysvals.verbose):
test.data.printDetails()
# add the time in between the tests as a new phase so we can see it
if(len(testruns) > 1):
t1e = testruns[0].getEnd()
t2s = testruns[-1].getStart()
testruns[-1].newPhaseWithSingleAction('user mode', \
'user mode', t1e, t2s, '#FF9966')
# Function: parseTraceLog
# Description:
# Analyze an ftrace log output file generated from this app during
# the execution phase. Used when the ftrace log is the primary data source
# and includes the suspend_resume and device_pm_callback trace events
# The ftrace filename is taken from sysvals
# Output:
# An array of Data objects
def parseTraceLog():
global sysvals
vprint('Analyzing the ftrace data...')
if(os.path.exists(sysvals.ftracefile) == False):
doError('%s doesnt exist' % sysvals.ftracefile, False)
# extract the callgraph and traceevent data
testruns = []
testdata = []
testrun = 0
data = 0
tf = open(sysvals.ftracefile, 'r')
phase = 'suspend_prepare'
for line in tf:
# remove any latent carriage returns
line = line.replace('\r\n', '')
# stamp line: each stamp means a new test run
m = re.match(sysvals.stampfmt, line)
if(m):
data = Data(len(testdata))
testdata.append(data)
testrun = TestRun(data)
testruns.append(testrun)
parseStamp(m, data)
continue
if(not data):
continue
# firmware line: pull out any firmware data
m = re.match(sysvals.firmwarefmt, line)
if(m):
data.fwSuspend = int(m.group('s'))
data.fwResume = int(m.group('r'))
if(data.fwSuspend > 0 or data.fwResume > 0):
data.fwValid = True
continue
# tracer type line: determine the trace data type
m = re.match(sysvals.tracertypefmt, line)
if(m):
tracer = m.group('t')
testrun.setTracerType(tracer)
continue
# post resume time line: did this test run include post-resume data
m = re.match(sysvals.postresumefmt, line)
if(m):
t = int(m.group('t'))
if(t > 0):
sysvals.postresumetime = t
continue
# ftrace line: parse only valid lines
m = re.match(testrun.ftrace_line_fmt, line)
if(not m):
continue
# gather the basic message data from the line
m_time = m.group('time')
m_pid = m.group('pid')
m_msg = m.group('msg')
if(testrun.cgformat):
m_param3 = m.group('dur')
else:
m_param3 = 'traceevent'
if(m_time and m_pid and m_msg):
t = FTraceLine(m_time, m_msg, m_param3)
pid = int(m_pid)
else:
continue
# the line should be a call, return, or event
if(not t.fcall and not t.freturn and not t.fevent):
continue
# only parse the ftrace data during suspend/resume
if(not testrun.inthepipe):
# look for the suspend start marker
if(t.fevent):
if(t.name == 'SUSPEND START'):
testrun.inthepipe = True
data.setStart(t.time)
continue
# trace event processing
if(t.fevent):
if(t.name == 'RESUME COMPLETE'):
if(sysvals.postresumetime > 0):
phase = 'post_resume'
data.newPhase(phase, t.time, t.time, '#FF9966', -1)
else:
testrun.inthepipe = False
data.setEnd(t.time)
continue
if(phase == 'post_resume'):
data.setEnd(t.time)
if(t.type == 'suspend_resume'):
# suspend_resume trace events have two types, begin and end
if(re.match('(?P<name>.*) begin$', t.name)):
isbegin = True
elif(re.match('(?P<name>.*) end$', t.name)):
isbegin = False
else:
continue
m = re.match('(?P<name>.*)\[(?P<val>[0-9]*)\] .*', t.name)
if(m):
val = m.group('val')
if val == '0':
name = m.group('name')
else:
name = m.group('name')+'['+val+']'
else:
m = re.match('(?P<name>.*) .*', t.name)
name = m.group('name')
# ignore these events
if(re.match('acpi_suspend\[.*', t.name) or
re.match('suspend_enter\[.*', name)):
continue
# -- phase changes --
# suspend_prepare start
if(re.match('dpm_prepare\[.*', t.name)):
phase = 'suspend_prepare'
if(not isbegin):
data.dmesg[phase]['end'] = t.time
continue
# suspend start
elif(re.match('dpm_suspend\[.*', t.name)):
phase = 'suspend'
data.setPhase(phase, t.time, isbegin)
continue
# suspend_late start
elif(re.match('dpm_suspend_late\[.*', t.name)):
phase = 'suspend_late'
data.setPhase(phase, t.time, isbegin)
continue
# suspend_noirq start
elif(re.match('dpm_suspend_noirq\[.*', t.name)):
phase = 'suspend_noirq'
data.setPhase(phase, t.time, isbegin)
if(not isbegin):
phase = 'suspend_machine'
data.dmesg[phase]['start'] = t.time
continue
# suspend_machine/resume_machine
elif(re.match('machine_suspend\[.*', t.name)):
if(isbegin):
phase = 'suspend_machine'
data.dmesg[phase]['end'] = t.time
data.tSuspended = t.time
else:
if(sysvals.suspendmode in ['mem', 'disk']):
data.dmesg['suspend_machine']['end'] = t.time
data.tSuspended = t.time
phase = 'resume_machine'
data.dmesg[phase]['start'] = t.time
data.tResumed = t.time
data.tLow = data.tResumed - data.tSuspended
continue
# resume_noirq start
elif(re.match('dpm_resume_noirq\[.*', t.name)):
phase = 'resume_noirq'
data.setPhase(phase, t.time, isbegin)
if(isbegin):
data.dmesg['resume_machine']['end'] = t.time
continue
# resume_early start
elif(re.match('dpm_resume_early\[.*', t.name)):
phase = 'resume_early'
data.setPhase(phase, t.time, isbegin)
continue
# resume start
elif(re.match('dpm_resume\[.*', t.name)):
phase = 'resume'
data.setPhase(phase, t.time, isbegin)
continue
# resume complete start
elif(re.match('dpm_complete\[.*', t.name)):
phase = 'resume_complete'
if(isbegin):
data.dmesg[phase]['start'] = t.time
continue
# is this trace event outside of the devices calls
if(data.isTraceEventOutsideDeviceCalls(pid, t.time)):
# global events (outside device calls) are simply graphed
if(name not in testrun.ttemp):
testrun.ttemp[name] = []
if(isbegin):
# create a new list entry
testrun.ttemp[name].append(\
{'begin': t.time, 'end': t.time})
else:
if(len(testrun.ttemp[name]) > 0):
# if an antry exists, assume this is its end
testrun.ttemp[name][-1]['end'] = t.time
elif(phase == 'post_resume'):
# post resume events can just have ends
testrun.ttemp[name].append({
'begin': data.dmesg[phase]['start'],
'end': t.time})
else:
if(isbegin):
data.addIntraDevTraceEvent('', name, pid, t.time)
else:
data.capIntraDevTraceEvent('', name, pid, t.time)
# device callback start
elif(t.type == 'device_pm_callback_start'):
m = re.match('(?P<drv>.*) (?P<d>.*), parent: *(?P<p>.*), .*',\
t.name);
if(not m):
continue
drv = m.group('drv')
n = m.group('d')
p = m.group('p')
if(n and p):
data.newAction(phase, n, pid, p, t.time, -1, drv)
# device callback finish
elif(t.type == 'device_pm_callback_end'):
m = re.match('(?P<drv>.*) (?P<d>.*), err.*', t.name);
if(not m):
continue
n = m.group('d')
list = data.dmesg[phase]['list']
if(n in list):
dev = list[n]
dev['length'] = t.time - dev['start']
dev['end'] = t.time
# callgraph processing
elif sysvals.usecallgraph:
# this shouldn't happen, but JIC, ignore callgraph data post-res
if(phase == 'post_resume'):
continue
# create a callgraph object for the data
if(pid not in testrun.ftemp):
testrun.ftemp[pid] = []
testrun.ftemp[pid].append(FTraceCallGraph())
# when the call is finished, see which device matches it
cg = testrun.ftemp[pid][-1]
if(cg.addLine(t, m)):
testrun.ftemp[pid].append(FTraceCallGraph())
tf.close()
for test in testruns:
# add the traceevent data to the device hierarchy
if(sysvals.usetraceevents):
for name in test.ttemp:
for event in test.ttemp[name]:
begin = event['begin']
end = event['end']
# if event starts before timeline start, expand timeline
if(begin < test.data.start):
test.data.setStart(begin)
# if event ends after timeline end, expand the timeline
if(end > test.data.end):
test.data.setEnd(end)
test.data.newActionGlobal(name, begin, end)
# add the callgraph data to the device hierarchy
borderphase = {
'dpm_prepare': 'suspend_prepare',
'dpm_complete': 'resume_complete'
}
for pid in test.ftemp:
for cg in test.ftemp[pid]:
if len(cg.list) < 2:
continue
if(not cg.sanityCheck()):
id = 'task %s cpu %s' % (pid, m.group('cpu'))
vprint('Sanity check failed for '+\
id+', ignoring this callback')
continue
callstart = cg.start
callend = cg.end
if(cg.list[0].name in borderphase):
p = borderphase[cg.list[0].name]
list = test.data.dmesg[p]['list']
for devname in list:
dev = list[devname]
if(pid == dev['pid'] and
callstart <= dev['start'] and
callend >= dev['end']):
dev['ftrace'] = cg.slice(dev['start'], dev['end'])
continue
if(cg.list[0].name != 'dpm_run_callback'):
continue
for p in test.data.phases:
if(test.data.dmesg[p]['start'] <= callstart and
callstart <= test.data.dmesg[p]['end']):
list = test.data.dmesg[p]['list']
for devname in list:
dev = list[devname]
if(pid == dev['pid'] and
callstart <= dev['start'] and
callend >= dev['end']):
dev['ftrace'] = cg
break
# fill in any missing phases
for data in testdata:
lp = data.phases[0]
for p in data.phases:
if(data.dmesg[p]['start'] < 0 and data.dmesg[p]['end'] < 0):
print('WARNING: phase "%s" is missing!' % p)
if(data.dmesg[p]['start'] < 0):
data.dmesg[p]['start'] = data.dmesg[lp]['end']
if(p == 'resume_machine'):
data.tSuspended = data.dmesg[lp]['end']
data.tResumed = data.dmesg[lp]['end']
data.tLow = 0
if(data.dmesg[p]['end'] < 0):
data.dmesg[p]['end'] = data.dmesg[p]['start']
lp = p
if(len(sysvals.devicefilter) > 0):
data.deviceFilter(sysvals.devicefilter)
data.fixupInitcallsThatDidntReturn()
if(sysvals.verbose):
data.printDetails()
# add the time in between the tests as a new phase so we can see it
if(len(testdata) > 1):
t1e = testdata[0].getEnd()
t2s = testdata[-1].getStart()
testdata[-1].newPhaseWithSingleAction('user mode', \
'user mode', t1e, t2s, '#FF9966')
return testdata
# Function: loadKernelLog
# Description:
# [deprecated for kernel 3.15.0 or newer]
# load the dmesg file into memory and fix up any ordering issues
# The dmesg filename is taken from sysvals
# Output:
# An array of empty Data objects with only their dmesgtext attributes set
def loadKernelLog():
global sysvals
vprint('Analyzing the dmesg data...')
if(os.path.exists(sysvals.dmesgfile) == False):
doError('%s doesnt exist' % sysvals.dmesgfile, False)
# there can be multiple test runs in a single file delineated by stamps
testruns = []
data = 0
lf = open(sysvals.dmesgfile, 'r')
for line in lf:
line = line.replace('\r\n', '')
idx = line.find('[')
if idx > 1:
line = line[idx:]
m = re.match(sysvals.stampfmt, line)
if(m):
if(data):
testruns.append(data)
data = Data(len(testruns))
parseStamp(m, data)
continue
if(not data):
continue
m = re.match(sysvals.firmwarefmt, line)
if(m):
data.fwSuspend = int(m.group('s'))
data.fwResume = int(m.group('r'))
if(data.fwSuspend > 0 or data.fwResume > 0):
data.fwValid = True
continue
m = re.match('[ \t]*(\[ *)(?P<ktime>[0-9\.]*)(\]) (?P<msg>.*)', line)
if(m):
data.dmesgtext.append(line)
if(re.match('ACPI: resume from mwait', m.group('msg'))):
print('NOTE: This suspend appears to be freeze rather than'+\
' %s, it will be treated as such' % sysvals.suspendmode)
sysvals.suspendmode = 'freeze'
else:
vprint('ignoring dmesg line: %s' % line.replace('\n', ''))
testruns.append(data)
lf.close()
if(not data):
print('ERROR: analyze_suspend header missing from dmesg log')
sys.exit()
# fix lines with same timestamp/function with the call and return swapped
for data in testruns:
last = ''
for line in data.dmesgtext:
mc = re.match('.*(\[ *)(?P<t>[0-9\.]*)(\]) calling '+\
'(?P<f>.*)\+ @ .*, parent: .*', line)
mr = re.match('.*(\[ *)(?P<t>[0-9\.]*)(\]) call '+\
'(?P<f>.*)\+ returned .* after (?P<dt>.*) usecs', last)
if(mc and mr and (mc.group('t') == mr.group('t')) and
(mc.group('f') == mr.group('f'))):
i = data.dmesgtext.index(last)
j = data.dmesgtext.index(line)
data.dmesgtext[i] = line
data.dmesgtext[j] = last
last = line
return testruns
# Function: parseKernelLog
# Description:
# [deprecated for kernel 3.15.0 or newer]
# Analyse a dmesg log output file generated from this app during
# the execution phase. Create a set of device structures in memory
# for subsequent formatting in the html output file
# This call is only for legacy support on kernels where the ftrace
# data lacks the suspend_resume or device_pm_callbacks trace events.
# Arguments:
# data: an empty Data object (with dmesgtext) obtained from loadKernelLog
# Output:
# The filled Data object
def parseKernelLog(data):
global sysvals
phase = 'suspend_runtime'
if(data.fwValid):
vprint('Firmware Suspend = %u ns, Firmware Resume = %u ns' % \
(data.fwSuspend, data.fwResume))
# dmesg phase match table
dm = {
'suspend_prepare': 'PM: Syncing filesystems.*',
'suspend': 'PM: Entering [a-z]* sleep.*',
'suspend_late': 'PM: suspend of devices complete after.*',
'suspend_noirq': 'PM: late suspend of devices complete after.*',
'suspend_machine': 'PM: noirq suspend of devices complete after.*',
'resume_machine': 'ACPI: Low-level resume complete.*',
'resume_noirq': 'ACPI: Waking up from system sleep state.*',
'resume_early': 'PM: noirq resume of devices complete after.*',
'resume': 'PM: early resume of devices complete after.*',
'resume_complete': 'PM: resume of devices complete after.*',
'post_resume': '.*Restarting tasks \.\.\..*',
}
if(sysvals.suspendmode == 'standby'):
dm['resume_machine'] = 'PM: Restoring platform NVS memory'
elif(sysvals.suspendmode == 'disk'):
dm['suspend_late'] = 'PM: freeze of devices complete after.*'
dm['suspend_noirq'] = 'PM: late freeze of devices complete after.*'
dm['suspend_machine'] = 'PM: noirq freeze of devices complete after.*'
dm['resume_machine'] = 'PM: Restoring platform NVS memory'
dm['resume_early'] = 'PM: noirq restore of devices complete after.*'
dm['resume'] = 'PM: early restore of devices complete after.*'
dm['resume_complete'] = 'PM: restore of devices complete after.*'
elif(sysvals.suspendmode == 'freeze'):
dm['resume_machine'] = 'ACPI: resume from mwait'
# action table (expected events that occur and show up in dmesg)
at = {
'sync_filesystems': {
'smsg': 'PM: Syncing filesystems.*',
'emsg': 'PM: Preparing system for mem sleep.*' },
'freeze_user_processes': {
'smsg': 'Freezing user space processes .*',
'emsg': 'Freezing remaining freezable tasks.*' },
'freeze_tasks': {
'smsg': 'Freezing remaining freezable tasks.*',
'emsg': 'PM: Entering (?P<mode>[a-z,A-Z]*) sleep.*' },
'ACPI prepare': {
'smsg': 'ACPI: Preparing to enter system sleep state.*',
'emsg': 'PM: Saving platform NVS memory.*' },
'PM vns': {
'smsg': 'PM: Saving platform NVS memory.*',
'emsg': 'Disabling non-boot CPUs .*' },
}
t0 = -1.0
cpu_start = -1.0
prevktime = -1.0
actions = dict()
for line in data.dmesgtext:
# -- preprocessing --
# parse each dmesg line into the time and message
m = re.match('[ \t]*(\[ *)(?P<ktime>[0-9\.]*)(\]) (?P<msg>.*)', line)
if(m):
val = m.group('ktime')
try:
ktime = float(val)
except:
doWarning('INVALID DMESG LINE: '+\
line.replace('\n', ''), 'dmesg')
continue
msg = m.group('msg')
# initialize data start to first line time
if t0 < 0:
data.setStart(ktime)
t0 = ktime
else:
continue
# hack for determining resume_machine end for freeze
if(not sysvals.usetraceevents and sysvals.suspendmode == 'freeze' \
and phase == 'resume_machine' and \
re.match('calling (?P<f>.*)\+ @ .*, parent: .*', msg)):
data.dmesg['resume_machine']['end'] = ktime
phase = 'resume_noirq'
data.dmesg[phase]['start'] = ktime
# -- phase changes --
# suspend start
if(re.match(dm['suspend_prepare'], msg)):
phase = 'suspend_prepare'
data.dmesg[phase]['start'] = ktime
data.setStart(ktime)
# suspend start
elif(re.match(dm['suspend'], msg)):
data.dmesg['suspend_prepare']['end'] = ktime
phase = 'suspend'
data.dmesg[phase]['start'] = ktime
# suspend_late start
elif(re.match(dm['suspend_late'], msg)):
data.dmesg['suspend']['end'] = ktime
phase = 'suspend_late'
data.dmesg[phase]['start'] = ktime
# suspend_noirq start
elif(re.match(dm['suspend_noirq'], msg)):
data.dmesg['suspend_late']['end'] = ktime
phase = 'suspend_noirq'
data.dmesg[phase]['start'] = ktime
# suspend_machine start
elif(re.match(dm['suspend_machine'], msg)):
data.dmesg['suspend_noirq']['end'] = ktime
phase = 'suspend_machine'
data.dmesg[phase]['start'] = ktime
# resume_machine start
elif(re.match(dm['resume_machine'], msg)):
if(sysvals.suspendmode in ['freeze', 'standby']):
data.tSuspended = prevktime
data.dmesg['suspend_machine']['end'] = prevktime
else:
data.tSuspended = ktime
data.dmesg['suspend_machine']['end'] = ktime
phase = 'resume_machine'
data.tResumed = ktime
data.tLow = data.tResumed - data.tSuspended
data.dmesg[phase]['start'] = ktime
# resume_noirq start
elif(re.match(dm['resume_noirq'], msg)):
data.dmesg['resume_machine']['end'] = ktime
phase = 'resume_noirq'
data.dmesg[phase]['start'] = ktime
# resume_early start
elif(re.match(dm['resume_early'], msg)):
data.dmesg['resume_noirq']['end'] = ktime
phase = 'resume_early'
data.dmesg[phase]['start'] = ktime
# resume start
elif(re.match(dm['resume'], msg)):
data.dmesg['resume_early']['end'] = ktime
phase = 'resume'
data.dmesg[phase]['start'] = ktime
# resume complete start
elif(re.match(dm['resume_complete'], msg)):
data.dmesg['resume']['end'] = ktime
phase = 'resume_complete'
data.dmesg[phase]['start'] = ktime
# post resume start
elif(re.match(dm['post_resume'], msg)):
data.dmesg['resume_complete']['end'] = ktime
data.setEnd(ktime)
phase = 'post_resume'
break
# -- device callbacks --
if(phase in data.phases):
# device init call
if(re.match('calling (?P<f>.*)\+ @ .*, parent: .*', msg)):
sm = re.match('calling (?P<f>.*)\+ @ '+\
'(?P<n>.*), parent: (?P<p>.*)', msg);
f = sm.group('f')
n = sm.group('n')
p = sm.group('p')
if(f and n and p):
data.newAction(phase, f, int(n), p, ktime, -1, '')
# device init return
elif(re.match('call (?P<f>.*)\+ returned .* after '+\
'(?P<t>.*) usecs', msg)):
sm = re.match('call (?P<f>.*)\+ returned .* after '+\
'(?P<t>.*) usecs(?P<a>.*)', msg);
f = sm.group('f')
t = sm.group('t')
list = data.dmesg[phase]['list']
if(f in list):
dev = list[f]
dev['length'] = int(t)
dev['end'] = ktime
# -- non-devicecallback actions --
# if trace events are not available, these are better than nothing
if(not sysvals.usetraceevents):
# look for known actions
for a in at:
if(re.match(at[a]['smsg'], msg)):
if(a not in actions):
actions[a] = []
actions[a].append({'begin': ktime, 'end': ktime})
if(re.match(at[a]['emsg'], msg)):
actions[a][-1]['end'] = ktime
# now look for CPU on/off events
if(re.match('Disabling non-boot CPUs .*', msg)):
# start of first cpu suspend
cpu_start = ktime
elif(re.match('Enabling non-boot CPUs .*', msg)):
# start of first cpu resume
cpu_start = ktime
elif(re.match('smpboot: CPU (?P<cpu>[0-9]*) is now offline', msg)):
# end of a cpu suspend, start of the next
m = re.match('smpboot: CPU (?P<cpu>[0-9]*) is now offline', msg)
cpu = 'CPU'+m.group('cpu')
if(cpu not in actions):
actions[cpu] = []
actions[cpu].append({'begin': cpu_start, 'end': ktime})
cpu_start = ktime
elif(re.match('CPU(?P<cpu>[0-9]*) is up', msg)):
# end of a cpu resume, start of the next
m = re.match('CPU(?P<cpu>[0-9]*) is up', msg)
cpu = 'CPU'+m.group('cpu')
if(cpu not in actions):
actions[cpu] = []
actions[cpu].append({'begin': cpu_start, 'end': ktime})
cpu_start = ktime
prevktime = ktime
# fill in any missing phases
lp = data.phases[0]
for p in data.phases:
if(data.dmesg[p]['start'] < 0 and data.dmesg[p]['end'] < 0):
print('WARNING: phase "%s" is missing, something went wrong!' % p)
print(' In %s, this dmesg line denotes the start of %s:' % \
(sysvals.suspendmode, p))
print(' "%s"' % dm[p])
if(data.dmesg[p]['start'] < 0):
data.dmesg[p]['start'] = data.dmesg[lp]['end']
if(p == 'resume_machine'):
data.tSuspended = data.dmesg[lp]['end']
data.tResumed = data.dmesg[lp]['end']
data.tLow = 0
if(data.dmesg[p]['end'] < 0):
data.dmesg[p]['end'] = data.dmesg[p]['start']
lp = p
# fill in any actions we've found
for name in actions:
for event in actions[name]:
begin = event['begin']
end = event['end']
# if event starts before timeline start, expand timeline
if(begin < data.start):
data.setStart(begin)
# if event ends after timeline end, expand the timeline
if(end > data.end):
data.setEnd(end)
data.newActionGlobal(name, begin, end)
if(sysvals.verbose):
data.printDetails()
if(len(sysvals.devicefilter) > 0):
data.deviceFilter(sysvals.devicefilter)
data.fixupInitcallsThatDidntReturn()
return True
# Function: setTimelineRows
# Description:
# Organize the timeline entries into the smallest
# number of rows possible, with no entry overlapping
# Arguments:
# list: the list of devices/actions for a single phase
# sortedkeys: cronologically sorted key list to use
# Output:
# The total number of rows needed to display this phase of the timeline
def setTimelineRows(list, sortedkeys):
# clear all rows and set them to undefined
remaining = len(list)
rowdata = dict()
row = 0
for item in list:
list[item]['row'] = -1
# try to pack each row with as many ranges as possible
while(remaining > 0):
if(row not in rowdata):
rowdata[row] = []
for item in sortedkeys:
if(list[item]['row'] < 0):
s = list[item]['start']
e = list[item]['end']
valid = True
for ritem in rowdata[row]:
rs = ritem['start']
re = ritem['end']
if(not (((s <= rs) and (e <= rs)) or
((s >= re) and (e >= re)))):
valid = False
break
if(valid):
rowdata[row].append(list[item])
list[item]['row'] = row
remaining -= 1
row += 1
return row
# Function: createTimeScale
# Description:
# Create the timescale header for the html timeline
# Arguments:
# t0: start time (suspend begin)
# tMax: end time (resume end)
# tSuspend: time when suspend occurs, i.e. the zero time
# Output:
# The html code needed to display the time scale
def createTimeScale(t0, tMax, tSuspended):
timescale = '<div class="t" style="right:{0}%">{1}</div>\n'
output = '<div id="timescale">\n'
# set scale for timeline
tTotal = tMax - t0
tS = 0.1
if(tTotal <= 0):
return output
if(tTotal > 4):
tS = 1
if(tSuspended < 0):
for i in range(int(tTotal/tS)+1):
pos = '%0.3f' % (100 - ((float(i)*tS*100)/tTotal))
if(i > 0):
val = '%0.fms' % (float(i)*tS*1000)
else:
val = ''
output += timescale.format(pos, val)
else:
tSuspend = tSuspended - t0
divTotal = int(tTotal/tS) + 1
divSuspend = int(tSuspend/tS)
s0 = (tSuspend - tS*divSuspend)*100/tTotal
for i in range(divTotal):
pos = '%0.3f' % (100 - ((float(i)*tS*100)/tTotal) - s0)
if((i == 0) and (s0 < 3)):
val = ''
elif(i == divSuspend):
val = 'S/R'
else:
val = '%0.fms' % (float(i-divSuspend)*tS*1000)
output += timescale.format(pos, val)
output += '</div>\n'
return output
# Function: createHTMLSummarySimple
# Description:
# Create summary html file for a series of tests
# Arguments:
# testruns: array of Data objects from parseTraceLog
def createHTMLSummarySimple(testruns, htmlfile):
global sysvals
# print out the basic summary of all the tests
hf = open(htmlfile, 'w')
# write the html header first (html head, css code, up to body start)
html = '<!DOCTYPE html>\n<html>\n<head>\n\
<meta http-equiv="content-type" content="text/html; charset=UTF-8">\n\
<title>AnalyzeSuspend Summary</title>\n\
<style type=\'text/css\'>\n\
body {overflow-y: scroll;}\n\
.stamp {width: 100%;text-align:center;background-color:#495E09;line-height:30px;color:white;font: 25px Arial;}\n\
table {width:100%;border-collapse: collapse;}\n\
.summary {font: 22px Arial;border:1px solid;}\n\
th {border: 1px solid black;background-color:#A7C942;color:white;}\n\
td {text-align: center;}\n\
tr.alt td {background-color:#EAF2D3;}\n\
tr.avg td {background-color:#BDE34C;}\n\
a:link {color: #90B521;}\n\
a:visited {color: #495E09;}\n\
a:hover {color: #B1DF28;}\n\
a:active {color: #FFFFFF;}\n\
</style>\n</head>\n<body>\n'
# group test header
count = len(testruns)
headline_stamp = '<div class="stamp">{0} {1} {2} {3} ({4} tests)</div>\n'
html += headline_stamp.format(sysvals.stamp['host'],
sysvals.stamp['kernel'], sysvals.stamp['mode'],
sysvals.stamp['time'], count)
# check to see if all the tests have the same value
stampcolumns = False
for data in testruns:
if diffStamp(sysvals.stamp, data.stamp):
stampcolumns = True
break
th = '\t<th>{0}</th>\n'
td = '\t<td>{0}</td>\n'
tdlink = '\t<td><a href="{0}">Click Here</a></td>\n'
# table header
html += '<table class="summary">\n<tr>\n'
html += th.format("Test #")
if stampcolumns:
html += th.format("Hostname")
html += th.format("Kernel Version")
html += th.format("Suspend Mode")
html += th.format("Test Time")
html += th.format("Suspend Time")
html += th.format("Resume Time")
html += th.format("Detail")
html += '</tr>\n'
# test data, 1 row per test
sTimeAvg = 0.0
rTimeAvg = 0.0
num = 1
for data in testruns:
# data.end is the end of post_resume
resumeEnd = data.dmesg['resume_complete']['end']
if num % 2 == 1:
html += '<tr class="alt">\n'
else:
html += '<tr>\n'
# test num
html += td.format("test %d" % num)
num += 1
if stampcolumns:
# host name
val = "unknown"
if('host' in data.stamp):
val = data.stamp['host']
html += td.format(val)
# host kernel
val = "unknown"
if('kernel' in data.stamp):
val = data.stamp['kernel']
html += td.format(val)
# suspend mode
val = "unknown"
if('mode' in data.stamp):
val = data.stamp['mode']
html += td.format(val)
# test time
val = "unknown"
if('time' in data.stamp):
val = data.stamp['time']
html += td.format(val)
# suspend time
sTime = (data.tSuspended - data.start)*1000
sTimeAvg += sTime
html += td.format("%3.3f ms" % sTime)
# resume time
rTime = (resumeEnd - data.tResumed)*1000
rTimeAvg += rTime
html += td.format("%3.3f ms" % rTime)
# link to the output html
html += tdlink.format(data.outfile)
html += '</tr>\n'
# last line: test average
if(count > 0):
sTimeAvg /= count
rTimeAvg /= count
html += '<tr class="avg">\n'
html += td.format('Average') # name
if stampcolumns:
html += td.format('') # host
html += td.format('') # kernel
html += td.format('') # mode
html += td.format('') # time
html += td.format("%3.3f ms" % sTimeAvg) # suspend time
html += td.format("%3.3f ms" % rTimeAvg) # resume time
html += td.format('') # output link
html += '</tr>\n'
# flush the data to file
hf.write(html+'</table>\n')
hf.write('</body>\n</html>\n')
hf.close()
# Function: createHTML
# Description:
# Create the output html file from the resident test data
# Arguments:
# testruns: array of Data objects from parseKernelLog or parseTraceLog
# Output:
# True if the html file was created, false if it failed
def createHTML(testruns):
global sysvals
for data in testruns:
data.normalizeTime(testruns[-1].tSuspended)
x2changes = ['', 'absolute']
if len(testruns) > 1:
x2changes = ['1', 'relative']
# html function templates
headline_stamp = '<div class="stamp">{0} {1} {2} {3}</div>\n'
html_devlist1 = '<button id="devlist1" class="devlist" style="float:left;">Device Detail%s</button>' % x2changes[0]
html_zoombox = '<center><button id="zoomin">ZOOM IN</button><button id="zoomout">ZOOM OUT</button><button id="zoomdef">ZOOM 1:1</button></center>\n'
html_devlist2 = '<button id="devlist2" class="devlist" style="float:right;">Device Detail2</button>\n'
html_timeline = '<div id="dmesgzoombox" class="zoombox">\n<div id="{0}" class="timeline" style="height:{1}px">\n'
html_device = '<div id="{0}" title="{1}" class="thread" style="left:{2}%;top:{3}%;height:{4}%;width:{5}%;">{6}</div>\n'
html_traceevent = '<div title="{0}" class="traceevent" style="left:{1}%;top:{2}%;height:{3}%;width:{4}%;border:1px solid {5};background-color:{5}">{6}</div>\n'
html_phase = '<div class="phase" style="left:{0}%;width:{1}%;top:{2}%;height:{3}%;background-color:{4}">{5}</div>\n'
html_phaselet = '<div id="{0}" class="phaselet" style="left:{1}%;width:{2}%;background-color:{3}"></div>\n'
html_legend = '<div class="square" style="left:{0}%;background-color:{1}"> {2}</div>\n'
html_timetotal = '<table class="time1">\n<tr>'\
'<td class="green">{2} Suspend Time: <b>{0} ms</b></td>'\
'<td class="yellow">{2} Resume Time: <b>{1} ms</b></td>'\
'</tr>\n</table>\n'
html_timetotal2 = '<table class="time1">\n<tr>'\
'<td class="green">{3} Suspend Time: <b>{0} ms</b></td>'\
'<td class="gray">'+sysvals.suspendmode+' time: <b>{1} ms</b></td>'\
'<td class="yellow">{3} Resume Time: <b>{2} ms</b></td>'\
'</tr>\n</table>\n'
html_timegroups = '<table class="time2">\n<tr>'\
'<td class="green">{4}Kernel Suspend: {0} ms</td>'\
'<td class="purple">{4}Firmware Suspend: {1} ms</td>'\
'<td class="purple">{4}Firmware Resume: {2} ms</td>'\
'<td class="yellow">{4}Kernel Resume: {3} ms</td>'\
'</tr>\n</table>\n'
# device timeline
vprint('Creating Device Timeline...')
devtl = Timeline()
# Generate the header for this timeline
textnum = ['First', 'Second']
for data in testruns:
tTotal = data.end - data.start
tEnd = data.dmesg['resume_complete']['end']
if(tTotal == 0):
print('ERROR: No timeline data')
sys.exit()
if(data.tLow > 0):
low_time = '%.0f'%(data.tLow*1000)
if data.fwValid:
suspend_time = '%.0f'%((data.tSuspended-data.start)*1000 + \
(data.fwSuspend/1000000.0))
resume_time = '%.0f'%((tEnd-data.tSuspended)*1000 + \
(data.fwResume/1000000.0))
testdesc1 = 'Total'
testdesc2 = ''
if(len(testruns) > 1):
testdesc1 = testdesc2 = textnum[data.testnumber]
testdesc2 += ' '
if(data.tLow == 0):
thtml = html_timetotal.format(suspend_time, \
resume_time, testdesc1)
else:
thtml = html_timetotal2.format(suspend_time, low_time, \
resume_time, testdesc1)
devtl.html['timeline'] += thtml
sktime = '%.3f'%((data.dmesg['suspend_machine']['end'] - \
data.getStart())*1000)
sftime = '%.3f'%(data.fwSuspend / 1000000.0)
rftime = '%.3f'%(data.fwResume / 1000000.0)
rktime = '%.3f'%((data.getEnd() - \
data.dmesg['resume_machine']['start'])*1000)
devtl.html['timeline'] += html_timegroups.format(sktime, \
sftime, rftime, rktime, testdesc2)
else:
suspend_time = '%.0f'%((data.tSuspended-data.start)*1000)
resume_time = '%.0f'%((tEnd-data.tSuspended)*1000)
testdesc = 'Kernel'
if(len(testruns) > 1):
testdesc = textnum[data.testnumber]+' '+testdesc
if(data.tLow == 0):
thtml = html_timetotal.format(suspend_time, \
resume_time, testdesc)
else:
thtml = html_timetotal2.format(suspend_time, low_time, \
resume_time, testdesc)
devtl.html['timeline'] += thtml
# time scale for potentially multiple datasets
t0 = testruns[0].start
tMax = testruns[-1].end
tSuspended = testruns[-1].tSuspended
tTotal = tMax - t0
# determine the maximum number of rows we need to draw
timelinerows = 0
for data in testruns:
for phase in data.dmesg:
list = data.dmesg[phase]['list']
rows = setTimelineRows(list, list)
data.dmesg[phase]['row'] = rows
if(rows > timelinerows):
timelinerows = rows
# calculate the timeline height and create bounding box, add buttons
devtl.setRows(timelinerows + 1)
devtl.html['timeline'] += html_devlist1
if len(testruns) > 1:
devtl.html['timeline'] += html_devlist2
devtl.html['timeline'] += html_zoombox
devtl.html['timeline'] += html_timeline.format('dmesg', devtl.height)
# draw the colored boxes for each of the phases
for data in testruns:
for b in data.dmesg:
phase = data.dmesg[b]
length = phase['end']-phase['start']
left = '%.3f' % (((phase['start']-t0)*100.0)/tTotal)
width = '%.3f' % ((length*100.0)/tTotal)
devtl.html['timeline'] += html_phase.format(left, width, \
'%.3f'%devtl.scaleH, '%.3f'%(100-devtl.scaleH), \
data.dmesg[b]['color'], '')
# draw the time scale, try to make the number of labels readable
devtl.html['scale'] = createTimeScale(t0, tMax, tSuspended)
devtl.html['timeline'] += devtl.html['scale']
for data in testruns:
for b in data.dmesg:
phaselist = data.dmesg[b]['list']
for d in phaselist:
name = d
drv = ''
dev = phaselist[d]
if(d in sysvals.altdevname):
name = sysvals.altdevname[d]
if('drv' in dev and dev['drv']):
drv = ' {%s}' % dev['drv']
height = (100.0 - devtl.scaleH)/data.dmesg[b]['row']
top = '%.3f' % ((dev['row']*height) + devtl.scaleH)
left = '%.3f' % (((dev['start']-t0)*100)/tTotal)
width = '%.3f' % (((dev['end']-dev['start'])*100)/tTotal)
length = ' (%0.3f ms) ' % ((dev['end']-dev['start'])*1000)
color = 'rgba(204,204,204,0.5)'
devtl.html['timeline'] += html_device.format(dev['id'], \
d+drv+length+b, left, top, '%.3f'%height, width, name+drv)
# draw any trace events found
for data in testruns:
for b in data.dmesg:
phaselist = data.dmesg[b]['list']
for name in phaselist:
dev = phaselist[name]
if('traceevents' in dev):
vprint('Debug trace events found for device %s' % name)
vprint('%20s %20s %10s %8s' % ('action', \
'name', 'time(ms)', 'length(ms)'))
for e in dev['traceevents']:
vprint('%20s %20s %10.3f %8.3f' % (e.action, \
e.name, e.time*1000, e.length*1000))
height = (100.0 - devtl.scaleH)/data.dmesg[b]['row']
top = '%.3f' % ((dev['row']*height) + devtl.scaleH)
left = '%.3f' % (((e.time-t0)*100)/tTotal)
width = '%.3f' % (e.length*100/tTotal)
color = 'rgba(204,204,204,0.5)'
devtl.html['timeline'] += \
html_traceevent.format(e.action+' '+e.name, \
left, top, '%.3f'%height, \
width, e.color, '')
# timeline is finished
devtl.html['timeline'] += '</div>\n</div>\n'
# draw a legend which describes the phases by color
data = testruns[-1]
devtl.html['legend'] = '<div class="legend">\n'
pdelta = 100.0/len(data.phases)
pmargin = pdelta / 4.0
for phase in data.phases:
order = '%.2f' % ((data.dmesg[phase]['order'] * pdelta) + pmargin)
name = string.replace(phase, '_', ' ')
devtl.html['legend'] += html_legend.format(order, \
data.dmesg[phase]['color'], name)
devtl.html['legend'] += '</div>\n'
hf = open(sysvals.htmlfile, 'w')
thread_height = 0
# write the html header first (html head, css code, up to body start)
html_header = '<!DOCTYPE html>\n<html>\n<head>\n\
<meta http-equiv="content-type" content="text/html; charset=UTF-8">\n\
<title>AnalyzeSuspend</title>\n\
<style type=\'text/css\'>\n\
body {overflow-y: scroll;}\n\
.stamp {width: 100%;text-align:center;background-color:gray;line-height:30px;color:white;font: 25px Arial;}\n\
.callgraph {margin-top: 30px;box-shadow: 5px 5px 20px black;}\n\
.callgraph article * {padding-left: 28px;}\n\
h1 {color:black;font: bold 30px Times;}\n\
t0 {color:black;font: bold 30px Times;}\n\
t1 {color:black;font: 30px Times;}\n\
t2 {color:black;font: 25px Times;}\n\
t3 {color:black;font: 20px Times;white-space:nowrap;}\n\
t4 {color:black;font: bold 30px Times;line-height:60px;white-space:nowrap;}\n\
table {width:100%;}\n\
.gray {background-color:rgba(80,80,80,0.1);}\n\
.green {background-color:rgba(204,255,204,0.4);}\n\
.purple {background-color:rgba(128,0,128,0.2);}\n\
.yellow {background-color:rgba(255,255,204,0.4);}\n\
.time1 {font: 22px Arial;border:1px solid;}\n\
.time2 {font: 15px Arial;border-bottom:1px solid;border-left:1px solid;border-right:1px solid;}\n\
td {text-align: center;}\n\
r {color:#500000;font:15px Tahoma;}\n\
n {color:#505050;font:15px Tahoma;}\n\
.tdhl {color: red;}\n\
.hide {display: none;}\n\
.pf {display: none;}\n\
.pf:checked + label {background: url(\'data:image/svg+xml;utf,<?xml version="1.0" standalone="no"?><svg xmlns="http://www.w3.org/2000/svg" height="18" width="18" version="1.1"><circle cx="9" cy="9" r="8" stroke="black" stroke-width="1" fill="white"/><rect x="4" y="8" width="10" height="2" style="fill:black;stroke-width:0"/><rect x="8" y="4" width="2" height="10" style="fill:black;stroke-width:0"/></svg>\') no-repeat left center;}\n\
.pf:not(:checked) ~ label {background: url(\'data:image/svg+xml;utf,<?xml version="1.0" standalone="no"?><svg xmlns="http://www.w3.org/2000/svg" height="18" width="18" version="1.1"><circle cx="9" cy="9" r="8" stroke="black" stroke-width="1" fill="white"/><rect x="4" y="8" width="10" height="2" style="fill:black;stroke-width:0"/></svg>\') no-repeat left center;}\n\
.pf:checked ~ *:not(:nth-child(2)) {display: none;}\n\
.zoombox {position: relative; width: 100%; overflow-x: scroll;}\n\
.timeline {position: relative; font-size: 14px;cursor: pointer;width: 100%; overflow: hidden; background-color:#dddddd;}\n\
.thread {position: absolute; height: '+'%.3f'%thread_height+'%; overflow: hidden; line-height: 30px; border:1px solid;text-align:center;white-space:nowrap;background-color:rgba(204,204,204,0.5);}\n\
.thread:hover {background-color:white;border:1px solid red;z-index:10;}\n\
.hover {background-color:white;border:1px solid red;z-index:10;}\n\
.traceevent {position: absolute;opacity: 0.3;height: '+'%.3f'%thread_height+'%;width:0;overflow:hidden;line-height:30px;text-align:center;white-space:nowrap;}\n\
.phase {position: absolute;overflow: hidden;border:0px;text-align:center;}\n\
.phaselet {position:absolute;overflow:hidden;border:0px;text-align:center;height:100px;font-size:24px;}\n\
.t {position:absolute;top:0%;height:100%;border-right:1px solid black;}\n\
.legend {position: relative; width: 100%; height: 40px; text-align: center;margin-bottom:20px}\n\
.legend .square {position:absolute;top:10px; width: 0px;height: 20px;border:1px solid;padding-left:20px;}\n\
button {height:40px;width:200px;margin-bottom:20px;margin-top:20px;font-size:24px;}\n\
.devlist {position:'+x2changes[1]+';width:190px;}\n\
#devicedetail {height:100px;box-shadow: 5px 5px 20px black;}\n\
</style>\n</head>\n<body>\n'
hf.write(html_header)
# write the test title and general info header
if(sysvals.stamp['time'] != ""):
hf.write(headline_stamp.format(sysvals.stamp['host'],
sysvals.stamp['kernel'], sysvals.stamp['mode'], \
sysvals.stamp['time']))
# write the device timeline
hf.write(devtl.html['timeline'])
hf.write(devtl.html['legend'])
hf.write('<div id="devicedetailtitle"></div>\n')
hf.write('<div id="devicedetail" style="display:none;">\n')
# draw the colored boxes for the device detail section
for data in testruns:
hf.write('<div id="devicedetail%d">\n' % data.testnumber)
for b in data.phases:
phase = data.dmesg[b]
length = phase['end']-phase['start']
left = '%.3f' % (((phase['start']-t0)*100.0)/tTotal)
width = '%.3f' % ((length*100.0)/tTotal)
hf.write(html_phaselet.format(b, left, width, \
data.dmesg[b]['color']))
hf.write('</div>\n')
hf.write('</div>\n')
# write the ftrace data (callgraph)
data = testruns[-1]
if(sysvals.usecallgraph):
hf.write('<section id="callgraphs" class="callgraph">\n')
# write out the ftrace data converted to html
html_func_top = '<article id="{0}" class="atop" style="background-color:{1}">\n<input type="checkbox" class="pf" id="f{2}" checked/><label for="f{2}">{3} {4}</label>\n'
html_func_start = '<article>\n<input type="checkbox" class="pf" id="f{0}" checked/><label for="f{0}">{1} {2}</label>\n'
html_func_end = '</article>\n'
html_func_leaf = '<article>{0} {1}</article>\n'
num = 0
for p in data.phases:
list = data.dmesg[p]['list']
for devname in data.sortedDevices(p):
if('ftrace' not in list[devname]):
continue
name = devname
if(devname in sysvals.altdevname):
name = sysvals.altdevname[devname]
devid = list[devname]['id']
cg = list[devname]['ftrace']
flen = '<r>(%.3f ms @ %.3f to %.3f)</r>' % \
((cg.end - cg.start)*1000, cg.start*1000, cg.end*1000)
hf.write(html_func_top.format(devid, data.dmesg[p]['color'], \
num, name+' '+p, flen))
num += 1
for line in cg.list:
if(line.length < 0.000000001):
flen = ''
else:
flen = '<n>(%.3f ms @ %.3f)</n>' % (line.length*1000, \
line.time*1000)
if(line.freturn and line.fcall):
hf.write(html_func_leaf.format(line.name, flen))
elif(line.freturn):
hf.write(html_func_end)
else:
hf.write(html_func_start.format(num, line.name, flen))
num += 1
hf.write(html_func_end)
hf.write('\n\n </section>\n')
# write the footer and close
addScriptCode(hf, testruns)
hf.write('</body>\n</html>\n')
hf.close()
return True
# Function: addScriptCode
# Description:
# Adds the javascript code to the output html
# Arguments:
# hf: the open html file pointer
# testruns: array of Data objects from parseKernelLog or parseTraceLog
def addScriptCode(hf, testruns):
t0 = (testruns[0].start - testruns[-1].tSuspended) * 1000
tMax = (testruns[-1].end - testruns[-1].tSuspended) * 1000
# create an array in javascript memory with the device details
detail = ' var devtable = [];\n'
for data in testruns:
topo = data.deviceTopology()
detail += ' devtable[%d] = "%s";\n' % (data.testnumber, topo)
detail += ' var bounds = [%f,%f];\n' % (t0, tMax)
# add the code which will manipulate the data in the browser
script_code = \
'<script type="text/javascript">\n'+detail+\
' function zoomTimeline() {\n'\
' var timescale = document.getElementById("timescale");\n'\
' var dmesg = document.getElementById("dmesg");\n'\
' var zoombox = document.getElementById("dmesgzoombox");\n'\
' var val = parseFloat(dmesg.style.width);\n'\
' var newval = 100;\n'\
' var sh = window.outerWidth / 2;\n'\
' if(this.id == "zoomin") {\n'\
' newval = val * 1.2;\n'\
' if(newval > 40000) newval = 40000;\n'\
' dmesg.style.width = newval+"%";\n'\
' zoombox.scrollLeft = ((zoombox.scrollLeft + sh) * newval / val) - sh;\n'\
' } else if (this.id == "zoomout") {\n'\
' newval = val / 1.2;\n'\
' if(newval < 100) newval = 100;\n'\
' dmesg.style.width = newval+"%";\n'\
' zoombox.scrollLeft = ((zoombox.scrollLeft + sh) * newval / val) - sh;\n'\
' } else {\n'\
' zoombox.scrollLeft = 0;\n'\
' dmesg.style.width = "100%";\n'\
' }\n'\
' var html = "";\n'\
' var t0 = bounds[0];\n'\
' var tMax = bounds[1];\n'\
' var tTotal = tMax - t0;\n'\
' var wTotal = tTotal * 100.0 / newval;\n'\
' for(var tS = 1000; (wTotal / tS) < 3; tS /= 10);\n'\
' if(tS < 1) tS = 1;\n'\
' for(var s = ((t0 / tS)|0) * tS; s < tMax; s += tS) {\n'\
' var pos = (tMax - s) * 100.0 / tTotal;\n'\
' var name = (s == 0)?"S/R":(s+"ms");\n'\
' html += "<div class=\\"t\\" style=\\"right:"+pos+"%\\">"+name+"</div>";\n'\
' }\n'\
' timescale.innerHTML = html;\n'\
' }\n'\
' function deviceHover() {\n'\
' var name = this.title.slice(0, this.title.indexOf(" ("));\n'\
' var dmesg = document.getElementById("dmesg");\n'\
' var dev = dmesg.getElementsByClassName("thread");\n'\
' var cpu = -1;\n'\
' if(name.match("CPU_ON\[[0-9]*\]"))\n'\
' cpu = parseInt(name.slice(7));\n'\
' else if(name.match("CPU_OFF\[[0-9]*\]"))\n'\
' cpu = parseInt(name.slice(8));\n'\
' for (var i = 0; i < dev.length; i++) {\n'\
' dname = dev[i].title.slice(0, dev[i].title.indexOf(" ("));\n'\
' if((cpu >= 0 && dname.match("CPU_O[NF]*\\\[*"+cpu+"\\\]")) ||\n'\
' (name == dname))\n'\
' {\n'\
' dev[i].className = "thread hover";\n'\
' } else {\n'\
' dev[i].className = "thread";\n'\
' }\n'\
' }\n'\
' }\n'\
' function deviceUnhover() {\n'\
' var dmesg = document.getElementById("dmesg");\n'\
' var dev = dmesg.getElementsByClassName("thread");\n'\
' for (var i = 0; i < dev.length; i++) {\n'\
' dev[i].className = "thread";\n'\
' }\n'\
' }\n'\
' function deviceTitle(title, total, cpu) {\n'\
' var prefix = "Total";\n'\
' if(total.length > 3) {\n'\
' prefix = "Average";\n'\
' total[1] = (total[1]+total[3])/2;\n'\
' total[2] = (total[2]+total[4])/2;\n'\
' }\n'\
' var devtitle = document.getElementById("devicedetailtitle");\n'\
' var name = title.slice(0, title.indexOf(" "));\n'\
' if(cpu >= 0) name = "CPU"+cpu;\n'\
' var driver = "";\n'\
' var tS = "<t2>(</t2>";\n'\
' var tR = "<t2>)</t2>";\n'\
' if(total[1] > 0)\n'\
' tS = "<t2>("+prefix+" Suspend:</t2><t0> "+total[1].toFixed(3)+" ms</t0> ";\n'\
' if(total[2] > 0)\n'\
' tR = " <t2>"+prefix+" Resume:</t2><t0> "+total[2].toFixed(3)+" ms<t2>)</t2></t0>";\n'\
' var s = title.indexOf("{");\n'\
' var e = title.indexOf("}");\n'\
' if((s >= 0) && (e >= 0))\n'\
' driver = title.slice(s+1, e) + " <t1>@</t1> ";\n'\
' if(total[1] > 0 && total[2] > 0)\n'\
' devtitle.innerHTML = "<t0>"+driver+name+"</t0> "+tS+tR;\n'\
' else\n'\
' devtitle.innerHTML = "<t0>"+title+"</t0>";\n'\
' return name;\n'\
' }\n'\
' function deviceDetail() {\n'\
' var devinfo = document.getElementById("devicedetail");\n'\
' devinfo.style.display = "block";\n'\
' var name = this.title.slice(0, this.title.indexOf(" ("));\n'\
' var cpu = -1;\n'\
' if(name.match("CPU_ON\[[0-9]*\]"))\n'\
' cpu = parseInt(name.slice(7));\n'\
' else if(name.match("CPU_OFF\[[0-9]*\]"))\n'\
' cpu = parseInt(name.slice(8));\n'\
' var dmesg = document.getElementById("dmesg");\n'\
' var dev = dmesg.getElementsByClassName("thread");\n'\
' var idlist = [];\n'\
' var pdata = [[]];\n'\
' var pd = pdata[0];\n'\
' var total = [0.0, 0.0, 0.0];\n'\
' for (var i = 0; i < dev.length; i++) {\n'\
' dname = dev[i].title.slice(0, dev[i].title.indexOf(" ("));\n'\
' if((cpu >= 0 && dname.match("CPU_O[NF]*\\\[*"+cpu+"\\\]")) ||\n'\
' (name == dname))\n'\
' {\n'\
' idlist[idlist.length] = dev[i].id;\n'\
' var tidx = 1;\n'\
' if(dev[i].id[0] == "a") {\n'\
' pd = pdata[0];\n'\
' } else {\n'\
' if(pdata.length == 1) pdata[1] = [];\n'\
' if(total.length == 3) total[3]=total[4]=0.0;\n'\
' pd = pdata[1];\n'\
' tidx = 3;\n'\
' }\n'\
' var info = dev[i].title.split(" ");\n'\
' var pname = info[info.length-1];\n'\
' pd[pname] = parseFloat(info[info.length-3].slice(1));\n'\
' total[0] += pd[pname];\n'\
' if(pname.indexOf("suspend") >= 0)\n'\
' total[tidx] += pd[pname];\n'\
' else\n'\
' total[tidx+1] += pd[pname];\n'\
' }\n'\
' }\n'\
' var devname = deviceTitle(this.title, total, cpu);\n'\
' var left = 0.0;\n'\
' for (var t = 0; t < pdata.length; t++) {\n'\
' pd = pdata[t];\n'\
' devinfo = document.getElementById("devicedetail"+t);\n'\
' var phases = devinfo.getElementsByClassName("phaselet");\n'\
' for (var i = 0; i < phases.length; i++) {\n'\
' if(phases[i].id in pd) {\n'\
' var w = 100.0*pd[phases[i].id]/total[0];\n'\
' var fs = 32;\n'\
' if(w < 8) fs = 4*w | 0;\n'\
' var fs2 = fs*3/4;\n'\
' phases[i].style.width = w+"%";\n'\
' phases[i].style.left = left+"%";\n'\
' phases[i].title = phases[i].id+" "+pd[phases[i].id]+" ms";\n'\
' left += w;\n'\
' var time = "<t4 style=\\"font-size:"+fs+"px\\">"+pd[phases[i].id]+" ms<br></t4>";\n'\
' var pname = "<t3 style=\\"font-size:"+fs2+"px\\">"+phases[i].id.replace("_", " ")+"</t3>";\n'\
' phases[i].innerHTML = time+pname;\n'\
' } else {\n'\
' phases[i].style.width = "0%";\n'\
' phases[i].style.left = left+"%";\n'\
' }\n'\
' }\n'\
' }\n'\
' var cglist = document.getElementById("callgraphs");\n'\
' if(!cglist) return;\n'\
' var cg = cglist.getElementsByClassName("atop");\n'\
' for (var i = 0; i < cg.length; i++) {\n'\
' if(idlist.indexOf(cg[i].id) >= 0) {\n'\
' cg[i].style.display = "block";\n'\
' } else {\n'\
' cg[i].style.display = "none";\n'\
' }\n'\
' }\n'\
' }\n'\
' function devListWindow(e) {\n'\
' var sx = e.clientX;\n'\
' if(sx > window.innerWidth - 440)\n'\
' sx = window.innerWidth - 440;\n'\
' var cfg="top="+e.screenY+", left="+sx+", width=440, height=720, scrollbars=yes";\n'\
' var win = window.open("", "_blank", cfg);\n'\
' if(window.chrome) win.moveBy(sx, 0);\n'\
' var html = "<title>"+e.target.innerHTML+"</title>"+\n'\
' "<style type=\\"text/css\\">"+\n'\
' " ul {list-style-type:circle;padding-left:10px;margin-left:10px;}"+\n'\
' "</style>"\n'\
' var dt = devtable[0];\n'\
' if(e.target.id != "devlist1")\n'\
' dt = devtable[1];\n'\
' win.document.write(html+dt);\n'\
' }\n'\
' window.addEventListener("load", function () {\n'\
' var dmesg = document.getElementById("dmesg");\n'\
' dmesg.style.width = "100%"\n'\
' document.getElementById("zoomin").onclick = zoomTimeline;\n'\
' document.getElementById("zoomout").onclick = zoomTimeline;\n'\
' document.getElementById("zoomdef").onclick = zoomTimeline;\n'\
' var devlist = document.getElementsByClassName("devlist");\n'\
' for (var i = 0; i < devlist.length; i++)\n'\
' devlist[i].onclick = devListWindow;\n'\
' var dev = dmesg.getElementsByClassName("thread");\n'\
' for (var i = 0; i < dev.length; i++) {\n'\
' dev[i].onclick = deviceDetail;\n'\
' dev[i].onmouseover = deviceHover;\n'\
' dev[i].onmouseout = deviceUnhover;\n'\
' }\n'\
' zoomTimeline();\n'\
' });\n'\
'</script>\n'
hf.write(script_code);
# Function: executeSuspend
# Description:
# Execute system suspend through the sysfs interface, then copy the output
# dmesg and ftrace files to the test output directory.
def executeSuspend():
global sysvals
detectUSB(False)
t0 = time.time()*1000
tp = sysvals.tpath
# execute however many s/r runs requested
for count in range(1,sysvals.execcount+1):
# clear the kernel ring buffer just as we start
os.system('dmesg -C')
# enable callgraph ftrace only for the second run
if(sysvals.usecallgraph and count == 2):
# set trace type
os.system('echo function_graph > '+tp+'current_tracer')
os.system('echo "" > '+tp+'set_ftrace_filter')
# set trace format options
os.system('echo funcgraph-abstime > '+tp+'trace_options')
os.system('echo funcgraph-proc > '+tp+'trace_options')
# focus only on device suspend and resume
os.system('cat '+tp+'available_filter_functions | '+\
'grep dpm_run_callback > '+tp+'set_graph_function')
# if this is test2 and there's a delay, start here
if(count > 1 and sysvals.x2delay > 0):
tN = time.time()*1000
while (tN - t0) < sysvals.x2delay:
tN = time.time()*1000
time.sleep(0.001)
# start ftrace
if(sysvals.usecallgraph or sysvals.usetraceevents):
print('START TRACING')
os.system('echo 1 > '+tp+'tracing_on')
# initiate suspend
if(sysvals.usecallgraph or sysvals.usetraceevents):
os.system('echo SUSPEND START > '+tp+'trace_marker')
if(sysvals.rtcwake):
print('SUSPEND START')
print('will autoresume in %d seconds' % sysvals.rtcwaketime)
sysvals.rtcWakeAlarm()
else:
print('SUSPEND START (press a key to resume)')
pf = open(sysvals.powerfile, 'w')
pf.write(sysvals.suspendmode)
# execution will pause here
pf.close()
t0 = time.time()*1000
# return from suspend
print('RESUME COMPLETE')
if(sysvals.usecallgraph or sysvals.usetraceevents):
os.system('echo RESUME COMPLETE > '+tp+'trace_marker')
# see if there's firmware timing data to be had
t = sysvals.postresumetime
if(t > 0):
print('Waiting %d seconds for POST-RESUME trace events...' % t)
time.sleep(t)
# stop ftrace
if(sysvals.usecallgraph or sysvals.usetraceevents):
os.system('echo 0 > '+tp+'tracing_on')
print('CAPTURING TRACE')
writeDatafileHeader(sysvals.ftracefile)
os.system('cat '+tp+'trace >> '+sysvals.ftracefile)
os.system('echo "" > '+tp+'trace')
# grab a copy of the dmesg output
print('CAPTURING DMESG')
writeDatafileHeader(sysvals.dmesgfile)
os.system('dmesg -c >> '+sysvals.dmesgfile)
def writeDatafileHeader(filename):
global sysvals
fw = getFPDT(False)
prt = sysvals.postresumetime
fp = open(filename, 'a')
fp.write(sysvals.teststamp+'\n')
if(fw):
fp.write('# fwsuspend %u fwresume %u\n' % (fw[0], fw[1]))
if(prt > 0):
fp.write('# post resume time %u\n' % prt)
fp.close()
# Function: executeAndroidSuspend
# Description:
# Execute system suspend through the sysfs interface
# on a remote android device, then transfer the output
# dmesg and ftrace files to the local output directory.
def executeAndroidSuspend():
global sysvals
# check to see if the display is currently off
tp = sysvals.tpath
out = os.popen(sysvals.adb+\
' shell dumpsys power | grep mScreenOn').read().strip()
# if so we need to turn it on so we can issue a new suspend
if(out.endswith('false')):
print('Waking the device up for the test...')
# send the KEYPAD_POWER keyevent to wake it up
os.system(sysvals.adb+' shell input keyevent 26')
# wait a few seconds so the user can see the device wake up
time.sleep(3)
# execute however many s/r runs requested
for count in range(1,sysvals.execcount+1):
# clear the kernel ring buffer just as we start
os.system(sysvals.adb+' shell dmesg -c > /dev/null 2>&1')
# start ftrace
if(sysvals.usetraceevents):
print('START TRACING')
os.system(sysvals.adb+" shell 'echo 1 > "+tp+"tracing_on'")
# initiate suspend
for count in range(1,sysvals.execcount+1):
if(sysvals.usetraceevents):
os.system(sysvals.adb+\
" shell 'echo SUSPEND START > "+tp+"trace_marker'")
print('SUSPEND START (press a key on the device to resume)')
os.system(sysvals.adb+" shell 'echo "+sysvals.suspendmode+\
" > "+sysvals.powerfile+"'")
# execution will pause here, then adb will exit
while(True):
check = os.popen(sysvals.adb+\
' shell pwd 2>/dev/null').read().strip()
if(len(check) > 0):
break
time.sleep(1)
if(sysvals.usetraceevents):
os.system(sysvals.adb+" shell 'echo RESUME COMPLETE > "+tp+\
"trace_marker'")
# return from suspend
print('RESUME COMPLETE')
# stop ftrace
if(sysvals.usetraceevents):
os.system(sysvals.adb+" shell 'echo 0 > "+tp+"tracing_on'")
print('CAPTURING TRACE')
os.system('echo "'+sysvals.teststamp+'" > '+sysvals.ftracefile)
os.system(sysvals.adb+' shell cat '+tp+\
'trace >> '+sysvals.ftracefile)
# grab a copy of the dmesg output
print('CAPTURING DMESG')
os.system('echo "'+sysvals.teststamp+'" > '+sysvals.dmesgfile)
os.system(sysvals.adb+' shell dmesg >> '+sysvals.dmesgfile)
# Function: setUSBDevicesAuto
# Description:
# Set the autosuspend control parameter of all USB devices to auto
# This can be dangerous, so use at your own risk, most devices are set
# to always-on since the kernel cant determine if the device can
# properly autosuspend
def setUSBDevicesAuto():
global sysvals
rootCheck()
for dirname, dirnames, filenames in os.walk('/sys/devices'):
if(re.match('.*/usb[0-9]*.*', dirname) and
'idVendor' in filenames and 'idProduct' in filenames):
os.system('echo auto > %s/power/control' % dirname)
name = dirname.split('/')[-1]
desc = os.popen('cat %s/product 2>/dev/null' % \
dirname).read().replace('\n', '')
ctrl = os.popen('cat %s/power/control 2>/dev/null' % \
dirname).read().replace('\n', '')
print('control is %s for %6s: %s' % (ctrl, name, desc))
# Function: yesno
# Description:
# Print out an equivalent Y or N for a set of known parameter values
# Output:
# 'Y', 'N', or ' ' if the value is unknown
def yesno(val):
yesvals = ['auto', 'enabled', 'active', '1']
novals = ['on', 'disabled', 'suspended', 'forbidden', 'unsupported']
if val in yesvals:
return 'Y'
elif val in novals:
return 'N'
return ' '
# Function: ms2nice
# Description:
# Print out a very concise time string in minutes and seconds
# Output:
# The time string, e.g. "1901m16s"
def ms2nice(val):
ms = 0
try:
ms = int(val)
except:
return 0.0
m = ms / 60000
s = (ms / 1000) - (m * 60)
return '%3dm%2ds' % (m, s)
# Function: detectUSB
# Description:
# Detect all the USB hosts and devices currently connected and add
# a list of USB device names to sysvals for better timeline readability
# Arguments:
# output: True to output the info to stdout, False otherwise
def detectUSB(output):
global sysvals
field = {'idVendor':'', 'idProduct':'', 'product':'', 'speed':''}
power = {'async':'', 'autosuspend':'', 'autosuspend_delay_ms':'',
'control':'', 'persist':'', 'runtime_enabled':'',
'runtime_status':'', 'runtime_usage':'',
'runtime_active_time':'',
'runtime_suspended_time':'',
'active_duration':'',
'connected_duration':''}
if(output):
print('LEGEND')
print('---------------------------------------------------------------------------------------------')
print(' A = async/sync PM queue Y/N D = autosuspend delay (seconds)')
print(' S = autosuspend Y/N rACTIVE = runtime active (min/sec)')
print(' P = persist across suspend Y/N rSUSPEN = runtime suspend (min/sec)')
print(' E = runtime suspend enabled/forbidden Y/N ACTIVE = active duration (min/sec)')
print(' R = runtime status active/suspended Y/N CONNECT = connected duration (min/sec)')
print(' U = runtime usage count')
print('---------------------------------------------------------------------------------------------')
print(' NAME ID DESCRIPTION SPEED A S P E R U D rACTIVE rSUSPEN ACTIVE CONNECT')
print('---------------------------------------------------------------------------------------------')
for dirname, dirnames, filenames in os.walk('/sys/devices'):
if(re.match('.*/usb[0-9]*.*', dirname) and
'idVendor' in filenames and 'idProduct' in filenames):
for i in field:
field[i] = os.popen('cat %s/%s 2>/dev/null' % \
(dirname, i)).read().replace('\n', '')
name = dirname.split('/')[-1]
if(len(field['product']) > 0):
sysvals.altdevname[name] = \
'%s [%s]' % (field['product'], name)
else:
sysvals.altdevname[name] = \
'%s:%s [%s]' % (field['idVendor'], \
field['idProduct'], name)
if(output):
for i in power:
power[i] = os.popen('cat %s/power/%s 2>/dev/null' % \
(dirname, i)).read().replace('\n', '')
if(re.match('usb[0-9]*', name)):
first = '%-8s' % name
else:
first = '%8s' % name
print('%s [%s:%s] %-20s %-4s %1s %1s %1s %1s %1s %1s %1s %s %s %s %s' % \
(first, field['idVendor'], field['idProduct'], \
field['product'][0:20], field['speed'], \
yesno(power['async']), \
yesno(power['control']), \
yesno(power['persist']), \
yesno(power['runtime_enabled']), \
yesno(power['runtime_status']), \
power['runtime_usage'], \
power['autosuspend'], \
ms2nice(power['runtime_active_time']), \
ms2nice(power['runtime_suspended_time']), \
ms2nice(power['active_duration']), \
ms2nice(power['connected_duration'])))
# Function: getModes
# Description:
# Determine the supported power modes on this system
# Output:
# A string list of the available modes
def getModes():
global sysvals
modes = ''
if(not sysvals.android):
if(os.path.exists(sysvals.powerfile)):
fp = open(sysvals.powerfile, 'r')
modes = string.split(fp.read())
fp.close()
else:
line = os.popen(sysvals.adb+' shell cat '+\
sysvals.powerfile).read().strip()
modes = string.split(line)
return modes
# Function: getFPDT
# Description:
# Read the acpi bios tables and pull out FPDT, the firmware data
# Arguments:
# output: True to output the info to stdout, False otherwise
def getFPDT(output):
global sysvals
rectype = {}
rectype[0] = 'Firmware Basic Boot Performance Record'
rectype[1] = 'S3 Performance Table Record'
prectype = {}
prectype[0] = 'Basic S3 Resume Performance Record'
prectype[1] = 'Basic S3 Suspend Performance Record'
rootCheck()
if(not os.path.exists(sysvals.fpdtpath)):
if(output):
doError('file doesnt exist: %s' % sysvals.fpdtpath, False)
return False
if(not os.access(sysvals.fpdtpath, os.R_OK)):
if(output):
doError('file isnt readable: %s' % sysvals.fpdtpath, False)
return False
if(not os.path.exists(sysvals.mempath)):
if(output):
doError('file doesnt exist: %s' % sysvals.mempath, False)
return False
if(not os.access(sysvals.mempath, os.R_OK)):
if(output):
doError('file isnt readable: %s' % sysvals.mempath, False)
return False
fp = open(sysvals.fpdtpath, 'rb')
buf = fp.read()
fp.close()
if(len(buf) < 36):
if(output):
doError('Invalid FPDT table data, should '+\
'be at least 36 bytes', False)
return False
table = struct.unpack('4sIBB6s8sI4sI', buf[0:36])
if(output):
print('')
print('Firmware Performance Data Table (%s)' % table[0])
print(' Signature : %s' % table[0])
print(' Table Length : %u' % table[1])
print(' Revision : %u' % table[2])
print(' Checksum : 0x%x' % table[3])
print(' OEM ID : %s' % table[4])
print(' OEM Table ID : %s' % table[5])
print(' OEM Revision : %u' % table[6])
print(' Creator ID : %s' % table[7])
print(' Creator Revision : 0x%x' % table[8])
print('')
if(table[0] != 'FPDT'):
if(output):
doError('Invalid FPDT table')
return False
if(len(buf) <= 36):
return False
i = 0
fwData = [0, 0]
records = buf[36:]
fp = open(sysvals.mempath, 'rb')
while(i < len(records)):
header = struct.unpack('HBB', records[i:i+4])
if(header[0] not in rectype):
continue
if(header[1] != 16):
continue
addr = struct.unpack('Q', records[i+8:i+16])[0]
try:
fp.seek(addr)
first = fp.read(8)
except:
doError('Bad address 0x%x in %s' % (addr, sysvals.mempath), False)
rechead = struct.unpack('4sI', first)
recdata = fp.read(rechead[1]-8)
if(rechead[0] == 'FBPT'):
record = struct.unpack('HBBIQQQQQ', recdata)
if(output):
print('%s (%s)' % (rectype[header[0]], rechead[0]))
print(' Reset END : %u ns' % record[4])
print(' OS Loader LoadImage Start : %u ns' % record[5])
print(' OS Loader StartImage Start : %u ns' % record[6])
print(' ExitBootServices Entry : %u ns' % record[7])
print(' ExitBootServices Exit : %u ns' % record[8])
elif(rechead[0] == 'S3PT'):
if(output):
print('%s (%s)' % (rectype[header[0]], rechead[0]))
j = 0
while(j < len(recdata)):
prechead = struct.unpack('HBB', recdata[j:j+4])
if(prechead[0] not in prectype):
continue
if(prechead[0] == 0):
record = struct.unpack('IIQQ', recdata[j:j+prechead[1]])
fwData[1] = record[2]
if(output):
print(' %s' % prectype[prechead[0]])
print(' Resume Count : %u' % \
record[1])
print(' FullResume : %u ns' % \
record[2])
print(' AverageResume : %u ns' % \
record[3])
elif(prechead[0] == 1):
record = struct.unpack('QQ', recdata[j+4:j+prechead[1]])
fwData[0] = record[1] - record[0]
if(output):
print(' %s' % prectype[prechead[0]])
print(' SuspendStart : %u ns' % \
record[0])
print(' SuspendEnd : %u ns' % \
record[1])
print(' SuspendTime : %u ns' % \
fwData[0])
j += prechead[1]
if(output):
print('')
i += header[1]
fp.close()
return fwData
# Function: statusCheck
# Description:
# Verify that the requested command and options will work, and
# print the results to the terminal
# Output:
# True if the test will work, False if not
def statusCheck():
global sysvals
status = True
if(sysvals.android):
print('Checking the android system ...')
else:
print('Checking this system (%s)...' % platform.node())
# check if adb is connected to a device
if(sysvals.android):
res = 'NO'
out = os.popen(sysvals.adb+' get-state').read().strip()
if(out == 'device'):
res = 'YES'
print(' is android device connected: %s' % res)
if(res != 'YES'):
print(' Please connect the device before using this tool')
return False
# check we have root access
res = 'NO (No features of this tool will work!)'
if(sysvals.android):
out = os.popen(sysvals.adb+' shell id').read().strip()
if('root' in out):
res = 'YES'
else:
if(os.environ['USER'] == 'root'):
res = 'YES'
print(' have root access: %s' % res)
if(res != 'YES'):
if(sysvals.android):
print(' Try running "adb root" to restart the daemon as root')
else:
print(' Try running this script with sudo')
return False
# check sysfs is mounted
res = 'NO (No features of this tool will work!)'
if(sysvals.android):
out = os.popen(sysvals.adb+' shell ls '+\
sysvals.powerfile).read().strip()
if(out == sysvals.powerfile):
res = 'YES'
else:
if(os.path.exists(sysvals.powerfile)):
res = 'YES'
print(' is sysfs mounted: %s' % res)
if(res != 'YES'):
return False
# check target mode is a valid mode
res = 'NO'
modes = getModes()
if(sysvals.suspendmode in modes):
res = 'YES'
else:
status = False
print(' is "%s" a valid power mode: %s' % (sysvals.suspendmode, res))
if(res == 'NO'):
print(' valid power modes are: %s' % modes)
print(' please choose one with -m')
# check if the tool can unlock the device
if(sysvals.android):
res = 'YES'
out1 = os.popen(sysvals.adb+\
' shell dumpsys power | grep mScreenOn').read().strip()
out2 = os.popen(sysvals.adb+\
' shell input').read().strip()
if(not out1.startswith('mScreenOn') or not out2.startswith('usage')):
res = 'NO (wake the android device up before running the test)'
print(' can I unlock the screen: %s' % res)
# check if ftrace is available
res = 'NO'
ftgood = verifyFtrace()
if(ftgood):
res = 'YES'
elif(sysvals.usecallgraph):
status = False
print(' is ftrace supported: %s' % res)
# what data source are we using
res = 'DMESG'
if(ftgood):
sysvals.usetraceeventsonly = True
sysvals.usetraceevents = False
for e in sysvals.traceevents:
check = False
if(sysvals.android):
out = os.popen(sysvals.adb+' shell ls -d '+\
sysvals.epath+e).read().strip()
if(out == sysvals.epath+e):
check = True
else:
if(os.path.exists(sysvals.epath+e)):
check = True
if(not check):
sysvals.usetraceeventsonly = False
if(e == 'suspend_resume' and check):
sysvals.usetraceevents = True
if(sysvals.usetraceevents and sysvals.usetraceeventsonly):
res = 'FTRACE (all trace events found)'
elif(sysvals.usetraceevents):
res = 'DMESG and FTRACE (suspend_resume trace event found)'
print(' timeline data source: %s' % res)
# check if rtcwake
res = 'NO'
if(sysvals.rtcpath != ''):
res = 'YES'
elif(sysvals.rtcwake):
status = False
print(' is rtcwake supported: %s' % res)
return status
# Function: doError
# Description:
# generic error function for catastrphic failures
# Arguments:
# msg: the error message to print
# help: True if printHelp should be called after, False otherwise
def doError(msg, help):
if(help == True):
printHelp()
print('ERROR: %s\n') % msg
sys.exit()
# Function: doWarning
# Description:
# generic warning function for non-catastrophic anomalies
# Arguments:
# msg: the warning message to print
# file: If not empty, a filename to request be sent to the owner for debug
def doWarning(msg, file):
print('/* %s */') % msg
if(file):
print('/* For a fix, please send this'+\
' %s file to <[email protected]> */' % file)
# Function: rootCheck
# Description:
# quick check to see if we have root access
def rootCheck():
if(os.environ['USER'] != 'root'):
doError('This script must be run as root', False)
# Function: getArgInt
# Description:
# pull out an integer argument from the command line with checks
def getArgInt(name, args, min, max):
try:
arg = args.next()
except:
doError(name+': no argument supplied', True)
try:
val = int(arg)
except:
doError(name+': non-integer value given', True)
if(val < min or val > max):
doError(name+': value should be between %d and %d' % (min, max), True)
return val
# Function: rerunTest
# Description:
# generate an output from an existing set of ftrace/dmesg logs
def rerunTest():
global sysvals
if(sysvals.ftracefile != ''):
doesTraceLogHaveTraceEvents()
if(sysvals.dmesgfile == '' and not sysvals.usetraceeventsonly):
doError('recreating this html output '+\
'requires a dmesg file', False)
sysvals.setOutputFile()
vprint('Output file: %s' % sysvals.htmlfile)
print('PROCESSING DATA')
if(sysvals.usetraceeventsonly):
testruns = parseTraceLog()
else:
testruns = loadKernelLog()
for data in testruns:
parseKernelLog(data)
if(sysvals.ftracefile != ''):
appendIncompleteTraceLog(testruns)
createHTML(testruns)
# Function: runTest
# Description:
# execute a suspend/resume, gather the logs, and generate the output
def runTest(subdir):
global sysvals
# prepare for the test
if(not sysvals.android):
initFtrace()
else:
initFtraceAndroid()
sysvals.initTestOutput(subdir)
vprint('Output files:\n %s' % sysvals.dmesgfile)
if(sysvals.usecallgraph or
sysvals.usetraceevents or
sysvals.usetraceeventsonly):
vprint(' %s' % sysvals.ftracefile)
vprint(' %s' % sysvals.htmlfile)
# execute the test
if(not sysvals.android):
executeSuspend()
else:
executeAndroidSuspend()
# analyze the data and create the html output
print('PROCESSING DATA')
if(sysvals.usetraceeventsonly):
# data for kernels 3.15 or newer is entirely in ftrace
testruns = parseTraceLog()
else:
# data for kernels older than 3.15 is primarily in dmesg
testruns = loadKernelLog()
for data in testruns:
parseKernelLog(data)
if(sysvals.usecallgraph or sysvals.usetraceevents):
appendIncompleteTraceLog(testruns)
createHTML(testruns)
# Function: runSummary
# Description:
# create a summary of tests in a sub-directory
def runSummary(subdir, output):
global sysvals
# get a list of ftrace output files
files = []
for dirname, dirnames, filenames in os.walk(subdir):
for filename in filenames:
if(re.match('.*_ftrace.txt', filename)):
files.append("%s/%s" % (dirname, filename))
# process the files in order and get an array of data objects
testruns = []
for file in sorted(files):
if output:
print("Test found in %s" % os.path.dirname(file))
sysvals.ftracefile = file
sysvals.dmesgfile = file.replace('_ftrace.txt', '_dmesg.txt')
doesTraceLogHaveTraceEvents()
sysvals.usecallgraph = False
if not sysvals.usetraceeventsonly:
if(not os.path.exists(sysvals.dmesgfile)):
print("Skipping %s: not a valid test input" % file)
continue
else:
if output:
f = os.path.basename(sysvals.ftracefile)
d = os.path.basename(sysvals.dmesgfile)
print("\tInput files: %s and %s" % (f, d))
testdata = loadKernelLog()
data = testdata[0]
parseKernelLog(data)
testdata = [data]
appendIncompleteTraceLog(testdata)
else:
if output:
print("\tInput file: %s" % os.path.basename(sysvals.ftracefile))
testdata = parseTraceLog()
data = testdata[0]
data.normalizeTime(data.tSuspended)
link = file.replace(subdir+'/', '').replace('_ftrace.txt', '.html')
data.outfile = link
testruns.append(data)
createHTMLSummarySimple(testruns, subdir+'/summary.html')
# Function: printHelp
# Description:
# print out the help text
def printHelp():
global sysvals
modes = getModes()
print('')
print('AnalyzeSuspend v%.1f' % sysvals.version)
print('Usage: sudo analyze_suspend.py <options>')
print('')
print('Description:')
print(' This tool is designed to assist kernel and OS developers in optimizing')
print(' their linux stack\'s suspend/resume time. Using a kernel image built')
print(' with a few extra options enabled, the tool will execute a suspend and')
print(' capture dmesg and ftrace data until resume is complete. This data is')
print(' transformed into a device timeline and an optional callgraph to give')
print(' a detailed view of which devices/subsystems are taking the most')
print(' time in suspend/resume.')
print('')
print(' Generates output files in subdirectory: suspend-mmddyy-HHMMSS')
print(' HTML output: <hostname>_<mode>.html')
print(' raw dmesg output: <hostname>_<mode>_dmesg.txt')
print(' raw ftrace output: <hostname>_<mode>_ftrace.txt')
print('')
print('Options:')
print(' [general]')
print(' -h Print this help text')
print(' -v Print the current tool version')
print(' -verbose Print extra information during execution and analysis')
print(' -status Test to see if the system is enabled to run this tool')
print(' -modes List available suspend modes')
print(' -m mode Mode to initiate for suspend %s (default: %s)') % (modes, sysvals.suspendmode)
print(' -rtcwake t Use rtcwake to autoresume after <t> seconds (default: disabled)')
print(' [advanced]')
print(' -f Use ftrace to create device callgraphs (default: disabled)')
print(' -filter "d1 d2 ..." Filter out all but this list of dev names')
print(' -x2 Run two suspend/resumes back to back (default: disabled)')
print(' -x2delay t Minimum millisecond delay <t> between the two test runs (default: 0 ms)')
print(' -postres t Time after resume completion to wait for post-resume events (default: 0 S)')
print(' -multi n d Execute <n> consecutive tests at <d> seconds intervals. The outputs will')
print(' be created in a new subdirectory with a summary page.')
print(' [utilities]')
print(' -fpdt Print out the contents of the ACPI Firmware Performance Data Table')
print(' -usbtopo Print out the current USB topology with power info')
print(' -usbauto Enable autosuspend for all connected USB devices')
print(' [android testing]')
print(' -adb binary Use the given adb binary to run the test on an android device.')
print(' The device should already be connected and with root access.')
print(' Commands will be executed on the device using "adb shell"')
print(' [re-analyze data from previous runs]')
print(' -ftrace ftracefile Create HTML output using ftrace input')
print(' -dmesg dmesgfile Create HTML output using dmesg (not needed for kernel >= 3.15)')
print(' -summary directory Create a summary of all test in this dir')
print('')
return True
# ----------------- MAIN --------------------
# exec start (skipped if script is loaded as library)
if __name__ == '__main__':
cmd = ''
cmdarg = ''
multitest = {'run': False, 'count': 0, 'delay': 0}
# loop through the command line arguments
args = iter(sys.argv[1:])
for arg in args:
if(arg == '-m'):
try:
val = args.next()
except:
doError('No mode supplied', True)
sysvals.suspendmode = val
elif(arg == '-adb'):
try:
val = args.next()
except:
doError('No adb binary supplied', True)
if(not os.path.exists(val)):
doError('file doesnt exist: %s' % val, False)
if(not os.access(val, os.X_OK)):
doError('file isnt executable: %s' % val, False)
try:
check = os.popen(val+' version').read().strip()
except:
doError('adb version failed to execute', False)
if(not re.match('Android Debug Bridge .*', check)):
doError('adb version failed to execute', False)
sysvals.adb = val
sysvals.android = True
elif(arg == '-x2'):
if(sysvals.postresumetime > 0):
doError('-x2 is not compatible with -postres', False)
sysvals.execcount = 2
elif(arg == '-x2delay'):
sysvals.x2delay = getArgInt('-x2delay', args, 0, 60000)
elif(arg == '-postres'):
if(sysvals.execcount != 1):
doError('-x2 is not compatible with -postres', False)
sysvals.postresumetime = getArgInt('-postres', args, 0, 3600)
elif(arg == '-f'):
sysvals.usecallgraph = True
elif(arg == '-modes'):
cmd = 'modes'
elif(arg == '-fpdt'):
cmd = 'fpdt'
elif(arg == '-usbtopo'):
cmd = 'usbtopo'
elif(arg == '-usbauto'):
cmd = 'usbauto'
elif(arg == '-status'):
cmd = 'status'
elif(arg == '-verbose'):
sysvals.verbose = True
elif(arg == '-v'):
print("Version %.1f" % sysvals.version)
sys.exit()
elif(arg == '-rtcwake'):
sysvals.rtcwake = True
sysvals.rtcwaketime = getArgInt('-rtcwake', args, 0, 3600)
elif(arg == '-multi'):
multitest['run'] = True
multitest['count'] = getArgInt('-multi n (exec count)', args, 2, 1000000)
multitest['delay'] = getArgInt('-multi d (delay between tests)', args, 0, 3600)
elif(arg == '-dmesg'):
try:
val = args.next()
except:
doError('No dmesg file supplied', True)
sysvals.notestrun = True
sysvals.dmesgfile = val
if(os.path.exists(sysvals.dmesgfile) == False):
doError('%s doesnt exist' % sysvals.dmesgfile, False)
elif(arg == '-ftrace'):
try:
val = args.next()
except:
doError('No ftrace file supplied', True)
sysvals.notestrun = True
sysvals.usecallgraph = True
sysvals.ftracefile = val
if(os.path.exists(sysvals.ftracefile) == False):
doError('%s doesnt exist' % sysvals.ftracefile, False)
elif(arg == '-summary'):
try:
val = args.next()
except:
doError('No directory supplied', True)
cmd = 'summary'
cmdarg = val
sysvals.notestrun = True
if(os.path.isdir(val) == False):
doError('%s isnt accesible' % val, False)
elif(arg == '-filter'):
try:
val = args.next()
except:
doError('No devnames supplied', True)
sysvals.setDeviceFilter(val)
elif(arg == '-h'):
printHelp()
sys.exit()
else:
doError('Invalid argument: '+arg, True)
# just run a utility command and exit
if(cmd != ''):
if(cmd == 'status'):
statusCheck()
elif(cmd == 'fpdt'):
if(sysvals.android):
doError('cannot read FPDT on android device', False)
getFPDT(True)
elif(cmd == 'usbtopo'):
if(sysvals.android):
doError('cannot read USB topology '+\
'on an android device', False)
detectUSB(True)
elif(cmd == 'modes'):
modes = getModes()
print modes
elif(cmd == 'usbauto'):
setUSBDevicesAuto()
elif(cmd == 'summary'):
print("Generating a summary of folder \"%s\"" % cmdarg)
runSummary(cmdarg, True)
sys.exit()
# run test on android device
if(sysvals.android):
if(sysvals.usecallgraph):
doError('ftrace (-f) is not yet supported '+\
'in the android kernel', False)
if(sysvals.notestrun):
doError('cannot analyze test files on the '+\
'android device', False)
# if instructed, re-analyze existing data files
if(sysvals.notestrun):
rerunTest()
sys.exit()
# verify that we can run a test
if(not statusCheck()):
print('Check FAILED, aborting the test run!')
sys.exit()
if multitest['run']:
# run multiple tests in a separte subdirectory
s = 'x%d' % multitest['count']
subdir = datetime.now().strftime('suspend-'+s+'-%m%d%y-%H%M%S')
os.mkdir(subdir)
for i in range(multitest['count']):
if(i != 0):
print('Waiting %d seconds...' % (multitest['delay']))
time.sleep(multitest['delay'])
print('TEST (%d/%d) START' % (i+1, multitest['count']))
runTest(subdir)
print('TEST (%d/%d) COMPLETE' % (i+1, multitest['count']))
runSummary(subdir, False)
else:
# run the test in the current directory
runTest(".")
|
gpl-2.0
|
RafaelTorrealba/odoo
|
addons/hr_timesheet_invoice/wizard/__init__.py
|
433
|
1159
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import hr_timesheet_invoice_create
import hr_timesheet_analytic_profit
import hr_timesheet_final_invoice_create
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
agpl-3.0
|
t794104/ansible
|
lib/ansible/plugins/doc_fragments/opennebula.py
|
44
|
1422
|
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, www.privaz.io Valletech AB
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
class ModuleDocFragment(object):
# OpenNebula common documentation
DOCUMENTATION = r'''
options:
api_url:
description:
- The ENDPOINT URL of the XMLRPC server.
- If not specified then the value of the ONE_URL environment variable, if any, is used.
type: str
aliases:
- api_endpoint
api_username:
description:
- The name of the user for XMLRPC authentication.
- If not specified then the value of the ONE_USERNAME environment variable, if any, is used.
type: str
api_password:
description:
- The password or token for XMLRPC authentication.
- If not specified then the value of the ONE_PASSWORD environment variable, if any, is used.
type: str
aliases:
- api_token
validate_certs:
description:
- Whether to validate the SSL certificates or not.
- This parameter is ignored if PYTHONHTTPSVERIFY environment variable is used.
type: bool
default: yes
wait_timeout:
description:
- Time to wait for the desired state to be reached before timeout, in seconds.
type: int
default: 300
'''
|
gpl-3.0
|
luizcieslak/AlGDock
|
Example/test_python.py
|
2
|
1452
|
import AlGDock.BindingPMF_plots
import os, shutil, glob
for run_type in ['cool','dock','postprocess','free_energies']:
self = AlGDock.BindingPMF_plots.BPMF_plots(\
dir_dock='dock', dir_cool='cool',\
ligand_tarball='prmtopcrd/ligand.tar.gz', \
ligand_database='ligand.db', \
forcefield='prmtopcrd/gaff.dat', \
ligand_prmtop='ligand.prmtop', \
ligand_inpcrd='ligand.trans.inpcrd', \
receptor_tarball='prmtopcrd/receptor.tar.gz', \
receptor_prmtop='receptor.prmtop', \
receptor_inpcrd='receptor.trans.inpcrd', \
receptor_fixed_atoms='receptor.pdb', \
complex_tarball='prmtopcrd/complex.tar.gz', \
complex_prmtop='complex.prmtop', \
complex_inpcrd='complex.trans.inpcrd', \
complex_fixed_atoms='complex.pdb', \
score = 'prmtopcrd/anchor_and_grow_scored.mol2', \
dir_grid='grids', \
protocol='Adaptive', cool_therm_speed=1.5, dock_therm_speed=1.5,\
sampler='NUTS', \
MCMC_moves=1, \
seeds_per_state=10, steps_per_seed=200,
sweeps_per_cycle=10, attempts_per_sweep=100, steps_per_sweep=50,
cool_repX_cycles=2, dock_repX_cycles=3, \
site='Sphere', site_center=[1.91650, 1.91650, 1.91650], site_max_R=0.01, \
site_density=10., \
phases=['NAMD_Gas','NAMD_GBSA'], \
cores=-1, \
rmsd=True)
self._run(run_type)
del self
# site='Sphere', site_center=[1.91650, 1.91650, 1.91650], site_max_R=0.01, \
# score = 'prmtopcrd/anchor_and_grow_scored.mol2', \
|
mit
|
windskyer/nova
|
nova/api/openstack/compute/hide_server_addresses.py
|
32
|
2998
|
# Copyright 2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Extension for hiding server addresses in certain states."""
from oslo_config import cfg
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.compute import vm_states
opts = [
cfg.ListOpt('osapi_hide_server_address_states',
default=[vm_states.BUILDING],
help='List of instance states that should hide network info'),
]
CONF = cfg.CONF
CONF.register_opts(opts)
ALIAS = 'os-hide-server-addresses'
authorize = extensions.os_compute_soft_authorizer(ALIAS)
class Controller(wsgi.Controller):
def __init__(self, *args, **kwargs):
super(Controller, self).__init__(*args, **kwargs)
hidden_states = CONF.osapi_hide_server_address_states
# NOTE(jkoelker) _ is not considered uppercase ;)
valid_vm_states = [getattr(vm_states, state)
for state in dir(vm_states)
if state.isupper()]
self.hide_address_states = [state.lower()
for state in hidden_states
if state in valid_vm_states]
def _perhaps_hide_addresses(self, instance, resp_server):
if instance.get('vm_state') in self.hide_address_states:
resp_server['addresses'] = {}
@wsgi.extends
def show(self, req, resp_obj, id):
resp = resp_obj
if not authorize(req.environ['nova.context']):
return
if 'server' in resp.obj and 'addresses' in resp.obj['server']:
instance = req.get_db_instance(id)
self._perhaps_hide_addresses(instance, resp.obj['server'])
@wsgi.extends
def detail(self, req, resp_obj):
resp = resp_obj
if not authorize(req.environ['nova.context']):
return
for server in list(resp.obj['servers']):
if 'addresses' in server:
instance = req.get_db_instance(server['id'])
self._perhaps_hide_addresses(instance, server)
class HideServerAddresses(extensions.V21APIExtensionBase):
"""Support hiding server addresses in certain states."""
name = 'HideServerAddresses'
alias = ALIAS
version = 1
def get_controller_extensions(self):
return [extensions.ControllerExtension(self, 'servers', Controller())]
def get_resources(self):
return []
|
gpl-2.0
|
aliceedn/piz-aioli
|
vendor/doctrine/orm/docs/en/conf.py
|
2448
|
6497
|
# -*- coding: utf-8 -*-
#
# Doctrine 2 ORM documentation build configuration file, created by
# sphinx-quickstart on Fri Dec 3 18:10:24 2010.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.append(os.path.abspath('_exts'))
# -- General configuration -----------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['configurationblock']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Doctrine 2 ORM'
copyright = u'2010-12, Doctrine Project Team'
# 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 = '2'
# The full version, including alpha/beta/rc tags.
release = '2'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
language = 'en'
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
#unused_docs = []
# List of directories, relative to source directory, that shouldn't be searched
# for source files.
exclude_trees = ['_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 = True
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
html_theme = 'doctrine'
# 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 = ['_theme']
# 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_use_modindex = 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, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = ''
# Output file base name for HTML help builder.
htmlhelp_basename = 'Doctrine2ORMdoc'
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'Doctrine2ORM.tex', u'Doctrine 2 ORM Documentation',
u'Doctrine Project Team', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_use_modindex = True
primary_domain = "dcorm"
def linkcode_resolve(domain, info):
if domain == 'dcorm':
return 'http://'
return None
|
bsd-3-clause
|
atsnyder/ITK
|
Wrapping/Generators/Python/Tests/notYetUsable/itkCurvatureFlowTestPython2.py
|
11
|
3693
|
#==========================================================================
#
# Copyright Insight Software Consortium
#
# 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.txt
#
# 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 InsightToolkit import *
import itkTesting
import sys
import os
import shutil
basename = os.path.basename(sys.argv[0])
name = os.path.splitext(basename)[0]
dir = "Algorithms"
testInput = itkTesting.ITK_TEST_INPUT
testOutput = itkTesting.ITK_TEST_OUTPUT
baseLine = itkTesting.ITK_TEST_BASELINE
reader = itkImageFileReaderF2_New()
reader.SetFileName(testInput + "/cthead1.png")
cf = itkCurvatureFlowImageFilterF2F2_New()
cf.SetInput(reader.GetOutput())
cf.SetTimeStep(0.25)
cf.SetNumberOfIterations(10)
cfss = itkShiftScaleImageFilterF2US2_New()
cfss.SetInput(cf.GetOutput())
cfss.SetShift(0.7)
cfss.SetScale(0.9)
valid = itkImageFileReaderUS2_New()
valid.SetFileName(baseLine + "/" + dir + "/" + name + ".png")
diff = itkDifferenceImageFilterUS2_New()
diff.SetValidInput(valid.GetOutput())
diff.SetTestInput(cfss.GetOutput())
diff.SetToleranceRadius(1)
diff.SetDifferenceThreshold(0)
diff.Update()
meanDiff = diff.GetMeanDifference()
totalDiff = diff.GetTotalDifference()
print("MeanDifference = ", meanDiff)
print("TotalDifference = ", totalDiff)
print ("<DartMeasurement name=\"MeanDifference\" type=\"numeric/double\">",
meanDiff, "</DartMeasurement>")
print ("<DartMeasurement name=\"TotalDifference\" type=\"numeric/double\">",
totalDiff, "</DartMeasurement>")
if (meanDiff > 0.1):
convert = itkCastImageFilterUS2UC2_New()
rescale = itkRescaleIntensityImageFilterUS2UC2_New()
rescale.SetInput(diff.GetOutput())
rescale.SetOutputMinimum(0)
rescale.SetOutputMaximum(255)
io = itkPNGImageIO_New()
io.SetUseCompression(1)
io.SetCompressionLevel(9)
writer = itkImageFileWriterUC2_New()
writer.SetImageIO(io.GetPointer())
writer.SetInput(convert.GetOutput())
writer.SetFileName(testOutput + "/" + name + ".test.png")
convert.SetInput(cfss.GetOutput())
writer.Write()
writer.SetFileName(testOutput + "/" + name + ".diff.png")
writer.SetInput(rescale.GetOutput())
writer.Write()
shutil.copyfile(
baseLine +
"/" +
dir +
"/" +
name +
".png",
testOutput +
"/" +
name +
".valid.png")
print ("<DartMeasurementFile name=\"TestImage\" type=\"image/png\">" +
testOutput + "/" + name + ".test.png</DartMeasurementFile>")
print ("<DartMeasurementFile name=\"DifferenceImage\" type=\"image/png\">"
+ testOutput + "/" + name + ".diff.png</DartMeasurementFile>")
print ("<DartMeasurementFile name=\"ValidImage\" type=\"image/png\">" +
testOutput + "/" + name + ".valid.png</DartMeasurementFile>")
pr = "<DartMeasurement name=\"DifferenceShift\" type=\"numeric/double\">"
print (pr, rescale.GetShift(), "</DartMeasurement>")
pr = "<DartMeasurement name=\"DifferenceScale\" type=\"numeric/double\">"
print (pr, rescale.GetScale(), "</DartMeasurement>")
# return 1
# return 0
|
apache-2.0
|
GraysonP/codecombat-1
|
scripts/devSetup/which.py
|
79
|
2385
|
__author__ = 'root'
#copied from python3
import os
import sys
def which(cmd, mode=os.F_OK | os.X_OK, path=None):
"""Given a command, mode, and a PATH string, return the path which
conforms to the given mode on the PATH, or None if there is no such
file.
`mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
of os.environ.get("PATH"), or can be overridden with a custom search
path.
"""
# Check that a given file can be accessed with the correct mode.
# Additionally check that `file` is not a directory, as on Windows
# directories pass the os.access check.
def _access_check(fn, mode):
return (os.path.exists(fn) and os.access(fn, mode)
and not os.path.isdir(fn))
# If we're given a path with a directory part, look it up directly rather
# than referring to PATH directories. This includes checking relative to the
# current directory, e.g. ./script
if os.path.dirname(cmd):
if _access_check(cmd, mode):
return cmd
return None
if path is None:
path = os.environ.get("PATH", os.defpath)
if not path:
return None
path = path.split(os.pathsep)
if sys.platform == "win32":
# The current directory takes precedence on Windows.
if not os.curdir in path:
path.insert(0, os.curdir)
# PATHEXT is necessary to check on Windows.
pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
# See if the given file matches any of the expected path extensions.
# This will allow us to short circuit when given "python.exe".
# If it does match, only test that one, otherwise we have to try
# others.
if any(cmd.lower().endswith(ext.lower()) for ext in pathext):
files = [cmd]
else:
files = [cmd + ext for ext in pathext]
else:
# On other platforms you don't have things like PATHEXT to tell you
# what file suffixes are executable, so just pass on cmd as-is.
files = [cmd]
seen = set()
for dir in path:
normdir = os.path.normcase(dir)
if not normdir in seen:
seen.add(normdir)
for thefile in files:
name = os.path.join(dir, thefile)
if _access_check(name, mode):
return name
return None
|
mit
|
writefaruq/lionface-app
|
django/contrib/gis/gdal/layer.py
|
12
|
8701
|
# Needed ctypes routines
from ctypes import c_double, byref
# Other GDAL imports.
from django.contrib.gis.gdal.base import GDALBase
from django.contrib.gis.gdal.envelope import Envelope, OGREnvelope
from django.contrib.gis.gdal.error import OGRException, OGRIndexError, SRSException
from django.contrib.gis.gdal.feature import Feature
from django.contrib.gis.gdal.field import OGRFieldTypes
from django.contrib.gis.gdal.geomtype import OGRGeomType
from django.contrib.gis.gdal.geometries import OGRGeometry
from django.contrib.gis.gdal.srs import SpatialReference
# GDAL ctypes function prototypes.
from django.contrib.gis.gdal.prototypes import ds as capi, geom as geom_api, srs as srs_api
# For more information, see the OGR C API source code:
# http://www.gdal.org/ogr/ogr__api_8h.html
#
# The OGR_L_* routines are relevant here.
class Layer(GDALBase):
"A class that wraps an OGR Layer, needs to be instantiated from a DataSource object."
#### Python 'magic' routines ####
def __init__(self, layer_ptr, ds):
"""
Initializes on an OGR C pointer to the Layer and the `DataSource` object
that owns this layer. The `DataSource` object is required so that a
reference to it is kept with this Layer. This prevents garbage
collection of the `DataSource` while this Layer is still active.
"""
if not layer_ptr:
raise OGRException('Cannot create Layer, invalid pointer given')
self.ptr = layer_ptr
self._ds = ds
self._ldefn = capi.get_layer_defn(self._ptr)
# Does the Layer support random reading?
self._random_read = self.test_capability('RandomRead')
def __getitem__(self, index):
"Gets the Feature at the specified index."
if isinstance(index, (int, long)):
# An integer index was given -- we cannot do a check based on the
# number of features because the beginning and ending feature IDs
# are not guaranteed to be 0 and len(layer)-1, respectively.
if index < 0: raise OGRIndexError('Negative indices are not allowed on OGR Layers.')
return self._make_feature(index)
elif isinstance(index, slice):
# A slice was given
start, stop, stride = index.indices(self.num_feat)
return [self._make_feature(fid) for fid in xrange(start, stop, stride)]
else:
raise TypeError('Integers and slices may only be used when indexing OGR Layers.')
def __iter__(self):
"Iterates over each Feature in the Layer."
# ResetReading() must be called before iteration is to begin.
capi.reset_reading(self._ptr)
for i in xrange(self.num_feat):
yield Feature(capi.get_next_feature(self._ptr), self._ldefn)
def __len__(self):
"The length is the number of features."
return self.num_feat
def __str__(self):
"The string name of the layer."
return self.name
def _make_feature(self, feat_id):
"""
Helper routine for __getitem__ that constructs a Feature from the given
Feature ID. If the OGR Layer does not support random-access reading,
then each feature of the layer will be incremented through until the
a Feature is found matching the given feature ID.
"""
if self._random_read:
# If the Layer supports random reading, return.
try:
return Feature(capi.get_feature(self.ptr, feat_id), self._ldefn)
except OGRException:
pass
else:
# Random access isn't supported, have to increment through
# each feature until the given feature ID is encountered.
for feat in self:
if feat.fid == feat_id: return feat
# Should have returned a Feature, raise an OGRIndexError.
raise OGRIndexError('Invalid feature id: %s.' % feat_id)
#### Layer properties ####
@property
def extent(self):
"Returns the extent (an Envelope) of this layer."
env = OGREnvelope()
capi.get_extent(self.ptr, byref(env), 1)
return Envelope(env)
@property
def name(self):
"Returns the name of this layer in the Data Source."
return capi.get_fd_name(self._ldefn)
@property
def num_feat(self, force=1):
"Returns the number of features in the Layer."
return capi.get_feature_count(self.ptr, force)
@property
def num_fields(self):
"Returns the number of fields in the Layer."
return capi.get_field_count(self._ldefn)
@property
def geom_type(self):
"Returns the geometry type (OGRGeomType) of the Layer."
return OGRGeomType(capi.get_fd_geom_type(self._ldefn))
@property
def srs(self):
"Returns the Spatial Reference used in this Layer."
try:
ptr = capi.get_layer_srs(self.ptr)
return SpatialReference(srs_api.clone_srs(ptr))
except SRSException:
return None
@property
def fields(self):
"""
Returns a list of string names corresponding to each of the Fields
available in this Layer.
"""
return [capi.get_field_name(capi.get_field_defn(self._ldefn, i))
for i in xrange(self.num_fields) ]
@property
def field_types(self):
"""
Returns a list of the types of fields in this Layer. For example,
the list [OFTInteger, OFTReal, OFTString] would be returned for
an OGR layer that had an integer, a floating-point, and string
fields.
"""
return [OGRFieldTypes[capi.get_field_type(capi.get_field_defn(self._ldefn, i))]
for i in xrange(self.num_fields)]
@property
def field_widths(self):
"Returns a list of the maximum field widths for the features."
return [capi.get_field_width(capi.get_field_defn(self._ldefn, i))
for i in xrange(self.num_fields)]
@property
def field_precisions(self):
"Returns the field precisions for the features."
return [capi.get_field_precision(capi.get_field_defn(self._ldefn, i))
for i in xrange(self.num_fields)]
def _get_spatial_filter(self):
try:
return OGRGeometry(geom_api.clone_geom(capi.get_spatial_filter(self.ptr)))
except OGRException:
return None
def _set_spatial_filter(self, filter):
if isinstance(filter, OGRGeometry):
capi.set_spatial_filter(self.ptr, filter.ptr)
elif isinstance(filter, (tuple, list)):
if not len(filter) == 4:
raise ValueError('Spatial filter list/tuple must have 4 elements.')
# Map c_double onto params -- if a bad type is passed in it
# will be caught here.
xmin, ymin, xmax, ymax = map(c_double, filter)
capi.set_spatial_filter_rect(self.ptr, xmin, ymin, xmax, ymax)
elif filter is None:
capi.set_spatial_filter(self.ptr, None)
else:
raise TypeError('Spatial filter must be either an OGRGeometry instance, a 4-tuple, or None.')
spatial_filter = property(_get_spatial_filter, _set_spatial_filter)
#### Layer Methods ####
def get_fields(self, field_name):
"""
Returns a list containing the given field name for every Feature
in the Layer.
"""
if not field_name in self.fields:
raise OGRException('invalid field name: %s' % field_name)
return [feat.get(field_name) for feat in self]
def get_geoms(self, geos=False):
"""
Returns a list containing the OGRGeometry for every Feature in
the Layer.
"""
if geos:
from django.contrib.gis.geos import GEOSGeometry
return [GEOSGeometry(feat.geom.wkb) for feat in self]
else:
return [feat.geom for feat in self]
def test_capability(self, capability):
"""
Returns a bool indicating whether the this Layer supports the given
capability (a string). Valid capability strings include:
'RandomRead', 'SequentialWrite', 'RandomWrite', 'FastSpatialFilter',
'FastFeatureCount', 'FastGetExtent', 'CreateField', 'Transactions',
'DeleteFeature', and 'FastSetNextByIndex'.
"""
return bool(capi.test_capability(self.ptr, capability))
|
bsd-3-clause
|
OptiPop/external_chromium_org
|
tools/findit/match_set.py
|
26
|
4358
|
# Copyright (c) 2014 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 re
from threading import Lock
import crash_utils
REVIEW_URL_PATTERN = re.compile(r'Review URL:( *)(.*?)/(\d+)')
class Match(object):
"""Represents a match entry.
A match is a CL that is suspected to have caused the crash. A match object
contains information about files it changes, their authors, etc.
Attributes:
is_revert: True if this CL is reverted by other CL.
revert_of: If this CL is a revert of some other CL, a revision number/
git hash of that CL.
crashed_line_numbers: The list of lines that caused crash for this CL.
function_list: The list of functions that caused the crash.
min_distance: The minimum distance between the lines that CL changed and
lines that caused the crash.
changed_files: The list of files that the CL changed.
changed_file_urls: The list of URLs for the file.
author: The author of the CL.
component_name: The name of the component that this CL belongs to.
stack_frame_indices: For files that caused crash, list of where in the
stackframe they occur.
priorities: A list of priorities for each of the changed file. A priority
is 1 if the file changes a crashed line, and 2 if it changes
the file but not the crashed line.
reivision_url: The revision URL of the CL.
review_url: The codereview URL that reviews this CL.
reviewers: The list of people that reviewed this CL.
reason: The reason why this CL is suspected.
"""
REVERT_PATTERN = re.compile(r'(revert\w*) r?(\d+)', re.I)
def __init__(self, revision, component_name):
self.is_revert = False
self.revert_of = None
self.message = None
self.crashed_line_numbers = []
self.function_list = []
self.min_distance = crash_utils.INFINITY
self.min_distance_info = None
self.changed_files = []
self.changed_file_urls = []
self.author = revision['author']
self.component_name = component_name
self.stack_frame_indices = []
self.priorities = []
self.revision_url = revision['url']
self.review_url = ''
self.reviewers = []
self.reason = None
def ParseMessage(self, message, codereview_api_url):
"""Parses the message.
It checks the message to extract the code review website and list of
reviewers, and it also checks if the CL is a revert of another CL.
Args:
message: The message to parse.
codereview_api_url: URL to retrieve codereview data from.
"""
self.message = message
for line in message.splitlines():
line = line.strip()
review_url_line_match = REVIEW_URL_PATTERN.match(line)
# Check if the line has the code review information.
if review_url_line_match:
# Get review number for the code review site from the line.
issue_number = review_url_line_match.group(3)
# Get JSON from the code review site, ignore the line if it fails.
url = codereview_api_url % issue_number
json_string = crash_utils.GetDataFromURL(url)
if not json_string:
continue
# Load the JSON from the string, and get the list of reviewers.
code_review = crash_utils.LoadJSON(json_string)
if code_review:
self.reviewers = code_review['reviewers']
# Check if this CL is a revert of other CL.
if line.lower().startswith('revert'):
self.is_revert = True
# Check if the line says what CL this CL is a revert of.
revert = self.REVERT_PATTERN.match(line)
if revert:
self.revert_of = revert.group(2)
return
class MatchSet(object):
"""Represents a set of matches.
Attributes:
matches: A map from CL to a match object.
cls_to_ignore: A set of CLs to ignore.
matches_lock: A lock guarding matches dictionary.
"""
def __init__(self, codereview_api_url):
self.codereview_api_url = codereview_api_url
self.matches = {}
self.cls_to_ignore = set()
self.matches_lock = Lock()
def RemoveRevertedCLs(self):
"""Removes CLs that are revert."""
for cl in self.matches:
if cl in self.cls_to_ignore:
del self.matches[cl]
|
bsd-3-clause
|
alikins/ansible
|
lib/ansible/modules/cloud/openstack/os_keystone_endpoint.py
|
25
|
6710
|
#!/usr/bin/python
# Copyright: (c) 2017, VEXXHOST, Inc.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: os_keystone_endpoint
short_description: Manage OpenStack Identity service endpoints
extends_documentation_fragment: openstack
author:
- Mohammed Naser (@mnaser)
- Alberto Murillo (@albertomurillo)
version_added: "2.5"
description:
- Create, update, or delete OpenStack Identity service endpoints. If a
service with the same combination of I(service), I(interface) and I(region)
exist, the I(url) and I(state) (C(present) or C(absent)) will be updated.
options:
service:
description:
- Name or id of the service.
required: true
interface:
description:
- Interface of the service.
choices: [admin, public, internal]
required: true
url:
description:
- URL of the service.
required: true
region:
description:
- Region that the service belongs to. Note that I(region_name) is used for authentication.
enabled:
description:
- Is the service enabled.
default: True
state:
description:
- Should the resource be C(present) or C(absent).
choices: [present, absent]
default: present
requirements:
- shade >= 1.11.0
'''
EXAMPLES = '''
- name: Create a service for glance
os_keystone_endpoint:
cloud: mycloud
service: glance
interface: public
url: http://controller:9292
region: RegionOne
state: present
- name: Delete a service for nova
os_keystone_endpoint:
cloud: mycloud
service: nova
interface: public
region: RegionOne
state: absent
'''
RETURN = '''
endpoint:
description: Dictionary describing the endpoint.
returned: On success when I(state) is C(present)
type: complex
contains:
id:
description: Endpoint ID.
type: string
sample: 3292f020780b4d5baf27ff7e1d224c44
region:
description: Region Name.
type: string
sample: RegionOne
service_id:
description: Service ID.
type: string
sample: b91f1318f735494a825a55388ee118f3
interface:
description: Endpoint Interface.
type: string
sample: public
url:
description: Service URL.
type: string
sample: http://controller:9292
enabled:
description: Service status.
type: boolean
sample: True
'''
from distutils.version import StrictVersion
try:
import shade
HAS_SHADE = True
except ImportError:
HAS_SHADE = False
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.openstack import openstack_full_argument_spec, openstack_module_kwargs
def _needs_update(module, endpoint):
if endpoint.enabled != module.params['enabled']:
return True
if endpoint.url != module.params['url']:
return True
return False
def _system_state_change(module, endpoint):
state = module.params['state']
if state == 'absent' and endpoint:
return True
if state == 'present':
if endpoint is None:
return True
return _needs_update(module, endpoint)
return False
def main():
argument_spec = openstack_full_argument_spec(
service=dict(type='str', required=True),
interface=dict(type='str', required=True, choices=['admin', 'public', 'internal']),
url=dict(type='str', required=True),
region=dict(type='str'),
enabled=dict(type='bool', default=True),
state=dict(type='str', default='present', choices=['absent', 'present']),
)
module_kwargs = openstack_module_kwargs()
module = AnsibleModule(argument_spec,
supports_check_mode=True,
**module_kwargs)
if not HAS_SHADE:
module.fail_json(msg='shade is required for this module')
if StrictVersion(shade.__version__) < StrictVersion('1.11.0'):
module.fail_json(msg="To utilize this module, the installed version of"
"the shade library MUST be >=1.11.0")
service_name_or_id = module.params['service']
interface = module.params['interface']
url = module.params['url']
region = module.params['region']
enabled = module.params['enabled']
state = module.params['state']
try:
cloud = shade.operator_cloud(**module.params)
service = cloud.get_service(service_name_or_id)
if service is None:
module.fail_json(msg='Service %s does not exist' % service_name_or_id)
filters = dict(service_id=service.id, interface=interface)
if region is not None:
filters['region'] = region
endpoints = cloud.search_endpoints(filters=filters)
if len(endpoints) > 1:
module.fail_json(msg='Service %s, interface %s and region %s are '
'not unique' %
(service_name_or_id, interface, region))
elif len(endpoints) == 1:
endpoint = endpoints[0]
else:
endpoint = None
if module.check_mode:
module.exit_json(changed=_system_state_change(module, endpoint))
if state == 'present':
if endpoint is None:
result = cloud.create_endpoint(service_name_or_id=service,
url=url, interface=interface,
region=region, enabled=enabled)
endpoint = result[0]
changed = True
else:
if _needs_update(module, endpoint):
endpoint = cloud.update_endpoint(
endpoint.id, url=url, enabled=enabled)
changed = True
else:
changed = False
module.exit_json(changed=changed, endpoint=endpoint)
elif state == 'absent':
if endpoint is None:
changed = False
else:
cloud.delete_endpoint(endpoint.id)
changed = True
module.exit_json(changed=changed)
except shade.OpenStackCloudException as e:
module.fail_json(msg=str(e))
if __name__ == '__main__':
main()
|
gpl-3.0
|
notsambeck/siftsite
|
siftsite/skeleton.py
|
1
|
3619
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This is a skeleton file that can serve as a starting point for a Python
console script. To run this script uncomment the following line in the
entry_points section in setup.cfg:
console_scripts =
fibonacci = siftsite.skeleton:run
Then run `python setup.py install` which will install the command `fibonacci`
inside your current environment.
Besides console scripts, the header (i.e. until _logger...) of this file can
also be used as template for Python modules.
Note: This skeleton file can be safely removed if not needed!
"""
from __future__ import division, print_function, absolute_import
import argparse
import sys
import os
import logging
import requests
from siftsite import __version__
__author__ = "Sam Beck"
__copyright__ = "Sam Beck"
__license__ = "mit"
_logger = logging.getLogger(__name__)
def upload_dir(filepath, label, source):
'''upload whole directory (calls upload on all .png)'''
base_dir = os.path.expanduser(os.path.dirname(filepath))
files = os.listdir(base_dir)
input('will upload {} files, continue or ctrl-c'.format(len(files)))
for f in files:
print(f[-4:])
if f[-4:] == '.png':
upload(os.path.join(base_dir, f), label, source)
def upload(filepath, label, source):
'''POST request to your API with "files" key in requests data dict'''
base_dir = os.path.expanduser(os.path.dirname(filepath))
# url = 'http://localhost:8000/api/'
url = 'https://still-taiga-56301.herokuapp.com/api/'
file_name = os.path.basename(filepath)
with open(os.path.join(base_dir, file_name), 'rb') as fin:
print('file:', base_dir, '/', file_name)
POST_data = {'correct_label': label, 'source': source,
'filename': file_name}
files = {'filename': (file_name, fin), 'file': file_name}
resp = requests.post(url, data=POST_data, files=files)
print(resp)
def setup_logging(loglevel):
"""Setup basic logging
Args:
loglevel (int): minimum loglevel for emitting messages
"""
logformat = "[%(asctime)s] %(levelname)s:%(name)s:%(message)s"
logging.basicConfig(level=loglevel, stream=sys.stdout,
format=logformat, datefmt="%Y-%m-%d %H:%M:%S")
def parse_args(args):
"""Parse command line parameters
Args:
args ([str]): command line parameters as list of strings
Returns:
:obj:`argparse.Namespace`: command line parameters namespace
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'--version',
action='version',
version='siftsite {ver}'.format(ver=__version__))
parser.add_argument(
'--upload',
dest="upload",
help="Path to image file for upload to labler API",
type=str)
parser.add_argument(
'-v',
'--verbose',
dest="loglevel",
help="set loglevel to INFO",
action='store_const',
const=logging.INFO)
parser.add_argument(
'-vv',
'--very-verbose',
dest="loglevel",
help="set loglevel to DEBUG",
action='store_const',
const=logging.DEBUG)
return parser.parse_known_args(args)
def main(args):
"""Main entry point allowing external calls
Args:
args ([str]): command line parameter list
"""
args, unknown = parse_args(args)
if args.upload:
upload(args.upload)
else:
print('yeah cool sure')
def run():
"""Entry point for console_scripts
"""
main(sys.argv[1:])
if __name__ == "__main__":
run()
|
mit
|
hugheaves/ardupilot-solo
|
mk/PX4/Tools/gencpp/scripts/gen_cpp.py
|
214
|
2168
|
#!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2009, Willow Garage, 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 Willow Garage, 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.
#
## ROS message source code generation for C++
##
## Converts ROS .msg files in a package into C++ source code implementations.
import sys
import os
import genmsg.template_tools
msg_template_map = { 'msg.h.template':'@[email protected]' }
srv_template_map = { 'srv.h.template':'@[email protected]' }
if __name__ == "__main__":
genmsg.template_tools.generate_from_command_line_options(sys.argv,
msg_template_map,
srv_template_map)
|
gpl-3.0
|
SimtterCom/gyp
|
test/actions/gyptest-all.py
|
243
|
3677
|
#!/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.
"""
Verifies simple actions when using an explicit build target of 'all'.
"""
import glob
import os
import TestGyp
test = TestGyp.TestGyp(workdir='workarea_all')
test.run_gyp('actions.gyp', chdir='src')
test.relocate('src', 'relocate/src')
# Some gyp files use an action that mentions an output but never
# writes it as a means to making the action run on every build. That
# doesn't mesh well with ninja's semantics. TODO(evan): figure out
# how to work always-run actions in to ninja.
# Android also can't do this as it doesn't have order-only dependencies.
if test.format in ['ninja', 'android']:
test.build('actions.gyp', test.ALL, chdir='relocate/src')
else:
# Test that an "always run" action increases a counter on multiple
# invocations, and that a dependent action updates in step.
test.build('actions.gyp', test.ALL, chdir='relocate/src')
test.must_match('relocate/src/subdir1/actions-out/action-counter.txt', '1')
test.must_match('relocate/src/subdir1/actions-out/action-counter_2.txt', '1')
test.build('actions.gyp', test.ALL, chdir='relocate/src')
test.must_match('relocate/src/subdir1/actions-out/action-counter.txt', '2')
test.must_match('relocate/src/subdir1/actions-out/action-counter_2.txt', '2')
# The "always run" action only counts to 2, but the dependent target
# will count forever if it's allowed to run. This verifies that the
# dependent target only runs when the "always run" action generates
# new output, not just because the "always run" ran.
test.build('actions.gyp', test.ALL, chdir='relocate/src')
test.must_match('relocate/src/subdir1/actions-out/action-counter.txt', '2')
test.must_match('relocate/src/subdir1/actions-out/action-counter_2.txt', '2')
expect = """\
Hello from program.c
Hello from make-prog1.py
Hello from make-prog2.py
"""
if test.format == 'xcode':
chdir = 'relocate/src/subdir1'
else:
chdir = 'relocate/src'
test.run_built_executable('program', chdir=chdir, stdout=expect)
test.must_match('relocate/src/subdir2/file.out', "Hello from make-file.py\n")
expect = "Hello from generate_main.py\n"
if test.format == 'xcode':
chdir = 'relocate/src/subdir3'
else:
chdir = 'relocate/src'
test.run_built_executable('null_input', chdir=chdir, stdout=expect)
# Clean out files which may have been created if test.ALL was run.
def clean_dep_files():
for file in (glob.glob('relocate/src/dep_*.txt') +
glob.glob('relocate/src/deps_all_done_*.txt')):
if os.path.exists(file):
os.remove(file)
# Confirm our clean.
clean_dep_files()
test.must_not_exist('relocate/src/dep_1.txt')
test.must_not_exist('relocate/src/deps_all_done_first_123.txt')
# Make sure all deps finish before an action is run on a 'None' target.
# If using the Make builder, add -j to make things more difficult.
arguments = []
if test.format == 'make':
arguments = ['-j']
test.build('actions.gyp', 'action_with_dependencies_123', chdir='relocate/src',
arguments=arguments)
test.must_exist('relocate/src/deps_all_done_first_123.txt')
# Try again with a target that has deps in reverse. Output files from
# previous tests deleted. Confirm this execution did NOT run the ALL
# target which would mess up our dep tests.
clean_dep_files()
test.build('actions.gyp', 'action_with_dependencies_321', chdir='relocate/src',
arguments=arguments)
test.must_exist('relocate/src/deps_all_done_first_321.txt')
test.must_not_exist('relocate/src/deps_all_done_first_123.txt')
test.pass_test()
|
bsd-3-clause
|
sinkuri256/python-for-android
|
python3-alpha/extra_modules/gdata/Crypto/Cipher/__init__.py
|
271
|
1145
|
"""Secret-key encryption algorithms.
Secret-key encryption algorithms transform plaintext in some way that
is dependent on a key, producing ciphertext. This transformation can
easily be reversed, if (and, hopefully, only if) one knows the key.
The encryption modules here all support the interface described in PEP
272, "API for Block Encryption Algorithms".
If you don't know which algorithm to choose, use AES because it's
standard and has undergone a fair bit of examination.
Crypto.Cipher.AES Advanced Encryption Standard
Crypto.Cipher.ARC2 Alleged RC2
Crypto.Cipher.ARC4 Alleged RC4
Crypto.Cipher.Blowfish
Crypto.Cipher.CAST
Crypto.Cipher.DES The Data Encryption Standard. Very commonly used
in the past, but today its 56-bit keys are too small.
Crypto.Cipher.DES3 Triple DES.
Crypto.Cipher.IDEA
Crypto.Cipher.RC5
Crypto.Cipher.XOR The simple XOR cipher.
"""
__all__ = ['AES', 'ARC2', 'ARC4',
'Blowfish', 'CAST', 'DES', 'DES3', 'IDEA', 'RC5',
'XOR'
]
__revision__ = "$Id: __init__.py,v 1.7 2003/02/28 15:28:35 akuchling Exp $"
|
apache-2.0
|
omwomotieno/tunza_v3
|
config/settings/production.py
|
2
|
8273
|
# -*- coding: utf-8 -*-
"""
Production Configurations
- Use djangosecure
- Use Amazon's S3 for storing static files and uploaded media
- Use mailgun to send emails
- Use Redis on Heroku
- Use sentry for error logging
- Use opbeat for error reporting
"""
from __future__ import absolute_import, unicode_literals
from boto.s3.connection import OrdinaryCallingFormat
from django.utils import six
import logging
from .common import * # noqa
# SECRET CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
# Raises ImproperlyConfigured exception if DJANGO_SECRET_KEY not in os.environ
SECRET_KEY = env('DJANGO_SECRET_KEY')
# This ensures that Django will be able to detect a secure connection
# properly on Heroku.
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# django-secure
# ------------------------------------------------------------------------------
INSTALLED_APPS += ('djangosecure', )
# raven sentry client
# See https://docs.getsentry.com/hosted/clients/python/integrations/django/
INSTALLED_APPS += ('raven.contrib.django.raven_compat', )
SECURITY_MIDDLEWARE = (
'djangosecure.middleware.SecurityMiddleware',
)
RAVEN_MIDDLEWARE = ('raven.contrib.django.raven_compat.middleware.Sentry404CatchMiddleware',
'raven.contrib.django.raven_compat.middleware.SentryResponseErrorIdMiddleware',)
MIDDLEWARE_CLASSES = SECURITY_MIDDLEWARE + \
RAVEN_MIDDLEWARE + MIDDLEWARE_CLASSES
# opbeat integration
# See https://opbeat.com/languages/django/
INSTALLED_APPS += ('opbeat.contrib.django',)
OPBEAT = {
'ORGANIZATION_ID': env('DJANGO_OPBEAT_ORGANIZATION_ID'),
'APP_ID': env('DJANGO_OPBEAT_APP_ID'),
'SECRET_TOKEN': env('DJANGO_OPBEAT_SECRET_TOKEN')
}
MIDDLEWARE_CLASSES = (
'opbeat.contrib.django.middleware.OpbeatAPMMiddleware',
) + MIDDLEWARE_CLASSES
# set this to 60 seconds and then to 518400 when you can prove it works
SECURE_HSTS_SECONDS = 60
SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool(
'DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS', default=True)
SECURE_FRAME_DENY = env.bool('DJANGO_SECURE_FRAME_DENY', default=True)
SECURE_CONTENT_TYPE_NOSNIFF = env.bool(
'DJANGO_SECURE_CONTENT_TYPE_NOSNIFF', default=True)
SECURE_BROWSER_XSS_FILTER = True
SESSION_COOKIE_SECURE = False
SESSION_COOKIE_HTTPONLY = True
SECURE_SSL_REDIRECT = env.bool('DJANGO_SECURE_SSL_REDIRECT', default=True)
# SITE CONFIGURATION
# ------------------------------------------------------------------------------
# Hosts/domain names that are valid for this site
# See https://docs.djangoproject.com/en/1.6/ref/settings/#allowed-hosts
ALLOWED_HOSTS = env.list('DJANGO_ALLOWED_HOSTS', default=['example.com'])
# END SITE CONFIGURATION
INSTALLED_APPS += ('gunicorn', )
# STORAGE CONFIGURATION
# ------------------------------------------------------------------------------
# Uploaded Media Files
# ------------------------
# See: http://django-storages.readthedocs.org/en/latest/index.html
INSTALLED_APPS += (
'storages',
)
AWS_ACCESS_KEY_ID = env('DJANGO_AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = env('DJANGO_AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = env('DJANGO_AWS_STORAGE_BUCKET_NAME')
AWS_AUTO_CREATE_BUCKET = True
AWS_QUERYSTRING_AUTH = False
AWS_S3_CALLING_FORMAT = OrdinaryCallingFormat()
# AWS cache settings, don't change unless you know what you're doing:
AWS_EXPIRY = 60 * 60 * 24 * 7
# TODO See: https://github.com/jschneier/django-storages/issues/47
# Revert the following and use str after the above-mentioned bug is fixed in
# either django-storage-redux or boto
AWS_HEADERS = {
'Cache-Control': six.b('max-age=%d, s-maxage=%d, must-revalidate' % (
AWS_EXPIRY, AWS_EXPIRY))
}
# URL that handles the media served from MEDIA_ROOT, used for managing
# stored files.
# See:http://stackoverflow.com/questions/10390244/
from storages.backends.s3boto import S3BotoStorage
StaticRootS3BotoStorage = lambda: S3BotoStorage(location='static')
MediaRootS3BotoStorage = lambda: S3BotoStorage(location='media')
DEFAULT_FILE_STORAGE = 'config.settings.production.MediaRootS3BotoStorage'
MEDIA_URL = 'https://s3.amazonaws.com/%s/media/' % AWS_STORAGE_BUCKET_NAME
# Static Assets
# ------------------------
STATIC_URL = 'https://s3.amazonaws.com/%s/static/' % AWS_STORAGE_BUCKET_NAME
STATICFILES_STORAGE = 'config.settings.production.StaticRootS3BotoStorage'
# See: https://github.com/antonagestam/collectfast
# For Django 1.7+, 'collectfast' should come before
# 'django.contrib.staticfiles'
AWS_PRELOAD_METADATA = True
INSTALLED_APPS = ('collectfast', ) + INSTALLED_APPS
# EMAIL
# ------------------------------------------------------------------------------
DEFAULT_FROM_EMAIL = env('DJANGO_DEFAULT_FROM_EMAIL',
default='tunza <[email protected]>')
EMAIL_BACKEND = 'django_mailgun.MailgunBackend'
MAILGUN_ACCESS_KEY = env('DJANGO_MAILGUN_API_KEY')
MAILGUN_SERVER_NAME = env('DJANGO_MAILGUN_SERVER_NAME')
EMAIL_SUBJECT_PREFIX = env('DJANGO_EMAIL_SUBJECT_PREFIX', default='[tunza] ')
SERVER_EMAIL = env('DJANGO_SERVER_EMAIL', default=DEFAULT_FROM_EMAIL)
NEW_RELIC_LICENSE_KEY = env('NEW_RELIC_LICENSE_KEY')
NEW_RELIC_APP_NAME = env('NEW_RELIC_APP_NAME')
# TEMPLATE CONFIGURATION
# ------------------------------------------------------------------------------
# See:
# https://docs.djangoproject.com/en/dev/ref/templates/api/#django.template.loaders.cached.Loader
TEMPLATES[0]['OPTIONS']['loaders'] = [
('django.template.loaders.cached.Loader', [
'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ]),
]
# DATABASE CONFIGURATION
# ------------------------------------------------------------------------------
# Raises ImproperlyConfigured exception if DATABASE_URL not in os.environ
DATABASES['default'] = env.db('DATABASE_URL')
# CACHING
# ------------------------------------------------------------------------------
# Heroku URL does not pass the DB number, so we parse it in
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': '{0}/{1}'.format(env('REDIS_URL', default='redis://127.0.0.1:6379'), 0),
'OPTIONS': {
'CLIENT_CLASS': 'django_redis.client.DefaultClient',
'IGNORE_EXCEPTIONS': True, # mimics memcache behavior.
# http://niwinz.github.io/django-redis/latest/#_memcached_exceptions_behavior
}
}
}
# Sentry Configuration
SENTRY_DSN = env('DJANGO_SENTRY_DSN')
SENTRY_CLIENT = env('DJANGO_SENTRY_CLIENT', default='raven.contrib.django.raven_compat.DjangoClient')
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'root': {
'level': 'WARNING',
'handlers': ['sentry'],
},
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s '
'%(process)d %(thread)d %(message)s'
},
},
'handlers': {
'sentry': {
'level': 'ERROR',
'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler',
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'verbose'
}
},
'loggers': {
'django.db.backends': {
'level': 'ERROR',
'handlers': ['console'],
'propagate': False,
},
'raven': {
'level': 'DEBUG',
'handlers': ['console'],
'propagate': False,
},
'sentry.errors': {
'level': 'DEBUG',
'handlers': ['console'],
'propagate': False,
},
'django.security.DisallowedHost': {
'level': 'ERROR',
'handlers': ['console', 'sentry'],
'propagate': False,
},
},
}
SENTRY_CELERY_LOGLEVEL = env.int('DJANGO_SENTRY_LOG_LEVEL', logging.INFO)
RAVEN_CONFIG = {
'CELERY_LOGLEVEL': env.int('DJANGO_SENTRY_LOG_LEVEL', logging.INFO),
'DSN': SENTRY_DSN
}
# Custom Admin URL, use {% url 'admin:index' %}
ADMIN_URL = env('DJANGO_ADMIN_URL')
# Your production stuff: Below this line define 3rd party library settings
|
mit
|
simplyvikram/google-chartwrapper
|
setup.py
|
7
|
2547
|
from distutils.core import setup
CLASSIFIERS = (
('Development Status :: 5 - Production/Stable'),
('Environment :: Console'),
('Environment :: Web Environment'),
('Framework :: Django'),
#('Framework :: Zope3'),
#('Framework :: Trac'),
#('Framework :: TurboGears :: Widgets'),
#('Framework :: Twisted'),
('Intended Audience :: Developers'),
('Intended Audience :: Science/Research'),
('Intended Audience :: System Administrators'),
('License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)'),
('Natural Language :: English'),
('Operating System :: OS Independent'),
('Programming Language :: Python'),
('Programming Language :: Python :: 2'),
('Programming Language :: Python :: 2.3'),
('Programming Language :: Python :: 2.4'),
('Programming Language :: Python :: 2.5'),
('Programming Language :: Python :: 2.6'),
('Programming Language :: Python :: 2.7'),
('Programming Language :: Python :: 3'),
('Programming Language :: Python :: 3.0'),
('Programming Language :: Python :: 3.1'),
('Topic :: Artistic Software'),
('Topic :: Internet :: WWW/HTTP'),
('Topic :: Internet :: WWW/HTTP :: Dynamic Content'),
('Topic :: Internet :: WWW/HTTP :: Dynamic Content :: CGI Tools/Libraries'),
('Topic :: Multimedia'),
('Topic :: Multimedia :: Graphics'),
('Topic :: Scientific/Engineering :: Visualization'),
('Topic :: Software Development :: Libraries :: Python Modules'),
('Topic :: Utilities'),
)
setup(
name='GChartWrapper',
version='0.9',
description='Python Google Chart Wrapper',
long_description="""Python wrapper for the Google Chart API.
The wrapper can render the URL of the Google chart, based on your parameters,
or it can render an HTML img tag to insert into webpages on the fly.
Made for dynamic python websites (Django,Zope,CGI,etc.) that need on the fly
chart generation without any extra modules. Can also grab the PIL Image
instance of the chart for manipulation. Works for Python 2 and 3""",
author="Justin Quick",
author_email='[email protected]',
url='http://code.google.com/p/google-chartwrapper/',
download_url='http://google-chartwrapper.googlecode.com/files/GChartWrapper-0.9.tar.gz',
platforms = ["Windows", "Linux", "Solaris", "Mac OS-X", "Unix"],
classifiers=CLASSIFIERS,
package_dir={'GChartWrapper': 'GChartWrapper'},
packages=['GChartWrapper', 'GChartWrapper.charts', 'GChartWrapper.charts.templatetags'],
)
|
bsd-3-clause
|
BaconPancakes/valor
|
lib/pip/_vendor/lockfile/pidlockfile.py
|
536
|
6090
|
# -*- coding: utf-8 -*-
# pidlockfile.py
#
# Copyright © 2008–2009 Ben Finney <[email protected]>
#
# This is free software: you may copy, modify, and/or distribute this work
# under the terms of the Python Software Foundation License, version 2 or
# later as published by the Python Software Foundation.
# No warranty expressed or implied. See the file LICENSE.PSF-2 for details.
""" Lockfile behaviour implemented via Unix PID files.
"""
from __future__ import absolute_import
import errno
import os
import time
from . import (LockBase, AlreadyLocked, LockFailed, NotLocked, NotMyLock,
LockTimeout)
class PIDLockFile(LockBase):
""" Lockfile implemented as a Unix PID file.
The lock file is a normal file named by the attribute `path`.
A lock's PID file contains a single line of text, containing
the process ID (PID) of the process that acquired the lock.
>>> lock = PIDLockFile('somefile')
>>> lock = PIDLockFile('somefile')
"""
def __init__(self, path, threaded=False, timeout=None):
# pid lockfiles don't support threaded operation, so always force
# False as the threaded arg.
LockBase.__init__(self, path, False, timeout)
self.unique_name = self.path
def read_pid(self):
""" Get the PID from the lock file.
"""
return read_pid_from_pidfile(self.path)
def is_locked(self):
""" Test if the lock is currently held.
The lock is held if the PID file for this lock exists.
"""
return os.path.exists(self.path)
def i_am_locking(self):
""" Test if the lock is held by the current process.
Returns ``True`` if the current process ID matches the
number stored in the PID file.
"""
return self.is_locked() and os.getpid() == self.read_pid()
def acquire(self, timeout=None):
""" Acquire the lock.
Creates the PID file for this lock, or raises an error if
the lock could not be acquired.
"""
timeout = timeout if timeout is not None else self.timeout
end_time = time.time()
if timeout is not None and timeout > 0:
end_time += timeout
while True:
try:
write_pid_to_pidfile(self.path)
except OSError as exc:
if exc.errno == errno.EEXIST:
# The lock creation failed. Maybe sleep a bit.
if time.time() > end_time:
if timeout is not None and timeout > 0:
raise LockTimeout("Timeout waiting to acquire"
" lock for %s" %
self.path)
else:
raise AlreadyLocked("%s is already locked" %
self.path)
time.sleep(timeout is not None and timeout / 10 or 0.1)
else:
raise LockFailed("failed to create %s" % self.path)
else:
return
def release(self):
""" Release the lock.
Removes the PID file to release the lock, or raises an
error if the current process does not hold the lock.
"""
if not self.is_locked():
raise NotLocked("%s is not locked" % self.path)
if not self.i_am_locking():
raise NotMyLock("%s is locked, but not by me" % self.path)
remove_existing_pidfile(self.path)
def break_lock(self):
""" Break an existing lock.
Removes the PID file if it already exists, otherwise does
nothing.
"""
remove_existing_pidfile(self.path)
def read_pid_from_pidfile(pidfile_path):
""" Read the PID recorded in the named PID file.
Read and return the numeric PID recorded as text in the named
PID file. If the PID file cannot be read, or if the content is
not a valid PID, return ``None``.
"""
pid = None
try:
pidfile = open(pidfile_path, 'r')
except IOError:
pass
else:
# According to the FHS 2.3 section on PID files in /var/run:
#
# The file must consist of the process identifier in
# ASCII-encoded decimal, followed by a newline character.
#
# Programs that read PID files should be somewhat flexible
# in what they accept; i.e., they should ignore extra
# whitespace, leading zeroes, absence of the trailing
# newline, or additional lines in the PID file.
line = pidfile.readline().strip()
try:
pid = int(line)
except ValueError:
pass
pidfile.close()
return pid
def write_pid_to_pidfile(pidfile_path):
""" Write the PID in the named PID file.
Get the numeric process ID (“PID”) of the current process
and write it to the named file as a line of text.
"""
open_flags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY)
open_mode = 0o644
pidfile_fd = os.open(pidfile_path, open_flags, open_mode)
pidfile = os.fdopen(pidfile_fd, 'w')
# According to the FHS 2.3 section on PID files in /var/run:
#
# The file must consist of the process identifier in
# ASCII-encoded decimal, followed by a newline character. For
# example, if crond was process number 25, /var/run/crond.pid
# would contain three characters: two, five, and newline.
pid = os.getpid()
pidfile.write("%s\n" % pid)
pidfile.close()
def remove_existing_pidfile(pidfile_path):
""" Remove the named PID file if it exists.
Removing a PID file that doesn't already exist puts us in the
desired state, so we ignore the condition if the file does not
exist.
"""
try:
os.remove(pidfile_path)
except OSError as exc:
if exc.errno == errno.ENOENT:
pass
else:
raise
|
gpl-3.0
|
martynovp/edx-platform
|
cms/djangoapps/contentstore/features/problem-editor.py
|
116
|
12757
|
# disable missing docstring
# pylint: disable=missing-docstring
import json
from lettuce import world, step
from nose.tools import assert_equal, assert_true # pylint: disable=no-name-in-module
from common import type_in_codemirror, open_new_course
from advanced_settings import change_value, ADVANCED_MODULES_KEY
from course_import import import_file
DISPLAY_NAME = "Display Name"
MAXIMUM_ATTEMPTS = "Maximum Attempts"
PROBLEM_WEIGHT = "Problem Weight"
RANDOMIZATION = 'Randomization'
SHOW_ANSWER = "Show Answer"
SHOW_RESET_BUTTON = "Show Reset Button"
TIMER_BETWEEN_ATTEMPTS = "Timer Between Attempts"
MATLAB_API_KEY = "Matlab API key"
@step('I have created a Blank Common Problem$')
def i_created_blank_common_problem(step):
step.given('I am in Studio editing a new unit')
step.given("I have created another Blank Common Problem")
@step('I have created a unit with advanced module "(.*)"$')
def i_created_unit_with_advanced_module(step, advanced_module):
step.given('I am in Studio editing a new unit')
url = world.browser.url
step.given("I select the Advanced Settings")
change_value(step, ADVANCED_MODULES_KEY, '["{}"]'.format(advanced_module))
world.visit(url)
world.wait_for_xmodule()
@step('I have created an advanced component "(.*)" of type "(.*)"')
def i_create_new_advanced_component(step, component_type, advanced_component):
world.create_component_instance(
step=step,
category='advanced',
component_type=component_type,
advanced_component=advanced_component
)
@step('I have created another Blank Common Problem$')
def i_create_new_common_problem(step):
world.create_component_instance(
step=step,
category='problem',
component_type='Blank Common Problem'
)
@step('when I mouseover on "(.*)"')
def i_mouseover_on_html_component(step, element_class):
action_css = '.{}'.format(element_class)
world.trigger_event(action_css, event='mouseover')
@step(u'I can see Reply to Annotation link$')
def i_see_reply_to_annotation_link(_step):
css_selector = 'a.annotatable-reply'
world.wait_for_visible(css_selector)
@step(u'I see that page has scrolled "(.*)" when I click on "(.*)" link$')
def i_see_annotation_problem_page_scrolls(_step, scroll_direction, link_css):
scroll_js = "$(window).scrollTop();"
scroll_height_before = world.browser.evaluate_script(scroll_js)
world.css_click("a.{}".format(link_css))
scroll_height_after = world.browser.evaluate_script(scroll_js)
if scroll_direction == "up":
assert scroll_height_after < scroll_height_before
elif scroll_direction == "down":
assert scroll_height_after > scroll_height_before
@step('I have created an advanced problem of type "(.*)"$')
def i_create_new_advanced_problem(step, component_type):
world.create_component_instance(
step=step,
category='problem',
component_type=component_type,
is_advanced=True
)
@step('I edit and select Settings$')
def i_edit_and_select_settings(_step):
world.edit_component_and_select_settings()
@step('I see the advanced settings and their expected values$')
def i_see_advanced_settings_with_values(step):
world.verify_all_setting_entries(
[
[DISPLAY_NAME, "Blank Common Problem", True],
[MATLAB_API_KEY, "", False],
[MAXIMUM_ATTEMPTS, "", False],
[PROBLEM_WEIGHT, "", False],
[RANDOMIZATION, "Never", False],
[SHOW_ANSWER, "Finished", False],
[SHOW_RESET_BUTTON, "False", False],
[TIMER_BETWEEN_ATTEMPTS, "0", False],
])
@step('I can modify the display name')
def i_can_modify_the_display_name(_step):
# Verifying that the display name can be a string containing a floating point value
# (to confirm that we don't throw an error because it is of the wrong type).
index = world.get_setting_entry_index(DISPLAY_NAME)
world.set_field_value(index, '3.4')
verify_modified_display_name()
@step('my display name change is persisted on save')
def my_display_name_change_is_persisted_on_save(step):
world.save_component_and_reopen(step)
verify_modified_display_name()
@step('the problem display name is "(.*)"$')
def verify_problem_display_name(step, name):
assert_equal(name.upper(), world.browser.find_by_css('.problem-header').text)
@step('I can specify special characters in the display name')
def i_can_modify_the_display_name_with_special_chars(_step):
index = world.get_setting_entry_index(DISPLAY_NAME)
world.set_field_value(index, "updated ' \" &")
verify_modified_display_name_with_special_chars()
@step('I can specify html in the display name and save')
def i_can_modify_the_display_name_with_html(_step):
"""
If alert appear on save then UnexpectedAlertPresentException
will occur and test will fail.
"""
index = world.get_setting_entry_index(DISPLAY_NAME)
world.set_field_value(index, "<script>alert('test')</script>")
verify_modified_display_name_with_html()
world.save_component()
@step('my special characters and persisted on save')
def special_chars_persisted_on_save(step):
world.save_component_and_reopen(step)
verify_modified_display_name_with_special_chars()
@step('I can revert the display name to unset')
def can_revert_display_name_to_unset(_step):
world.revert_setting_entry(DISPLAY_NAME)
verify_unset_display_name()
@step('my display name is unset on save')
def my_display_name_is_persisted_on_save(step):
world.save_component_and_reopen(step)
verify_unset_display_name()
@step('I can select Per Student for Randomization')
def i_can_select_per_student_for_randomization(_step):
world.browser.select(RANDOMIZATION, "Per Student")
verify_modified_randomization()
@step('my change to randomization is persisted')
def my_change_to_randomization_is_persisted(step):
world.save_component_and_reopen(step)
verify_modified_randomization()
@step('I can revert to the default value for randomization')
def i_can_revert_to_default_for_randomization(step):
world.revert_setting_entry(RANDOMIZATION)
world.save_component_and_reopen(step)
world.verify_setting_entry(world.get_setting_entry(RANDOMIZATION), RANDOMIZATION, "Never", False)
@step('I can set the weight to "(.*)"?')
def i_can_set_weight(_step, weight):
set_weight(weight)
verify_modified_weight()
@step('my change to weight is persisted')
def my_change_to_weight_is_persisted(step):
world.save_component_and_reopen(step)
verify_modified_weight()
@step('I can revert to the default value of unset for weight')
def i_can_revert_to_default_for_unset_weight(step):
world.revert_setting_entry(PROBLEM_WEIGHT)
world.save_component_and_reopen(step)
world.verify_setting_entry(world.get_setting_entry(PROBLEM_WEIGHT), PROBLEM_WEIGHT, "", False)
@step('if I set the weight to "(.*)", it remains unset')
def set_the_weight_to_abc(step, bad_weight):
set_weight(bad_weight)
# We show the clear button immediately on type, hence the "True" here.
world.verify_setting_entry(world.get_setting_entry(PROBLEM_WEIGHT), PROBLEM_WEIGHT, "", True)
world.save_component_and_reopen(step)
# But no change was actually ever sent to the model, so on reopen, explicitly_set is False
world.verify_setting_entry(world.get_setting_entry(PROBLEM_WEIGHT), PROBLEM_WEIGHT, "", False)
@step('if I set the max attempts to "(.*)", it will persist as a valid integer$')
def set_the_max_attempts(step, max_attempts_set):
# on firefox with selenium, the behavior is different.
# eg 2.34 displays as 2.34 and is persisted as 2
index = world.get_setting_entry_index(MAXIMUM_ATTEMPTS)
world.set_field_value(index, max_attempts_set)
world.save_component_and_reopen(step)
value = world.css_value('input.setting-input', index=index)
assert value != "", "max attempts is blank"
assert int(value) >= 0
@step('Edit High Level Source is not visible')
def edit_high_level_source_not_visible(step):
verify_high_level_source_links(step, False)
@step('Edit High Level Source is visible')
def edit_high_level_source_links_visible(step):
verify_high_level_source_links(step, True)
@step('If I press Cancel my changes are not persisted')
def cancel_does_not_save_changes(step):
world.cancel_component(step)
step.given("I edit and select Settings")
step.given("I see the advanced settings and their expected values")
@step('I have enabled latex compiler')
def enable_latex_compiler(step):
url = world.browser.url
step.given("I select the Advanced Settings")
change_value(step, 'Enable LaTeX Compiler', 'true')
world.visit(url)
world.wait_for_xmodule()
@step('I have created a LaTeX Problem')
def create_latex_problem(step):
step.given('I am in Studio editing a new unit')
step.given('I have enabled latex compiler')
world.create_component_instance(
step=step,
category='problem',
component_type='Problem Written in LaTeX',
is_advanced=True
)
@step('I edit and compile the High Level Source')
def edit_latex_source(_step):
open_high_level_source()
type_in_codemirror(1, "hi")
world.css_click('.hls-compile')
@step('my change to the High Level Source is persisted')
def high_level_source_persisted(_step):
def verify_text(driver):
css_sel = '.problem div>span'
return world.css_text(css_sel) == 'hi'
world.wait_for(verify_text, timeout=10)
@step('I view the High Level Source I see my changes')
def high_level_source_in_editor(_step):
open_high_level_source()
assert_equal('hi', world.css_value('.source-edit-box'))
@step(u'I have an empty course')
def i_have_empty_course(step):
open_new_course()
@step(u'I import the file "([^"]*)"$')
def i_import_the_file(_step, filename):
import_file(filename)
@step(u'I go to the vertical "([^"]*)"$')
def i_go_to_vertical(_step, vertical):
world.css_click("span:contains('{0}')".format(vertical))
@step(u'I go to the unit "([^"]*)"$')
def i_go_to_unit(_step, unit):
loc = "window.location = $(\"span:contains('{0}')\").closest('a').attr('href')".format(unit)
world.browser.execute_script(loc)
@step(u'I see a message that says "([^"]*)"$')
def i_can_see_message(_step, msg):
msg = json.dumps(msg) # escape quotes
world.css_has_text("h2.title", msg)
@step(u'I can edit the problem$')
def i_can_edit_problem(_step):
world.edit_component()
@step(u'I edit first blank advanced problem for annotation response$')
def i_edit_blank_problem_for_annotation_response(_step):
world.edit_component(1)
text = """
<problem>
<annotationresponse>
<annotationinput><text>Text of annotation</text></annotationinput>
</annotationresponse>
</problem>"""
type_in_codemirror(0, text)
world.save_component()
@step(u'I can see cheatsheet$')
def verify_cheat_sheet_displaying(_step):
world.css_click("a.cheatsheet-toggle")
css_selector = 'article.simple-editor-cheatsheet'
world.wait_for_visible(css_selector)
def verify_high_level_source_links(step, visible):
if visible:
assert_true(world.is_css_present('.launch-latex-compiler'),
msg="Expected to find the latex button but it is not present.")
else:
assert_true(world.is_css_not_present('.launch-latex-compiler'),
msg="Expected not to find the latex button but it is present.")
world.cancel_component(step)
def verify_modified_weight():
world.verify_setting_entry(world.get_setting_entry(PROBLEM_WEIGHT), PROBLEM_WEIGHT, "3.5", True)
def verify_modified_randomization():
world.verify_setting_entry(world.get_setting_entry(RANDOMIZATION), RANDOMIZATION, "Per Student", True)
def verify_modified_display_name():
world.verify_setting_entry(world.get_setting_entry(DISPLAY_NAME), DISPLAY_NAME, '3.4', True)
def verify_modified_display_name_with_special_chars():
world.verify_setting_entry(world.get_setting_entry(DISPLAY_NAME), DISPLAY_NAME, "updated ' \" &", True)
def verify_modified_display_name_with_html():
world.verify_setting_entry(world.get_setting_entry(DISPLAY_NAME), DISPLAY_NAME, "<script>alert('test')</script>", True)
def verify_unset_display_name():
world.verify_setting_entry(world.get_setting_entry(DISPLAY_NAME), DISPLAY_NAME, 'Blank Advanced Problem', False)
def set_weight(weight):
index = world.get_setting_entry_index(PROBLEM_WEIGHT)
world.set_field_value(index, weight)
def open_high_level_source():
world.edit_component()
world.css_click('.launch-latex-compiler > a')
|
agpl-3.0
|
wakermahmud/sync-engine
|
inbox/util/consistency_check/__main__.py
|
6
|
9625
|
"""
Integrity check debugging tool for IMAP accounts.
Run as:
python -m inbox.util.consistency_check --help
"""
from __future__ import absolute_import, division, print_function
import argparse
import errno
import os
import pkg_resources
import subprocess
import sys
from fnmatch import fnmatch
from inbox.models import Account, Namespace
from inbox.models.session import session_scope
from inbox.sqlalchemy_ext.util import (
b36_to_bin,
int128_to_b36, # XXX: should probably be called bin_to_b36
)
from .sqlite3_db import connect_sqlite3_db, init_sqlite3_db
class _ALL_ACCOUNTS(object):
def __str__(self):
return "all accounts" # for --help
ALL_ACCOUNTS = _ALL_ACCOUNTS()
def execute_hooks(plugins, method_name):
def f(*args, **kwargs):
results = []
for name, plugin in plugins:
res = execute_hook(plugin, method_name)(*args, **kwargs)
results.append(res)
return results
return f
def execute_hook(plugin, method_name):
def f(*args, **kwargs):
func = getattr(plugin, method_name, None)
if func is None:
return None
return func(*args, **kwargs)
return f
def main():
# Load plugins
group = 'inbox.consistency_check_plugins'
plugins = [] # see ListPlugin as an example
for entry_point in pkg_resources.iter_entry_points(group):
plugin_factory = entry_point.load() # usually a python class
plugin = plugin_factory()
plugins.append((entry_point.name, plugin))
# Create argument parser
# NOTE: In the future, the interface may change to accept namespace
# public_ids instead of account public_ids.
parser = argparse.ArgumentParser(
description="""
Shows differences between metadata fetched from the specified
account(s) and what's stored in the local Inbox database.
""",
epilog = """
Only Gmail accounts are currently supported.
""")
parser.add_argument(
"public_ids", nargs='*', metavar="PUBLIC_ID",
type=lambda x: int128_to_b36(b36_to_bin(x)), default=ALL_ACCOUNTS,
help="account(s) to check (default: %(default)s)")
parser.add_argument(
'--cache-dir', default='./cache',
help="cache directory (default: %(default)s)")
parser.add_argument(
'--no-overwrite', action='store_false', dest='force_overwrite',
help="skip cache files already generated (default: overwrite them)")
parser.add_argument(
'--no-fetch', action='store_false', dest='do_slurp',
help="don't fetch")
parser.add_argument(
'--no-dump', action='store_false', dest='do_dump',
help="don't dump")
parser.add_argument(
'--no-diff', action='store_false', dest='do_diff',
help="don't diff")
execute_hooks(plugins, 'argparse_addoption')(parser)
# Parse arguments
args = parser.parse_args()
execute_hooks(plugins, 'argparse_args')(args)
# Make sure the cache directory exists.
if not os.path.exists(args.cache_dir):
os.mkdir(args.cache_dir)
with session_scope() as db_session:
# Query the list of accounts
query = db_session.query(Account)
if args.public_ids is not ALL_ACCOUNTS:
query = query.filter(Account.public_id.in_(args.public_ids))
accounts = query.all()
# list.py uses this hook to show a list of accounts
execute_hooks(plugins, 'process_accounts')(accounts)
# hax
if args.do_list:
return
# Query namespaces
query = (
db_session.query(Namespace, Account)
.filter(Namespace.account_id == Account.id)
.order_by(Namespace.id)
)
if args.public_ids is not ALL_ACCOUNTS:
query = query.filter(Namespace.public_id.in_(args.public_ids))
nnaa = query.all()
# check for discrepancies
missing_accounts = (set(a.public_id for ns, a in nnaa) ^
set(a.public_id for a in accounts))
if missing_accounts:
raise AssertionError("Missing accounts: %r" % (missing_accounts,))
# Fetch metadata for each account and save it into a sqlite3 database
# in the cache_dir.
# - See imap_gm.py & local_gm.py
# - See sqlite3_db.py for sqlite3 database schema.
# This creates files like:
# - cache/<account.public_id>.<namespace.public_id>.imap_gm.sqlite3
# - cache/<account.public_id>.<namespace.public_id>.local_gm.sqlite3
if args.do_slurp:
for namespace, account in nnaa:
can_slurp = execute_hooks(plugins, 'can_slurp_namespace')(
namespace=namespace,
account=account)
for i, (plugin_name, plugin) in enumerate(plugins):
if not can_slurp[i]:
continue
db_path = os.path.join(
args.cache_dir,
cachefile_basename(
namespace=namespace,
account=account,
plugin_name=plugin_name,
ext='.sqlite3'))
if os.path.exists(db_path):
if not args.force_overwrite:
# already saved
print(
"skipping {0}: already exists".format(db_path),
file=sys.stderr)
continue
os.unlink(db_path)
db = init_sqlite3_db(connect_sqlite3_db(db_path))
with db:
execute_hook(plugin, 'slurp_namespace')(
namespace=namespace,
account=account,
db=db)
# Generate canonical-format text files from the sqlite3 databases.
# - See dump_gm.py
# This creates files like:
# - cache/<account.public_id>.<namespace.public_id>.imap_gm.txt
# - cache/<account.public_id>.<namespace.public_id>.local_gm.txt
if args.do_dump:
for namespace, account in nnaa:
can_dump = execute_hooks(plugins, 'can_dump_namespace')(
namespace=namespace,
account=account)
for i, (plugin_name, plugin) in enumerate(plugins):
if not can_dump[i]:
continue
db_path = os.path.join(args.cache_dir, cachefile_basename(
namespace=namespace,
account=account,
plugin_name=plugin_name,
ext='.sqlite3'))
txt_path = os.path.join(args.cache_dir, cachefile_basename(
namespace=namespace,
account=account,
plugin_name=plugin_name,
ext='.txt'))
try:
db_stat = os.stat(db_path)
except OSError as e:
if e.errno != errno.ENOENT:
raise
db_stat = None
try:
txt_stat = os.stat(txt_path)
except OSError as e:
if e.errno != errno.ENOENT:
raise
txt_stat = None
if (db_stat and txt_stat and
db_stat.st_mtime < txt_stat.st_mtime):
print(
"skipping {0}: already exists".format(txt_path),
file=sys.stderr)
continue
db = connect_sqlite3_db(db_path)
with db, open(txt_path, "w") as txtfile:
execute_hook(plugin, 'dump_namespace')(
db=db,
txtfile=txtfile)
# Show differences between the text files in the cache directory.
# Basically, this runs something like the following for each account:
# vimdiff cache/${acct_pubid}.${ns_pubid).imap_gm.txt cache/${acct_pubid}.${ns_pubid).local_gm.txt
if args.do_diff:
if os.system("which vimdiff >/dev/null") == 0:
diff_cmd = ['vimdiff']
else:
diff_cmd = ['diff', '-u']
for namespace, account in nnaa:
# plugins here would be nice here, too
# This is such a hack
files_to_diff = sorted(
os.path.join(args.cache_dir, f)
for f in os.listdir(args.cache_dir)
if fnmatch(f, cachefile_basename(
namespace=namespace,
account=account,
plugin_name='*',
ext='.txt')))
if files_to_diff:
status = subprocess.call(diff_cmd + files_to_diff)
if status not in (0, 1):
raise AssertionError("error running diff")
def cachefile_basename(namespace, account, plugin_name, ext=''):
return '{acct_pubid}.{ns_pubid}.{plugin_name}{ext}'.format(
acct_pubid=account.public_id,
ns_pubid=namespace.public_id,
plugin_name=plugin_name,
ext=ext)
if __name__ == '__main__':
main()
|
agpl-3.0
|
0-wiz-0/audacity
|
lib-src/lv2/lv2/plugins/eg-sampler.lv2/waflib/Configure.py
|
181
|
9880
|
#! /usr/bin/env python
# encoding: utf-8
# WARNING! Do not edit! http://waf.googlecode.com/git/docs/wafbook/single.html#_obtaining_the_waf_file
import os,shlex,sys,time
from waflib import ConfigSet,Utils,Options,Logs,Context,Build,Errors
try:
from urllib import request
except ImportError:
from urllib import urlopen
else:
urlopen=request.urlopen
BREAK='break'
CONTINUE='continue'
WAF_CONFIG_LOG='config.log'
autoconfig=False
conf_template='''# project %(app)s configured on %(now)s by
# waf %(wafver)s (abi %(abi)s, python %(pyver)x on %(systype)s)
# using %(args)s
#'''
def download_check(node):
pass
def download_tool(tool,force=False,ctx=None):
for x in Utils.to_list(Context.remote_repo):
for sub in Utils.to_list(Context.remote_locs):
url='/'.join((x,sub,tool+'.py'))
try:
web=urlopen(url)
try:
if web.getcode()!=200:
continue
except AttributeError:
pass
except Exception:
continue
else:
tmp=ctx.root.make_node(os.sep.join((Context.waf_dir,'waflib','extras',tool+'.py')))
tmp.write(web.read(),'wb')
Logs.warn('Downloaded %s from %s'%(tool,url))
download_check(tmp)
try:
module=Context.load_tool(tool)
except Exception:
Logs.warn('The tool %s from %s is unusable'%(tool,url))
try:
tmp.delete()
except Exception:
pass
continue
return module
raise Errors.WafError('Could not load the Waf tool')
class ConfigurationContext(Context.Context):
'''configures the project'''
cmd='configure'
error_handlers=[]
def __init__(self,**kw):
super(ConfigurationContext,self).__init__(**kw)
self.environ=dict(os.environ)
self.all_envs={}
self.top_dir=None
self.out_dir=None
self.tools=[]
self.hash=0
self.files=[]
self.tool_cache=[]
self.setenv('')
def setenv(self,name,env=None):
if name not in self.all_envs or env:
if not env:
env=ConfigSet.ConfigSet()
self.prepare_env(env)
else:
env=env.derive()
self.all_envs[name]=env
self.variant=name
def get_env(self):
return self.all_envs[self.variant]
def set_env(self,val):
self.all_envs[self.variant]=val
env=property(get_env,set_env)
def init_dirs(self):
top=self.top_dir
if not top:
top=Options.options.top
if not top:
top=getattr(Context.g_module,Context.TOP,None)
if not top:
top=self.path.abspath()
top=os.path.abspath(top)
self.srcnode=(os.path.isabs(top)and self.root or self.path).find_dir(top)
assert(self.srcnode)
out=self.out_dir
if not out:
out=Options.options.out
if not out:
out=getattr(Context.g_module,Context.OUT,None)
if not out:
out=Options.lockfile.replace('.lock-waf_%s_'%sys.platform,'').replace('.lock-waf','')
self.bldnode=(os.path.isabs(out)and self.root or self.path).make_node(out)
self.bldnode.mkdir()
if not os.path.isdir(self.bldnode.abspath()):
conf.fatal('Could not create the build directory %s'%self.bldnode.abspath())
def execute(self):
self.init_dirs()
self.cachedir=self.bldnode.make_node(Build.CACHE_DIR)
self.cachedir.mkdir()
path=os.path.join(self.bldnode.abspath(),WAF_CONFIG_LOG)
self.logger=Logs.make_logger(path,'cfg')
app=getattr(Context.g_module,'APPNAME','')
if app:
ver=getattr(Context.g_module,'VERSION','')
if ver:
app="%s (%s)"%(app,ver)
now=time.ctime()
pyver=sys.hexversion
systype=sys.platform
args=" ".join(sys.argv)
wafver=Context.WAFVERSION
abi=Context.ABI
self.to_log(conf_template%vars())
self.msg('Setting top to',self.srcnode.abspath())
self.msg('Setting out to',self.bldnode.abspath())
if id(self.srcnode)==id(self.bldnode):
Logs.warn('Setting top == out (remember to use "update_outputs")')
elif id(self.path)!=id(self.srcnode):
if self.srcnode.is_child_of(self.path):
Logs.warn('Are you certain that you do not want to set top="." ?')
super(ConfigurationContext,self).execute()
self.store()
Context.top_dir=self.srcnode.abspath()
Context.out_dir=self.bldnode.abspath()
env=ConfigSet.ConfigSet()
env['argv']=sys.argv
env['options']=Options.options.__dict__
env.run_dir=Context.run_dir
env.top_dir=Context.top_dir
env.out_dir=Context.out_dir
env['hash']=self.hash
env['files']=self.files
env['environ']=dict(self.environ)
if not self.env.NO_LOCK_IN_RUN:
env.store(Context.run_dir+os.sep+Options.lockfile)
if not self.env.NO_LOCK_IN_TOP:
env.store(Context.top_dir+os.sep+Options.lockfile)
if not self.env.NO_LOCK_IN_OUT:
env.store(Context.out_dir+os.sep+Options.lockfile)
def prepare_env(self,env):
if not env.PREFIX:
if Options.options.prefix or Utils.is_win32:
env.PREFIX=os.path.abspath(os.path.expanduser(Options.options.prefix))
else:
env.PREFIX=''
if not env.BINDIR:
env.BINDIR=Utils.subst_vars('${PREFIX}/bin',env)
if not env.LIBDIR:
env.LIBDIR=Utils.subst_vars('${PREFIX}/lib',env)
def store(self):
n=self.cachedir.make_node('build.config.py')
n.write('version = 0x%x\ntools = %r\n'%(Context.HEXVERSION,self.tools))
if not self.all_envs:
self.fatal('nothing to store in the configuration context!')
for key in self.all_envs:
tmpenv=self.all_envs[key]
tmpenv.store(os.path.join(self.cachedir.abspath(),key+Build.CACHE_SUFFIX))
def load(self,input,tooldir=None,funs=None,download=True):
tools=Utils.to_list(input)
if tooldir:tooldir=Utils.to_list(tooldir)
for tool in tools:
mag=(tool,id(self.env),funs)
if mag in self.tool_cache:
self.to_log('(tool %s is already loaded, skipping)'%tool)
continue
self.tool_cache.append(mag)
module=None
try:
module=Context.load_tool(tool,tooldir)
except ImportError ,e:
if Options.options.download:
module=download_tool(tool,ctx=self)
if not module:
self.fatal('Could not load the Waf tool %r or download a suitable replacement from the repository (sys.path %r)\n%s'%(tool,sys.path,e))
else:
self.fatal('Could not load the Waf tool %r from %r (try the --download option?):\n%s'%(tool,sys.path,e))
except Exception ,e:
self.to_log('imp %r (%r & %r)'%(tool,tooldir,funs))
self.to_log(Utils.ex_stack())
raise
if funs is not None:
self.eval_rules(funs)
else:
func=getattr(module,'configure',None)
if func:
if type(func)is type(Utils.readf):func(self)
else:self.eval_rules(func)
self.tools.append({'tool':tool,'tooldir':tooldir,'funs':funs})
def post_recurse(self,node):
super(ConfigurationContext,self).post_recurse(node)
self.hash=Utils.h_list((self.hash,node.read('rb')))
self.files.append(node.abspath())
def eval_rules(self,rules):
self.rules=Utils.to_list(rules)
for x in self.rules:
f=getattr(self,x)
if not f:self.fatal("No such method '%s'."%x)
try:
f()
except Exception ,e:
ret=self.err_handler(x,e)
if ret==BREAK:
break
elif ret==CONTINUE:
continue
else:
raise
def err_handler(self,fun,error):
pass
def conf(f):
def fun(*k,**kw):
mandatory=True
if'mandatory'in kw:
mandatory=kw['mandatory']
del kw['mandatory']
try:
return f(*k,**kw)
except Errors.ConfigurationError:
if mandatory:
raise
setattr(ConfigurationContext,f.__name__,fun)
setattr(Build.BuildContext,f.__name__,fun)
return f
@conf
def add_os_flags(self,var,dest=None):
try:self.env.append_value(dest or var,shlex.split(self.environ[var]))
except KeyError:pass
@conf
def cmd_to_list(self,cmd):
if isinstance(cmd,str)and cmd.find(' '):
try:
os.stat(cmd)
except OSError:
return shlex.split(cmd)
else:
return[cmd]
return cmd
@conf
def check_waf_version(self,mini='1.6.99',maxi='1.8.0'):
self.start_msg('Checking for waf version in %s-%s'%(str(mini),str(maxi)))
ver=Context.HEXVERSION
if Utils.num2ver(mini)>ver:
self.fatal('waf version should be at least %r (%r found)'%(Utils.num2ver(mini),ver))
if Utils.num2ver(maxi)<ver:
self.fatal('waf version should be at most %r (%r found)'%(Utils.num2ver(maxi),ver))
self.end_msg('ok')
@conf
def find_file(self,filename,path_list=[]):
for n in Utils.to_list(filename):
for d in Utils.to_list(path_list):
p=os.path.join(d,n)
if os.path.exists(p):
return p
self.fatal('Could not find %r'%filename)
@conf
def find_program(self,filename,**kw):
exts=kw.get('exts',Utils.is_win32 and'.exe,.com,.bat,.cmd'or',.sh,.pl,.py')
environ=kw.get('environ',os.environ)
ret=''
filename=Utils.to_list(filename)
var=kw.get('var','')
if not var:
var=filename[0].upper()
if self.env[var]:
ret=self.env[var]
elif var in environ:
ret=environ[var]
path_list=kw.get('path_list','')
if not ret:
if path_list:
path_list=Utils.to_list(path_list)
else:
path_list=environ.get('PATH','').split(os.pathsep)
if not isinstance(filename,list):
filename=[filename]
for a in exts.split(','):
if ret:
break
for b in filename:
if ret:
break
for c in path_list:
if ret:
break
x=os.path.expanduser(os.path.join(c,b+a))
if os.path.isfile(x):
ret=x
if not ret and Utils.winreg:
ret=Utils.get_registry_app_path(Utils.winreg.HKEY_CURRENT_USER,filename)
if not ret and Utils.winreg:
ret=Utils.get_registry_app_path(Utils.winreg.HKEY_LOCAL_MACHINE,filename)
self.msg('Checking for program '+','.join(filename),ret or False)
self.to_log('find program=%r paths=%r var=%r -> %r'%(filename,path_list,var,ret))
if not ret:
self.fatal(kw.get('errmsg','')or'Could not find the program %s'%','.join(filename))
if var:
self.env[var]=ret
return ret
@conf
def find_perl_program(self,filename,path_list=[],var=None,environ=None,exts=''):
try:
app=self.find_program(filename,path_list=path_list,var=var,environ=environ,exts=exts)
except Exception:
self.find_program('perl',var='PERL')
app=self.find_file(filename,os.environ['PATH'].split(os.pathsep))
if not app:
raise
if var:
self.env[var]=Utils.to_list(self.env['PERL'])+[app]
self.msg('Checking for %r'%filename,app)
|
gpl-2.0
|
Hairo/trackma
|
trackma/ui/curses.py
|
1
|
40982
|
# This file is part of Trackma.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import sys
import os
import subprocess
try:
import urwid
except ImportError:
print("urwid not found. Make sure you installed the "
"urwid package.")
sys.exit(-1)
import re
import urwid
import webbrowser
from operator import itemgetter
from itertools import cycle
from trackma.engine import Engine
from trackma.accounts import AccountManager
from trackma import messenger
from trackma import utils
class Trackma_urwid():
"""
Main class for the urwid version of Trackma
"""
"""Main objects"""
engine = None
mainloop = None
cur_sort = 'title'
sorts_iter = cycle(('my_progress', 'total', 'my_score', 'id', 'title'))
cur_order = False
orders_iter = cycle((True, False))
keymapping = dict()
positions = list()
last_search = None
last_update_prompt = ()
"""Widgets"""
header = None
listbox = None
view = None
def __init__(self):
"""Creates main widgets and creates mainloop"""
self.config = utils.parse_config(utils.to_config_path('ui-curses.json'), utils.curses_defaults)
keymap = utils.curses_defaults['keymap']
keymap.update(self.config['keymap'])
self.keymap_str = self.get_keymap_str(keymap)
self.keymapping = self.map_key_to_func(keymap)
palette = []
for k, color in self.config['palette'].items():
palette.append( (k, color[0], color[1]) )
# Prepare header
sys.stdout.write("\x1b]0;Trackma-curses "+utils.VERSION+"\x07");
self.header_title = urwid.Text('Trackma-curses ' + utils.VERSION)
self.header_api = urwid.Text('API:')
self.header_filter = urwid.Text('Filter:')
self.header_sort = urwid.Text('Sort:title')
self.header_order = urwid.Text('Order:d')
self.header = urwid.AttrMap(urwid.Columns([
self.header_title,
('fixed', 30, self.header_filter),
('fixed', 17, self.header_sort),
('fixed', 16, self.header_api)]), 'status')
top_pile = [self.header]
if self.config['show_help']:
top_text = "{help}:Help {sort}:Sort " + \
"{update}:Update {play}:Play " + \
"{status}:Status {score}:Score " + \
"{quit}:Quit"
top_text = top_text.format(**self.keymap_str)
top_pile.append(urwid.AttrMap(urwid.Text(top_text), 'status'))
self.top_pile = urwid.Pile(top_pile)
# Prepare status bar
self.status_text = urwid.Text('Trackma-curses '+utils.VERSION)
self.status_queue = urwid.Text('Q:N/A')
self.status_tracker = urwid.Text('T:N/A')
self.statusbar = urwid.AttrMap(urwid.Columns([
self.status_text,
('fixed', 10, self.status_tracker),
('fixed', 6, self.status_queue),
]), 'status')
self.listheader = urwid.AttrMap(
urwid.Columns([
('weight', 1, urwid.Text('Title')),
('fixed', 10, urwid.Text('Progress')),
('fixed', 7, urwid.Text('Score')),
]), 'header')
self.listwalker = ShowWalker([])
self.listbox = urwid.ListBox(self.listwalker)
self.listframe = urwid.Frame(self.listbox, header=self.listheader)
self.viewing_info = False
self.view = urwid.Frame(self.listframe, header=self.top_pile, footer=self.statusbar)
self.mainloop = urwid.MainLoop(self.view, palette, unhandled_input=self.keystroke, screen=urwid.raw_display.Screen())
def run(self):
self.mainloop.set_alarm_in(0, self.do_switch_account)
self.mainloop.run()
def map_key_to_func(self, keymap):
keymapping = dict()
funcmap = { 'help': self.do_help,
'prev_filter': self.do_prev_filter,
'next_filter': self.do_next_filter,
'sort': self.do_sort,
'sort_order': self.change_sort_order,
'update': self.do_update,
'play': self.do_play,
'openfolder': self.do_openfolder,
'play_random': self.do_play_random,
'status': self.do_status,
'score': self.do_score,
'send': self.do_send,
'retrieve': self.do_retrieve,
'addsearch': self.do_addsearch,
'reload': self.do_reload,
'switch_account': self.do_switch_account,
'delete': self.do_delete,
'quit': self.do_quit,
'altname': self.do_altname,
'search': self.do_search,
'neweps': self.do_neweps,
'details': self.do_info,
'details_exit': self.do_info_exit,
'open_web': self.do_open_web,
'left': self.key_left,
'down': self.key_down,
'up': self.key_up,
'right': self.key_right,
'page_down': self.key_page_down,
'page_up': self.key_page_up,
}
for func, keybind in keymap.items():
try:
if isinstance(keybind, list):
for keybindm in keybind:
keymapping[keybindm] = funcmap[func]
else:
keymapping[keybind] = funcmap[func]
except KeyError:
# keymap.json requested an action not available in funcmap
pass
return keymapping
def get_keymap_str(self, keymap):
stringed = {}
for k, keybind in keymap.items():
if isinstance(keybind, list):
stringed[k] = ','.join(keybind)
else:
stringed[k] = keybind
return stringed
def _rebuild(self):
self.header_api.set_text('API:%s' % self.engine.api_info['name'])
self.lists = dict()
self.filters = self.engine.mediainfo['statuses_dict']
self.filters_nums = self.engine.mediainfo['statuses']
self.filters_sizes = []
track_info = self.engine.tracker_status()
if track_info:
self.tracker_state(track_info)
for status in self.filters_nums:
self.lists[status] = urwid.ListBox(ShowWalker([]))
self._rebuild_lists()
# Put the number of shows in every status in a list
for status in self.filters_nums:
self.filters_sizes.append(len(self.lists[status].body))
self.set_filter(0)
self.status('Ready.')
self.started = True
def _rebuild_lists(self, status=None):
if status:
self.lists[status].body[:] = []
showlist = self.engine.filter_list(status)
else:
for _status in self.lists.keys():
self.lists[_status].body[:] = []
showlist = self.engine.get_list()
library = self.engine.library()
sortedlist = sorted(showlist, key=itemgetter(self.cur_sort), reverse=self.cur_order)
for show in sortedlist:
item = ShowItem(show, self.engine.mediainfo['has_progress'], self.engine.altname(show['id']), library.get(show['id']))
self.lists[show['my_status']].body.append(item)
def start(self, account):
"""Starts the engine"""
# Engine configuration
self.started = False
self.status("Starting engine...")
self.engine = Engine(account, self.message_handler)
self.engine.connect_signal('episode_changed', self.changed_show)
self.engine.connect_signal('score_changed', self.changed_show)
self.engine.connect_signal('status_changed', self.changed_show_status)
self.engine.connect_signal('playing', self.playing_show)
self.engine.connect_signal('show_added', self.changed_list)
self.engine.connect_signal('show_deleted', self.changed_list)
self.engine.connect_signal('show_synced', self.changed_show)
self.engine.connect_signal('queue_changed', self.changed_queue)
self.engine.connect_signal('prompt_for_update', self.prompt_update)
self.engine.connect_signal('tracker_state', self.tracker_state)
# Engine start and list rebuildi
self.status("Building lists...")
self.engine.start()
self._rebuild()
def set_filter(self, filter_num):
self.cur_filter = filter_num
_filter = self.filters_nums[self.cur_filter]
self.header_filter.set_text("Filter:%s (%d)" % (self.filters[_filter], self.filters_sizes[self.cur_filter]))
self.listframe.body = self.lists[_filter]
def _get_cur_list(self):
_filter = self.filters_nums[self.cur_filter]
return self.lists[_filter].body
def _get_selected_item(self):
return self._get_cur_list().get_focus()[0]
def status(self, msg):
self.status_text.set_text(msg)
def error(self, msg):
self.status_text.set_text([('error', "Error: %s" % msg)])
def message_handler(self, classname, msgtype, msg):
if msgtype != messenger.TYPE_DEBUG:
try:
self.status(msg)
self.mainloop.draw_screen()
except AssertionError:
print(msg)
def keystroke(self, input):
try:
self.keymapping[input]()
except KeyError:
# Unbinded key pressed; do nothing
pass
def key_left(self):
self.mainloop.process_input(['left'])
def key_down(self):
self.mainloop.process_input(['down'])
def key_up(self):
self.mainloop.process_input(['up'])
def key_right(self):
self.mainloop.process_input(['right'])
def key_page_down(self):
self.mainloop.process_input(['page down'])
def key_page_up(self):
self.mainloop.process_input(['page up'])
def forget_account(self):
manager = AccountManager()
manager.set_default(None)
def do_switch_account(self, loop=None, data=None):
manager = AccountManager()
if self.engine is None:
if manager.get_default():
self.start(manager.get_default())
else:
self.dialog = AccountDialog(self.mainloop, manager, False)
urwid.connect_signal(self.dialog, 'done', self.start)
else:
self.dialog = AccountDialog(self.mainloop, manager, True)
urwid.connect_signal(self.dialog, 'done', self.do_reload_engine)
def do_addsearch(self):
self.ask('Search on remote: ', self.addsearch_request)
def do_delete(self):
if self._get_selected_item():
self.question('Delete selected show? [y/n] ', self.delete_request)
def do_prev_filter(self):
if self.cur_filter > 0:
self.set_filter(self.cur_filter - 1)
def do_next_filter(self):
if self.cur_filter < len(self.filters)-1:
self.set_filter(self.cur_filter + 1)
def do_sort(self):
self.status("Sorting...")
_sort = next(self.sorts_iter)
self.cur_sort = _sort
self.header_sort.set_text("Sort:%s" % _sort)
self._rebuild_lists()
self.status("Ready.")
def change_sort_order(self):
self.status("Sorting...")
_order = next(self.orders_iter)
self.cur_order = _order
self._rebuild_lists()
self.status("Ready.")
def do_update(self):
item = self._get_selected_item()
if item:
show = self.engine.get_show_info(item.showid)
self.ask('[Update] Episode # to update to: ', self.update_request, show['my_progress']+1)
def do_play(self):
item = self._get_selected_item()
if item:
show = self.engine.get_show_info(item.showid)
self.ask('[Play] Episode # to play: ', self.play_request, show['my_progress']+1)
def do_openfolder(self):
item = self._get_selected_item()
try:
show = self.engine.get_show_info(item.showid)
filename = self.engine.get_episode_path(show, 1)
with open(os.devnull, 'wb') as DEVNULL:
if sys.platform == 'darwin':
subprocess.Popen(["open",
os.path.dirname(filename)], stdout=DEVNULL, stderr=DEVNULL)
elif sys.platform == 'win32':
subprocess.Popen(["explorer",
os.path.dirname(filename)], stdout=DEVNULL, stderr=DEVNULL)
else:
subprocess.Popen(["/usr/bin/xdg-open",
os.path.dirname(filename)], stdout=DEVNULL, stderr=DEVNULL)
except OSError:
# xdg-open failed.
raise utils.EngineError("Could not open folder.")
except utils.EngineError:
# Show not in library.
self.error("No folder found.")
def do_play_random(self):
try:
self.engine.play_random()
except utils.TrackmaError as e:
self.error(e)
return
def do_send(self):
self.engine.list_upload()
self.status("Ready.")
def do_retrieve(self):
try:
self.engine.list_download()
self._rebuild_lists()
self.status("Ready.")
except utils.TrackmaError as e:
self.error(e)
def do_help(self):
helptext = "Trackma-curses "+utils.VERSION+" by z411 ([email protected])\n\n"
helptext += "Trackma is an open source client for media tracking websites.\n"
helptext += "http://github.com/z411/trackma\n\n"
helptext += "This program is licensed under the GPLv3,\nfor more information read COPYING file.\n\n"
helptext += "More controls:\n {prev_filter}/{next_filter}:Change Filter\n {search}:Search\n {addsearch}:Add\n {reload}:Change API/Mediatype\n"
helptext += " {delete}:Delete\n {send}:Send changes\n {sort_order}:Change sort order\n {retrieve}:Retrieve list\n {details}: View details\n {open_web}: Open website\n {openfolder}: Open folder containing show\n {altname}:Set alternative title\n {neweps}:Search for new episodes\n {play_random}:Play Random\n {switch_account}: Change account"
helptext = helptext.format(**self.keymap_str)
ok_button = urwid.Button('OK', self.help_close)
ok_button_wrap = urwid.Padding(urwid.AttrMap(ok_button, 'button', 'button hilight'), 'center', 6)
pile = urwid.Pile([urwid.Text(helptext), ok_button_wrap])
self.dialog = Dialog(pile, self.mainloop, width=62, title='About/Help')
self.dialog.show()
def help_close(self, widget):
self.dialog.close()
def do_altname(self):
item = self._get_selected_item()
if item:
show = self.engine.get_show_info(item.showid)
self.status(show['title'])
self.ask('[Altname] New alternative name: ', self.altname_request, self.engine.altname(item.showid))
def do_score(self):
item = self._get_selected_item()
if item:
show = self.engine.get_show_info(item.showid)
self.ask('[Score] Score to change to: ', self.score_request, show['my_score'])
def do_status(self):
item = self._get_selected_item()
if not item:
return
show = self.engine.get_show_info(item.showid)
buttons = list()
num = 1
selected = 1
title = urwid.Text('Choose status:')
title.align = 'center'
buttons.append(title)
for status in self.filters_nums:
name = self.filters[status]
button = urwid.Button(name, self.status_request, status)
button._label.align = 'center'
buttons.append(urwid.AttrMap(button, 'button', 'button hilight'))
if status == show['my_status']:
selected = num
num += 1
pile = urwid.Pile(buttons)
pile.set_focus(selected)
self.dialog = Dialog(pile, self.mainloop, width=22)
self.dialog.show()
def do_reload(self):
# Create a list of buttons to select the mediatype
rb_mt = []
mediatypes = []
for mediatype in self.engine.api_info['supported_mediatypes']:
but = urwid.RadioButton(rb_mt, mediatype)
# Make it selected if it's the current mediatype
if self.engine.api_info['mediatype'] == mediatype:
but.set_state(True)
urwid.connect_signal(but, 'change', self.reload_request, [None, mediatype])
mediatypes.append(urwid.AttrMap(but, 'button', 'button hilight'))
mediatype = urwid.Columns([urwid.Text('Mediatype:'), urwid.Pile(mediatypes)])
#main_pile = urwid.Pile([mediatype, urwid.Divider(), api])
self.dialog = Dialog(mediatype, self.mainloop, width=30, title='Change media type')
self.dialog.show()
def do_reload_engine(self, account=None, mediatype=None):
self.started = False
self.engine.reload(account, mediatype)
self._rebuild()
def do_open_web(self):
item = self._get_selected_item()
if item:
show = self.engine.get_show_info(item.showid)
if show['url']:
webbrowser.open(show['url'], 2, True)
def do_info(self):
if self.viewing_info:
return
item = self._get_selected_item()
if not item:
return
show = self.engine.get_show_info(item.showid)
self.status("Getting show details...")
try:
details = self.engine.get_show_details(show)
except utils.TrackmaError as e:
self.error(e)
return
title = urwid.Text( ('info_title', show['title']), 'center', 'any')
widgets = []
for line in details['extra']:
if line[0] and line[1]:
widgets.append( urwid.Text( ('info_section', "%s: " % line[0] ) ) )
if isinstance(line[1], dict):
linestr = repr(line[1])
elif isinstance(line[1], int) or isinstance(line[1], list):
linestr = str(line[1])
else:
linestr = line[1]
widgets.append( urwid.Padding(urwid.Text( linestr + "\n" ), left=3) )
self.view.body = urwid.Frame(urwid.ListBox(widgets), header=title)
self.viewing_info = True
self.status("Detail View | ESC:Return Up/Down:Scroll O:View website")
def do_info_exit(self):
if self.viewing_info:
self.view.body = self.listframe
self.viewing_info = False
self.status("Ready.")
def do_neweps(self):
try:
shows = self.engine.scan_library(rescan=True)
self._rebuild_lists()
self.status("Ready.")
except utils.TrackmaError as e:
self.error(e)
def do_quit(self):
if self.viewing_info:
self.do_info_exit()
else:
self.engine.unload()
raise urwid.ExitMainLoop()
def addsearch_request(self, data):
self.ask_finish(self.addsearch_request)
if data:
try:
shows = self.engine.search(data)
except utils.TrackmaError as e:
self.error(e)
return
if len(shows) > 0:
self.status("Ready.")
self.dialog = AddDialog(self.mainloop, self.engine, showlist=shows, width=('relative', 80))
urwid.connect_signal(self.dialog, 'done', self.addsearch_do)
self.dialog.show()
else:
self.status("No results.")
def addsearch_do(self, show):
self.dialog.close()
# Add show as current status
_filter = self.filters_nums[self.cur_filter]
try:
self.engine.add_show(show, _filter)
except utils.TrackmaError as e:
self.error(e)
def delete_request(self, data):
self.ask_finish(self.delete_request)
if data == 'y':
showid = self._get_selected_item().showid
show = self.engine.get_show_info(showid)
try:
self.engine.delete_show(show)
except utils.TrackmaError as e:
self.error(e)
def status_request(self, widget, data=None):
self.dialog.close()
if data is not None:
item = self._get_selected_item()
try:
show = self.engine.set_status(item.showid, data)
except utils.TrackmaError as e:
self.error(e)
return
def reload_request(self, widget, selected, data):
if selected:
self.dialog.close()
self.do_reload_engine(data[0], data[1])
def update_request(self, data):
self.ask_finish(self.update_request)
if data:
item = self._get_selected_item()
try:
show = self.engine.set_episode(item.showid, data)
except utils.TrackmaError as e:
self.error(e)
return
def score_request(self, data):
self.ask_finish(self.score_request)
if data:
item = self._get_selected_item()
try:
show = self.engine.set_score(item.showid, data)
except utils.TrackmaError as e:
self.error(e)
return
def altname_request(self, data):
self.ask_finish(self.altname_request)
if data:
item = self._get_selected_item()
try:
self.engine.altname(item.showid, data)
item.update_altname(self.engine.altname(item.showid))
except utils.TrackmaError as e:
self.error(e)
return
def play_request(self, data):
self.ask_finish(self.play_request)
if data:
item = self._get_selected_item()
show = self.engine.get_show_info(item.showid)
try:
self.engine.play_episode(show, data)
except utils.TrackmaError as e:
self.error(e)
return
def prompt_update_request(self, data):
(show, episode) = self.last_update_prompt
self.ask_finish(self.prompt_update_request)
if data == 'y':
try:
show = self.engine.set_episode(show['id'], episode)
except utils.TrackmaError as e:
self.error(e)
return
else:
self.status('Ready.')
def prompt_update(self, show, episode):
self.last_update_prompt = (show, episode)
self.question("Update %s to episode %d? [y/N] " % (show['title'], episode), self.prompt_update_request)
def changed_show(self, show, changes=None):
if self.started and show:
status = show['my_status']
self.lists[status].body.update_show(show)
self.mainloop.draw_screen()
def changed_show_status(self, show, old_status=None):
self._rebuild_lists(show['my_status'])
if old_status is not None:
self._rebuild_lists(old_status)
go_filter = 0
for _filter in self.filters_nums:
if _filter == show['my_status']:
break
go_filter += 1
self.set_filter(go_filter)
self._get_cur_list().select_show(show)
def changed_queue(self, queue):
self.status_queue.set_text("Q:{}".format(len(queue)))
def tracker_state(self, status):
state = status['state']
timer = status['timer']
paused = status['paused']
if state == utils.TRACKER_NOVIDEO:
st = 'LISTEN'
elif state == utils.TRACKER_PLAYING:
st = '{}{}'.format('#' if paused else '+', timer)
elif state == utils.TRACKER_UNRECOGNIZED:
st = 'UNRECOG'
elif state == utils.TRACKER_NOT_FOUND:
st = 'NOTFOUN'
elif state == utils.TRACKER_IGNORED:
st = 'IGNORE'
else:
st = '???'
self.status_tracker.set_text("T:{}".format(st))
self.mainloop.draw_screen()
def playing_show(self, show, is_playing, episode=None):
status = show['my_status']
self.lists[status].body.playing_show(show, is_playing)
self.mainloop.draw_screen()
def changed_list(self, show):
self._rebuild_lists(show['my_status'])
def ask(self, msg, callback, data=u''):
self.asker = Asker(msg, str(data))
self.view.set_footer(urwid.AttrMap(self.asker, 'status'))
self.view.set_focus('footer')
urwid.connect_signal(self.asker, 'done', callback)
def question(self, msg, callback, data=u''):
self.asker = QuestionAsker(msg, str(data))
self.view.set_footer(urwid.AttrMap(self.asker, 'status'))
self.view.set_focus('footer')
urwid.connect_signal(self.asker, 'done', callback)
def ask_finish(self, callback):
self.view.set_focus('body')
urwid.disconnect_signal(self, self.asker, 'done', callback)
self.view.set_footer(self.statusbar)
def do_search(self, key=''):
if self.last_search:
text = "Search forward [%s]: " % self.last_search
else:
text = "Search forward: "
self.ask(text, self.search_request, key)
#urwid.connect_signal(self.asker, 'change', self.search_live)
#def search_live(self, widget, data):
# if data:
# self.listwalker.select_match(data)
def search_request(self, data):
self.ask_finish(self.search_request)
try:
if data:
self.last_search = data
self._get_cur_list().select_match(data)
elif self.last_search:
self._get_cur_list().select_match(self.last_search)
except re.error as e:
self.error(e)
class Dialog(urwid.Overlay):
def __init__(self, widget, loop, width=30, height=None, title=''):
self.widget = urwid.AttrMap(urwid.LineBox(widget, title=title), 'window')
self.oldwidget = loop.widget
self.loop = loop
super().__init__(self.widget, loop.widget,
align="center",
width=width,
valign="middle",
height=height)
def show(self):
self.loop.widget = self
def close(self):
self.loop.widget = self.oldwidget
def keypress(self, size, key):
if key in ('up', 'down', 'left', 'right', 'enter'):
self.widget.keypress(size, key)
elif key == 'esc':
self.close()
class AddDialog(Dialog):
__metaclass__ = urwid.signals.MetaSignals
signals = ['done']
def __init__(self, loop, engine, showlist={}, width=30):
self.viewing_info = False
self.engine = engine
self.listheader = urwid.Columns([
('fixed', 7, urwid.Text('ID')),
('weight', 1, urwid.Text('Title')),
('fixed', 10, urwid.Text('Type')),
('fixed', 7, urwid.Text('Total')),
])
self.listwalker = urwid.SimpleListWalker([])
self.listbox = urwid.ListBox(self.listwalker)
# Add results to the list
for show in showlist:
self.listwalker.append(SearchItem(show))
self.info_txt = urwid.Text("Add View | Enter:Add i:Info O:Website Esc:Cancel")
self.frame = urwid.Frame(self.listbox, header=self.listheader, footer=self.info_txt)
super().__init__(self.frame, loop, width=width, height=('relative', 80), title='Search results')
def keypress(self, size, key):
if key in ('up', 'down', 'left', 'right', 'tab'):
self.widget.keypress(size, key)
elif key == 'enter':
show = self.listwalker.get_focus()[0].show
urwid.emit_signal(self, 'done', show)
elif key == 'i':
show = self.listwalker.get_focus()[0].show
self.do_info()
elif key == 'O':
show = self.listwalker.get_focus()[0].show
webbrowser.open(show['url'], 2, True)
elif key == 'esc':
self.do_info_exit()
def do_info(self):
if self.viewing_info:
return
show = self.listwalker.get_focus()[0].show
#self.status("Getting show details...")
details = self.engine.get_show_details(show)
title = urwid.Text( ('info_title', show['title']), 'center', 'any')
widgets = []
for line in details['extra']:
if line[0] and line[1]:
widgets.append( urwid.Text( ('info_section', "%s: " % line[0] ) ) )
if isinstance(line[1], dict):
linestr = repr(line[1])
elif isinstance(line[1], int):
linestr = str(line[1])
else:
linestr = line[1]
widgets.append( urwid.Padding(urwid.Text( linestr + "\n" ), left=3) )
self.frame.body = urwid.ListBox(widgets)
self.frame.header = title
self.viewing_info = True
self.info_txt.set_text("Detail View | ESC:Return Up/Down:Scroll O:View website")
def do_info_exit(self):
if self.viewing_info:
self.frame.body = self.listbox
self.frame.header = self.listheader
self.info_txt.set_text("Add View | Enter:Add i:Info O:Website Esc:Cancel")
self.viewing_info = False
else:
self.close()
class AccountDialog(Dialog):
__metaclass__ = urwid.signals.MetaSignals
signals = ['done']
adding_data = dict()
def __init__(self, loop, manager, switch=False, width=50):
self.switch = switch
self.manager = manager
listheader = urwid.Columns([
('weight', 1, urwid.Text('Username')),
('fixed', 15, urwid.Text('Site')),
])
self.listwalker = urwid.SimpleListWalker([])
listbox = urwid.ListBox(self.listwalker)
self.build_list()
self.foot = urwid.Text('enter:Use once r:Use always a:Add D:Delete')
self.frame = urwid.Frame(listbox, header=listheader, footer=self.foot)
super().__init__(self.frame, loop, width=width, height=15, title='Select Account')
self.adding = False
self.show()
def build_list(self):
self.listwalker[:] = []
for k, account in self.manager.get_accounts():
self.listwalker.append(AccountItem(k, account))
def keypress(self, size, key):
#if key in ('up', 'down', 'left', 'right', 'tab'):
# self.widget.keypress(size, key)
if self.adding:
if key == 'esc':
self.foot_clear()
else:
self.widget.keypress(size, key)
else:
if key == 'enter':
self.do_select(False)
elif key == 'a':
self.do_add_api()
elif key == 'r':
self.do_select(True)
elif key == 'D':
self.do_delete_ask()
elif key == 'esc':
self.close()
if not self.switch:
raise urwid.ExitMainLoop()
else:
self.widget.keypress(size, key)
def do_add_api(self):
self.adding = True
available_libs = ', '.join(sorted(utils.available_libs.keys()))
ask = Asker("API (%s): " % available_libs)
self.frame.footer = ask
self.frame.set_focus('footer')
urwid.connect_signal(ask, 'done', self.do_add_username)
def do_add_username(self, data):
self.adding_data['apiname'] = data
try:
self.adding_data['api'] = api = utils.available_libs[data]
except KeyError:
self.adding = False
self.frame.footer = urwid.Text("Error: Invalid API.")
self.frame.set_focus('body')
return
if api[2] == utils.LOGIN_OAUTH:
ask = Asker("Account name: ")
else:
ask = Asker("Username: ")
self.frame.footer = ask
urwid.connect_signal(ask, 'done', self.do_add_password)
def do_add_password(self, data):
self.adding_data['username'] = data
if self.adding_data['api'][2] == utils.LOGIN_OAUTH:
ask = Asker("Please go to the following URL and paste the PIN.\n"
"{0}\nPIN: ".format(self.adding_data['api'][3]))
else:
ask = Asker("Password: ")
self.frame.footer = ask
urwid.connect_signal(ask, 'done', self.do_add)
def do_delete_ask(self):
self.adding = True
ask = QuestionAsker("Do you want to delete this account? [y/n] ")
self.frame.footer = ask
self.frame.set_focus('footer')
urwid.connect_signal(ask, 'done', self.do_delete)
def do_delete(self, data):
if data == 'y':
accountitem = self.listwalker.get_focus()[0]
self.manager.delete_account(accountitem.num)
self.build_list()
self.foot_clear()
def do_add(self, data):
username = self.adding_data['username']
password = data
api = self.adding_data['apiname']
try:
self.manager.add_account(username, password, api)
except utils.AccountError as e:
self.adding = False
self.frame.footer = urwid.Text("Error: %s" % e)
self.frame.set_focus('body')
return
self.build_list()
self.foot_clear()
def foot_clear(self):
self.adding = False
self.frame.footer = self.foot
self.frame.set_focus('body')
def do_select(self, remember):
accountitem = self.listwalker.get_focus()[0]
if remember:
self.manager.set_default(accountitem.num)
else:
self.manager.set_default(None)
self.close()
urwid.emit_signal(self, 'done', accountitem.account)
class AccountItem(urwid.WidgetWrap):
def __init__(self, num, account):
self.num = num
self.account = account
self.item = [
('weight', 1, urwid.Text(account['username'])),
('fixed', 15, urwid.Text(account['api'])),
]
w = urwid.AttrMap(urwid.Columns(self.item), 'window', 'focus')
super().__init__(w)
def selectable(self):
return True
def keypress(self, size, key):
return key
class SearchItem(urwid.WidgetWrap):
def __init__(self, show, has_progress=True):
self.show = show
self.item = [
('weight', 1, urwid.Text(show['title'])),
('fixed', 10, urwid.Text(str(show['type']))),
('fixed', 7, urwid.Text("%d" % show['total'])),
]
w = urwid.AttrMap(urwid.Columns(self.item), 'window', 'focus')
super().__init__(w)
def selectable(self):
return True
def keypress(self, size, key):
return key
class ShowWalker(urwid.SimpleListWalker):
def _get_showitem(self, showid):
for i, item in enumerate(self):
if showid == item.showid:
return (i, item)
#raise Exception('Show not found in ShowWalker.')
return (None, None)
def highlight_show(self, show, tocolor):
(position, showitem) = self._get_showitem(show['id'])
showitem.highlight(tocolor)
def update_show(self, show):
(position, showitem) = self._get_showitem(show['id'])
if showitem:
showitem.update(show)
return True
else:
return False
def playing_show(self, show, is_playing):
(position, showitem) = self._get_showitem(show['id'])
if showitem:
showitem.playing = is_playing
showitem.highlight(show)
return True
else:
return False
def select_show(self, show):
(position, showitem) = self._get_showitem(show['id'])
if showitem:
self.set_focus(position)
def select_match(self, searchstr):
pos = self.get_focus()[1]
for i, item in enumerate(self):
if i <= pos:
continue
if re.search(searchstr, item.showtitle, re.I):
self.set_focus(i)
break
class ShowItem(urwid.WidgetWrap):
def __init__(self, show, has_progress=True, altname=None, eps=None):
if has_progress:
self.episodes_str = urwid.Text("{0:3} / {1}".format(show['my_progress'], show['total'] or '?'))
else:
self.episodes_str = urwid.Text("-")
if eps:
self.eps = eps.keys()
else:
self.eps = None
self.score_str = urwid.Text("{0:^5}".format(show['my_score']))
self.has_progress = has_progress
self.playing = False
self.show = show
self.showid = show['id']
self.showtitle = show['title']
if altname:
self.showtitle += " (%s)" % altname
self.title_str = urwid.Text(self.showtitle)
self.item = [
('weight', 1, self.title_str),
('fixed', 10, self.episodes_str),
('fixed', 7, self.score_str),
]
# If the show should be highlighted, do it
# otherwise color it according to its status
if self.playing:
self.color = 'item_playing'
elif show.get('queued'):
self.color = 'item_updated'
elif self.eps and max(self.eps) > show['my_progress']:
self.color = 'item_neweps'
elif show['status'] == utils.STATUS_AIRING:
self.color = 'item_airing'
elif show['status'] == utils.STATUS_NOTYET:
self.color = 'item_notaired'
else:
self.color = 'body'
self.m = urwid.AttrMap(urwid.Columns(self.item), self.color, 'focus')
super().__init__(self.m)
def get_showid(self):
return self.showid
def update(self, show):
if show['id'] == self.showid:
# Update progress
if self.has_progress:
self.episodes_str.set_text("{0:3} / {1}".format(show['my_progress'], show['total']))
self.score_str.set_text("{0:^5}".format(show['my_score']))
# Update color
self.highlight(show)
else:
print("Warning: Tried to update a show with a different ID! (%d -> %d)" % (show['id'], self.showid))
def update_altname(self, altname):
# Update title
self.showtitle = "%s (%s)" % (self.show['title'], altname)
self.title_str.set_text(self.showtitle)
def highlight(self, show):
if self.playing:
self.color = 'item_playing'
elif show.get('queued'):
self.color = 'item_updated'
elif self.eps and max(self.eps) > show['my_progress']:
self.color = 'item_neweps'
elif show['status'] == 1:
self.color = 'item_airing'
elif show['status'] == 3:
self.color = 'item_notaired'
else:
self.color = 'body'
self.m.set_attr_map({None: self.color})
def selectable(self):
return True
def keypress(self, size, key):
return key
class Asker(urwid.Edit):
__metaclass__ = urwid.signals.MetaSignals
signals = ['done']
def keypress(self, size, key):
if key == 'enter':
urwid.emit_signal(self, 'done', self.get_edit_text())
return
elif key == 'esc':
urwid.emit_signal(self, 'done', None)
return
urwid.Edit.keypress(self, size, key)
class QuestionAsker(Asker):
def keypress(self, size, key):
if key.lower() in 'yn':
urwid.emit_signal(self, 'done', key.lower())
def main():
ui = Trackma_urwid()
try:
ui.run()
except utils.TrackmaFatal as e:
ui.forget_account()
print("Fatal error: %s" % e)
if __name__ == '__main__':
main()
|
gpl-3.0
|
mollstam/UnrealPy
|
UnrealPyEmbed/Development/Python/2015.08.07-Python2710-x64-Source-vs2015/Python27/Source/reportlab-3.2.0/src/reportlab/pdfbase/_fontdata_widths_courieroblique.py
|
224
|
3664
|
widths = {'A': 600,
'AE': 600,
'Aacute': 600,
'Acircumflex': 600,
'Adieresis': 600,
'Agrave': 600,
'Aring': 600,
'Atilde': 600,
'B': 600,
'C': 600,
'Ccedilla': 600,
'D': 600,
'E': 600,
'Eacute': 600,
'Ecircumflex': 600,
'Edieresis': 600,
'Egrave': 600,
'Eth': 600,
'Euro': 600,
'F': 600,
'G': 600,
'H': 600,
'I': 600,
'Iacute': 600,
'Icircumflex': 600,
'Idieresis': 600,
'Igrave': 600,
'J': 600,
'K': 600,
'L': 600,
'Lslash': 600,
'M': 600,
'N': 600,
'Ntilde': 600,
'O': 600,
'OE': 600,
'Oacute': 600,
'Ocircumflex': 600,
'Odieresis': 600,
'Ograve': 600,
'Oslash': 600,
'Otilde': 600,
'P': 600,
'Q': 600,
'R': 600,
'S': 600,
'Scaron': 600,
'T': 600,
'Thorn': 600,
'U': 600,
'Uacute': 600,
'Ucircumflex': 600,
'Udieresis': 600,
'Ugrave': 600,
'V': 600,
'W': 600,
'X': 600,
'Y': 600,
'Yacute': 600,
'Ydieresis': 600,
'Z': 600,
'Zcaron': 600,
'a': 600,
'aacute': 600,
'acircumflex': 600,
'acute': 600,
'adieresis': 600,
'ae': 600,
'agrave': 600,
'ampersand': 600,
'aring': 600,
'asciicircum': 600,
'asciitilde': 600,
'asterisk': 600,
'at': 600,
'atilde': 600,
'b': 600,
'backslash': 600,
'bar': 600,
'braceleft': 600,
'braceright': 600,
'bracketleft': 600,
'bracketright': 600,
'breve': 600,
'brokenbar': 600,
'bullet': 600,
'c': 600,
'caron': 600,
'ccedilla': 600,
'cedilla': 600,
'cent': 600,
'circumflex': 600,
'colon': 600,
'comma': 600,
'copyright': 600,
'currency': 600,
'd': 600,
'dagger': 600,
'daggerdbl': 600,
'degree': 600,
'dieresis': 600,
'divide': 600,
'dollar': 600,
'dotaccent': 600,
'dotlessi': 600,
'e': 600,
'eacute': 600,
'ecircumflex': 600,
'edieresis': 600,
'egrave': 600,
'eight': 600,
'ellipsis': 600,
'emdash': 600,
'endash': 600,
'equal': 600,
'eth': 600,
'exclam': 600,
'exclamdown': 600,
'f': 600,
'fi': 600,
'five': 600,
'fl': 600,
'florin': 600,
'four': 600,
'fraction': 600,
'g': 600,
'germandbls': 600,
'grave': 600,
'greater': 600,
'guillemotleft': 600,
'guillemotright': 600,
'guilsinglleft': 600,
'guilsinglright': 600,
'h': 600,
'hungarumlaut': 600,
'hyphen': 600,
'i': 600,
'iacute': 600,
'icircumflex': 600,
'idieresis': 600,
'igrave': 600,
'j': 600,
'k': 600,
'l': 600,
'less': 600,
'logicalnot': 600,
'lslash': 600,
'm': 600,
'macron': 600,
'minus': 600,
'mu': 600,
'multiply': 600,
'n': 600,
'nine': 600,
'ntilde': 600,
'numbersign': 600,
'o': 600,
'oacute': 600,
'ocircumflex': 600,
'odieresis': 600,
'oe': 600,
'ogonek': 600,
'ograve': 600,
'one': 600,
'onehalf': 600,
'onequarter': 600,
'onesuperior': 600,
'ordfeminine': 600,
'ordmasculine': 600,
'oslash': 600,
'otilde': 600,
'p': 600,
'paragraph': 600,
'parenleft': 600,
'parenright': 600,
'percent': 600,
'period': 600,
'periodcentered': 600,
'perthousand': 600,
'plus': 600,
'plusminus': 600,
'q': 600,
'question': 600,
'questiondown': 600,
'quotedbl': 600,
'quotedblbase': 600,
'quotedblleft': 600,
'quotedblright': 600,
'quoteleft': 600,
'quoteright': 600,
'quotesinglbase': 600,
'quotesingle': 600,
'r': 600,
'registered': 600,
'ring': 600,
's': 600,
'scaron': 600,
'section': 600,
'semicolon': 600,
'seven': 600,
'six': 600,
'slash': 600,
'space': 600,
'sterling': 600,
't': 600,
'thorn': 600,
'three': 600,
'threequarters': 600,
'threesuperior': 600,
'tilde': 600,
'trademark': 600,
'two': 600,
'twosuperior': 600,
'u': 600,
'uacute': 600,
'ucircumflex': 600,
'udieresis': 600,
'ugrave': 600,
'underscore': 600,
'v': 600,
'w': 600,
'x': 600,
'y': 600,
'yacute': 600,
'ydieresis': 600,
'yen': 600,
'z': 600,
'zcaron': 600,
'zero': 600}
|
mit
|
newerthcom/savagerebirth
|
libs/python-2.72/Lib/plat-mac/gensuitemodule.py
|
40
|
44464
|
"""
gensuitemodule - Generate an AE suite module from an aete/aeut resource
Based on aete.py.
Reading and understanding this code is left as an exercise to the reader.
"""
from warnings import warnpy3k
warnpy3k("In 3.x, the gensuitemodule module is removed.", stacklevel=2)
import MacOS
import EasyDialogs
import os
import string
import sys
import types
import StringIO
import keyword
import macresource
import aetools
import distutils.sysconfig
import OSATerminology
from Carbon.Res import *
import Carbon.Folder
import MacOS
import getopt
import plistlib
_MAC_LIB_FOLDER=os.path.dirname(aetools.__file__)
DEFAULT_STANDARD_PACKAGEFOLDER=os.path.join(_MAC_LIB_FOLDER, 'lib-scriptpackages')
DEFAULT_USER_PACKAGEFOLDER=distutils.sysconfig.get_python_lib()
def usage():
sys.stderr.write("Usage: %s [opts] application-or-resource-file\n" % sys.argv[0])
sys.stderr.write("""Options:
--output pkgdir Pathname of the output package (short: -o)
--resource Parse resource file in stead of launching application (-r)
--base package Use another base package in stead of default StdSuites (-b)
--edit old=new Edit suite names, use empty new to skip a suite (-e)
--creator code Set creator code for package (-c)
--dump Dump aete resource to stdout in stead of creating module (-d)
--verbose Tell us what happens (-v)
""")
sys.exit(1)
def main():
if len(sys.argv) > 1:
SHORTOPTS = "rb:o:e:c:dv"
LONGOPTS = ("resource", "base=", "output=", "edit=", "creator=", "dump", "verbose")
try:
opts, args = getopt.getopt(sys.argv[1:], SHORTOPTS, LONGOPTS)
except getopt.GetoptError:
usage()
process_func = processfile
basepkgname = 'StdSuites'
output = None
edit_modnames = []
creatorsignature = None
dump = None
verbose = None
for o, a in opts:
if o in ('-r', '--resource'):
process_func = processfile_fromresource
if o in ('-b', '--base'):
basepkgname = a
if o in ('-o', '--output'):
output = a
if o in ('-e', '--edit'):
split = a.split('=')
if len(split) != 2:
usage()
edit_modnames.append(split)
if o in ('-c', '--creator'):
if len(a) != 4:
sys.stderr.write("creator must be 4-char string\n")
sys.exit(1)
creatorsignature = a
if o in ('-d', '--dump'):
dump = sys.stdout
if o in ('-v', '--verbose'):
verbose = sys.stderr
if output and len(args) > 1:
sys.stderr.write("%s: cannot specify --output with multiple inputs\n" % sys.argv[0])
sys.exit(1)
for filename in args:
process_func(filename, output=output, basepkgname=basepkgname,
edit_modnames=edit_modnames, creatorsignature=creatorsignature,
dump=dump, verbose=verbose)
else:
main_interactive()
def main_interactive(interact=0, basepkgname='StdSuites'):
if interact:
# Ask for save-filename for each module
edit_modnames = None
else:
# Use default filenames for each module
edit_modnames = []
appsfolder = Carbon.Folder.FSFindFolder(-32765, 'apps', 0)
filename = EasyDialogs.AskFileForOpen(
message='Select scriptable application',
dialogOptionFlags=0x1056, # allow selection of .app bundles
defaultLocation=appsfolder)
if not filename:
return
if not is_scriptable(filename):
if EasyDialogs.AskYesNoCancel(
"Warning: application does not seem scriptable",
yes="Continue", default=2, no="") <= 0:
return
try:
processfile(filename, edit_modnames=edit_modnames, basepkgname=basepkgname,
verbose=sys.stderr)
except MacOS.Error, arg:
print "Error getting terminology:", arg
print "Retry, manually parsing resources"
processfile_fromresource(filename, edit_modnames=edit_modnames,
basepkgname=basepkgname, verbose=sys.stderr)
def is_scriptable(application):
"""Return true if the application is scriptable"""
if os.path.isdir(application):
plistfile = os.path.join(application, 'Contents', 'Info.plist')
if not os.path.exists(plistfile):
return False
plist = plistlib.Plist.fromFile(plistfile)
return plist.get('NSAppleScriptEnabled', False)
# If it is a file test for an aete/aeut resource.
currf = CurResFile()
try:
refno = macresource.open_pathname(application)
except MacOS.Error:
return False
UseResFile(refno)
n_terminology = Count1Resources('aete') + Count1Resources('aeut') + \
Count1Resources('scsz') + Count1Resources('osiz')
CloseResFile(refno)
UseResFile(currf)
return n_terminology > 0
def processfile_fromresource(fullname, output=None, basepkgname=None,
edit_modnames=None, creatorsignature=None, dump=None, verbose=None):
"""Process all resources in a single file"""
if not is_scriptable(fullname) and verbose:
print >>verbose, "Warning: app does not seem scriptable: %s" % fullname
cur = CurResFile()
if verbose:
print >>verbose, "Processing", fullname
rf = macresource.open_pathname(fullname)
try:
UseResFile(rf)
resources = []
for i in range(Count1Resources('aete')):
res = Get1IndResource('aete', 1+i)
resources.append(res)
for i in range(Count1Resources('aeut')):
res = Get1IndResource('aeut', 1+i)
resources.append(res)
if verbose:
print >>verbose, "\nLISTING aete+aeut RESOURCES IN", repr(fullname)
aetelist = []
for res in resources:
if verbose:
print >>verbose, "decoding", res.GetResInfo(), "..."
data = res.data
aete = decode(data, verbose)
aetelist.append((aete, res.GetResInfo()))
finally:
if rf != cur:
CloseResFile(rf)
UseResFile(cur)
# switch back (needed for dialogs in Python)
UseResFile(cur)
if dump:
dumpaetelist(aetelist, dump)
compileaetelist(aetelist, fullname, output=output,
basepkgname=basepkgname, edit_modnames=edit_modnames,
creatorsignature=creatorsignature, verbose=verbose)
def processfile(fullname, output=None, basepkgname=None,
edit_modnames=None, creatorsignature=None, dump=None,
verbose=None):
"""Ask an application for its terminology and process that"""
if not is_scriptable(fullname) and verbose:
print >>verbose, "Warning: app does not seem scriptable: %s" % fullname
if verbose:
print >>verbose, "\nASKING FOR aete DICTIONARY IN", repr(fullname)
try:
aedescobj, launched = OSATerminology.GetAppTerminology(fullname)
except MacOS.Error, arg:
if arg[0] in (-1701, -192): # errAEDescNotFound, resNotFound
if verbose:
print >>verbose, "GetAppTerminology failed with errAEDescNotFound/resNotFound, trying manually"
aedata, sig = getappterminology(fullname, verbose=verbose)
if not creatorsignature:
creatorsignature = sig
else:
raise
else:
if launched:
if verbose:
print >>verbose, "Launched", fullname
raw = aetools.unpack(aedescobj)
if not raw:
if verbose:
print >>verbose, 'Unpack returned empty value:', raw
return
if not raw[0].data:
if verbose:
print >>verbose, 'Unpack returned value without data:', raw
return
aedata = raw[0]
aete = decode(aedata.data, verbose)
if dump:
dumpaetelist([aete], dump)
return
compileaete(aete, None, fullname, output=output, basepkgname=basepkgname,
creatorsignature=creatorsignature, edit_modnames=edit_modnames,
verbose=verbose)
def getappterminology(fullname, verbose=None):
"""Get application terminology by sending an AppleEvent"""
# First check that we actually can send AppleEvents
if not MacOS.WMAvailable():
raise RuntimeError, "Cannot send AppleEvents, no access to window manager"
# Next, a workaround for a bug in MacOS 10.2: sending events will hang unless
# you have created an event loop first.
import Carbon.Evt
Carbon.Evt.WaitNextEvent(0,0)
if os.path.isdir(fullname):
# Now get the signature of the application, hoping it is a bundle
pkginfo = os.path.join(fullname, 'Contents', 'PkgInfo')
if not os.path.exists(pkginfo):
raise RuntimeError, "No PkgInfo file found"
tp_cr = open(pkginfo, 'rb').read()
cr = tp_cr[4:8]
else:
# Assume it is a file
cr, tp = MacOS.GetCreatorAndType(fullname)
# Let's talk to it and ask for its AETE
talker = aetools.TalkTo(cr)
try:
talker._start()
except (MacOS.Error, aetools.Error), arg:
if verbose:
print >>verbose, 'Warning: start() failed, continuing anyway:', arg
reply = talker.send("ascr", "gdte")
#reply2 = talker.send("ascr", "gdut")
# Now pick the bits out of the return that we need.
return reply[1]['----'], cr
def compileaetelist(aetelist, fullname, output=None, basepkgname=None,
edit_modnames=None, creatorsignature=None, verbose=None):
for aete, resinfo in aetelist:
compileaete(aete, resinfo, fullname, output=output,
basepkgname=basepkgname, edit_modnames=edit_modnames,
creatorsignature=creatorsignature, verbose=verbose)
def dumpaetelist(aetelist, output):
import pprint
pprint.pprint(aetelist, output)
def decode(data, verbose=None):
"""Decode a resource into a python data structure"""
f = StringIO.StringIO(data)
aete = generic(getaete, f)
aete = simplify(aete)
processed = f.tell()
unprocessed = len(f.read())
total = f.tell()
if unprocessed and verbose:
verbose.write("%d processed + %d unprocessed = %d total\n" %
(processed, unprocessed, total))
return aete
def simplify(item):
"""Recursively replace singleton tuples by their constituent item"""
if type(item) is types.ListType:
return map(simplify, item)
elif type(item) == types.TupleType and len(item) == 2:
return simplify(item[1])
else:
return item
# Here follows the aete resource decoder.
# It is presented bottom-up instead of top-down because there are direct
# references to the lower-level part-decoders from the high-level part-decoders.
def getbyte(f, *args):
c = f.read(1)
if not c:
raise EOFError, 'in getbyte' + str(args)
return ord(c)
def getword(f, *args):
getalign(f)
s = f.read(2)
if len(s) < 2:
raise EOFError, 'in getword' + str(args)
return (ord(s[0])<<8) | ord(s[1])
def getlong(f, *args):
getalign(f)
s = f.read(4)
if len(s) < 4:
raise EOFError, 'in getlong' + str(args)
return (ord(s[0])<<24) | (ord(s[1])<<16) | (ord(s[2])<<8) | ord(s[3])
def getostype(f, *args):
getalign(f)
s = f.read(4)
if len(s) < 4:
raise EOFError, 'in getostype' + str(args)
return s
def getpstr(f, *args):
c = f.read(1)
if len(c) < 1:
raise EOFError, 'in getpstr[1]' + str(args)
nbytes = ord(c)
if nbytes == 0: return ''
s = f.read(nbytes)
if len(s) < nbytes:
raise EOFError, 'in getpstr[2]' + str(args)
return s
def getalign(f):
if f.tell() & 1:
c = f.read(1)
##if c != '\0':
## print align:', repr(c)
def getlist(f, description, getitem):
count = getword(f)
list = []
for i in range(count):
list.append(generic(getitem, f))
getalign(f)
return list
def alt_generic(what, f, *args):
print "generic", repr(what), args
res = vageneric(what, f, args)
print '->', repr(res)
return res
def generic(what, f, *args):
if type(what) == types.FunctionType:
return apply(what, (f,) + args)
if type(what) == types.ListType:
record = []
for thing in what:
item = apply(generic, thing[:1] + (f,) + thing[1:])
record.append((thing[1], item))
return record
return "BAD GENERIC ARGS: %r" % (what,)
getdata = [
(getostype, "type"),
(getpstr, "description"),
(getword, "flags")
]
getargument = [
(getpstr, "name"),
(getostype, "keyword"),
(getdata, "what")
]
getevent = [
(getpstr, "name"),
(getpstr, "description"),
(getostype, "suite code"),
(getostype, "event code"),
(getdata, "returns"),
(getdata, "accepts"),
(getlist, "optional arguments", getargument)
]
getproperty = [
(getpstr, "name"),
(getostype, "code"),
(getdata, "what")
]
getelement = [
(getostype, "type"),
(getlist, "keyform", getostype)
]
getclass = [
(getpstr, "name"),
(getostype, "class code"),
(getpstr, "description"),
(getlist, "properties", getproperty),
(getlist, "elements", getelement)
]
getcomparison = [
(getpstr, "operator name"),
(getostype, "operator ID"),
(getpstr, "operator comment"),
]
getenumerator = [
(getpstr, "enumerator name"),
(getostype, "enumerator ID"),
(getpstr, "enumerator comment")
]
getenumeration = [
(getostype, "enumeration ID"),
(getlist, "enumerator", getenumerator)
]
getsuite = [
(getpstr, "suite name"),
(getpstr, "suite description"),
(getostype, "suite ID"),
(getword, "suite level"),
(getword, "suite version"),
(getlist, "events", getevent),
(getlist, "classes", getclass),
(getlist, "comparisons", getcomparison),
(getlist, "enumerations", getenumeration)
]
getaete = [
(getword, "major/minor version in BCD"),
(getword, "language code"),
(getword, "script code"),
(getlist, "suites", getsuite)
]
def compileaete(aete, resinfo, fname, output=None, basepkgname=None,
edit_modnames=None, creatorsignature=None, verbose=None):
"""Generate code for a full aete resource. fname passed for doc purposes"""
[version, language, script, suites] = aete
major, minor = divmod(version, 256)
if not creatorsignature:
creatorsignature, dummy = MacOS.GetCreatorAndType(fname)
packagename = identify(os.path.splitext(os.path.basename(fname))[0])
if language:
packagename = packagename+'_lang%d'%language
if script:
packagename = packagename+'_script%d'%script
if len(packagename) > 27:
packagename = packagename[:27]
if output:
# XXXX Put this in site-packages if it isn't a full pathname?
if not os.path.exists(output):
os.mkdir(output)
pathname = output
else:
pathname = EasyDialogs.AskFolder(message='Create and select package folder for %s'%packagename,
defaultLocation=DEFAULT_USER_PACKAGEFOLDER)
output = pathname
if not pathname:
return
packagename = os.path.split(os.path.normpath(pathname))[1]
if not basepkgname:
basepkgname = EasyDialogs.AskFolder(message='Package folder for base suite (usually StdSuites)',
defaultLocation=DEFAULT_STANDARD_PACKAGEFOLDER)
if basepkgname:
dirname, basepkgname = os.path.split(os.path.normpath(basepkgname))
if dirname and not dirname in sys.path:
sys.path.insert(0, dirname)
basepackage = __import__(basepkgname)
else:
basepackage = None
suitelist = []
allprecompinfo = []
allsuites = []
for suite in suites:
compiler = SuiteCompiler(suite, basepackage, output, edit_modnames, verbose)
code, modname, precompinfo = compiler.precompilesuite()
if not code:
continue
allprecompinfo = allprecompinfo + precompinfo
suiteinfo = suite, pathname, modname
suitelist.append((code, modname))
allsuites.append(compiler)
for compiler in allsuites:
compiler.compilesuite(major, minor, language, script, fname, allprecompinfo)
initfilename = os.path.join(output, '__init__.py')
fp = open(initfilename, 'w')
MacOS.SetCreatorAndType(initfilename, 'Pyth', 'TEXT')
fp.write('"""\n')
fp.write("Package generated from %s\n"%ascii(fname))
if resinfo:
fp.write("Resource %s resid %d %s\n"%(ascii(resinfo[1]), resinfo[0], ascii(resinfo[2])))
fp.write('"""\n')
fp.write('import aetools\n')
fp.write('Error = aetools.Error\n')
suitelist.sort()
for code, modname in suitelist:
fp.write("import %s\n" % modname)
fp.write("\n\n_code_to_module = {\n")
for code, modname in suitelist:
fp.write(" '%s' : %s,\n"%(ascii(code), modname))
fp.write("}\n\n")
fp.write("\n\n_code_to_fullname = {\n")
for code, modname in suitelist:
fp.write(" '%s' : ('%s.%s', '%s'),\n"%(ascii(code), packagename, modname, modname))
fp.write("}\n\n")
for code, modname in suitelist:
fp.write("from %s import *\n"%modname)
# Generate property dicts and element dicts for all types declared in this module
fp.write("\ndef getbaseclasses(v):\n")
fp.write(" if not getattr(v, '_propdict', None):\n")
fp.write(" v._propdict = {}\n")
fp.write(" v._elemdict = {}\n")
fp.write(" for superclassname in getattr(v, '_superclassnames', []):\n")
fp.write(" superclass = eval(superclassname)\n")
fp.write(" getbaseclasses(superclass)\n")
fp.write(" v._propdict.update(getattr(superclass, '_propdict', {}))\n")
fp.write(" v._elemdict.update(getattr(superclass, '_elemdict', {}))\n")
fp.write(" v._propdict.update(getattr(v, '_privpropdict', {}))\n")
fp.write(" v._elemdict.update(getattr(v, '_privelemdict', {}))\n")
fp.write("\n")
fp.write("import StdSuites\n")
allprecompinfo.sort()
if allprecompinfo:
fp.write("\n#\n# Set property and element dictionaries now that all classes have been defined\n#\n")
for codenamemapper in allprecompinfo:
for k, v in codenamemapper.getall('class'):
fp.write("getbaseclasses(%s)\n" % v)
# Generate a code-to-name mapper for all of the types (classes) declared in this module
application_class = None
if allprecompinfo:
fp.write("\n#\n# Indices of types declared in this module\n#\n")
fp.write("_classdeclarations = {\n")
for codenamemapper in allprecompinfo:
for k, v in codenamemapper.getall('class'):
fp.write(" %r : %s,\n" % (k, v))
if k == 'capp':
application_class = v
fp.write("}\n")
if suitelist:
fp.write("\n\nclass %s(%s_Events"%(packagename, suitelist[0][1]))
for code, modname in suitelist[1:]:
fp.write(",\n %s_Events"%modname)
fp.write(",\n aetools.TalkTo):\n")
fp.write(" _signature = %r\n\n"%(creatorsignature,))
fp.write(" _moduleName = '%s'\n\n"%packagename)
if application_class:
fp.write(" _elemdict = %s._elemdict\n" % application_class)
fp.write(" _propdict = %s._propdict\n" % application_class)
fp.close()
class SuiteCompiler:
def __init__(self, suite, basepackage, output, edit_modnames, verbose):
self.suite = suite
self.basepackage = basepackage
self.edit_modnames = edit_modnames
self.output = output
self.verbose = verbose
# Set by precompilesuite
self.pathname = None
self.modname = None
# Set by compilesuite
self.fp = None
self.basemodule = None
self.enumsneeded = {}
def precompilesuite(self):
"""Parse a single suite without generating the output. This step is needed
so we can resolve recursive references by suites to enums/comps/etc declared
in other suites"""
[name, desc, code, level, version, events, classes, comps, enums] = self.suite
modname = identify(name)
if len(modname) > 28:
modname = modname[:27]
if self.edit_modnames is None:
self.pathname = EasyDialogs.AskFileForSave(message='Python output file',
savedFileName=modname+'.py')
else:
for old, new in self.edit_modnames:
if old == modname:
modname = new
if modname:
self.pathname = os.path.join(self.output, modname + '.py')
else:
self.pathname = None
if not self.pathname:
return None, None, None
self.modname = os.path.splitext(os.path.split(self.pathname)[1])[0]
if self.basepackage and code in self.basepackage._code_to_module:
# We are an extension of a baseclass (usually an application extending
# Standard_Suite or so). Import everything from our base module
basemodule = self.basepackage._code_to_module[code]
else:
# We are not an extension.
basemodule = None
self.enumsneeded = {}
for event in events:
self.findenumsinevent(event)
objc = ObjectCompiler(None, self.modname, basemodule, interact=(self.edit_modnames is None),
verbose=self.verbose)
for cls in classes:
objc.compileclass(cls)
for cls in classes:
objc.fillclasspropsandelems(cls)
for comp in comps:
objc.compilecomparison(comp)
for enum in enums:
objc.compileenumeration(enum)
for enum in self.enumsneeded.keys():
objc.checkforenum(enum)
objc.dumpindex()
precompinfo = objc.getprecompinfo(self.modname)
return code, self.modname, precompinfo
def compilesuite(self, major, minor, language, script, fname, precompinfo):
"""Generate code for a single suite"""
[name, desc, code, level, version, events, classes, comps, enums] = self.suite
# Sort various lists, so re-generated source is easier compared
def class_sorter(k1, k2):
"""Sort classes by code, and make sure main class sorts before synonyms"""
# [name, code, desc, properties, elements] = cls
if k1[1] < k2[1]: return -1
if k1[1] > k2[1]: return 1
if not k2[3] or k2[3][0][1] == 'c@#!':
# This is a synonym, the other one is better
return -1
if not k1[3] or k1[3][0][1] == 'c@#!':
# This is a synonym, the other one is better
return 1
return 0
events.sort()
classes.sort(class_sorter)
comps.sort()
enums.sort()
self.fp = fp = open(self.pathname, 'w')
MacOS.SetCreatorAndType(self.pathname, 'Pyth', 'TEXT')
fp.write('"""Suite %s: %s\n' % (ascii(name), ascii(desc)))
fp.write("Level %d, version %d\n\n" % (level, version))
fp.write("Generated from %s\n"%ascii(fname))
fp.write("AETE/AEUT resource version %d/%d, language %d, script %d\n" % \
(major, minor, language, script))
fp.write('"""\n\n')
fp.write('import aetools\n')
fp.write('import MacOS\n\n')
fp.write("_code = %r\n\n"% (code,))
if self.basepackage and code in self.basepackage._code_to_module:
# We are an extension of a baseclass (usually an application extending
# Standard_Suite or so). Import everything from our base module
fp.write('from %s import *\n'%self.basepackage._code_to_fullname[code][0])
basemodule = self.basepackage._code_to_module[code]
elif self.basepackage and code.lower() in self.basepackage._code_to_module:
# This is needed by CodeWarrior and some others.
fp.write('from %s import *\n'%self.basepackage._code_to_fullname[code.lower()][0])
basemodule = self.basepackage._code_to_module[code.lower()]
else:
# We are not an extension.
basemodule = None
self.basemodule = basemodule
self.compileclassheader()
self.enumsneeded = {}
if events:
for event in events:
self.compileevent(event)
else:
fp.write(" pass\n\n")
objc = ObjectCompiler(fp, self.modname, basemodule, precompinfo, interact=(self.edit_modnames is None),
verbose=self.verbose)
for cls in classes:
objc.compileclass(cls)
for cls in classes:
objc.fillclasspropsandelems(cls)
for comp in comps:
objc.compilecomparison(comp)
for enum in enums:
objc.compileenumeration(enum)
for enum in self.enumsneeded.keys():
objc.checkforenum(enum)
objc.dumpindex()
def compileclassheader(self):
"""Generate class boilerplate"""
classname = '%s_Events'%self.modname
if self.basemodule:
modshortname = string.split(self.basemodule.__name__, '.')[-1]
baseclassname = '%s_Events'%modshortname
self.fp.write("class %s(%s):\n\n"%(classname, baseclassname))
else:
self.fp.write("class %s:\n\n"%classname)
def compileevent(self, event):
"""Generate code for a single event"""
[name, desc, code, subcode, returns, accepts, arguments] = event
fp = self.fp
funcname = identify(name)
#
# generate name->keyword map
#
if arguments:
fp.write(" _argmap_%s = {\n"%funcname)
for a in arguments:
fp.write(" %r : %r,\n"%(identify(a[0]), a[1]))
fp.write(" }\n\n")
#
# Generate function header
#
has_arg = (not is_null(accepts))
opt_arg = (has_arg and is_optional(accepts))
fp.write(" def %s(self, "%funcname)
if has_arg:
if not opt_arg:
fp.write("_object, ") # Include direct object, if it has one
else:
fp.write("_object=None, ") # Also include if it is optional
else:
fp.write("_no_object=None, ") # For argument checking
fp.write("_attributes={}, **_arguments):\n") # include attribute dict and args
#
# Generate doc string (important, since it may be the only
# available documentation, due to our name-remaping)
#
fp.write(' """%s: %s\n'%(ascii(name), ascii(desc)))
if has_arg:
fp.write(" Required argument: %s\n"%getdatadoc(accepts))
elif opt_arg:
fp.write(" Optional argument: %s\n"%getdatadoc(accepts))
for arg in arguments:
fp.write(" Keyword argument %s: %s\n"%(identify(arg[0]),
getdatadoc(arg[2])))
fp.write(" Keyword argument _attributes: AppleEvent attribute dictionary\n")
if not is_null(returns):
fp.write(" Returns: %s\n"%getdatadoc(returns))
fp.write(' """\n')
#
# Fiddle the args so everything ends up in 'arguments' dictionary
#
fp.write(" _code = %r\n"% (code,))
fp.write(" _subcode = %r\n\n"% (subcode,))
#
# Do keyword name substitution
#
if arguments:
fp.write(" aetools.keysubst(_arguments, self._argmap_%s)\n"%funcname)
else:
fp.write(" if _arguments: raise TypeError, 'No optional args expected'\n")
#
# Stuff required arg (if there is one) into arguments
#
if has_arg:
fp.write(" _arguments['----'] = _object\n")
elif opt_arg:
fp.write(" if _object:\n")
fp.write(" _arguments['----'] = _object\n")
else:
fp.write(" if _no_object is not None: raise TypeError, 'No direct arg expected'\n")
fp.write("\n")
#
# Do enum-name substitution
#
for a in arguments:
if is_enum(a[2]):
kname = a[1]
ename = a[2][0]
if ename != '****':
fp.write(" aetools.enumsubst(_arguments, %r, _Enum_%s)\n" %
(kname, identify(ename)))
self.enumsneeded[ename] = 1
fp.write("\n")
#
# Do the transaction
#
fp.write(" _reply, _arguments, _attributes = self.send(_code, _subcode,\n")
fp.write(" _arguments, _attributes)\n")
#
# Error handling
#
fp.write(" if _arguments.get('errn', 0):\n")
fp.write(" raise aetools.Error, aetools.decodeerror(_arguments)\n")
fp.write(" # XXXX Optionally decode result\n")
#
# Decode result
#
fp.write(" if '----' in _arguments:\n")
if is_enum(returns):
fp.write(" # XXXX Should do enum remapping here...\n")
fp.write(" return _arguments['----']\n")
fp.write("\n")
def findenumsinevent(self, event):
"""Find all enums for a single event"""
[name, desc, code, subcode, returns, accepts, arguments] = event
for a in arguments:
if is_enum(a[2]):
ename = a[2][0]
if ename != '****':
self.enumsneeded[ename] = 1
#
# This class stores the code<->name translations for a single module. It is used
# to keep the information while we're compiling the module, but we also keep these objects
# around so if one suite refers to, say, an enum in another suite we know where to
# find it. Finally, if we really can't find a code, the user can add modules by
# hand.
#
class CodeNameMapper:
def __init__(self, interact=1, verbose=None):
self.code2name = {
"property" : {},
"class" : {},
"enum" : {},
"comparison" : {},
}
self.name2code = {
"property" : {},
"class" : {},
"enum" : {},
"comparison" : {},
}
self.modulename = None
self.star_imported = 0
self.can_interact = interact
self.verbose = verbose
def addnamecode(self, type, name, code):
self.name2code[type][name] = code
if code not in self.code2name[type]:
self.code2name[type][code] = name
def hasname(self, name):
for dict in self.name2code.values():
if name in dict:
return True
return False
def hascode(self, type, code):
return code in self.code2name[type]
def findcodename(self, type, code):
if not self.hascode(type, code):
return None, None, None
name = self.code2name[type][code]
if self.modulename and not self.star_imported:
qualname = '%s.%s'%(self.modulename, name)
else:
qualname = name
return name, qualname, self.modulename
def getall(self, type):
return self.code2name[type].items()
def addmodule(self, module, name, star_imported):
self.modulename = name
self.star_imported = star_imported
for code, name in module._propdeclarations.items():
self.addnamecode('property', name, code)
for code, name in module._classdeclarations.items():
self.addnamecode('class', name, code)
for code in module._enumdeclarations.keys():
self.addnamecode('enum', '_Enum_'+identify(code), code)
for code, name in module._compdeclarations.items():
self.addnamecode('comparison', name, code)
def prepareforexport(self, name=None):
if not self.modulename:
self.modulename = name
return self
class ObjectCompiler:
def __init__(self, fp, modname, basesuite, othernamemappers=None, interact=1,
verbose=None):
self.fp = fp
self.verbose = verbose
self.basesuite = basesuite
self.can_interact = interact
self.modulename = modname
self.namemappers = [CodeNameMapper(self.can_interact, self.verbose)]
if othernamemappers:
self.othernamemappers = othernamemappers[:]
else:
self.othernamemappers = []
if basesuite:
basemapper = CodeNameMapper(self.can_interact, self.verbose)
basemapper.addmodule(basesuite, '', 1)
self.namemappers.append(basemapper)
def getprecompinfo(self, modname):
list = []
for mapper in self.namemappers:
emapper = mapper.prepareforexport(modname)
if emapper:
list.append(emapper)
return list
def findcodename(self, type, code):
while 1:
# First try: check whether we already know about this code.
for mapper in self.namemappers:
if mapper.hascode(type, code):
return mapper.findcodename(type, code)
# Second try: maybe one of the other modules knows about it.
for mapper in self.othernamemappers:
if mapper.hascode(type, code):
self.othernamemappers.remove(mapper)
self.namemappers.append(mapper)
if self.fp:
self.fp.write("import %s\n"%mapper.modulename)
break
else:
# If all this has failed we ask the user for a guess on where it could
# be and retry.
if self.fp:
m = self.askdefinitionmodule(type, code)
else:
m = None
if not m: return None, None, None
mapper = CodeNameMapper(self.can_interact, self.verbose)
mapper.addmodule(m, m.__name__, 0)
self.namemappers.append(mapper)
def hasname(self, name):
for mapper in self.othernamemappers:
if mapper.hasname(name) and mapper.modulename != self.modulename:
if self.verbose:
print >>self.verbose, "Duplicate Python identifier:", name, self.modulename, mapper.modulename
return True
return False
def askdefinitionmodule(self, type, code):
if not self.can_interact:
if self.verbose:
print >>self.verbose, "** No definition for %s '%s' found" % (type, code)
return None
path = EasyDialogs.AskFileForSave(message='Where is %s %s declared?'%(type, code))
if not path: return
path, file = os.path.split(path)
modname = os.path.splitext(file)[0]
if not path in sys.path:
sys.path.insert(0, path)
m = __import__(modname)
self.fp.write("import %s\n"%modname)
return m
def compileclass(self, cls):
[name, code, desc, properties, elements] = cls
pname = identify(name)
if self.namemappers[0].hascode('class', code):
# plural forms and such
othername, dummy, dummy = self.namemappers[0].findcodename('class', code)
if self.fp:
self.fp.write("\n%s = %s\n"%(pname, othername))
else:
if self.fp:
self.fp.write('\nclass %s(aetools.ComponentItem):\n' % pname)
self.fp.write(' """%s - %s """\n' % (ascii(name), ascii(desc)))
self.fp.write(' want = %r\n' % (code,))
self.namemappers[0].addnamecode('class', pname, code)
is_application_class = (code == 'capp')
properties.sort()
for prop in properties:
self.compileproperty(prop, is_application_class)
elements.sort()
for elem in elements:
self.compileelement(elem)
def compileproperty(self, prop, is_application_class=False):
[name, code, what] = prop
if code == 'c@#!':
# Something silly with plurals. Skip it.
return
pname = identify(name)
if self.namemappers[0].hascode('property', code):
# plural forms and such
othername, dummy, dummy = self.namemappers[0].findcodename('property', code)
if pname == othername:
return
if self.fp:
self.fp.write("\n_Prop_%s = _Prop_%s\n"%(pname, othername))
else:
if self.fp:
self.fp.write("class _Prop_%s(aetools.NProperty):\n" % pname)
self.fp.write(' """%s - %s """\n' % (ascii(name), ascii(what[1])))
self.fp.write(" which = %r\n" % (code,))
self.fp.write(" want = %r\n" % (what[0],))
self.namemappers[0].addnamecode('property', pname, code)
if is_application_class and self.fp:
self.fp.write("%s = _Prop_%s()\n" % (pname, pname))
def compileelement(self, elem):
[code, keyform] = elem
if self.fp:
self.fp.write("# element %r as %s\n" % (code, keyform))
def fillclasspropsandelems(self, cls):
[name, code, desc, properties, elements] = cls
cname = identify(name)
if self.namemappers[0].hascode('class', code) and \
self.namemappers[0].findcodename('class', code)[0] != cname:
# This is an other name (plural or so) for something else. Skip.
if self.fp and (elements or len(properties) > 1 or (len(properties) == 1 and
properties[0][1] != 'c@#!')):
if self.verbose:
print >>self.verbose, '** Skip multiple %s of %s (code %r)' % (cname, self.namemappers[0].findcodename('class', code)[0], code)
raise RuntimeError, "About to skip non-empty class"
return
plist = []
elist = []
superclasses = []
for prop in properties:
[pname, pcode, what] = prop
if pcode == "c@#^":
superclasses.append(what)
if pcode == 'c@#!':
continue
pname = identify(pname)
plist.append(pname)
superclassnames = []
for superclass in superclasses:
superId, superDesc, dummy = superclass
superclassname, fullyqualifiedname, module = self.findcodename("class", superId)
# I don't think this is correct:
if superclassname == cname:
pass # superclassnames.append(fullyqualifiedname)
else:
superclassnames.append(superclassname)
if self.fp:
self.fp.write("%s._superclassnames = %r\n"%(cname, superclassnames))
for elem in elements:
[ecode, keyform] = elem
if ecode == 'c@#!':
continue
name, ename, module = self.findcodename('class', ecode)
if not name:
if self.fp:
self.fp.write("# XXXX %s element %r not found!!\n"%(cname, ecode))
else:
elist.append((name, ename))
plist.sort()
elist.sort()
if self.fp:
self.fp.write("%s._privpropdict = {\n"%cname)
for n in plist:
self.fp.write(" '%s' : _Prop_%s,\n"%(n, n))
self.fp.write("}\n")
self.fp.write("%s._privelemdict = {\n"%cname)
for n, fulln in elist:
self.fp.write(" '%s' : %s,\n"%(n, fulln))
self.fp.write("}\n")
def compilecomparison(self, comp):
[name, code, comment] = comp
iname = identify(name)
self.namemappers[0].addnamecode('comparison', iname, code)
if self.fp:
self.fp.write("class %s(aetools.NComparison):\n" % iname)
self.fp.write(' """%s - %s """\n' % (ascii(name), ascii(comment)))
def compileenumeration(self, enum):
[code, items] = enum
name = "_Enum_%s" % identify(code)
if self.fp:
self.fp.write("%s = {\n" % name)
for item in items:
self.compileenumerator(item)
self.fp.write("}\n\n")
self.namemappers[0].addnamecode('enum', name, code)
return code
def compileenumerator(self, item):
[name, code, desc] = item
self.fp.write(" %r : %r,\t# %s\n" % (identify(name), code, ascii(desc)))
def checkforenum(self, enum):
"""This enum code is used by an event. Make sure it's available"""
name, fullname, module = self.findcodename('enum', enum)
if not name:
if self.fp:
self.fp.write("_Enum_%s = None # XXXX enum %s not found!!\n"%(identify(enum), ascii(enum)))
return
if module:
if self.fp:
self.fp.write("from %s import %s\n"%(module, name))
def dumpindex(self):
if not self.fp:
return
self.fp.write("\n#\n# Indices of types declared in this module\n#\n")
self.fp.write("_classdeclarations = {\n")
classlist = self.namemappers[0].getall('class')
classlist.sort()
for k, v in classlist:
self.fp.write(" %r : %s,\n" % (k, v))
self.fp.write("}\n")
self.fp.write("\n_propdeclarations = {\n")
proplist = self.namemappers[0].getall('property')
proplist.sort()
for k, v in proplist:
self.fp.write(" %r : _Prop_%s,\n" % (k, v))
self.fp.write("}\n")
self.fp.write("\n_compdeclarations = {\n")
complist = self.namemappers[0].getall('comparison')
complist.sort()
for k, v in complist:
self.fp.write(" %r : %s,\n" % (k, v))
self.fp.write("}\n")
self.fp.write("\n_enumdeclarations = {\n")
enumlist = self.namemappers[0].getall('enum')
enumlist.sort()
for k, v in enumlist:
self.fp.write(" %r : %s,\n" % (k, v))
self.fp.write("}\n")
def compiledata(data):
[type, description, flags] = data
return "%r -- %r %s" % (type, description, compiledataflags(flags))
def is_null(data):
return data[0] == 'null'
def is_optional(data):
return (data[2] & 0x8000)
def is_enum(data):
return (data[2] & 0x2000)
def getdatadoc(data):
[type, descr, flags] = data
if descr:
return ascii(descr)
if type == '****':
return 'anything'
if type == 'obj ':
return 'an AE object reference'
return "undocumented, typecode %r"%(type,)
dataflagdict = {15: "optional", 14: "list", 13: "enum", 12: "mutable"}
def compiledataflags(flags):
bits = []
for i in range(16):
if flags & (1<<i):
if i in dataflagdict.keys():
bits.append(dataflagdict[i])
else:
bits.append(repr(i))
return '[%s]' % string.join(bits)
def ascii(str):
"""Return a string with all non-ascii characters hex-encoded"""
if type(str) != type(''):
return map(ascii, str)
rv = ''
for c in str:
if c in ('\t', '\n', '\r') or ' ' <= c < chr(0x7f):
rv = rv + c
else:
rv = rv + '\\' + 'x%02.2x' % ord(c)
return rv
def identify(str):
"""Turn any string into an identifier:
- replace space by _
- replace other illegal chars by _xx_ (hex code)
- append _ if the result is a python keyword
"""
if not str:
return "empty_ae_name_"
rv = ''
ok = string.ascii_letters + '_'
ok2 = ok + string.digits
for c in str:
if c in ok:
rv = rv + c
elif c == ' ':
rv = rv + '_'
else:
rv = rv + '_%02.2x_'%ord(c)
ok = ok2
if keyword.iskeyword(rv):
rv = rv + '_'
return rv
# Call the main program
if __name__ == '__main__':
main()
sys.exit(1)
|
gpl-2.0
|
hefen1/chromium
|
third_party/closure_compiler/checker.py
|
1
|
10762
|
#!/usr/bin/python
# Copyright 2014 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.
"""Runs Closure compiler on a JavaScript file to check for errors."""
import argparse
import os
import re
import subprocess
import sys
import tempfile
import build.inputs
import processor
import error_filter
class Checker(object):
"""Runs the Closure compiler on a given source file and returns the
success/errors."""
_COMMON_CLOSURE_ARGS = [
"--accept_const_keyword",
"--jscomp_error=accessControls",
"--jscomp_error=ambiguousFunctionDecl",
"--jscomp_error=checkStructDictInheritance",
"--jscomp_error=checkTypes",
"--jscomp_error=checkVars",
"--jscomp_error=constantProperty",
"--jscomp_error=deprecated",
"--jscomp_error=externsValidation",
"--jscomp_error=globalThis",
"--jscomp_error=invalidCasts",
"--jscomp_error=missingProperties",
"--jscomp_error=missingReturn",
"--jscomp_error=nonStandardJsDocs",
"--jscomp_error=suspiciousCode",
"--jscomp_error=undefinedNames",
"--jscomp_error=undefinedVars",
"--jscomp_error=unknownDefines",
"--jscomp_error=uselessCode",
"--jscomp_error=visibility",
"--language_in=ECMASCRIPT5_STRICT",
"--summary_detail_level=3",
]
# These are the extra flags used when compiling in 'strict' mode.
# Flags that are normally disabled are turned on for strict mode.
_STRICT_CLOSURE_ARGS = [
"--jscomp_error=reportUnknownTypes",
"--jscomp_error=duplicate",
"--jscomp_error=misplacedTypeAnnotation",
]
_DISABLED_CLOSURE_ARGS = [
# TODO(dbeam): happens when the same file is <include>d multiple times.
"--jscomp_off=duplicate",
# TODO(fukino): happens when cr.defineProperty() has a type annotation.
# Avoiding parse-time warnings needs 2 pass compiling. crbug.com/421562.
"--jscomp_off=misplacedTypeAnnotation",
]
_JAR_COMMAND = [
"java",
"-jar",
"-Xms1024m",
"-client",
"-XX:+TieredCompilation"
]
_found_java = False
def __init__(self, verbose=False, strict=False):
current_dir = os.path.join(os.path.dirname(__file__))
self._runner_jar = os.path.join(current_dir, "runner", "runner.jar")
self._temp_files = []
self._verbose = verbose
self._strict = strict
self._error_filter = error_filter.PromiseErrorFilter()
def _clean_up(self):
if not self._temp_files:
return
self._debug("Deleting temporary files: %s" % ", ".join(self._temp_files))
for f in self._temp_files:
os.remove(f)
self._temp_files = []
def _debug(self, msg, error=False):
if self._verbose:
print "(INFO) %s" % msg
def _error(self, msg):
print >> sys.stderr, "(ERROR) %s" % msg
self._clean_up()
def _common_args(self):
"""Returns an array of the common closure compiler args."""
if self._strict:
return self._COMMON_CLOSURE_ARGS + self._STRICT_CLOSURE_ARGS
return self._COMMON_CLOSURE_ARGS + self._DISABLED_CLOSURE_ARGS
def _run_command(self, cmd):
"""Runs a shell command.
Args:
cmd: A list of tokens to be joined into a shell command.
Return:
True if the exit code was 0, else False.
"""
cmd_str = " ".join(cmd)
self._debug("Running command: %s" % cmd_str)
devnull = open(os.devnull, "w")
return subprocess.Popen(
cmd_str, stdout=devnull, stderr=subprocess.PIPE, shell=True)
def _check_java_path(self):
"""Checks that `java` is on the system path."""
if not self._found_java:
proc = self._run_command(["which", "java"])
proc.communicate()
if proc.returncode == 0:
self._found_java = True
else:
self._error("Cannot find java (`which java` => %s)" % proc.returncode)
return self._found_java
def _run_jar(self, jar, args=None):
args = args or []
self._check_java_path()
return self._run_command(self._JAR_COMMAND + [jar] + args)
def _fix_line_number(self, match):
"""Changes a line number from /tmp/file:300 to /orig/file:100.
Args:
match: A re.MatchObject from matching against a line number regex.
Returns:
The fixed up /file and :line number.
"""
real_file = self._processor.get_file_from_line(match.group(1))
return "%s:%d" % (os.path.abspath(real_file.file), real_file.line_number)
def _fix_up_error(self, error):
"""Filter out irrelevant errors or fix line numbers.
Args:
error: A Closure compiler error (2 line string with error and source).
Return:
The fixed up error string (blank if it should be ignored).
"""
if " first declared in " in error:
# Ignore "Variable x first declared in /same/file".
return ""
expanded_file = self._expanded_file
fixed = re.sub("%s:(\d+)" % expanded_file, self._fix_line_number, error)
return fixed.replace(expanded_file, os.path.abspath(self._file_arg))
def _format_errors(self, errors):
"""Formats Closure compiler errors to easily spot compiler output."""
errors = filter(None, errors)
contents = "\n## ".join("\n\n".join(errors).splitlines())
return "## %s" % contents if contents else ""
def _create_temp_file(self, contents):
with tempfile.NamedTemporaryFile(mode="wt", delete=False) as tmp_file:
self._temp_files.append(tmp_file.name)
tmp_file.write(contents)
return tmp_file.name
def run_js_check(self, sources, externs=None):
if not self._check_java_path():
return 1, ""
args = ["--js=%s" % s for s in sources]
if externs:
args += ["--externs=%s" % e for e in externs]
args_file_content = " %s" % " ".join(self._common_args() + args)
self._debug("Args: %s" % args_file_content.strip())
args_file = self._create_temp_file(args_file_content)
self._debug("Args file: %s" % args_file)
runner_args = ["--compiler-args-file=%s" % args_file]
runner_cmd = self._run_jar(self._runner_jar, args=runner_args)
_, stderr = runner_cmd.communicate()
errors = stderr.strip().split("\n\n")
self._debug("Summary: %s" % errors.pop())
self._clean_up()
return errors, stderr
def check(self, source_file, depends=None, externs=None):
"""Closure compile a file and check for errors.
Args:
source_file: A file to check.
depends: Other files that would be included with a <script> earlier in
the page.
externs: @extern files that inform the compiler about custom globals.
Returns:
(has_errors, output) A boolean indicating if there were errors and the
Closure compiler output (as a string).
"""
depends = depends or []
externs = externs or set()
if not self._check_java_path():
return 1, ""
self._debug("FILE: %s" % source_file)
if source_file.endswith("_externs.js"):
self._debug("Skipping externs: %s" % source_file)
return
self._file_arg = source_file
tmp_dir = tempfile.gettempdir()
rel_path = lambda f: os.path.join(os.path.relpath(os.getcwd(), tmp_dir), f)
includes = [rel_path(f) for f in depends + [source_file]]
contents = ['<include src="%s">' % i for i in includes]
meta_file = self._create_temp_file("\n".join(contents))
self._debug("Meta file: %s" % meta_file)
self._processor = processor.Processor(meta_file)
self._expanded_file = self._create_temp_file(self._processor.contents)
self._debug("Expanded file: %s" % self._expanded_file)
errors, stderr = self.run_js_check([self._expanded_file], externs)
# Filter out false-positive promise chain errors.
# See https://github.com/google/closure-compiler/issues/715 for details.
errors = self._error_filter.filter(errors);
output = self._format_errors(map(self._fix_up_error, errors))
if errors:
prefix = "\n" if output else ""
self._error("Error in: %s%s%s" % (source_file, prefix, output))
elif output:
self._debug("Output: %s" % output)
return bool(errors), output
def check_multiple(self, sources):
"""Closure compile a set of files and check for errors.
Args:
sources: An array of files to check.
Returns:
(has_errors, output) A boolean indicating if there were errors and the
Closure compiler output (as a string).
"""
errors, stderr = self.run_js_check(sources)
return bool(errors), stderr
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Typecheck JavaScript using Closure compiler")
parser.add_argument("sources", nargs=argparse.ONE_OR_MORE,
help="Path to a source file to typecheck")
single_file_group = parser.add_mutually_exclusive_group()
single_file_group.add_argument("--single-file", dest="single_file",
action="store_true",
help="Process each source file individually")
single_file_group.add_argument("--no-single-file", dest="single_file",
action="store_false",
help="Process all source files as a group")
parser.add_argument("-d", "--depends", nargs=argparse.ZERO_OR_MORE)
parser.add_argument("-e", "--externs", nargs=argparse.ZERO_OR_MORE)
parser.add_argument("-o", "--out_file", help="A place to output results")
parser.add_argument("-v", "--verbose", action="store_true",
help="Show more information as this script runs")
parser.add_argument("--strict", action="store_true",
help="Enable strict type checking")
parser.add_argument("--success-stamp",
help="Timestamp file to update upon success")
parser.set_defaults(single_file=True, strict=False)
opts = parser.parse_args()
depends = opts.depends or []
externs = opts.externs or set()
checker = Checker(verbose=opts.verbose, strict=opts.strict)
if opts.single_file:
for source in opts.sources:
depends, externs = build.inputs.resolve_recursive_dependencies(
source,
depends,
externs)
has_errors, _ = checker.check(source, depends=depends, externs=externs)
if has_errors:
sys.exit(1)
if opts.out_file:
out_dir = os.path.dirname(opts.out_file)
if not os.path.exists(out_dir):
os.makedirs(out_dir)
# TODO(dbeam): write compiled file to |opts.out_file|.
open(opts.out_file, "w").write("")
else:
has_errors, errors = checker.check_multiple(opts.sources)
if has_errors:
print errors
sys.exit(1)
if opts.success_stamp:
with open(opts.success_stamp, 'w'):
os.utime(opts.success_stamp, None)
|
bsd-3-clause
|
vauxoo-dev/docker-odoo-image
|
build.py
|
1
|
2810
|
# coding: utf-8
"""Check if any file has changed and then build this Dockerfile"""
import os
import sys
import subprocess
import argparse
class DockerOdooImages(object):
"""Class to build if has changed any file"""
def __init__(self, folder, docker_image):
"""Init method
folder : Folder to containt the Dockerfile
docker_image : Docker image to build
"""
self._folder = folder
self._relpath = os.path.relpath(self._folder)
self._docker_file_path = os.path.join(self._folder, 'Dockerfile')
self._docker_image = docker_image
self._path = os.getcwd()
def check_path(self):
"""Check if Docker file is present and the format"""
if (not os.path.isdir(self._folder) or
not os.path.isfile(self._docker_file_path)):
raise Exception('No Dockerfile', 'The folder %s not containt'
' Dockerfile' % self._folder, ' or not exist')
cmd = ['dockerlint', os.path.join(self._relpath, 'Dockerfile')]
try:
print subprocess.check_output(cmd)
except subprocess.CalledProcessError:
raise Exception('Dockerfile file is bad formatted')
return True
def build(self):
"""Build changed image"""
cmd = ['git', 'remote', '-v']
print " ".join(cmd)
print subprocess.check_output(cmd)
cmd = ['git', 'branch', '-a']
print " ".join(cmd)
print subprocess.check_output(cmd)
can_be_build = self.check_path()
cmd = ['git', 'diff', 'HEAD^', 'HEAD', '--name-only',
'--relative=%s' % self._relpath]
print " ".join(cmd)
diffs = subprocess.check_output(cmd)
if isinstance(diffs, basestring):
differences = [diff for diff in diffs.split('\n') if diff != '']
if not differences:
can_be_build = False
if can_be_build:
cmd = ["docker", "build", "--rm", "-t", self._docker_image,
self._folder]
print " ".join(cmd)
subprocess.call(cmd)
return 0
if __name__ == "__main__":
argument_parser = argparse.ArgumentParser()
argument_parser.add_argument('-f', '--folder', help='Folder to containt'
'the Dockerfile', dest='folder',
required=True)
argument_parser.add_argument('-di', '--docker-image', help='Docker image'
'to build', dest='docker_image',
required=True)
arguments = argument_parser.parse_args()
docker_odoo_images = DockerOdooImages(arguments.folder,
arguments.docker_image)
sys.exit(docker_odoo_images.build())
|
gpl-2.0
|
vdods/fabric
|
bddtests/steps/peer_rest_impl.py
|
11
|
1869
|
#
# Copyright IBM Corp. 2016 All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import requests
from behave import *
from peer_basic_impl import getAttributeFromJSON
from bdd_request_util import httpGetToContainerAlias
from bdd_test_util import bdd_log
@when(u'I request transaction certs with query parameters on "{containerAlias}"')
def step_impl(context, containerAlias):
assert 'table' in context, "table (of query parameters) not found in context"
assert 'userName' in context, "userName not found in context"
assert 'compose_containers' in context, "compose_containers not found in context"
queryParams = {}
for row in context.table.rows:
key, value = row['key'], row['value']
queryParams[key] = value
endpoint = "/registrar/{0}/tcert".format(context.userName)
context.response = httpGetToContainerAlias(context, containerAlias, endpoint)
@then(u'I should get a JSON response with "{expectedValue}" different transaction certs')
def step_impl(context, expectedValue):
bdd_log(context.response.json())
foundValue = getAttributeFromJSON("OK", context.response.json())
bdd_log(len(set(foundValue)))
assert (len(set(foundValue)) == int(expectedValue)), "For attribute OK, expected different transaction cert of size (%s), instead found (%s)" % (expectedValue, len(set(foundValue)))
|
apache-2.0
|
dalepartridge/seapy
|
roms/interp.py
|
1
|
32584
|
#!/usr/bin/env python
"""
roms.interp
Methods to interpolate ROMS fields onto other grids
Written by Brian Powell on 11/02/13
Copyright (c)2017 University of Hawaii under the BSD-License.
"""
import numpy as np
import netCDF4
import os
import seapy
from seapy.timeout import timeout, TimeoutError
from joblib import Parallel, delayed
from warnings import warn
_up_scaling = {"zeta": 1.0, "u": 1.0, "v": 1.0, "temp": 1.0, "salt": 1.0}
_down_scaling = {"zeta": 1.0, "u": 0.9, "v": 0.9, "temp": 0.95, "salt": 1.05}
_ksize_range = (7, 15)
# Limit amount of memory to process in a single read. This determines how to
# divide up the time-records in interpolation
_max_memory = 768 * 1024 * 1024
def __mask_z_grid(z_data, src_depth, z_depth):
"""
When interpolating to z-grid, we need to apply depth dependent masking
based on the original ROMS depths
"""
for k in np.arange(0, z_depth.shape[0]):
idx = np.nonzero(z_depth[k, :, :] < src_depth)
if z_data.ndim == 4:
z_data.mask[:, k, idx[0], idx[1]] = True
elif z_data.ndim == 3:
z_data.mask[k, idx[0], idx[1]] = True
def __interp2_thread(rx, ry, data, zx, zy, pmap, weight, nx, ny, mask):
"""
internal routine: 2D interpolation thread for parallel interpolation
"""
data = np.ma.fix_invalid(data, copy=False)
# Convolve the water over the land
ksize = 2 * np.round(np.sqrt((nx / np.median(np.diff(rx)))**2 +
(ny / np.median(np.diff(ry.T)))**2)) + 1
if ksize < _ksize_range[0]:
warn("nx or ny values are too small for stable OA, {:f}".format(ksize))
ksize = _ksize_range[0]
elif ksize > _ksize_range[1]:
warn("nx or ny values are too large for stable OA, {:f}".format(ksize))
ksize = _ksize_range[1]
data = seapy.convolve_mask(data, ksize=ksize, copy=False)
# Interpolate the field and return the result
with timeout(minutes=30):
res, pm = seapy.oasurf(rx, ry, data, zx, zy, pmap, weight, nx, ny)
return np.ma.masked_where(np.logical_or(mask == 0, np.abs(res) > 9e4), res,
copy=False)
def __interp3_thread(rx, ry, rz, data, zx, zy, zz, pmap,
weight, nx, ny, mask, up_factor=1.0, down_factor=1.0):
"""
internal routine: 3D interpolation thread for parallel interpolation
"""
# Make the mask 3D
mask = seapy.adddim(mask, zz.shape[0])
data = np.ma.fix_invalid(data, copy=False)
# To avoid extrapolation, we are going to convolve ocean over the land
# and add a new top and bottom layer that replicates the data of the
# existing current and top. 1) iteratively convolve until we have
# filled most of the points, 2) Determine which way the
# depth goes and add/subtract new layers, and 3) fill in masked values
# from the layer above/below.
gradsrc = (rz[0, 1, 1] - rz[-1, 1, 1]) > 0
# Convolve the water over the land
ksize = 2 * np.round(np.sqrt((nx / np.median(np.diff(rx)))**2 +
(ny / np.median(np.diff(ry.T)))**2)) + 1
if ksize < _ksize_range[0]:
warn("nx or ny values are too small for stable OA, {:f}".format(ksize))
ksize = _ksize_range[0]
elif ksize > _ksize_range[1]:
warn("nx or ny values are too large for stable OA, {:f}".format(ksize))
ksize = _ksize_range[1]
# Iterate at most 5 times, but we will hopefully break out before that by
# checking if we have filled at least 40% of the bottom to be like
# the surface
bot = -1 if gradsrc else 0
top = 0 if gradsrc else -1
topmask = np.maximum(1, np.ma.count_masked(data[top, :, :]))
if np.ma.count_masked(data[bot, :, :]) > 0:
for iter in range(5):
# Check if we have most everything by checking the bottom
data = seapy.convolve_mask(data, ksize=ksize + iter, copy=False)
if topmask / np.maximum(1, np.ma.count_masked(data[bot, :, :])) > 0.4:
break
# Now fill vertically
nrz = np.zeros((data.shape[0] + 2, data.shape[1], data.shape[2]))
nrz[1:-1, :, :] = rz
nrz[bot, :, :] = rz[bot, :, :] - 5000
nrz[top, :, :] = np.minimum(rz[top, :, :] + 50, 0)
if not gradsrc:
# The first level is the bottom
factor = down_factor
levs = np.arange(data.shape[0], 0, -1) - 1
else:
# The first level is the top
factor = up_factor
levs = np.arange(0, data.shape[0])
# Fill in missing values where we have them from the shallower layer
for k in levs[1:]:
if np.ma.count_masked(data[k, :, :]) == 0:
continue
idx = np.nonzero(np.logical_xor(data.mask[k, :, :],
data.mask[k - 1, :, :]))
data.mask[k, idx[0], idx[1]] = data.mask[k - 1, idx[0], idx[1]]
data[k, idx[0], idx[1]] = data[k - 1, idx[0], idx[1]] * factor
# Add upper and lower boundaries
ndat = np.zeros((data.shape[0] + 2, data.shape[1], data.shape[2]))
ndat[0, :, :] = data[0, :, :].filled(np.nan) * factor
ndat[1:-1, :, :] = data.filled(np.nan)
ndat[-1, :, :] = data[-1, :, :].filled(np.nan) * factor
# Interpolate the field and return the result
with timeout(minutes=30):
if gradsrc:
res, pm = seapy.oavol(rx, ry, nrz[::-1, :, :], ndat[::-1, :, :],
zx, zy, zz, pmap, weight, nx, ny)
else:
res, pm = seapy.oavol(rx, ry, nrz, ndat, zx, zy, zz,
pmap, weight, nx, ny)
return np.ma.masked_where(np.logical_or(mask == 0, np.abs(res) > 9e4), res,
copy=False)
def __interp3_vel_thread(rx, ry, rz, ra, u, v, zx, zy, zz, za, pmap,
weight, nx, ny, mask):
"""
internal routine: 3D velocity interpolation thread for parallel interpolation
"""
# Put on the same grid
if u.shape != v.shape:
u = seapy.model.u2rho(u, fill=True)
v = seapy.model.v2rho(v, fill=True)
# Rotate the fields (NOTE: ROMS angle is negative relative to "true")
if ra is not None:
u, v = seapy.rotate(u, v, ra)
# Interpolate
u = __interp3_thread(rx, ry, rz, u, zx, zy, zz, pmap,
weight, nx, ny, mask, _up_scaling["u"],
_down_scaling["u"])
v = __interp3_thread(rx, ry, rz, v, zx, zy, zz, pmap,
weight, nx, ny, mask, _up_scaling["v"],
_down_scaling["v"])
# Rotate to destination (NOTE: ROMS angle is negative relative to "true")
if za is not None:
u, v = seapy.rotate(u, v, -za)
# Return the masked data
return u, v
def __interp_grids(src_grid, child_grid, ncout, records=None,
threads=2, nx=0, ny=0, weight=10, vmap=None, z_mask=False,
pmap=None):
"""
internal method: Given a model file (average, history, etc.),
interpolate the fields onto another gridded file.
Parameters
----------
src_grid : seapy.model.grid data source (History, Average, etc. file)
child_grid : seapy.model.grid output data grid
ncout : netcdf output file
[records] : array of the record indices to interpolate
[threads] : number of processing threads
[nx] : decorrelation length in grid-cells for x
[ny] : decorrelation length in grid-cells for y
[vmap] : variable name mapping
[z_mask] : mask out depths in z-grids
[pmap] : use the specified pmap rather than compute it
Returns
-------
None
"""
# If we don't have a variable map, then do a one-to-one mapping
if vmap is None:
vmap = dict()
for k in seapy.roms.fields:
vmap[k] = k
# Generate a file to store the pmap information
sname = getattr(src_grid, 'name', None)
cname = getattr(child_grid, 'name', None)
pmap_file = None if any(v is None for v in (sname, cname)) else \
sname + "_" + cname + "_pmap.npz"
# Create or load the pmaps depending on if they exist
if nx == 0:
if hasattr(src_grid, "dm") and hasattr(child_grid, "dm"):
nx = np.ceil(np.mean(src_grid.dm) / np.mean(child_grid.dm))
else:
nx = 5
if ny == 0:
if hasattr(src_grid, "dn") and hasattr(child_grid, "dn"):
ny = np.ceil(np.mean(src_grid.dn) / np.mean(child_grid.dn))
else:
ny = 5
if pmap is None:
if pmap_file is not None and os.path.isfile(pmap_file):
pmap = np.load(pmap_file)
else:
tmp = np.ma.masked_equal(src_grid.mask_rho, 0)
tmp, pmaprho = seapy.oasurf(src_grid.lon_rho, src_grid.lat_rho,
tmp, child_grid.lon_rho, child_grid.lat_rho,
weight=weight, nx=nx, ny=ny)
tmp = np.ma.masked_equal(src_grid.mask_u, 0)
tmp, pmapu = seapy.oasurf(src_grid.lon_u, src_grid.lat_u,
tmp, child_grid.lon_rho, child_grid.lat_rho,
weight=weight, nx=nx, ny=ny)
tmp = np.ma.masked_equal(src_grid.mask_v, 0)
tmp, pmapv = seapy.oasurf(src_grid.lon_v, src_grid.lat_v,
tmp, child_grid.lon_rho, child_grid.lat_rho,
weight=weight, nx=nx, ny=ny)
if pmap_file is not None:
np.savez(pmap_file, pmaprho=pmaprho, pmapu=pmapu, pmapv=pmapv)
pmap = {"pmaprho": pmaprho, "pmapu": pmapu, "pmapv": pmapv}
# Get the time field
ncsrc = seapy.netcdf(src_grid.filename)
time = seapy.roms.get_timevar(ncsrc)
# Interpolate the depths from the source to final grid
src_depth = np.min(src_grid.depth_rho, 0)
dst_depth = __interp2_thread(src_grid.lon_rho, src_grid.lat_rho, src_depth,
child_grid.lon_rho, child_grid.lat_rho, pmap[
"pmaprho"],
weight, nx, ny, child_grid.mask_rho)
# Interpolate the scalar fields
records = np.arange(0, ncsrc.variables[time].shape[0]) \
if records is None else np.atleast_1d(records)
for src in vmap:
dest = vmap[src]
# Extra fields will probably be user tracers (biogeochemical)
fld = seapy.roms.fields.get(dest, {"dims": 3})
# Only interpolate the fields we want in the destination
if (dest not in ncout.variables) or ("rotate" in fld):
continue
if fld["dims"] == 2:
# Compute the max number of hold in memory
maxrecs = np.maximum(1, np.minimum(len(records),
np.int(_max_memory / (child_grid.lon_rho.nbytes +
src_grid.lon_rho.nbytes))))
for rn, recs in enumerate(seapy.chunker(records, maxrecs)):
outr = np.s_[
rn * maxrecs:np.minimum((rn + 1) * maxrecs, len(records))]
ndata = np.ma.array(Parallel(n_jobs=threads, verbose=2, max_nbytes=_max_memory)
(delayed(__interp2_thread)(
src_grid.lon_rho, src_grid.lat_rho,
ncsrc.variables[src][i, :, :],
child_grid.lon_rho, child_grid.lat_rho,
pmap["pmaprho"], weight,
nx, ny, child_grid.mask_rho)
for i in recs), copy=False)
ncout.variables[dest][outr, :, :] = ndata
ncout.sync()
else:
maxrecs = np.maximum(1, np.minimum(
len(records), np.int(_max_memory /
(child_grid.lon_rho.nbytes *
child_grid.n +
src_grid.lon_rho.nbytes *
src_grid.n))))
for rn, recs in enumerate(seapy.chunker(records, maxrecs)):
outr = np.s_[
rn * maxrecs:np.minimum((rn + 1) * maxrecs, len(records))]
ndata = np.ma.array(Parallel(n_jobs=threads, verbose=2, max_nbytes=_max_memory)
(delayed(__interp3_thread)(
src_grid.lon_rho, src_grid.lat_rho,
src_grid.depth_rho,
ncsrc.variables[src][i, :, :, :],
child_grid.lon_rho, child_grid.lat_rho,
child_grid.depth_rho,
pmap["pmaprho"], weight,
nx, ny, child_grid.mask_rho,
up_factor=_up_scaling.get(dest, 1.0),
down_factor=_down_scaling.get(dest, 1.0))
for i in recs), copy=False)
if z_mask:
__mask_z_grid(ndata, dst_depth, child_grid.depth_rho)
ncout.variables[dest][outr, :, :, :] = ndata
ncout.sync()
# Rotate and Interpolate the vector fields. First, determine which
# are the "u" and the "v" vmap fields
try:
velmap = {
"u": list(vmap.keys())[list(vmap.values()).index("u")],
"v": list(vmap.keys())[list(vmap.values()).index("v")]}
except:
warn("velocity not present in source file")
return
srcangle = src_grid.angle if src_grid.cgrid else None
dstangle = child_grid.angle if child_grid.cgrid else None
maxrecs = np.minimum(len(records),
np.int(_max_memory /
(2 * (child_grid.lon_rho.nbytes *
child_grid.n +
src_grid.lon_rho.nbytes *
src_grid.n))))
for nr, recs in enumerate(seapy.chunker(records, maxrecs)):
vel = Parallel(n_jobs=threads, verbose=2, max_nbytes=_max_memory)(delayed(__interp3_vel_thread)(
src_grid.lon_rho, src_grid.lat_rho,
src_grid.depth_rho, srcangle,
ncsrc.variables[velmap["u"]][i, :, :, :],
ncsrc.variables[velmap["v"]][i, :, :, :],
child_grid.lon_rho, child_grid.lat_rho,
child_grid.depth_rho, dstangle,
pmap["pmaprho"], weight, nx, ny,
child_grid.mask_rho) for i in recs)
for j in range(len(vel)):
vel_u = np.ma.array(vel[j][0], copy=False)
vel_v = np.ma.array(vel[j][1], copy=False)
if z_mask:
__mask_z_grid(vel_u, dst_depth, child_grid.depth_rho)
__mask_z_grid(vel_v, dst_depth, child_grid.depth_rho)
if child_grid.cgrid:
vel_u = seapy.model.rho2u(vel_u)
vel_v = seapy.model.rho2v(vel_v)
ncout.variables["u"][nr * maxrecs + j, :] = vel_u
ncout.variables["v"][nr * maxrecs + j, :] = vel_v
if "ubar" in ncout.variables:
# Create ubar and vbar
# depth = seapy.adddim(child_grid.depth_u, vel_u.shape[0])
ncout.variables["ubar"][nr * maxrecs + j, :] = \
np.sum(vel_u * child_grid.depth_u, axis=0) / \
np.sum(child_grid.depth_u, axis=0)
if "vbar" in ncout.variables:
# depth = seapy.adddim(child_grid.depth_v, vel_v.shape[0])
ncout.variables["vbar"][nr * maxrecs + j, :] = \
np.sum(vel_v * child_grid.depth_v, axis=0) / \
np.sum(child_grid.depth_v, axis=0)
ncout.sync()
# Return the pmap that was used
return pmap
def field2d(src_lon, src_lat, src_field, dest_lon, dest_lat, dest_mask=None,
nx=0, ny=0, weight=10, threads=2, pmap=None):
"""
Given a 2D field with time (dimensions [time, lat, lon]), interpolate
onto a new grid and return the new field. This is a helper function
when needing to interpolate data within files, etc.
Parameters
----------
src_lon: numpy.ndarray
longitude that field is on
src_lat: numpy.ndarray
latitude that field is on
src_field: numpy.ndarray
field to interpolate
dest_lon: numpy.ndarray
output longitudes to interpolate to
dest_lat: numpy.ndarray
output latitudes to interpolate to
dest_mask: numpy.ndarray, optional
mask to apply to interpolated data
reftime: datetime, optional:
Reference time as the epoch for z-grid file
nx : float, optional:
decorrelation length-scale for OA (same units as source data)
ny : float, optional:
decorrelation length-scale for OA (same units as source data)
weight : int, optional:
number of points to use in weighting matrix
threads : int, optional:
number of processing threads
pmap : numpy.ndarray, optional:
use the specified pmap rather than compute it
Output
------
ndarray:
interpolated field on the destination grid
pmap:
the pmap used in the inerpolation
"""
if pmap is None:
tmp, pmap = seapy.oasurf(src_lon, src_lat, src_lat,
dest_lon, dest_lat, weight=weight, nx=nx, ny=ny)
if dest_mask is None:
dest_mask = np.ones(dest_lat.shape)
records = np.arange(0, src_field.shape[0])
maxrecs = np.maximum(1,
np.minimum(records.size,
np.int(_max_memory /
(dest_lon.nbytes + src_lon.nbytes))))
for rn, recs in enumerate(seapy.chunker(records, maxrecs)):
nfield = np.ma.array(Parallel(n_jobs=threads, verbose=2)
(delayed(__interp2_thread)(
src_lon, src_lat, src_field[i, :, :],
dest_lon, dest_lat,
pmap, weight,
nx, ny, dest_mask)
for i in recs), copy=False)
return nfield, pmap
def field3d(src_lon, src_lat, src_depth, src_field, dest_lon, dest_lat,
dest_depth, dest_mask=None, nx=0, ny=0, weight=10,
threads=2, pmap=None):
"""
Given a 3D field with time (dimensions [time, z, lat, lon]), interpolate
onto a new grid and return the new field. This is a helper function
when needing to interpolate data within files, etc.
Parameters
----------
src_lon: numpy.ndarray
longitude that field is on
src_lat: numpy.ndarray
latitude that field is on
srf_depth: numpy.ndarray
depths of the field
src_field: numpy.ndarray
field to interpolate
dest_lon: numpy.ndarray
output longitudes to interpolate to
dest_lat: numpy.ndarray
output latitudes to interpolate to
dest_depth: numpy.ndarray
output depths to interpolate to
dest_mask: numpy.ndarray, optional
mask to apply to interpolated data
reftime: datetime, optional:
Reference time as the epoch for z-grid file
nx : float, optional:
decorrelation length-scale for OA (same units as source data)
ny : float, optional:
decorrelation length-scale for OA (same units as source data)
weight : int, optional:
number of points to use in weighting matrix
threads : int, optional:
number of processing threads
pmap : numpy.ndarray, optional:
use the specified pmap rather than compute it
Output
------
ndarray:
interpolated field on the destination grid
pmap:
the pmap used in the inerpolation
"""
if pmap is None:
tmp, pmap = seapy.oasurf(src_lon, src_lat, src_lat,
dest_lon, dest_lat, weight=weight, nx=nx, ny=ny)
if dest_mask is None:
dest_mask = np.ones(dest_lat.shape)
records = np.arange(0, src_field.shape[0])
maxrecs = np.maximum(1,
np.minimum(records.size,
np.int(_max_memory /
(dest_lon.nbytes *
dest_depth.shape[0] +
src_lon.nbytes *
src_depth.shape[0]))))
for rn, recs in enumerate(seapy.chunker(records, maxrecs)):
nfield = np.ma.array(Parallel(n_jobs=threads, verbose=2)
(delayed(__interp3_thread)(
src_lon, src_lat, src_depth,
src_field[i, :, :],
dest_lon, dest_lat, dest_depth,
pmap, weight, nx, ny, dest_mask,
up_factor=1, down_factor=1)
for i in recs), copy=False)
return nfield, pmap
def to_zgrid(roms_file, z_file, z_grid=None, depth=None, records=None,
threads=2, reftime=None, nx=0, ny=0, weight=10, vmap=None,
cdlfile=None, dims=2, pmap=None):
"""
Given an existing ROMS history or average file, create (if does not exit)
a new z-grid file. Use the given z_grid or otherwise build one with the
same horizontal extent and the specified depths and interpolate the
ROMS fields onto the z-grid.
Parameters
----------
roms_file : string,
File name of src file to interpolate from
z_file : string,
Name of desination file to write to
z_grid: (string or seapy.model.grid), optional:
Name or instance of output definition
depth: numpy.ndarray, optional:
array of depths to use for z-level
records : numpy.ndarray, optional:
Record indices to interpolate
threads : int, optional:
number of processing threads
reftime: datetime, optional:
Reference time as the epoch for z-grid file
nx : float, optional:
decorrelation length-scale for OA (same units as source data)
ny : float, optional:
decorrelation length-scale for OA (same units as source data)
weight : int, optional:
number of points to use in weighting matrix
vmap : dictionary, optional
mapping source and destination variables
cdlfile : string, optional
cdlfile to use for generating the z-file
dims : int, optional
number of dimensions to use for lat/lon arrays (default 2)
pmap : numpy.ndarray, optional:
use the specified pmap rather than compute it
Returns
-------
pmap : ndarray
the weighting matrix computed during the interpolation
"""
roms_grid = seapy.model.asgrid(roms_file)
ncroms = seapy.netcdf(roms_file)
src_ref, time = seapy.roms.get_reftime(ncroms)
if reftime is not None:
src_ref = reftime
records = np.arange(0, ncroms.variables[time].shape[0]) \
if records is None else np.atleast_1d(records)
# Load the grid
if z_grid is not None:
z_grid = seapy.model.asgrid(z_grid)
elif os.path.isfile(z_file):
z_grid = seapy.model.asgrid(z_file)
if not os.path.isfile(z_file):
if z_grid is None:
lat = roms_grid.lat_rho.shape[0]
lon = roms_grid.lat_rho.shape[1]
if depth is None:
raise ValueError("depth must be specified")
ncout = seapy.roms.ncgen.create_zlevel(z_file, lat, lon,
len(depth), src_ref, "ROMS z-level",
cdlfile=cdlfile, dims=dims)
if dims == 1:
ncout.variables["lat"][:] = roms_grid.lat_rho[:, 0]
ncout.variables["lon"][:] = roms_grid.lon_rho[0, :]
else:
ncout.variables["lat"][:] = roms_grid.lat_rho
ncout.variables["lon"][:] = roms_grid.lon_rho
ncout.variables["depth"][:] = depth
ncout.variables["mask"][:] = roms_grid.mask_rho
ncout.sync()
z_grid = seapy.model.grid(z_file)
else:
lat = z_grid.lat_rho.shape[0]
lon = z_grid.lat_rho.shape[1]
dims = z_grid.spatial_dims
ncout = seapy.roms.ncgen.create_zlevel(z_file, lat, lon,
len(z_grid.z), src_ref, "ROMS z-level",
cdlfile=cdlfile, dims=dims)
if dims == 1:
ncout.variables["lat"][:] = z_grid.lat_rho[:, 0]
ncout.variables["lon"][:] = z_grid.lon_rho[0, :]
else:
ncout.variables["lat"][:] = z_grid.lat_rho
ncout.variables["lon"][:] = z_grid.lon_rho
ncout.variables["depth"][:] = z_grid.z
ncout.variables["mask"][:] = z_grid.mask_rho
else:
ncout = netCDF4.Dataset(z_file, "a")
ncout.variables["time"][:] = netCDF4.date2num(
netCDF4.num2date(ncroms.variables[time][records],
ncroms.variables[time].units),
ncout.variables["time"].units)
ncroms.close()
# Call the interpolation
try:
roms_grid.set_east(z_grid.east())
pmap = __interp_grids(roms_grid, z_grid, ncout, records=records,
threads=threads, nx=nx, ny=ny, vmap=vmap, weight=weight,
z_mask=True, pmap=pmap)
except TimeoutError:
print("Timeout: process is hung, deleting output.")
# Delete the output file
os.remove(z_file)
finally:
# Clean up
ncout.close()
return pmap
def to_grid(src_file, dest_file, dest_grid=None, records=None, threads=2,
reftime=None, nx=0, ny=0, weight=10, vmap=None, pmap=None):
"""
Given an existing model file, create (if does not exit) a
new ROMS history file using the given ROMS destination grid and
interpolate the ROMS fields onto the new grid. If an existing destination
file is given, it is interpolated onto the specified.
Parameters
----------
src_file : string,
Filename of src file to interpolate from
dest_file : string,
Name of desination file to write to
dest_grid: (string or seapy.model.grid), optional:
Name or instance of output definition
records : numpy.ndarray, optional:
Record indices to interpolate
threads : int, optional:
number of processing threads
reftime: datetime, optional:
Reference time as the epoch for ROMS file
nx : float, optional:
decorrelation length-scale for OA (same units as source data)
ny : float, optional:
decorrelation length-scale for OA (same units as source data)
weight : int, optional:
number of points to use in weighting matrix
vmap : dictionary, optional
mapping source and destination variables
pmap : numpy.ndarray, optional:
use the specified pmap rather than compute it
Returns
-------
pmap : ndarray
the weighting matrix computed during the interpolation
"""
src_grid = seapy.model.asgrid(src_file)
if dest_grid is not None:
destg = seapy.model.asgrid(dest_grid)
if not os.path.isfile(dest_file):
ncsrc = seapy.netcdf(src_file)
src_ref, time = seapy.roms.get_reftime(ncsrc)
if reftime is not None:
src_ref = reftime
records = np.arange(0, ncsrc.variables[time].shape[0]) \
if records is None else np.atleast_1d(records)
ncout = seapy.roms.ncgen.create_ini(dest_file,
eta_rho=destg.eta_rho,
xi_rho=destg.xi_rho,
s_rho=destg.n,
reftime=src_ref,
title="interpolated from " + src_file)
destg.to_netcdf(ncout)
ncout.variables["ocean_time"][:] = netCDF4.date2num(
netCDF4.num2date(ncsrc.variables[time][records],
ncsrc.variables[time].units),
ncout.variables["ocean_time"].units)
ncsrc.close()
if os.path.isfile(dest_file):
ncout = netCDF4.Dataset(dest_file, "a")
if dest_grid is None:
destg = seapy.model.asgrid(dest_file)
# Call the interpolation
try:
src_grid.set_east(destg.east())
pmap = __interp_grids(src_grid, destg, ncout, records=records,
threads=threads, nx=nx, ny=ny, weight=weight,
vmap=vmap, pmap=pmap)
except TimeoutError:
print("Timeout: process is hung, deleting output.")
# Delete the output file
os.remove(dest_file)
finally:
# Clean up
ncout.close()
return pmap
def to_clim(src_file, dest_file, dest_grid=None, records=None, threads=2,
reftime=None, nx=0, ny=0, weight=10, vmap=None, pmap=None):
"""
Given an model output file, create (if does not exit) a
new ROMS climatology file using the given ROMS destination grid and
interpolate the ROMS fields onto the new grid. If an existing destination
file is given, it is interpolated onto the specified.
Parameters
----------
src_file : string,
Filename of src file to interpolate from
dest_file : string,
Name of desination file to write to
dest_grid: (string or seapy.model.grid), optional:
Name or instance of output definition
records : numpy.ndarray, optional:
Record indices to interpolate
threads : int, optional:
number of processing threads
reftime: datetime, optional:
Reference time as the epoch for climatology file
nx : float, optional:
decorrelation length-scale for OA (same units as source data)
ny : float, optional:
decorrelation length-scale for OA (same units as source data)
weight : int, optional:
number of points to use in weighting matrix
vmap : dictionary, optional
mapping source and destination variables
pmap : numpy.ndarray, optional:
use the specified pmap rather than compute it
Returns
-------
pmap : ndarray
the weighting matrix computed during the interpolation
"""
if dest_grid is not None:
destg = seapy.model.asgrid(dest_grid)
src_grid = seapy.model.asgrid(src_file)
ncsrc = seapy.netcdf(src_file)
src_ref, time = seapy.roms.get_reftime(ncsrc)
if reftime is not None:
src_ref = reftime
records = np.arange(0, ncsrc.variables[time].shape[0]) \
if records is None else np.atleast_1d(records)
ncout = seapy.roms.ncgen.create_clim(dest_file,
eta_rho=destg.ln,
xi_rho=destg.lm,
s_rho=destg.n,
reftime=src_ref,
title="interpolated from " + src_file)
src_time = netCDF4.num2date(ncsrc.variables[time][records],
ncsrc.variables[time].units)
ncout.variables["clim_time"][:] = netCDF4.date2num(
src_time, ncout.variables["clim_time"].units)
ncsrc.close()
else:
raise AttributeError(
"you must supply a destination file or a grid to make the file")
# Call the interpolation
try:
src_grid.set_east(destg.east())
pmap = __interp_grids(src_grid, destg, ncout, records=records, threads=threads,
nx=nx, ny=ny, vmap=vmap, weight=weight, pmap=pmap)
except TimeoutError:
print("Timeout: process is hung, deleting output.")
# Delete the output file
os.remove(dest_file)
finally:
# Clean up
ncout.close()
return pmap
pass
|
mit
|
WillamLi/itool
|
mysql_tool/mysql_concat/test.py
|
1
|
2436
|
#!/bin/python
#coding=utf-8
import MySQLdb
import sys
from optparse import OptionParser
user_value="reboot"
pass_value='reboot123'
port_value=3306
def CHECK_ARGV():
argv_dict = {}
usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage)
parser.add_option("-H","--host",dest="hostname",help="hostname,you DB Hostname or IP")
parser.add_option("-d","--database",dest="db",help="read database ")
parser.add_option("-t","--table",dest="tb",help="read table")
parser.add_option("-u","--user",dest="user",help="conn user")
parser.add_option("-p","--passwd",dest="passwd",help="conn passwd")
parser.add_option("-P","--port",dest="port",default=3306,help="MySQL Port")
parser.add_option("-C","--character",dest="character",default='utf8',help="MySQL Charset")
parser.add_option("-E","--SQL",dest="execsql",default="",help="Input U Exec SQL")
(options,args)=parser.parse_args()
len_argv=len(sys.argv[1:])
# print "len_argv:",len_argv
if len_argv == 0 :
print parser.print_help()
parser.exit(1)
if not options.db or not options.tb or not options.hostname:
print 'Need database and table'
else:
#print type(parser.values)
#m=str(parser.values)
exec("argv_dict ="+str(options))
# print argv_dict
# print type(argv_dict)
return argv_dict
#print type(options)
#return n
#return options
# print "---------"
def Mysql_con(config):
# print config
host_value = config['hostname']
user_value = config['user']
passwd_value = config['passwd']
db_value = config['db']
tb_value = config['tb']
port_value = config['port']
charset_value = config['character']
print host_value,user_value,passwd_value,db_value,tb_value,port_value,charset_value
try:
db = MySQLdb.connect(user=user_value,host=host_value,passwd=passwd_value,port=port_value,charset=charset_value)
cursor = db.cursor()
# sql="select * from lr.tt"
# cursor.execute(sql)
# result = cursor.fetchall()
# print result
return cursor
except Exception,e:
print "---",e
if __name__ == '__main__':
a=CHECK_ARGV()
# print a
# print type(a)
cursor = Mysql_con(a)
print cursor
sql="select * from lr.tt"
cursor.execute(sql)
result=cursor.fetchall()
print result
|
gpl-2.0
|
alvin319/CarnotKE
|
jyhton/lib-python/2.7/multiprocessing/queues.py
|
103
|
12318
|
#
# Module implementing queues
#
# multiprocessing/queues.py
#
# Copyright (c) 2006-2008, R Oudkerk
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. 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.
# 3. Neither the name of author nor the names of any contributors may be
# used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
#
__all__ = ['Queue', 'SimpleQueue', 'JoinableQueue']
import sys
import os
import threading
import collections
import time
import atexit
import weakref
from Queue import Empty, Full
import _multiprocessing
from multiprocessing import Pipe
from multiprocessing.synchronize import Lock, BoundedSemaphore, Semaphore, Condition
from multiprocessing.util import debug, info, Finalize, register_after_fork
from multiprocessing.forking import assert_spawning
#
# Queue type using a pipe, buffer and thread
#
class Queue(object):
def __init__(self, maxsize=0):
if maxsize <= 0:
maxsize = _multiprocessing.SemLock.SEM_VALUE_MAX
self._maxsize = maxsize
self._reader, self._writer = Pipe(duplex=False)
self._rlock = Lock()
self._opid = os.getpid()
if sys.platform == 'win32':
self._wlock = None
else:
self._wlock = Lock()
self._sem = BoundedSemaphore(maxsize)
self._after_fork()
if sys.platform != 'win32':
register_after_fork(self, Queue._after_fork)
def __getstate__(self):
assert_spawning(self)
return (self._maxsize, self._reader, self._writer,
self._rlock, self._wlock, self._sem, self._opid)
def __setstate__(self, state):
(self._maxsize, self._reader, self._writer,
self._rlock, self._wlock, self._sem, self._opid) = state
self._after_fork()
def _after_fork(self):
debug('Queue._after_fork()')
self._notempty = threading.Condition(threading.Lock())
self._buffer = collections.deque()
self._thread = None
self._jointhread = None
self._joincancelled = False
self._closed = False
self._close = None
self._send = self._writer.send
self._recv = self._reader.recv
self._poll = self._reader.poll
def put(self, obj, block=True, timeout=None):
assert not self._closed
if not self._sem.acquire(block, timeout):
raise Full
self._notempty.acquire()
try:
if self._thread is None:
self._start_thread()
self._buffer.append(obj)
self._notempty.notify()
finally:
self._notempty.release()
def get(self, block=True, timeout=None):
if block and timeout is None:
self._rlock.acquire()
try:
res = self._recv()
self._sem.release()
return res
finally:
self._rlock.release()
else:
if block:
deadline = time.time() + timeout
if not self._rlock.acquire(block, timeout):
raise Empty
try:
if block:
timeout = deadline - time.time()
if timeout < 0 or not self._poll(timeout):
raise Empty
elif not self._poll():
raise Empty
res = self._recv()
self._sem.release()
return res
finally:
self._rlock.release()
def qsize(self):
# Raises NotImplementedError on Mac OSX because of broken sem_getvalue()
return self._maxsize - self._sem._semlock._get_value()
def empty(self):
return not self._poll()
def full(self):
return self._sem._semlock._is_zero()
def get_nowait(self):
return self.get(False)
def put_nowait(self, obj):
return self.put(obj, False)
def close(self):
self._closed = True
self._reader.close()
if self._close:
self._close()
def join_thread(self):
debug('Queue.join_thread()')
assert self._closed
if self._jointhread:
self._jointhread()
def cancel_join_thread(self):
debug('Queue.cancel_join_thread()')
self._joincancelled = True
try:
self._jointhread.cancel()
except AttributeError:
pass
def _start_thread(self):
debug('Queue._start_thread()')
# Start thread which transfers data from buffer to pipe
self._buffer.clear()
self._thread = threading.Thread(
target=Queue._feed,
args=(self._buffer, self._notempty, self._send,
self._wlock, self._writer.close),
name='QueueFeederThread'
)
self._thread.daemon = True
debug('doing self._thread.start()')
self._thread.start()
debug('... done self._thread.start()')
# On process exit we will wait for data to be flushed to pipe.
if not self._joincancelled:
self._jointhread = Finalize(
self._thread, Queue._finalize_join,
[weakref.ref(self._thread)],
exitpriority=-5
)
# Send sentinel to the thread queue object when garbage collected
self._close = Finalize(
self, Queue._finalize_close,
[self._buffer, self._notempty],
exitpriority=10
)
@staticmethod
def _finalize_join(twr):
debug('joining queue thread')
thread = twr()
if thread is not None:
thread.join()
debug('... queue thread joined')
else:
debug('... queue thread already dead')
@staticmethod
def _finalize_close(buffer, notempty):
debug('telling queue thread to quit')
notempty.acquire()
try:
buffer.append(_sentinel)
notempty.notify()
finally:
notempty.release()
@staticmethod
def _feed(buffer, notempty, send, writelock, close):
debug('starting thread to feed data to pipe')
from .util import is_exiting
nacquire = notempty.acquire
nrelease = notempty.release
nwait = notempty.wait
bpopleft = buffer.popleft
sentinel = _sentinel
if sys.platform != 'win32':
wacquire = writelock.acquire
wrelease = writelock.release
else:
wacquire = None
try:
while 1:
nacquire()
try:
if not buffer:
nwait()
finally:
nrelease()
try:
while 1:
obj = bpopleft()
if obj is sentinel:
debug('feeder thread got sentinel -- exiting')
close()
return
if wacquire is None:
send(obj)
else:
wacquire()
try:
send(obj)
finally:
wrelease()
except IndexError:
pass
except Exception, e:
# Since this runs in a daemon thread the resources it uses
# may be become unusable while the process is cleaning up.
# We ignore errors which happen after the process has
# started to cleanup.
try:
if is_exiting():
info('error in queue thread: %s', e)
else:
import traceback
traceback.print_exc()
except Exception:
pass
_sentinel = object()
#
# A queue type which also supports join() and task_done() methods
#
# Note that if you do not call task_done() for each finished task then
# eventually the counter's semaphore may overflow causing Bad Things
# to happen.
#
class JoinableQueue(Queue):
def __init__(self, maxsize=0):
Queue.__init__(self, maxsize)
self._unfinished_tasks = Semaphore(0)
self._cond = Condition()
def __getstate__(self):
return Queue.__getstate__(self) + (self._cond, self._unfinished_tasks)
def __setstate__(self, state):
Queue.__setstate__(self, state[:-2])
self._cond, self._unfinished_tasks = state[-2:]
def put(self, obj, block=True, timeout=None):
assert not self._closed
if not self._sem.acquire(block, timeout):
raise Full
self._notempty.acquire()
self._cond.acquire()
try:
if self._thread is None:
self._start_thread()
self._buffer.append(obj)
self._unfinished_tasks.release()
self._notempty.notify()
finally:
self._cond.release()
self._notempty.release()
def task_done(self):
self._cond.acquire()
try:
if not self._unfinished_tasks.acquire(False):
raise ValueError('task_done() called too many times')
if self._unfinished_tasks._semlock._is_zero():
self._cond.notify_all()
finally:
self._cond.release()
def join(self):
self._cond.acquire()
try:
if not self._unfinished_tasks._semlock._is_zero():
self._cond.wait()
finally:
self._cond.release()
#
# Simplified Queue type -- really just a locked pipe
#
class SimpleQueue(object):
def __init__(self):
self._reader, self._writer = Pipe(duplex=False)
self._rlock = Lock()
if sys.platform == 'win32':
self._wlock = None
else:
self._wlock = Lock()
self._make_methods()
def empty(self):
return not self._reader.poll()
def __getstate__(self):
assert_spawning(self)
return (self._reader, self._writer, self._rlock, self._wlock)
def __setstate__(self, state):
(self._reader, self._writer, self._rlock, self._wlock) = state
self._make_methods()
def _make_methods(self):
recv = self._reader.recv
racquire, rrelease = self._rlock.acquire, self._rlock.release
def get():
racquire()
try:
return recv()
finally:
rrelease()
self.get = get
if self._wlock is None:
# writes to a message oriented win32 pipe are atomic
self.put = self._writer.send
else:
send = self._writer.send
wacquire, wrelease = self._wlock.acquire, self._wlock.release
def put(obj):
wacquire()
try:
return send(obj)
finally:
wrelease()
self.put = put
|
apache-2.0
|
rmoorman/feedhq
|
feedhq/reader/authentication.py
|
2
|
1407
|
from django.core.cache import cache
from rest_framework.authentication import (BaseAuthentication,
get_authorization_header)
from ..profiles.models import User
from .exceptions import PermissionDenied
from .models import check_auth_token
class GoogleLoginAuthentication(BaseAuthentication):
def authenticate_header(self, request):
return 'GoogleLogin'
def authenticate(self, request):
"""GoogleLogin auth=<token>"""
auth = get_authorization_header(request).decode('utf-8').split()
if not auth or auth[0].lower() != 'googlelogin':
raise PermissionDenied()
if len(auth) == 1:
raise PermissionDenied()
if not auth[1].startswith('auth='):
raise PermissionDenied()
token = auth[1].split('auth=', 1)[1]
return self.authenticate_credentials(token)
def authenticate_credentials(self, token):
user_id = check_auth_token(token)
if user_id is False:
raise PermissionDenied()
cache_key = 'reader_user:{0}'.format(user_id)
user = cache.get(cache_key)
if user is None:
try:
user = User.objects.get(pk=user_id, is_active=True)
except User.DoesNotExist:
raise PermissionDenied()
cache.set(cache_key, user, 5*60)
return user, token
|
bsd-3-clause
|
taaviteska/django
|
tests/staticfiles_tests/test_storage.py
|
24
|
26035
|
import os
import shutil
import sys
import tempfile
import unittest
from io import StringIO
from django.conf import settings
from django.contrib.staticfiles import finders, storage
from django.contrib.staticfiles.management.commands.collectstatic import \
Command as CollectstaticCommand
from django.core.cache.backends.base import BaseCache
from django.core.management import call_command
from django.test import override_settings
from .cases import CollectionTestCase
from .settings import TEST_ROOT
def hashed_file_path(test, path):
fullpath = test.render_template(test.static_template_snippet(path))
return fullpath.replace(settings.STATIC_URL, '')
class TestHashedFiles:
hashed_file_path = hashed_file_path
def setUp(self):
self._max_post_process_passes = storage.staticfiles_storage.max_post_process_passes
super().setUp()
def tearDown(self):
# Clear hashed files to avoid side effects among tests.
storage.staticfiles_storage.hashed_files.clear()
storage.staticfiles_storage.max_post_process_passes = self._max_post_process_passes
def assertPostCondition(self):
"""
Assert post conditions for a test are met. Must be manually called at
the end of each test.
"""
pass
def test_template_tag_return(self):
"""
Test the CachedStaticFilesStorage backend.
"""
self.assertStaticRaises(ValueError, "does/not/exist.png", "/static/does/not/exist.png")
self.assertStaticRenders("test/file.txt", "/static/test/file.dad0999e4f8f.txt")
self.assertStaticRenders("test/file.txt", "/static/test/file.dad0999e4f8f.txt", asvar=True)
self.assertStaticRenders("cached/styles.css", "/static/cached/styles.5e0040571e1a.css")
self.assertStaticRenders("path/", "/static/path/")
self.assertStaticRenders("path/?query", "/static/path/?query")
self.assertPostCondition()
def test_template_tag_simple_content(self):
relpath = self.hashed_file_path("cached/styles.css")
self.assertEqual(relpath, "cached/styles.5e0040571e1a.css")
with storage.staticfiles_storage.open(relpath) as relfile:
content = relfile.read()
self.assertNotIn(b"cached/other.css", content)
self.assertIn(b"other.d41d8cd98f00.css", content)
self.assertPostCondition()
def test_path_ignored_completely(self):
relpath = self.hashed_file_path("cached/css/ignored.css")
self.assertEqual(relpath, "cached/css/ignored.554da52152af.css")
with storage.staticfiles_storage.open(relpath) as relfile:
content = relfile.read()
self.assertIn(b'#foobar', content)
self.assertIn(b'http:foobar', content)
self.assertIn(b'https:foobar', content)
self.assertIn(b'data:foobar', content)
self.assertIn(b'chrome:foobar', content)
self.assertIn(b'//foobar', content)
self.assertPostCondition()
def test_path_with_querystring(self):
relpath = self.hashed_file_path("cached/styles.css?spam=eggs")
self.assertEqual(relpath, "cached/styles.5e0040571e1a.css?spam=eggs")
with storage.staticfiles_storage.open("cached/styles.5e0040571e1a.css") as relfile:
content = relfile.read()
self.assertNotIn(b"cached/other.css", content)
self.assertIn(b"other.d41d8cd98f00.css", content)
self.assertPostCondition()
def test_path_with_fragment(self):
relpath = self.hashed_file_path("cached/styles.css#eggs")
self.assertEqual(relpath, "cached/styles.5e0040571e1a.css#eggs")
with storage.staticfiles_storage.open("cached/styles.5e0040571e1a.css") as relfile:
content = relfile.read()
self.assertNotIn(b"cached/other.css", content)
self.assertIn(b"other.d41d8cd98f00.css", content)
self.assertPostCondition()
def test_path_with_querystring_and_fragment(self):
relpath = self.hashed_file_path("cached/css/fragments.css")
self.assertEqual(relpath, "cached/css/fragments.c4e6753b52d3.css")
with storage.staticfiles_storage.open(relpath) as relfile:
content = relfile.read()
self.assertIn(b'fonts/font.a4b0478549d0.eot?#iefix', content)
self.assertIn(b'fonts/font.b8d603e42714.svg#webfontIyfZbseF', content)
self.assertIn(b'fonts/font.b8d603e42714.svg#path/to/../../fonts/font.svg', content)
self.assertIn(b'data:font/woff;charset=utf-8;base64,d09GRgABAAAAADJoAA0AAAAAR2QAAQAAAAAAAAAAAAA', content)
self.assertIn(b'#default#VML', content)
self.assertPostCondition()
def test_template_tag_absolute(self):
relpath = self.hashed_file_path("cached/absolute.css")
self.assertEqual(relpath, "cached/absolute.eb04def9f9a4.css")
with storage.staticfiles_storage.open(relpath) as relfile:
content = relfile.read()
self.assertNotIn(b"/static/cached/styles.css", content)
self.assertIn(b"/static/cached/styles.5e0040571e1a.css", content)
self.assertNotIn(b"/static/styles_root.css", content)
self.assertIn(b"/static/styles_root.401f2509a628.css", content)
self.assertIn(b'/static/cached/img/relative.acae32e4532b.png', content)
self.assertPostCondition()
def test_template_tag_absolute_root(self):
"""
Like test_template_tag_absolute, but for a file in STATIC_ROOT (#26249).
"""
relpath = self.hashed_file_path("absolute_root.css")
self.assertEqual(relpath, "absolute_root.f821df1b64f7.css")
with storage.staticfiles_storage.open(relpath) as relfile:
content = relfile.read()
self.assertNotIn(b"/static/styles_root.css", content)
self.assertIn(b"/static/styles_root.401f2509a628.css", content)
self.assertPostCondition()
def test_template_tag_relative(self):
relpath = self.hashed_file_path("cached/relative.css")
self.assertEqual(relpath, "cached/relative.c3e9e1ea6f2e.css")
with storage.staticfiles_storage.open(relpath) as relfile:
content = relfile.read()
self.assertNotIn(b"../cached/styles.css", content)
self.assertNotIn(b'@import "styles.css"', content)
self.assertNotIn(b'url(img/relative.png)', content)
self.assertIn(b'url("img/relative.acae32e4532b.png")', content)
self.assertIn(b"../cached/styles.5e0040571e1a.css", content)
self.assertPostCondition()
def test_import_replacement(self):
"See #18050"
relpath = self.hashed_file_path("cached/import.css")
self.assertEqual(relpath, "cached/import.f53576679e5a.css")
with storage.staticfiles_storage.open(relpath) as relfile:
self.assertIn(b"""import url("styles.5e0040571e1a.css")""", relfile.read())
self.assertPostCondition()
def test_template_tag_deep_relative(self):
relpath = self.hashed_file_path("cached/css/window.css")
self.assertEqual(relpath, "cached/css/window.5d5c10836967.css")
with storage.staticfiles_storage.open(relpath) as relfile:
content = relfile.read()
self.assertNotIn(b'url(img/window.png)', content)
self.assertIn(b'url("img/window.acae32e4532b.png")', content)
self.assertPostCondition()
def test_template_tag_url(self):
relpath = self.hashed_file_path("cached/url.css")
self.assertEqual(relpath, "cached/url.902310b73412.css")
with storage.staticfiles_storage.open(relpath) as relfile:
self.assertIn(b"https://", relfile.read())
self.assertPostCondition()
@override_settings(
STATICFILES_DIRS=[os.path.join(TEST_ROOT, 'project', 'loop')],
STATICFILES_FINDERS=['django.contrib.staticfiles.finders.FileSystemFinder'],
)
def test_import_loop(self):
finders.get_finder.cache_clear()
err = StringIO()
with self.assertRaisesMessage(RuntimeError, 'Max post-process passes exceeded'):
call_command('collectstatic', interactive=False, verbosity=0, stderr=err)
self.assertEqual("Post-processing 'All' failed!\n\n", err.getvalue())
self.assertPostCondition()
def test_post_processing(self):
"""
post_processing behaves correctly.
Files that are alterable should always be post-processed; files that
aren't should be skipped.
collectstatic has already been called once in setUp() for this testcase,
therefore we check by verifying behavior on a second run.
"""
collectstatic_args = {
'interactive': False,
'verbosity': 0,
'link': False,
'clear': False,
'dry_run': False,
'post_process': True,
'use_default_ignore_patterns': True,
'ignore_patterns': ['*.ignoreme'],
}
collectstatic_cmd = CollectstaticCommand()
collectstatic_cmd.set_options(**collectstatic_args)
stats = collectstatic_cmd.collect()
self.assertIn(os.path.join('cached', 'css', 'window.css'), stats['post_processed'])
self.assertIn(os.path.join('cached', 'css', 'img', 'window.png'), stats['unmodified'])
self.assertIn(os.path.join('test', 'nonascii.css'), stats['post_processed'])
self.assertPostCondition()
def test_css_import_case_insensitive(self):
relpath = self.hashed_file_path("cached/styles_insensitive.css")
self.assertEqual(relpath, "cached/styles_insensitive.3fa427592a53.css")
with storage.staticfiles_storage.open(relpath) as relfile:
content = relfile.read()
self.assertNotIn(b"cached/other.css", content)
self.assertIn(b"other.d41d8cd98f00.css", content)
self.assertPostCondition()
@override_settings(
STATICFILES_DIRS=[os.path.join(TEST_ROOT, 'project', 'faulty')],
STATICFILES_FINDERS=['django.contrib.staticfiles.finders.FileSystemFinder'],
)
def test_post_processing_failure(self):
"""
post_processing indicates the origin of the error when it fails.
"""
finders.get_finder.cache_clear()
err = StringIO()
with self.assertRaises(Exception):
call_command('collectstatic', interactive=False, verbosity=0, stderr=err)
self.assertEqual("Post-processing 'faulty.css' failed!\n\n", err.getvalue())
self.assertPostCondition()
@override_settings(
STATICFILES_STORAGE='django.contrib.staticfiles.storage.CachedStaticFilesStorage',
)
class TestCollectionCachedStorage(TestHashedFiles, CollectionTestCase):
"""
Tests for the Cache busting storage
"""
def test_cache_invalidation(self):
name = "cached/styles.css"
hashed_name = "cached/styles.5e0040571e1a.css"
# check if the cache is filled correctly as expected
cache_key = storage.staticfiles_storage.hash_key(name)
cached_name = storage.staticfiles_storage.hashed_files.get(cache_key)
self.assertEqual(self.hashed_file_path(name), cached_name)
# clearing the cache to make sure we re-set it correctly in the url method
storage.staticfiles_storage.hashed_files.clear()
cached_name = storage.staticfiles_storage.hashed_files.get(cache_key)
self.assertIsNone(cached_name)
self.assertEqual(self.hashed_file_path(name), hashed_name)
cached_name = storage.staticfiles_storage.hashed_files.get(cache_key)
self.assertEqual(cached_name, hashed_name)
# Check files that had to be hashed multiple times since their content
# includes other files that were hashed.
name = 'cached/relative.css'
hashed_name = 'cached/relative.c3e9e1ea6f2e.css'
cache_key = storage.staticfiles_storage.hash_key(name)
cached_name = storage.staticfiles_storage.hashed_files.get(cache_key)
self.assertIsNone(cached_name)
self.assertEqual(self.hashed_file_path(name), hashed_name)
cached_name = storage.staticfiles_storage.hashed_files.get(cache_key)
self.assertEqual(cached_name, hashed_name)
def test_cache_key_memcache_validation(self):
"""
Handle cache key creation correctly, see #17861.
"""
name = (
"/some crazy/long filename/ with spaces Here and ?#%#$/other/stuff"
"/some crazy/long filename/ with spaces Here and ?#%#$/other/stuff"
"/some crazy/long filename/ with spaces Here and ?#%#$/other/stuff"
"/some crazy/long filename/ with spaces Here and ?#%#$/other/stuff"
"/some crazy/long filename/ with spaces Here and ?#%#$/other/stuff"
"/some crazy/\x16\xb4"
)
cache_key = storage.staticfiles_storage.hash_key(name)
cache_validator = BaseCache({})
cache_validator.validate_key(cache_key)
self.assertEqual(cache_key, 'staticfiles:821ea71ef36f95b3922a77f7364670e7')
def test_corrupt_intermediate_files(self):
configured_storage = storage.staticfiles_storage
# Clear cache to force rehashing of the files
configured_storage.hashed_files.clear()
# Simulate a corrupt chain of intermediate files by ensuring they don't
# resolve before the max post-process count, which would normally be
# high enough.
configured_storage.max_post_process_passes = 1
# File without intermediates that can be rehashed without a problem.
self.hashed_file_path('cached/css/img/window.png')
# File with too many intermediates to rehash with the low max
# post-process passes.
err_msg = "The name 'cached/styles.css' could not be hashed with %r." % (configured_storage._wrapped,)
with self.assertRaisesMessage(ValueError, err_msg):
self.hashed_file_path('cached/styles.css')
@override_settings(
STATICFILES_STORAGE='staticfiles_tests.storage.ExtraPatternsCachedStaticFilesStorage',
)
class TestExtraPatternsCachedStorage(CollectionTestCase):
def setUp(self):
storage.staticfiles_storage.hashed_files.clear() # avoid cache interference
super().setUp()
def cached_file_path(self, path):
fullpath = self.render_template(self.static_template_snippet(path))
return fullpath.replace(settings.STATIC_URL, '')
def test_multi_extension_patterns(self):
"""
With storage classes having several file extension patterns, only the
files matching a specific file pattern should be affected by the
substitution (#19670).
"""
# CSS files shouldn't be touched by JS patterns.
relpath = self.cached_file_path("cached/import.css")
self.assertEqual(relpath, "cached/import.f53576679e5a.css")
with storage.staticfiles_storage.open(relpath) as relfile:
self.assertIn(b'import url("styles.5e0040571e1a.css")', relfile.read())
# Confirm JS patterns have been applied to JS files.
relpath = self.cached_file_path("cached/test.js")
self.assertEqual(relpath, "cached/test.388d7a790d46.js")
with storage.staticfiles_storage.open(relpath) as relfile:
self.assertIn(b'JS_URL("import.f53576679e5a.css")', relfile.read())
@override_settings(
STATICFILES_STORAGE='django.contrib.staticfiles.storage.ManifestStaticFilesStorage',
)
class TestCollectionManifestStorage(TestHashedFiles, CollectionTestCase):
"""
Tests for the Cache busting storage
"""
def setUp(self):
super().setUp()
temp_dir = tempfile.mkdtemp()
os.makedirs(os.path.join(temp_dir, 'test'))
self._clear_filename = os.path.join(temp_dir, 'test', 'cleared.txt')
with open(self._clear_filename, 'w') as f:
f.write('to be deleted in one test')
self.patched_settings = self.settings(
STATICFILES_DIRS=settings.STATICFILES_DIRS + [temp_dir])
self.patched_settings.enable()
self.addCleanup(shutil.rmtree, temp_dir)
self._manifest_strict = storage.staticfiles_storage.manifest_strict
def tearDown(self):
self.patched_settings.disable()
if os.path.exists(self._clear_filename):
os.unlink(self._clear_filename)
storage.staticfiles_storage.manifest_strict = self._manifest_strict
super().tearDown()
def assertPostCondition(self):
hashed_files = storage.staticfiles_storage.hashed_files
# The in-memory version of the manifest matches the one on disk
# since a properly created manifest should cover all filenames.
if hashed_files:
manifest = storage.staticfiles_storage.load_manifest()
self.assertEqual(hashed_files, manifest)
def test_manifest_exists(self):
filename = storage.staticfiles_storage.manifest_name
path = storage.staticfiles_storage.path(filename)
self.assertTrue(os.path.exists(path))
def test_loaded_cache(self):
self.assertNotEqual(storage.staticfiles_storage.hashed_files, {})
manifest_content = storage.staticfiles_storage.read_manifest()
self.assertIn(
'"version": "%s"' % storage.staticfiles_storage.manifest_version,
manifest_content
)
def test_parse_cache(self):
hashed_files = storage.staticfiles_storage.hashed_files
manifest = storage.staticfiles_storage.load_manifest()
self.assertEqual(hashed_files, manifest)
def test_clear_empties_manifest(self):
cleared_file_name = storage.staticfiles_storage.clean_name(os.path.join('test', 'cleared.txt'))
# collect the additional file
self.run_collectstatic()
hashed_files = storage.staticfiles_storage.hashed_files
self.assertIn(cleared_file_name, hashed_files)
manifest_content = storage.staticfiles_storage.load_manifest()
self.assertIn(cleared_file_name, manifest_content)
original_path = storage.staticfiles_storage.path(cleared_file_name)
self.assertTrue(os.path.exists(original_path))
# delete the original file form the app, collect with clear
os.unlink(self._clear_filename)
self.run_collectstatic(clear=True)
self.assertFileNotFound(original_path)
hashed_files = storage.staticfiles_storage.hashed_files
self.assertNotIn(cleared_file_name, hashed_files)
manifest_content = storage.staticfiles_storage.load_manifest()
self.assertNotIn(cleared_file_name, manifest_content)
def test_missing_entry(self):
missing_file_name = 'cached/missing.css'
configured_storage = storage.staticfiles_storage
self.assertNotIn(missing_file_name, configured_storage.hashed_files)
# File name not found in manifest
with self.assertRaisesMessage(ValueError, "Missing staticfiles manifest entry for '%s'" % missing_file_name):
self.hashed_file_path(missing_file_name)
configured_storage.manifest_strict = False
# File doesn't exist on disk
err_msg = "The file '%s' could not be found with %r." % (missing_file_name, configured_storage._wrapped)
with self.assertRaisesMessage(ValueError, err_msg):
self.hashed_file_path(missing_file_name)
content = StringIO()
content.write('Found')
configured_storage.save(missing_file_name, content)
# File exists on disk
self.hashed_file_path(missing_file_name)
@override_settings(
STATICFILES_STORAGE='staticfiles_tests.storage.SimpleCachedStaticFilesStorage',
)
class TestCollectionSimpleCachedStorage(CollectionTestCase):
"""
Tests for the Cache busting storage
"""
hashed_file_path = hashed_file_path
def setUp(self):
storage.staticfiles_storage.hashed_files.clear() # avoid cache interference
super().setUp()
def test_template_tag_return(self):
"""
Test the CachedStaticFilesStorage backend.
"""
self.assertStaticRaises(ValueError, "does/not/exist.png", "/static/does/not/exist.png")
self.assertStaticRenders("test/file.txt", "/static/test/file.deploy12345.txt")
self.assertStaticRenders("cached/styles.css", "/static/cached/styles.deploy12345.css")
self.assertStaticRenders("path/", "/static/path/")
self.assertStaticRenders("path/?query", "/static/path/?query")
def test_template_tag_simple_content(self):
relpath = self.hashed_file_path("cached/styles.css")
self.assertEqual(relpath, "cached/styles.deploy12345.css")
with storage.staticfiles_storage.open(relpath) as relfile:
content = relfile.read()
self.assertNotIn(b"cached/other.css", content)
self.assertIn(b"other.deploy12345.css", content)
class CustomStaticFilesStorage(storage.StaticFilesStorage):
"""
Used in TestStaticFilePermissions
"""
def __init__(self, *args, **kwargs):
kwargs['file_permissions_mode'] = 0o640
kwargs['directory_permissions_mode'] = 0o740
super().__init__(*args, **kwargs)
@unittest.skipIf(sys.platform.startswith('win'), "Windows only partially supports chmod.")
class TestStaticFilePermissions(CollectionTestCase):
command_params = {
'interactive': False,
'verbosity': 0,
'ignore_patterns': ['*.ignoreme'],
}
def setUp(self):
self.umask = 0o027
self.old_umask = os.umask(self.umask)
super().setUp()
def tearDown(self):
os.umask(self.old_umask)
super().tearDown()
# Don't run collectstatic command in this test class.
def run_collectstatic(self, **kwargs):
pass
@override_settings(
FILE_UPLOAD_PERMISSIONS=0o655,
FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765,
)
def test_collect_static_files_permissions(self):
call_command('collectstatic', **self.command_params)
test_file = os.path.join(settings.STATIC_ROOT, "test.txt")
test_dir = os.path.join(settings.STATIC_ROOT, "subdir")
file_mode = os.stat(test_file)[0] & 0o777
dir_mode = os.stat(test_dir)[0] & 0o777
self.assertEqual(file_mode, 0o655)
self.assertEqual(dir_mode, 0o765)
@override_settings(
FILE_UPLOAD_PERMISSIONS=None,
FILE_UPLOAD_DIRECTORY_PERMISSIONS=None,
)
def test_collect_static_files_default_permissions(self):
call_command('collectstatic', **self.command_params)
test_file = os.path.join(settings.STATIC_ROOT, "test.txt")
test_dir = os.path.join(settings.STATIC_ROOT, "subdir")
file_mode = os.stat(test_file)[0] & 0o777
dir_mode = os.stat(test_dir)[0] & 0o777
self.assertEqual(file_mode, 0o666 & ~self.umask)
self.assertEqual(dir_mode, 0o777 & ~self.umask)
@override_settings(
FILE_UPLOAD_PERMISSIONS=0o655,
FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765,
STATICFILES_STORAGE='staticfiles_tests.test_storage.CustomStaticFilesStorage',
)
def test_collect_static_files_subclass_of_static_storage(self):
call_command('collectstatic', **self.command_params)
test_file = os.path.join(settings.STATIC_ROOT, "test.txt")
test_dir = os.path.join(settings.STATIC_ROOT, "subdir")
file_mode = os.stat(test_file)[0] & 0o777
dir_mode = os.stat(test_dir)[0] & 0o777
self.assertEqual(file_mode, 0o640)
self.assertEqual(dir_mode, 0o740)
@override_settings(
STATICFILES_STORAGE='django.contrib.staticfiles.storage.CachedStaticFilesStorage',
)
class TestCollectionHashedFilesCache(CollectionTestCase):
"""
Files referenced from CSS use the correct final hashed name regardless of
the order in which the files are post-processed.
"""
hashed_file_path = hashed_file_path
def setUp(self):
super().setUp()
self._temp_dir = temp_dir = tempfile.mkdtemp()
os.makedirs(os.path.join(temp_dir, 'test'))
self.addCleanup(shutil.rmtree, temp_dir)
def _get_filename_path(self, filename):
return os.path.join(self._temp_dir, 'test', filename)
def test_file_change_after_collectstatic(self):
# Create initial static files.
file_contents = (
('foo.png', 'foo'),
('bar.css', 'url("foo.png")\nurl("xyz.png")'),
('xyz.png', 'xyz'),
)
for filename, content in file_contents:
with open(self._get_filename_path(filename), 'w') as f:
f.write(content)
with self.modify_settings(STATICFILES_DIRS={'append': self._temp_dir}):
finders.get_finder.cache_clear()
err = StringIO()
# First collectstatic run.
call_command('collectstatic', interactive=False, verbosity=0, stderr=err)
relpath = self.hashed_file_path('test/bar.css')
with storage.staticfiles_storage.open(relpath) as relfile:
content = relfile.read()
self.assertIn(b'foo.acbd18db4cc2.png', content)
self.assertIn(b'xyz.d16fb36f0911.png', content)
# Change the contents of the png files.
for filename in ('foo.png', 'xyz.png'):
with open(self._get_filename_path(filename), 'w+b') as f:
f.write(b"new content of file to change its hash")
# The hashes of the png files in the CSS file are updated after
# a second collectstatic.
call_command('collectstatic', interactive=False, verbosity=0, stderr=err)
relpath = self.hashed_file_path('test/bar.css')
with storage.staticfiles_storage.open(relpath) as relfile:
content = relfile.read()
self.assertIn(b'foo.57a5cb9ba68d.png', content)
self.assertIn(b'xyz.57a5cb9ba68d.png', content)
|
bsd-3-clause
|
daevaorn/sentry
|
src/sentry/migrations/0034_auto__add_groupbookmark__add_unique_groupbookmark_project_user_group.py
|
36
|
14391
|
# 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):
# Adding model 'GroupBookmark'
db.create_table('sentry_groupbookmark', (
('id', self.gf('sentry.db.models.fields.bounded.BoundedBigAutoField')(primary_key=True)),
('project', self.gf('sentry.db.models.fields.FlexibleForeignKey')(to=orm['sentry.Project'])),
('group', self.gf('sentry.db.models.fields.FlexibleForeignKey')(to=orm['sentry.Group'])),
('user', self.gf('sentry.db.models.fields.FlexibleForeignKey')(to=orm['sentry.User'])),
))
db.send_create_signal('sentry', ['GroupBookmark'])
# Adding unique constraint on 'GroupBookmark', fields ['project', 'user', 'group']
db.create_unique('sentry_groupbookmark', ['project_id', 'user_id', 'group_id'])
def backwards(self, orm):
# Removing unique constraint on 'GroupBookmark', fields ['project', 'user', 'group']
db.delete_unique('sentry_groupbookmark', ['project_id', 'user_id', 'group_id'])
# Deleting model 'GroupBookmark'
db.delete_table('sentry_groupbookmark')
models = {
'sentry.user': {
'Meta': {'object_name': 'User', 'db_table': "'auth_user'"},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': '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'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'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': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'sentry.event': {
'Meta': {'object_name': 'Event', 'db_table': "'sentry_message'"},
'checksum': ('django.db.models.fields.CharField', [], {'max_length': '32', 'db_index': 'True'}),
'culprit': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'db_column': "'view'", 'blank': 'True'}),
'data': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'datetime': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'event_id': ('django.db.models.fields.CharField', [], {'max_length': '32', 'unique': 'True', 'null': 'True', 'db_column': "'message_id'"}),
'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'blank': 'True', 'related_name': "'event_set'", 'null': 'True', 'to': "orm['sentry.Group']"}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'level': ('django.db.models.fields.PositiveIntegerField', [], {'default': '40', 'db_index': 'True', 'blank': 'True'}),
'logger': ('django.db.models.fields.CharField', [], {'default': "'root'", 'max_length': '64', 'db_index': 'True', 'blank': 'True'}),
'message': ('django.db.models.fields.TextField', [], {}),
'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}),
'server_name': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'db_index': 'True'}),
'site': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'db_index': 'True'}),
'time_spent': ('django.db.models.fields.FloatField', [], {'null': 'True'})
},
'sentry.filtervalue': {
'Meta': {'unique_together': "(('project', 'key', 'value'),)", 'object_name': 'FilterValue'},
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}),
'value': ('django.db.models.fields.CharField', [], {'max_length': '200'})
},
'sentry.group': {
'Meta': {'unique_together': "(('project', 'logger', 'culprit', 'checksum'),)", 'object_name': 'Group', 'db_table': "'sentry_groupedmessage'"},
'checksum': ('django.db.models.fields.CharField', [], {'max_length': '32', 'db_index': 'True'}),
'culprit': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'db_column': "'view'", 'blank': 'True'}),
'data': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'first_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'level': ('django.db.models.fields.PositiveIntegerField', [], {'default': '40', 'db_index': 'True', 'blank': 'True'}),
'logger': ('django.db.models.fields.CharField', [], {'default': "'root'", 'max_length': '64', 'db_index': 'True', 'blank': 'True'}),
'message': ('django.db.models.fields.TextField', [], {}),
'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}),
'score': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'status': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0', 'db_index': 'True'}),
'time_spent_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'time_spent_total': ('django.db.models.fields.FloatField', [], {'default': '0'}),
'times_seen': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1', 'db_index': 'True'}),
'views': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['sentry.View']", 'symmetrical': 'False', 'blank': 'True'})
},
'sentry.groupbookmark': {
'Meta': {'unique_together': "(('project', 'user', 'group'),)", 'object_name': 'GroupBookmark'},
'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}),
'user': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.User']"})
},
'sentry.groupmeta': {
'Meta': {'unique_together': "(('group', 'key', 'value'),)", 'object_name': 'GroupMeta'},
'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
'value': ('django.db.models.fields.TextField', [], {})
},
'sentry.messagecountbyminute': {
'Meta': {'unique_together': "(('project', 'group', 'date'),)", 'object_name': 'MessageCountByMinute'},
'date': ('django.db.models.fields.DateTimeField', [], {}),
'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}),
'time_spent_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'time_spent_total': ('django.db.models.fields.FloatField', [], {'default': '0'}),
'times_seen': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'})
},
'sentry.messagefiltervalue': {
'Meta': {'unique_together': "(('project', 'key', 'value', 'group'),)", 'object_name': 'MessageFilterValue'},
'group': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Group']"}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}),
'times_seen': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'value': ('django.db.models.fields.CharField', [], {'max_length': '200'})
},
'sentry.messageindex': {
'Meta': {'unique_together': "(('column', 'value', 'object_id'),)", 'object_name': 'MessageIndex'},
'column': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
'value': ('django.db.models.fields.CharField', [], {'max_length': '128'})
},
'sentry.option': {
'Meta': {'unique_together': "(('key', 'value'),)", 'object_name': 'Option'},
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
'value': ('django.db.models.fields.CharField', [], {'max_length': '200'})
},
'sentry.project': {
'Meta': {'object_name': 'Project'},
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'owner': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'owned_project_set'", 'null': 'True', 'to': "orm['sentry.User']"}),
'public': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'status': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0', 'db_index': 'True'})
},
'sentry.projectdomain': {
'Meta': {'unique_together': "(('project', 'domain'),)", 'object_name': 'ProjectDomain'},
'domain': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'domain_set'", 'to': "orm['sentry.Project']"})
},
'sentry.projectmember': {
'Meta': {'unique_together': "(('project', 'user'),)", 'object_name': 'ProjectMember'},
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'member_set'", 'to': "orm['sentry.Project']"}),
'public_key': ('django.db.models.fields.CharField', [], {'max_length': '32', 'unique': 'True', 'null': 'True'}),
'secret_key': ('django.db.models.fields.CharField', [], {'max_length': '32', 'unique': 'True', 'null': 'True'}),
'type': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'user': ('sentry.db.models.fields.FlexibleForeignKey', [], {'related_name': "'project_set'", 'to': "orm['sentry.User']"})
},
'sentry.projectoption': {
'Meta': {'unique_together': "(('project', 'key', 'value'),)", 'object_name': 'ProjectOption', 'db_table': "'sentry_projectoptions'"},
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
'project': ('sentry.db.models.fields.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}),
'value': ('django.db.models.fields.CharField', [], {'max_length': '200'})
},
'sentry.view': {
'Meta': {'object_name': 'View'},
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'path': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}),
'verbose_name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True'}),
'verbose_name_plural': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True'})
}
}
complete_apps = ['sentry']
|
bsd-3-clause
|
isotoma/django-cms
|
cms/migrations/0016_author_copy.py
|
525
|
20033
|
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
try:
from django.contrib.auth import get_user_model
except ImportError: # django < 1.5
from django.contrib.auth.models import User
else:
User = get_user_model()
user_orm_label = '%s.%s' % (User._meta.app_label, User._meta.object_name)
user_model_label = '%s.%s' % (User._meta.app_label, User._meta.module_name)
user_ptr_name = '%s_ptr' % User._meta.object_name.lower()
class Migration(SchemaMigration):
def forwards(self, orm):
# Dummy migration
pass
def backwards(self, orm):
# Dummy migration
pass
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'})
},
user_model_label: {
'Meta': {'object_name': User.__name__, 'db_table': "'%s'" % User._meta.db_table},
'date_joined': ('django.db.models.fields.DateTimeField', [],
{'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [],
{'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [],
{'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [],
{'to': "orm['auth.Group']", 'symmetrical': 'False',
'blank': 'True'}),
'id': (
'django.db.models.fields.AutoField', [], {'primary_key': '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'}),
'password': (
'django.db.models.fields.CharField', [], {'max_length': '128'}),
'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'})
},
'cms.cmsplugin': {
'Meta': {'object_name': 'CMSPlugin'},
'changed_date': ('django.db.models.fields.DateTimeField', [],
{'auto_now': 'True', 'blank': 'True'}),
'creation_date': ('django.db.models.fields.DateTimeField', [],
{'default': 'datetime.datetime.now'}),
'id': (
'django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'language': ('django.db.models.fields.CharField', [],
{'max_length': '15', 'db_index': 'True'}),
'level': ('django.db.models.fields.PositiveIntegerField', [],
{'db_index': 'True'}),
'lft': ('django.db.models.fields.PositiveIntegerField', [],
{'db_index': 'True'}),
'parent': ('django.db.models.fields.related.ForeignKey', [],
{'to': "orm['cms.CMSPlugin']", 'null': 'True',
'blank': 'True'}),
'placeholder': ('django.db.models.fields.related.ForeignKey', [],
{'to': "orm['cms.Placeholder']", 'null': 'True'}),
'plugin_type': ('django.db.models.fields.CharField', [],
{'max_length': '50', 'db_index': 'True'}),
'position': ('django.db.models.fields.PositiveSmallIntegerField', [],
{'null': 'True', 'blank': 'True'}),
'rght': ('django.db.models.fields.PositiveIntegerField', [],
{'db_index': 'True'}),
'tree_id': ('django.db.models.fields.PositiveIntegerField', [],
{'db_index': 'True'})
},
'cms.globalpagepermission': {
'Meta': {'object_name': 'GlobalPagePermission'},
'can_add': (
'django.db.models.fields.BooleanField', [], {'default': 'True'}),
'can_change': (
'django.db.models.fields.BooleanField', [], {'default': 'True'}),
'can_change_advanced_settings': (
'django.db.models.fields.BooleanField', [], {'default': 'False'}),
'can_change_permissions': (
'django.db.models.fields.BooleanField', [], {'default': 'False'}),
'can_delete': (
'django.db.models.fields.BooleanField', [], {'default': 'True'}),
'can_moderate': (
'django.db.models.fields.BooleanField', [], {'default': 'True'}),
'can_move_page': (
'django.db.models.fields.BooleanField', [], {'default': 'True'}),
'can_publish': (
'django.db.models.fields.BooleanField', [], {'default': 'True'}),
'can_recover_page': (
'django.db.models.fields.BooleanField', [], {'default': 'True'}),
'can_view': (
'django.db.models.fields.BooleanField', [], {'default': 'False'}),
'group': ('django.db.models.fields.related.ForeignKey', [],
{'to': "orm['auth.Group']", 'null': 'True', 'blank': 'True'}),
'id': (
'django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'sites': ('django.db.models.fields.related.ManyToManyField', [],
{'symmetrical': 'False', 'to': "orm['sites.Site']",
'null': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [],
{'to': "orm['%s']" % user_orm_label, 'null': 'True', 'blank': 'True'})
},
'cms.page': {
'Meta': {'ordering': "('site', 'tree_id', 'lft')",
'object_name': 'Page'},
'changed_by': (
'django.db.models.fields.CharField', [], {'max_length': '70'}),
'changed_date': ('django.db.models.fields.DateTimeField', [],
{'auto_now': 'True', 'blank': 'True'}),
'created_by': (
'django.db.models.fields.CharField', [], {'max_length': '70'}),
'creation_date': ('django.db.models.fields.DateTimeField', [],
{'auto_now_add': 'True', 'blank': 'True'}),
'id': (
'django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'in_navigation': ('django.db.models.fields.BooleanField', [],
{'default': 'True', 'db_index': 'True'}),
'level': ('django.db.models.fields.PositiveIntegerField', [],
{'db_index': 'True'}),
'lft': ('django.db.models.fields.PositiveIntegerField', [],
{'db_index': 'True'}),
'limit_visibility_in_menu': (
'django.db.models.fields.SmallIntegerField', [],
{'default': 'None', 'null': 'True', 'db_index': 'True',
'blank': 'True'}),
'login_required': (
'django.db.models.fields.BooleanField', [], {'default': 'False'}),
'moderator_state': ('django.db.models.fields.SmallIntegerField', [],
{'default': '1', 'blank': 'True'}),
'navigation_extenders': ('django.db.models.fields.CharField', [],
{'db_index': 'True', 'max_length': '80',
'null': 'True', 'blank': 'True'}),
'parent': ('django.db.models.fields.related.ForeignKey', [],
{'blank': 'True', 'related_name': "'children'",
'null': 'True', 'to': "orm['cms.Page']"}),
'placeholders': ('django.db.models.fields.related.ManyToManyField', [],
{'to': "orm['cms.Placeholder']",
'symmetrical': 'False'}),
'publication_date': ('django.db.models.fields.DateTimeField', [],
{'db_index': 'True', 'null': 'True',
'blank': 'True'}),
'publication_end_date': ('django.db.models.fields.DateTimeField', [],
{'db_index': 'True', 'null': 'True',
'blank': 'True'}),
'published': (
'django.db.models.fields.BooleanField', [], {'default': 'False'}),
'publisher_is_draft': ('django.db.models.fields.BooleanField', [],
{'default': 'True', 'db_index': 'True'}),
'publisher_public': (
'django.db.models.fields.related.OneToOneField', [],
{'related_name': "'publisher_draft'", 'unique': 'True', 'null': 'True',
'to': "orm['cms.Page']"}),
'publisher_state': ('django.db.models.fields.SmallIntegerField', [],
{'default': '0', 'db_index': 'True'}),
'reverse_id': ('django.db.models.fields.CharField', [],
{'db_index': 'True', 'max_length': '40', 'null': 'True',
'blank': 'True'}),
'rght': ('django.db.models.fields.PositiveIntegerField', [],
{'db_index': 'True'}),
'site': ('django.db.models.fields.related.ForeignKey', [],
{'to': "orm['sites.Site']"}),
'soft_root': ('django.db.models.fields.BooleanField', [],
{'default': 'False', 'db_index': 'True'}),
'template': (
'django.db.models.fields.CharField', [], {'max_length': '100'}),
'tree_id': ('django.db.models.fields.PositiveIntegerField', [],
{'db_index': 'True'})
},
'cms.pagemoderator': {
'Meta': {'object_name': 'PageModerator'},
'id': (
'django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'moderate_children': (
'django.db.models.fields.BooleanField', [], {'default': 'False'}),
'moderate_descendants': (
'django.db.models.fields.BooleanField', [], {'default': 'False'}),
'moderate_page': (
'django.db.models.fields.BooleanField', [], {'default': 'False'}),
'page': ('django.db.models.fields.related.ForeignKey', [],
{'to': "orm['cms.Page']"}),
'user': ('django.db.models.fields.related.ForeignKey', [],
{'to': "orm['%s']" % user_orm_label})
},
'cms.pagemoderatorstate': {
'Meta': {'ordering': "('page', 'action', '-created')",
'object_name': 'PageModeratorState'},
'action': ('django.db.models.fields.CharField', [],
{'max_length': '3', 'null': 'True', 'blank': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [],
{'auto_now_add': 'True', 'blank': 'True'}),
'id': (
'django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'message': ('django.db.models.fields.TextField', [],
{'default': "''", 'max_length': '1000', 'blank': 'True'}),
'page': ('django.db.models.fields.related.ForeignKey', [],
{'to': "orm['cms.Page']"}),
'user': ('django.db.models.fields.related.ForeignKey', [],
{'to': "orm['%s']" % user_orm_label, 'null': 'True'})
},
'cms.pagepermission': {
'Meta': {'object_name': 'PagePermission'},
'can_add': (
'django.db.models.fields.BooleanField', [], {'default': 'True'}),
'can_change': (
'django.db.models.fields.BooleanField', [], {'default': 'True'}),
'can_change_advanced_settings': (
'django.db.models.fields.BooleanField', [], {'default': 'False'}),
'can_change_permissions': (
'django.db.models.fields.BooleanField', [], {'default': 'False'}),
'can_delete': (
'django.db.models.fields.BooleanField', [], {'default': 'True'}),
'can_moderate': (
'django.db.models.fields.BooleanField', [], {'default': 'True'}),
'can_move_page': (
'django.db.models.fields.BooleanField', [], {'default': 'True'}),
'can_publish': (
'django.db.models.fields.BooleanField', [], {'default': 'True'}),
'can_view': (
'django.db.models.fields.BooleanField', [], {'default': 'False'}),
'grant_on': (
'django.db.models.fields.IntegerField', [], {'default': '5'}),
'group': ('django.db.models.fields.related.ForeignKey', [],
{'to': "orm['auth.Group']", 'null': 'True', 'blank': 'True'}),
'id': (
'django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'page': ('django.db.models.fields.related.ForeignKey', [],
{'to': "orm['cms.Page']", 'null': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [],
{'to': "orm['%s']" % user_orm_label, 'null': 'True', 'blank': 'True'})
},
'cms.pageuser': {
'Meta': {'object_name': 'PageUser', '_ormbases': [user_orm_label]},
'created_by': ('django.db.models.fields.related.ForeignKey', [],
{'related_name': "'created_users'",
'to': "orm['%s']" % user_orm_label}),
'user_ptr': ('django.db.models.fields.related.OneToOneField', [],
{'to': "orm['%s']" % user_orm_label, 'unique': 'True',
'primary_key': 'True'})
},
'cms.pageusergroup': {
'Meta': {'object_name': 'PageUserGroup', '_ormbases': ['auth.Group']},
'created_by': ('django.db.models.fields.related.ForeignKey', [],
{'related_name': "'created_usergroups'",
'to': "orm['%s']" % user_orm_label}),
'group_ptr': ('django.db.models.fields.related.OneToOneField', [],
{'to': "orm['auth.Group']", 'unique': 'True',
'primary_key': 'True'})
},
'cms.placeholder': {
'Meta': {'object_name': 'Placeholder'},
'default_width': (
'django.db.models.fields.PositiveSmallIntegerField', [],
{'null': 'True'}),
'id': (
'django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'slot': ('django.db.models.fields.CharField', [],
{'max_length': '50', 'db_index': 'True'})
},
'cms.title': {
'Meta': {'unique_together': "(('language', 'page'),)",
'object_name': 'Title'},
'application_urls': ('django.db.models.fields.CharField', [],
{'db_index': 'True', 'max_length': '200',
'null': 'True', 'blank': 'True'}),
'creation_date': ('django.db.models.fields.DateTimeField', [],
{'default': 'datetime.datetime.now'}),
'has_url_overwrite': ('django.db.models.fields.BooleanField', [],
{'default': 'False', 'db_index': 'True'}),
'id': (
'django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'language': ('django.db.models.fields.CharField', [],
{'max_length': '15', 'db_index': 'True'}),
'menu_title': ('django.db.models.fields.CharField', [],
{'max_length': '255', 'null': 'True', 'blank': 'True'}),
'meta_description': ('django.db.models.fields.TextField', [],
{'max_length': '255', 'null': 'True',
'blank': 'True'}),
'meta_keywords': ('django.db.models.fields.CharField', [],
{'max_length': '255', 'null': 'True',
'blank': 'True'}),
'page': ('django.db.models.fields.related.ForeignKey', [],
{'related_name': "'title_set'", 'to': "orm['cms.Page']"}),
'page_title': ('django.db.models.fields.CharField', [],
{'max_length': '255', 'null': 'True', 'blank': 'True'}),
'path': ('django.db.models.fields.CharField', [],
{'max_length': '255', 'db_index': 'True'}),
'redirect': ('django.db.models.fields.CharField', [],
{'max_length': '255', 'null': 'True', 'blank': 'True'}),
'slug': (
'django.db.models.fields.SlugField', [], {'max_length': '255'}),
'title': (
'django.db.models.fields.CharField', [], {'max_length': '255'})
},
'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'})
},
'sites.site': {
'Meta': {'ordering': "('domain',)", 'object_name': 'Site',
'db_table': "'django_site'"},
'domain': (
'django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': (
'django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
}
}
complete_apps = ['cms']
|
bsd-3-clause
|
YangLiu928/NDP_Projects
|
Python_Projects/Python_MySQL/pipe_delimit_2014_FTD/pipe_delimition.py
|
1
|
1719
|
import codecs
from os.path import join,isfile,isdir
from os import mkdir
def get_intervals(layout):
results = []
layout = codecs.open(layout,'r')
count = 0
for line in layout:
count = count + 1
if count < 8:
continue
if line.strip()=='':
continue
# print line.split(' ')
numbers = ''
segments = line.split(' ')
for index in range (0,len(segments)):
numbers = segments[index]
if len(numbers)!=0:
break
left = int(numbers.split('\t')[0].split('-')[0]) - 1
right = int(numbers.split('\t')[0].split('-')[1])
results.append([left,right])
return results
def pipe_delimition(import_or_export):
if import_or_export.lower()!='import' and import_or_export.lower()!='export':
return
if import_or_export.lower() == 'export':
layout = 'EXP_DETL.lay'
input_file = 'EXP_DETL.TXT'
input_folder = 'MERCHEXH2014'
output_file = 'PIPE_DELIMITED_EXP_DETL.TXT'
else:
layout = 'IMP_DETL.lay'
input_file = 'IMP_DETL.TXT'
input_folder = 'MERCHIMH2014'
output_file = 'PIPE_DELIMITED_IMP_DETL.TXT'
input_path = join(input_folder,input_file)
output = codecs.open(output_file,'w','utf-8')
input = codecs.open(input_path,'r','utf-8')
intervals = get_intervals(layout)
print intervals
line_count = 0
for line in input:
line_count = line_count + 1
string = u''
for index in range (0,len(intervals)-1):
string = string + line[intervals[index][0]:intervals[index][1]].strip() + '|'
string = string + line[intervals[len(intervals)-1][0]:intervals[len(intervals)-1][1]].strip() + '\r'
output.write(string)
if line_count==1000:
break
output.close()
input.close()
if __name__ == '__main__':
pipe_delimition('import')
pipe_delimition('export')
|
mit
|
supergis/micropython
|
drivers/onewire/onewire.py
|
66
|
11789
|
"""
OneWire library ported to MicroPython by Jason Hildebrand.
TODO:
* implement and test parasite-power mode (as an init option)
* port the crc checks
The original upstream copyright and terms follow.
------------------------------------------------------------------------------
Copyright (c) 2007, Jim Studt (original old version - many contributors since)
OneWire has been maintained by Paul Stoffregen ([email protected]) since
January 2010.
26 Sept 2008 -- Robin James
Jim Studt's original library was modified by Josh Larios.
Tom Pollard, [email protected], contributed around May 20, 2008
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Much of the code was inspired by Derek Yerger's code, though I don't
think much of that remains. In any event that was..
(copyleft) 2006 by Derek Yerger - Free to distribute freely.
"""
import pyb
from pyb import disable_irq
from pyb import enable_irq
class OneWire:
def __init__(self, pin):
"""
Pass the data pin connected to your one-wire device(s), for example Pin('X1').
The one-wire protocol allows for multiple devices to be attached.
"""
self.data_pin = pin
self.write_delays = (1, 40, 40, 1)
self.read_delays = (1, 1, 40)
# cache a bunch of methods and attributes. This is necessary in _write_bit and
# _read_bit to achieve the timing required by the OneWire protocol.
self.cache = (pin.init, pin.value, pin.OUT_PP, pin.IN, pin.PULL_NONE)
pin.init(pin.IN, pin.PULL_UP)
def reset(self):
"""
Perform the onewire reset function.
Returns 1 if a device asserted a presence pulse, 0 otherwise.
If you receive 0, then check your wiring and make sure you are providing
power and ground to your devices.
"""
retries = 25
self.data_pin.init(self.data_pin.IN, self.data_pin.PULL_UP)
# We will wait up to 250uS for
# the bus to come high, if it doesn't then it is broken or shorted
# and we return a 0;
# wait until the wire is high... just in case
while True:
if self.data_pin.value():
break
retries -= 1
if retries == 0:
raise OSError("OneWire pin didn't go high")
pyb.udelay(10)
# pull the bus low for at least 480us
self.data_pin.low()
self.data_pin.init(self.data_pin.OUT_PP)
pyb.udelay(480)
# If there is a slave present, it should pull the bus low within 60us
i = pyb.disable_irq()
self.data_pin.init(self.data_pin.IN, self.data_pin.PULL_UP)
pyb.udelay(70)
presence = not self.data_pin.value()
pyb.enable_irq(i)
pyb.udelay(410)
return presence
def write_bit(self, value):
"""
Write a single bit.
"""
pin_init, pin_value, Pin_OUT_PP, Pin_IN, Pin_PULL_UP = self.cache
self._write_bit(value, pin_init, pin_value, Pin_OUT_PP)
def _write_bit(self, value, pin_init, pin_value, Pin_OUT_PP):
"""
Write a single bit - requires cached methods/attributes be passed as arguments.
See also write_bit()
"""
d0, d1, d2, d3 = self.write_delays
udelay = pyb.udelay
if value:
# write 1
i = disable_irq()
pin_value(0)
pin_init(Pin_OUT_PP)
udelay(d0)
pin_value(1)
enable_irq(i)
udelay(d1)
else:
# write 0
i = disable_irq()
pin_value(0)
pin_init(Pin_OUT_PP)
udelay(d2)
pin_value(1)
enable_irq(i)
udelay(d3)
def write_byte(self, value):
"""
Write a byte. The pin will go tri-state at the end of the write to avoid
heating in a short or other mishap.
"""
pin_init, pin_value, Pin_OUT_PP, Pin_IN, Pin_PULL_UP = self.cache
for i in range(8):
self._write_bit(value & 1, pin_init, pin_value, Pin_OUT_PP)
value >>= 1
pin_init(Pin_IN, Pin_PULL_UP)
def write_bytes(self, bytestring):
"""
Write a sequence of bytes.
"""
for byte in bytestring:
self.write_byte(byte)
def _read_bit(self, pin_init, pin_value, Pin_OUT_PP, Pin_IN, Pin_PULL_UP):
"""
Read a single bit - requires cached methods/attributes be passed as arguments.
See also read_bit()
"""
d0, d1, d2 = self.read_delays
udelay = pyb.udelay
pin_init(Pin_IN, Pin_PULL_UP) # TODO why do we need this?
i = disable_irq()
pin_value(0)
pin_init(Pin_OUT_PP)
udelay(d0)
pin_init(Pin_IN, Pin_PULL_UP)
udelay(d1)
value = pin_value()
enable_irq(i)
udelay(d2)
return value
def read_bit(self):
"""
Read a single bit.
"""
pin_init, pin_value, Pin_OUT_PP, Pin_IN, Pin_PULL_UP = self.cache
return self._read_bit(pin_init, pin_value, Pin_OUT_PP, Pin_IN, Pin_PULL_UP)
def read_byte(self):
"""
Read a single byte and return the value as an integer.
See also read_bytes()
"""
pin_init, pin_value, Pin_OUT_PP, Pin_IN, Pin_PULL_UP = self.cache
value = 0
for i in range(8):
bit = self._read_bit(pin_init, pin_value, Pin_OUT_PP, Pin_IN, Pin_PULL_UP)
value |= bit << i
return value
def read_bytes(self, count):
"""
Read a sequence of N bytes.
The bytes are returned as a bytearray.
"""
s = bytearray(count)
for i in range(count):
s[i] = self.read_byte()
return s
def select_rom(self, rom):
"""
Select a specific device to talk to. Pass in rom as a bytearray (8 bytes).
"""
assert len(rom) == 8, "ROM must be 8 bytes"
self.reset()
self.write_byte(0x55) # ROM MATCH
self.write_bytes(rom)
def read_rom(self):
"""
Read the ROM - this works if there is only a single device attached.
"""
self.reset()
self.write_byte(0x33) # READ ROM
rom = self.read_bytes(8)
# TODO: check CRC of the ROM
return rom
def skip_rom(self):
"""
Send skip-rom command - this works if there is only one device attached.
"""
self.write_byte(0xCC) # SKIP ROM
def depower(self):
self.data_pin.init(self.data_pin.IN, self.data_pin.PULL_NONE)
def scan(self):
"""
Return a list of ROMs for all attached devices.
Each ROM is returned as a bytes object of 8 bytes.
"""
devices = []
self._reset_search()
while True:
rom = self._search()
if not rom:
return devices
devices.append(rom)
def _reset_search(self):
self.last_discrepancy = 0
self.last_device_flag = False
self.last_family_discrepancy = 0
self.rom = bytearray(8)
def _search(self):
# initialize for search
id_bit_number = 1
last_zero = 0
rom_byte_number = 0
rom_byte_mask = 1
search_result = 0
pin_init, pin_value, Pin_OUT_PP, Pin_IN, Pin_PULL_UP = self.cache
# if the last call was not the last one
if not self.last_device_flag:
# 1-Wire reset
if not self.reset():
self._reset_search()
return None
# issue the search command
self.write_byte(0xF0)
# loop to do the search
while rom_byte_number < 8: # loop until through all ROM bytes 0-7
# read a bit and its complement
id_bit = self._read_bit(pin_init, pin_value, Pin_OUT_PP, Pin_IN, Pin_PULL_UP)
cmp_id_bit = self._read_bit(pin_init, pin_value, Pin_OUT_PP, Pin_IN, Pin_PULL_UP)
# check for no devices on 1-wire
if (id_bit == 1) and (cmp_id_bit == 1):
break
else:
# all devices coupled have 0 or 1
if (id_bit != cmp_id_bit):
search_direction = id_bit # bit write value for search
else:
# if this discrepancy if before the Last Discrepancy
# on a previous next then pick the same as last time
if (id_bit_number < self.last_discrepancy):
search_direction = (self.rom[rom_byte_number] & rom_byte_mask) > 0
else:
# if equal to last pick 1, if not then pick 0
search_direction = (id_bit_number == self.last_discrepancy)
# if 0 was picked then record its position in LastZero
if search_direction == 0:
last_zero = id_bit_number
# check for Last discrepancy in family
if last_zero < 9:
self.last_family_discrepancy = last_zero
# set or clear the bit in the ROM byte rom_byte_number
# with mask rom_byte_mask
if search_direction == 1:
self.rom[rom_byte_number] |= rom_byte_mask
else:
self.rom[rom_byte_number] &= ~rom_byte_mask
# serial number search direction write bit
#print('sd', search_direction)
self.write_bit(search_direction)
# increment the byte counter id_bit_number
# and shift the mask rom_byte_mask
id_bit_number += 1
rom_byte_mask <<= 1
# if the mask is 0 then go to new SerialNum byte rom_byte_number and reset mask
if rom_byte_mask == 0x100:
rom_byte_number += 1
rom_byte_mask = 1
# if the search was successful then
if not (id_bit_number < 65):
# search successful so set last_discrepancy,last_device_flag,search_result
self.last_discrepancy = last_zero
# check for last device
if self.last_discrepancy == 0:
self.last_device_flag = True
search_result = True
# if no device found then reset counters so next 'search' will be like a first
if not search_result or not self.rom[0]:
self._reset_search()
return None
else:
return bytes(self.rom)
|
mit
|
retsu0/FFmepg-Android
|
jni/x264/tools/test_x264.py
|
138
|
16077
|
#!/usr/bin/env python
import operator
from optparse import OptionGroup
import sys
from time import time
from digress.cli import Dispatcher as _Dispatcher
from digress.errors import ComparisonError, FailedTestError, DisabledTestError
from digress.testing import depends, comparer, Fixture, Case
from digress.comparers import compare_pass
from digress.scm import git as x264git
from subprocess import Popen, PIPE, STDOUT
import os
import re
import shlex
import inspect
from random import randrange, seed
from math import ceil
from itertools import imap, izip
os.chdir(os.path.join(os.path.dirname(__file__), ".."))
# options
OPTIONS = [
[ "--tune %s" % t for t in ("film", "zerolatency") ],
("", "--intra-refresh"),
("", "--no-cabac"),
("", "--interlaced"),
("", "--slice-max-size 1000"),
("", "--frame-packing 5"),
[ "--preset %s" % p for p in ("ultrafast",
"superfast",
"veryfast",
"faster",
"fast",
"medium",
"slow",
"slower",
"veryslow",
"placebo") ]
]
# end options
def compare_yuv_output(width, height):
def _compare_yuv_output(file_a, file_b):
size_a = os.path.getsize(file_a)
size_b = os.path.getsize(file_b)
if size_a != size_b:
raise ComparisonError("%s is not the same size as %s" % (
file_a,
file_b
))
BUFFER_SIZE = 8196
offset = 0
with open(file_a) as f_a:
with open(file_b) as f_b:
for chunk_a, chunk_b in izip(
imap(
lambda i: f_a.read(BUFFER_SIZE),
xrange(size_a // BUFFER_SIZE + 1)
),
imap(
lambda i: f_b.read(BUFFER_SIZE),
xrange(size_b // BUFFER_SIZE + 1)
)
):
chunk_size = len(chunk_a)
if chunk_a != chunk_b:
for i in xrange(chunk_size):
if chunk_a[i] != chunk_b[i]:
# calculate the macroblock, plane and frame from the offset
offs = offset + i
y_plane_area = width * height
u_plane_area = y_plane_area + y_plane_area * 0.25
v_plane_area = u_plane_area + y_plane_area * 0.25
pixel = offs % v_plane_area
frame = offs // v_plane_area
if pixel < y_plane_area:
plane = "Y"
pixel_x = pixel % width
pixel_y = pixel // width
macroblock = (ceil(pixel_x / 16.0), ceil(pixel_y / 16.0))
elif pixel < u_plane_area:
plane = "U"
pixel -= y_plane_area
pixel_x = pixel % width
pixel_y = pixel // width
macroblock = (ceil(pixel_x / 8.0), ceil(pixel_y / 8.0))
else:
plane = "V"
pixel -= u_plane_area
pixel_x = pixel % width
pixel_y = pixel // width
macroblock = (ceil(pixel_x / 8.0), ceil(pixel_y / 8.0))
macroblock = tuple([ int(x) for x in macroblock ])
raise ComparisonError("%s differs from %s at frame %d, " \
"macroblock %s on the %s plane (offset %d)" % (
file_a,
file_b,
frame,
macroblock,
plane,
offs)
)
offset += chunk_size
return _compare_yuv_output
def program_exists(program):
def is_exe(fpath):
return os.path.exists(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None
class x264(Fixture):
scm = x264git
class Compile(Case):
@comparer(compare_pass)
def test_configure(self):
Popen([
"make",
"distclean"
], stdout=PIPE, stderr=STDOUT).communicate()
configure_proc = Popen([
"./configure"
] + self.fixture.dispatcher.configure, stdout=PIPE, stderr=STDOUT)
output = configure_proc.communicate()[0]
if configure_proc.returncode != 0:
raise FailedTestError("configure failed: %s" % output.replace("\n", " "))
@depends("configure")
@comparer(compare_pass)
def test_make(self):
make_proc = Popen([
"make",
"-j5"
], stdout=PIPE, stderr=STDOUT)
output = make_proc.communicate()[0]
if make_proc.returncode != 0:
raise FailedTestError("make failed: %s" % output.replace("\n", " "))
_dimension_pattern = re.compile(r"\w+ [[]info[]]: (\d+)x(\d+)[pi] \d+:\d+ @ \d+/\d+ fps [(][vc]fr[)]")
def _YUVOutputComparisonFactory():
class YUVOutputComparison(Case):
_dimension_pattern = _dimension_pattern
depends = [ Compile ]
options = []
def __init__(self):
for name, meth in inspect.getmembers(self):
if name[:5] == "test_" and name[5:] not in self.fixture.dispatcher.yuv_tests:
delattr(self.__class__, name)
def _run_x264(self):
x264_proc = Popen([
"./x264",
"-o",
"%s.264" % self.fixture.dispatcher.video,
"--dump-yuv",
"x264-output.yuv"
] + self.options + [
self.fixture.dispatcher.video
], stdout=PIPE, stderr=STDOUT)
output = x264_proc.communicate()[0]
if x264_proc.returncode != 0:
raise FailedTestError("x264 did not complete properly: %s" % output.replace("\n", " "))
matches = _dimension_pattern.match(output)
return (int(matches.group(1)), int(matches.group(2)))
@comparer(compare_pass)
def test_jm(self):
if not program_exists("ldecod"): raise DisabledTestError("jm unavailable")
try:
runres = self._run_x264()
jm_proc = Popen([
"ldecod",
"-i",
"%s.264" % self.fixture.dispatcher.video,
"-o",
"jm-output.yuv"
], stdout=PIPE, stderr=STDOUT)
output = jm_proc.communicate()[0]
if jm_proc.returncode != 0:
raise FailedTestError("jm did not complete properly: %s" % output.replace("\n", " "))
try:
compare_yuv_output(*runres)("x264-output.yuv", "jm-output.yuv")
except ComparisonError, e:
raise FailedTestError(e)
finally:
try: os.remove("x264-output.yuv")
except: pass
try: os.remove("%s.264" % self.fixture.dispatcher.video)
except: pass
try: os.remove("jm-output.yuv")
except: pass
try: os.remove("log.dec")
except: pass
try: os.remove("dataDec.txt")
except: pass
@comparer(compare_pass)
def test_ffmpeg(self):
if not program_exists("ffmpeg"): raise DisabledTestError("ffmpeg unavailable")
try:
runres = self._run_x264()
ffmpeg_proc = Popen([
"ffmpeg",
"-vsync 0",
"-i",
"%s.264" % self.fixture.dispatcher.video,
"ffmpeg-output.yuv"
], stdout=PIPE, stderr=STDOUT)
output = ffmpeg_proc.communicate()[0]
if ffmpeg_proc.returncode != 0:
raise FailedTestError("ffmpeg did not complete properly: %s" % output.replace("\n", " "))
try:
compare_yuv_output(*runres)("x264-output.yuv", "ffmpeg-output.yuv")
except ComparisonError, e:
raise FailedTestError(e)
finally:
try: os.remove("x264-output.yuv")
except: pass
try: os.remove("%s.264" % self.fixture.dispatcher.video)
except: pass
try: os.remove("ffmpeg-output.yuv")
except: pass
return YUVOutputComparison
class Regression(Case):
depends = [ Compile ]
_psnr_pattern = re.compile(r"x264 [[]info[]]: PSNR Mean Y:\d+[.]\d+ U:\d+[.]\d+ V:\d+[.]\d+ Avg:\d+[.]\d+ Global:(\d+[.]\d+) kb/s:\d+[.]\d+")
_ssim_pattern = re.compile(r"x264 [[]info[]]: SSIM Mean Y:(\d+[.]\d+) [(]\d+[.]\d+db[)]")
def __init__(self):
if self.fixture.dispatcher.x264:
self.__class__.__name__ += " %s" % " ".join(self.fixture.dispatcher.x264)
def test_psnr(self):
try:
x264_proc = Popen([
"./x264",
"-o",
"%s.264" % self.fixture.dispatcher.video,
"--psnr"
] + self.fixture.dispatcher.x264 + [
self.fixture.dispatcher.video
], stdout=PIPE, stderr=STDOUT)
output = x264_proc.communicate()[0]
if x264_proc.returncode != 0:
raise FailedTestError("x264 did not complete properly: %s" % output.replace("\n", " "))
for line in output.split("\n"):
if line.startswith("x264 [info]: PSNR Mean"):
return float(self._psnr_pattern.match(line).group(1))
raise FailedTestError("no PSNR output caught from x264")
finally:
try: os.remove("%s.264" % self.fixture.dispatcher.video)
except: pass
def test_ssim(self):
try:
x264_proc = Popen([
"./x264",
"-o",
"%s.264" % self.fixture.dispatcher.video,
"--ssim"
] + self.fixture.dispatcher.x264 + [
self.fixture.dispatcher.video
], stdout=PIPE, stderr=STDOUT)
output = x264_proc.communicate()[0]
if x264_proc.returncode != 0:
raise FailedTestError("x264 did not complete properly: %s" % output.replace("\n", " "))
for line in output.split("\n"):
if line.startswith("x264 [info]: SSIM Mean"):
return float(self._ssim_pattern.match(line).group(1))
raise FailedTestError("no PSNR output caught from x264")
finally:
try: os.remove("%s.264" % self.fixture.dispatcher.video)
except: pass
def _generate_random_commandline():
commandline = []
for suboptions in OPTIONS:
commandline.append(suboptions[randrange(0, len(suboptions))])
return filter(None, reduce(operator.add, [ shlex.split(opt) for opt in commandline ]))
_generated = []
fixture = x264()
fixture.register_case(Compile)
fixture.register_case(Regression)
class Dispatcher(_Dispatcher):
video = "akiyo_qcif.y4m"
products = 50
configure = []
x264 = []
yuv_tests = [ "jm" ]
def _populate_parser(self):
super(Dispatcher, self)._populate_parser()
# don't do a whole lot with this
tcase = _YUVOutputComparisonFactory()
yuv_tests = [ name[5:] for name, meth in filter(lambda pair: pair[0][:5] == "test_", inspect.getmembers(tcase)) ]
group = OptionGroup(self.optparse, "x264 testing-specific options")
group.add_option(
"-v",
"--video",
metavar="FILENAME",
action="callback",
dest="video",
type=str,
callback=lambda option, opt, value, parser: setattr(self, "video", value),
help="yuv video to perform testing on (default: %s)" % self.video
)
group.add_option(
"-s",
"--seed",
metavar="SEED",
action="callback",
dest="seed",
type=int,
callback=lambda option, opt, value, parser: setattr(self, "seed", value),
help="seed for the random number generator (default: unix timestamp)"
)
group.add_option(
"-p",
"--product-tests",
metavar="NUM",
action="callback",
dest="video",
type=int,
callback=lambda option, opt, value, parser: setattr(self, "products", value),
help="number of cartesian products to generate for yuv comparison testing (default: %d)" % self.products
)
group.add_option(
"--configure-with",
metavar="FLAGS",
action="callback",
dest="configure",
type=str,
callback=lambda option, opt, value, parser: setattr(self, "configure", shlex.split(value)),
help="options to run ./configure with"
)
group.add_option(
"--yuv-tests",
action="callback",
dest="yuv_tests",
type=str,
callback=lambda option, opt, value, parser: setattr(self, "yuv_tests", [
val.strip() for val in value.split(",")
]),
help="select tests to run with yuv comparisons (default: %s, available: %s)" % (
", ".join(self.yuv_tests),
", ".join(yuv_tests)
)
)
group.add_option(
"--x264-with",
metavar="FLAGS",
action="callback",
dest="x264",
type=str,
callback=lambda option, opt, value, parser: setattr(self, "x264", shlex.split(value)),
help="additional options to run ./x264 with"
)
self.optparse.add_option_group(group)
def pre_dispatch(self):
if not hasattr(self, "seed"):
self.seed = int(time())
print "Using seed: %d" % self.seed
seed(self.seed)
for i in xrange(self.products):
YUVOutputComparison = _YUVOutputComparisonFactory()
commandline = _generate_random_commandline()
counter = 0
while commandline in _generated:
counter += 1
commandline = _generate_random_commandline()
if counter > 100:
print >>sys.stderr, "Maximum command-line regeneration exceeded. " \
"Try a different seed or specify fewer products to generate."
sys.exit(1)
commandline += self.x264
_generated.append(commandline)
YUVOutputComparison.options = commandline
YUVOutputComparison.__name__ = ("%s %s" % (YUVOutputComparison.__name__, " ".join(commandline)))
fixture.register_case(YUVOutputComparison)
Dispatcher(fixture).dispatch()
|
mit
|
maestrano/odoo
|
addons/resource/faces/task.py
|
433
|
126405
|
#@+leo-ver=4
#@+node:@file task.py
#@@language python
#@<< Copyright >>
#@+node:<< Copyright >>
############################################################################
# Copyright (C) 2005, 2006, 2007, 2008 by Reithinger GmbH
# [email protected]
#
# This file is part of faces.
#
# faces 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.
#
# faces 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 Street, Fifth Floor, Boston, MA 02110-1301 USA
############################################################################
#@-node:<< Copyright >>
#@nl
"""
This module contains all classes for project plan objects
"""
#@<< Imports >>
#@+node:<< Imports >>
import pcalendar
import resource
import types
import sys
import datetime
import operator as op
import warnings
import locale
import weakref
import opcode
import new
try:
set
except NameError:
from sets import Set as set
#@-node:<< Imports >>
#@nl
_is_source = True
STRICT = 3
SLOPPY = 2
SMART = 1
#@+others
#@+node:Exceptions
#@+node:class AttributeError
class AttributeError(AttributeError):
#@ << class AttributeError declarations >>
#@+node:<< class AttributeError declarations >>
is_frozen = False
#@-node:<< class AttributeError declarations >>
#@nl
#@-node:class AttributeError
#@+node:class RecursionError
class RecursionError(Exception):
"""This exception is raised in cas of cirular dependencies
within an project"""
#@ << class RecursionError declarations >>
#@+node:<< class RecursionError declarations >>
pass
#@-node:<< class RecursionError declarations >>
#@nl
#@-node:class RecursionError
#@+node:class _IncompleteError
class _IncompleteError(Exception):
"""This exception is raised, when there is not enough
data specified to calculate as task"""
#@ @+others
#@+node:__init__
def __init__(self, *args):
if isinstance(args[0], (basestring)):
Exception.__init__(self, *args)
else:
Exception.__init__(self,
"Not enough data for calculating task, "\
"maybe you have a recursive reference.",
*args)
#@-node:__init__
#@-others
#@-node:class _IncompleteError
#@-node:Exceptions
#@+node:Proxies for self referencing
#@+node:class _MeProxy
class _MeProxy(object):
"""
A Proxy class for the me attribute of tasks in the compile case
"""
#@ << declarations >>
#@+node:<< declarations >>
__slots__ = "task"
#@-node:<< declarations >>
#@nl
#@ @+others
#@+node:__init__
def __init__(self, task):
object.__setattr__(self, "task", task)
#@-node:__init__
#@+node:__getattr__
def __getattr__(self, name):
if self.task._is_frozen:
return getattr(self.task, name)
if name in ("name", "up", "root", "path",
"depth", "index", "calendar",
"children", "resource", "balance"):
return getattr(self.task, name)
value = self.task.__dict__.get(name, _NEVER_USED_)
def make_val(default):
if value is _NEVER_USED_: return default
return value
if name in ("start", "end"):
return self.task._to_start(make_val("1.1.2006"))
if name in ("length", "effort", "duration", "todo", "done",
"buffer", "performed", "performed_effort",
"performed_end", "performed_start",
"performed_work_time" ):
return self.task._to_delta(make_val("0d"))
if name in ("complete", "priority", "efficiency"):
return make_val(0)
if value is _NEVER_USED_:
raise AttributeError("'%s' is not a valid attribute." % (name))
return value
#@-node:__getattr__
#@+node:__setattr__
def __setattr__(self, name, value):
self.task._set_attrib(name, value)
#@-node:__setattr__
#@+node:__iter__
def __iter__(self):
return iter(self.task)
#@nonl
#@-node:__iter__
#@+node:add_attrib
def add_attrib(self, name_or_iter, val=None):
if not isinstance(name_or_iter, str):
for n, v in name_or_iter:
setattr(self, n, v)
else:
setattr(self, name_or_iter, val)
#@-node:add_attrib
#@-others
#@nonl
#@-node:class _MeProxy
#@+node:class _MeProxyRecalc
class _MeProxyRecalc(_MeProxy):
"""
A Proxy class for the me attribute of tasks in the recalc case
"""
#@ @+others
#@+node:__setattr__
def __setattr__(self, name, value):
if self.task._properties.has_key(name):
self.task._set_attrib(name, value)
#@-node:__setattr__
#@-others
#@-node:class _MeProxyRecalc
#@+node:class _MeProxyError
class _MeProxyError(_MeProxy):
#@ << declarations >>
#@+node:<< declarations >>
__slots__ = ("task", "attrib", "exc")
#@-node:<< declarations >>
#@nl
#@ @+others
#@+node:__init__
def __init__(self, task, attrib, exc):
_MeProxy.__init__(self, task)
object.__setattr__(self, "attrib", attrib)
object.__setattr__(self, "exc", exc)
#@-node:__init__
#@+node:__setattr__
def __setattr__(self, name, value):
if name == self.attrib or not self.attrib:
raise self.exc
#@-node:__setattr__
#@-others
#@-node:class _MeProxyError
#@+node:class _MeProxyWarn
class _MeProxyWarn(_MeProxy):
#@ << declarations >>
#@+node:<< declarations >>
__slots__ = ("task", "attrib", "message")
#@-node:<< declarations >>
#@nl
#@ @+others
#@+node:__init__
def __init__(self, task, attrib, message):
_MeProxy.__init__(self, task)
object.__setattr__(self, "attrib", attrib)
object.__setattr__(self, "message", message)
#@-node:__init__
#@+node:__setattr__
def __setattr__(self, name, value):
if name == self.attrib or not self.attrib:
warnings.warn(self.message, RuntimeWarning, 2)
if not self.attrib:
#warn only one time!
object.__setattr__(self, "attrib", 1)
#@-node:__setattr__
#@-others
#@-node:class _MeProxyWarn
#@-node:Proxies for self referencing
#@+node:Task instrumentation
#@+doc
# This section contains code for byte code instrumenting
# the task functions
#@-doc
#@nonl
#@+node:_int_to_arg
def _int_to_arg(value):
return value % 256, value / 256
#@-node:_int_to_arg
#@+node:_correct_labels
def _correct_labels(old_code, new_code):
#@ << localize dot variables >>
#@+node:<< localize dot variables >>
hasjrel = opcode.hasjrel
hasjabs = opcode.hasjabs
HAVE_ARGUMENT = opcode.HAVE_ARGUMENT
#@nonl
#@-node:<< localize dot variables >>
#@nl
#@ << loop initialization >>
#@+node:<< loop initialization >>
labels = {}
old_new_map = {} # map old code offset to new code offset
n = len(old_code)
i = 0
j = 0
#@nonl
#@-node:<< loop initialization >>
#@nl
while i < n:
op = old_code[i]
nop = new_code[j]
old_new_map[i] = j
i = i + 1
j = j + 1
if op >= HAVE_ARGUMENT:
oparg = old_code[i] + old_code[i + 1] * 256
i = i + 2
j = j + 2
if nop != op:
j += 3 # skip the 3 addition opcodes for attrib access
else:
#@ << add label if necessary >>
#@+node:<< add label if necessary >>
label = -1
if op in hasjrel:
label = i + oparg
elif op in hasjabs:
label = oparg
if label >= 0:
labels[i] = label
#@nonl
#@-node:<< add label if necessary >>
#@nl
for offset, label in labels.iteritems():
new_offset = old_new_map[offset]
new_label = old_new_map[label]
op = new_code[new_offset - 3]
#change jump arguments
if op in hasjrel:
jump = _int_to_arg(new_label - new_offset)
new_code[new_offset - 2:new_offset] = jump
elif op in hasjabs:
new_code[new_offset - 2:new_offset] = _int_to_arg(new_label)
#@nonl
#@-node:_correct_labels
#@+node:_instrument
def _instrument(func):
#@ << localize dot variables >>
#@+node:<< localize dot variables >>
opname = opcode.opname
opmap = opcode.opmap
jumps = opcode.hasjrel + opcode.hasjabs
HAVE_ARGUMENT = opcode.HAVE_ARGUMENT
co = func.func_code
local_names = co.co_varnames
all_names = list(co.co_names)
global_names = set()
#@-node:<< localize dot variables >>
#@nl
#@ << define local functions list_to_dict and is_local >>
#@+node:<< define local functions list_to_dict and is_local >>
def list_to_dict(l):
return dict([(t[1], t[0]) for t in enumerate(l)])
def is_local(name):
return name[0] == "_" and name != "__constraint__"
#@nonl
#@-node:<< define local functions list_to_dict and is_local >>
#@nl
#convert code
#@ << loop initialization >>
#@+node:<< loop initialization >>
# all_name_map maps names to the all_names index
# (same like all_names.index())
all_name_map = list_to_dict(all_names)
if not all_name_map.has_key("me"):
all_name_map["me"] = len(all_names)
all_names.append("me")
#<python 2.5>
for ln in local_names:
if not all_name_map.has_key(ln):
all_name_map[ln] = len(all_names)
all_names.append(ln)
#</python 2.5>
new_local_names = filter(is_local, local_names)
new_local_name_map = list_to_dict(new_local_names)
me_arg = _int_to_arg(all_name_map["me"])
old_lnotab = map(ord, co.co_lnotab)
new_lnotab = []
tab_pos = 0
try:
next_tab_point = old_lnotab[0]
except IndexError:
next_tab_point = None
last_tab_point = 0
code = map(ord, co.co_code)
new_code = []
has_labels = False
n = len(code)
i = 0
#@nonl
#@-node:<< loop initialization >>
#@nl
while i < n:
if i == next_tab_point:
#@ << calculate new tab point >>
#@+node:<< calculate new tab point >>
increment = len(new_code) - last_tab_point
new_lnotab.extend((increment, old_lnotab[tab_pos + 1]))
tab_pos += 2
try:
next_tab_point = i + old_lnotab[tab_pos]
last_tab_point = len(new_code)
except IndexError:
next_tab_point = -1
#@nonl
#@-node:<< calculate new tab point >>
#@nl
op = code[i]
i += 1
if op >= HAVE_ARGUMENT:
#@ << calculate argument >>
#@+node:<< calculate argument >>
arg0 = code[i]
arg1 = code[i+1]
oparg = arg0 + arg1 * 256
#@nonl
#@-node:<< calculate argument >>
#@nl
i += 2
if opname[op] == "LOAD_GLOBAL":
global_names.add(oparg)
elif opname[op] == "STORE_FAST":
#@ << change "store fast" to "store attribute" >>
#@+node:<< change "store fast" to "store attribute" >>
name = local_names[oparg]
if not is_local(name):
new_code.append(opmap["LOAD_GLOBAL"])
new_code.extend(me_arg)
op = opmap["STORE_ATTR"]
arg0, arg1 = _int_to_arg(all_name_map[name])
else:
arg0, arg1 = _int_to_arg(new_local_name_map[name])
#@nonl
#@-node:<< change "store fast" to "store attribute" >>
#@nl
elif opname[op] == "LOAD_FAST":
#@ << change "load fast" to "load attribute" >>
#@+node:<< change "load fast" to "load attribute" >>
name = local_names[oparg]
if not is_local(name):
new_code.append(opmap["LOAD_GLOBAL"])
new_code.extend(me_arg)
op = opmap["LOAD_ATTR"]
arg0, arg1 = _int_to_arg(all_name_map[name])
else:
arg0, arg1 = _int_to_arg(new_local_name_map[name])
#@nonl
#@-node:<< change "load fast" to "load attribute" >>
#@nl
elif op in jumps:
has_labels = True
new_code.extend((op, arg0, arg1))
else:
new_code.append(op)
if has_labels:
_correct_labels(code, new_code)
#@ << create new code and function objects and return >>
#@+node:<< create new code and function objects and return >>
new_code = "".join(map(chr, new_code))
new_lnotab = "".join(map(chr, new_lnotab))
new_co = new.code(co.co_argcount,
len(new_local_names),
max(co.co_stacksize, 2),
co.co_flags,
new_code,
co.co_consts,
tuple(all_names),
tuple(new_local_names),
co.co_filename,
co.co_name,
co.co_firstlineno,
new_lnotab,
co.co_freevars,
co.co_cellvars)
func = new.function(new_co,
func.func_globals,
func.func_name,
func.func_defaults,
func.func_closure)
func.global_names = tuple([all_names[index] for index in global_names])
return func
#@nonl
#@-node:<< create new code and function objects and return >>
#@nl
#@nonl
#@-node:_instrument
#@-node:Task instrumentation
#@+node:Wrappers
#@+node:class _Path
class _Path(object):
"""
This class represents an instrumented path, to
a task. If it points to an attribute of a task, it
not only returns the value of the attribute. You can also
find out the source attribute (task and attribute name)
of the value.
"""
#@ @+others
#@+node:__init__
def __init__(self, task, path_str):
self._task = task
self._path_str = path_str
#@-node:__init__
#@+node:__getattr__
def __getattr__(self, name):
new = getattr(self._task, name)
if isinstance(new, Task):
return _Path(new, self._path_str + "." + name)
return _ValueWrapper(new, [(self._task, name)])
#@-node:__getattr__
#@+node:__str__
def __str__(self):
return self._path_str
#@-node:__str__
#@+node:__iter__
def __iter__(self):
return iter(self._task)
#@nonl
#@-node:__iter__
#@-others
#@-node:class _Path
#@+node:_val
#helper functions for _ValueWrapper
#----------------------------------
def _val(val):
if isinstance(val, _ValueWrapper):
return val._value
return val
#@-node:_val
#@+node:_ref
def _ref(val):
if isinstance(val, _ValueWrapper):
return val._ref
return []
#@-node:_ref
#@+node:_sref
def _sref(val, ref):
if isinstance(val, _ValueWrapper):
val._ref = ref
#@nonl
#@-node:_sref
#@+node:_refsum
def _refsum(refs):
return reduce(lambda a, b: a + b, refs, [])
#@nonl
#@-node:_refsum
#@+node:class _ValueWrapper
class _ValueWrapper(object):
"""
This class represents a value, of a task attribute or
a return value of a task method. It contains the value,
and the supplier of that value
"""
#@ @+others
#@+node:__init__
def __init__(self, value, ref):
self._value = value
self._ref = ref
#@-node:__init__
#@+node:unicode
def unicode(self, *args):
if isinstance(self._value, str):
return unicode(self._value, *args)
return unicode(self._value)
#@nonl
#@-node:unicode
#@+node:_vw
def _vw(self, operand, *args):
refs = _refsum(map(_ref, args))
vals = map(_val, args)
result = operand(*vals)
return self.__class__(result, refs)
#@-node:_vw
#@+node:_cmp
def _cmp(self, operand, *args):
refs = _refsum(map(_ref, args))
vals = map(_val, args)
result = operand(*vals)
map(lambda a: _sref(a, refs), args)
return result
#@-node:_cmp
#@+node:__getattr__
def __getattr__(self, name):
return getattr(self._value, name)
#@-node:__getattr__
#@+node:__getitem__
def __getitem__(self, slice):
return self.__class__(self._value[slice], self._ref)
#@nonl
#@-node:__getitem__
#@+node:__str__
def __str__(self): return str(self._value)
#@-node:__str__
#@+node:__unicode__
def __unicode__(self): return unicode(self._value)
#@nonl
#@-node:__unicode__
#@+node:__repr__
def __repr__(self): return repr(self._value)
#@-node:__repr__
#@+node:__nonzero__
def __nonzero__(self): return bool(self._value)
#@-node:__nonzero__
#@+node:__lt__
def __lt__(self, other): return self._cmp(op.lt, self, other)
#@-node:__lt__
#@+node:__le__
def __le__(self, other): return self._cmp(op.le, self, other)
#@-node:__le__
#@+node:__eq__
def __eq__(self, other): return self._cmp(op.eq, self, other)
#@-node:__eq__
#@+node:__ne__
def __ne__(self, other): return self._cmp(op.ne, self, other)
#@-node:__ne__
#@+node:__gt__
def __gt__(self, other): return self._cmp(op.gt, self, other)
#@-node:__gt__
#@+node:__ge__
def __ge__(self, other): return self._cmp(op.ge, self, other)
#@-node:__ge__
#@+node:__add__
def __add__(self, other): return self._vw(op.add, self, other)
#@nonl
#@-node:__add__
#@+node:__sub__
def __sub__(self, other): return self._vw(op.sub, self, other)
#@-node:__sub__
#@+node:__mul__
def __mul__(self, other): return self._vw(op.mul, self, other)
#@-node:__mul__
#@+node:__floordiv__
def __floordiv__(self, other): return self._vw(op.floordiv, self, other)
#@-node:__floordiv__
#@+node:__mod__
def __mod__(self, other): return self._vw(op.mod, self, other)
#@-node:__mod__
#@+node:__divmod__
def __divmod__(self, other): return self._vw(op.divmod, self, other)
#@-node:__divmod__
#@+node:__pow__
def __pow__(self, other): return self._vw(op.pow, self, other)
#@-node:__pow__
#@+node:__lshift__
def __lshift__(self, other): return self._vw(op.lshift, self, other)
#@-node:__lshift__
#@+node:__rshift__
def __rshift__(self, other): return self._vw(op.rshift, self, other)
#@-node:__rshift__
#@+node:__and__
def __and__(self, other): return self._vw(op.and_, self, other)
#@-node:__and__
#@+node:__xor__
def __xor__(self, other): return self._vw(op.xor, self, other)
#@-node:__xor__
#@+node:__or__
def __or__(self, other): return self._vw(op.or_, self, other)
#@-node:__or__
#@+node:__div__
def __div__(self, other): return self._vw(op.div, self, other)
#@-node:__div__
#@+node:__radd__
def __radd__(self, other): return self._vw(op.add, other, self)
#@-node:__radd__
#@+node:__rsub__
def __rsub__(self, other): return self._vw(op.sub, other, self)
#@-node:__rsub__
#@+node:__rmul__
def __rmul__(self, other): return self._vw(op.mul, other, self)
#@-node:__rmul__
#@+node:__rdiv__
def __rdiv__(self, other): return self._vw(op.div, other, self)
#@-node:__rdiv__
#@+node:__rtruediv__
def __rtruediv__(self, other): return self._vw(op.truediv, other, self)
#@-node:__rtruediv__
#@+node:__rfloordiv__
def __rfloordiv__(self, other): return self._vw(op.floordiv, other, self)
#@-node:__rfloordiv__
#@+node:__rmod__
def __rmod__(self, other): return self._vw(op.mod, other, self)
#@-node:__rmod__
#@+node:__rdivmod__
def __rdivmod__(self, other): return self._vw(op.divmod, other, self)
#@-node:__rdivmod__
#@+node:__rpow__
def __rpow__(self, other): return self._vw(op.pow, other, self)
#@-node:__rpow__
#@+node:__rlshift__
def __rlshift__(self, other): return self._vw(op.lshift, other, self)
#@-node:__rlshift__
#@+node:__rrshift__
def __rrshift__(self, other): return self._vw(op.rshift, other, self)
#@-node:__rrshift__
#@+node:__rand__
def __rand__(self, other): return self._vw(op.and_, other, self)
#@-node:__rand__
#@+node:__rxor__
def __rxor__(self, other): return self._vw(op.xor, other, self)
#@-node:__rxor__
#@+node:__ror__
def __ror__(self, other): return self._vw(op.or_, other, self)
#@-node:__ror__
#@+node:__int__
def __int__(self): return int(self._value)
#@-node:__int__
#@+node:__long__
def __long__(self): return long(self._value)
#@-node:__long__
#@+node:__float__
def __float__(self): return float(self._value)
#@-node:__float__
#@+node:__len__
def __len__(self): return len(self._value)
#@-node:__len__
#@+node:__iter__
def __iter__(self): return iter(self._value)
#@-node:__iter__
#@+node:__hash__
def __hash__(self): return hash(self._value)
#@-node:__hash__
#@-others
#@-node:class _ValueWrapper
#@-node:Wrappers
#@+node:Utilities
#@+node:class _NEVER_USED_
class _NEVER_USED_:
pass
#@-node:class _NEVER_USED_
#@+node:class _StringConverter
class _StringConverter(object):
"""This class is a helper for the to_string mechanism
of tasks"""
#@ @+others
#@+node:__init__
def __init__(self, source, format=None):
self.source = source
self.format = format
#@-node:__init__
#@+node:__getitem__
def __getitem__(self, format):
return _StringConverter(self.source, format)
#@-node:__getitem__
#@+node:__getattr__
def __getattr__(self, name):
class StrWrapper(object):
def __init__(self, value, name, source, format):
self._value = value
self.name = name
self.source = source
self.format = format
def __call__(self, arg):
formatter = self.source.formatter(self.name,
arg,
self.format)
return formatter(self._value(arg))
value = getattr(self.source, name)
if callable(value):
#for methods the wrapper has to
return StrWrapper(value, name, self.source, self.format)
formatter = self.source.formatter(name, format=self.format)
return formatter(value)
#@-node:__getattr__
#@-others
#@-node:class _StringConverter
#@+node:Multi
def Multi(val, **kwargs):
"""returns a directory for mutlivalued attributes"""
return dict(_default=val, **kwargs)
#@nonl
#@-node:Multi
#@+node:create_relative_path
def create_relative_path(from_, to_):
"""
creates a relative path from absolute path
from_ to absolute path to_
"""
from_ = from_.split(".")
to_ = to_.split(".")
for i, parts in enumerate(zip(from_, to_)):
from_part, to_part = parts
if from_part != to_part:
break
from_ = from_[i:]
to_ = to_[i:]
return "up." * len(from_) + ".".join(to_)
#@nonl
#@-node:create_relative_path
#@+node:create_absolute_path
def create_absolute_path(from_, to_):
"""
creates a absolute path from absolute path
from_ to relative path to_
"""
from_ = from_.split(".")
to_ = to_.split(".")
for i, part in enumerate(to_):
if part != "up":
break
from_ = from_[:-i]
to_ = to_[i:]
return "%s.%s" % (".".join(from_), ".".join(to_))
#@-node:create_absolute_path
#@+node:_split_path
def _split_path(path):
try:
index = path.rindex(".")
return path[:index], path[index + 1:]
except:
return path
#@-node:_split_path
#@+node:_to_datetime
_to_datetime = pcalendar.to_datetime
#@nonl
#@-node:_to_datetime
#@+node:_get_tasks_of_sources
def _get_tasks_of_sources(task, attrib_filter="end,start,effort,length,duration"):
#return all source tasks, this task is dependend on
dep_tasks = {}
while task:
for dep in task._sources.values():
for d in dep:
path, attrib = _split_path(d)
if attrib and attrib_filter.find(attrib) >= 0:
dep_tasks[path] = True
task = task.up
return dep_tasks.keys()
#@-node:_get_tasks_of_sources
#@+node:_build_balancing_list
def _build_balancing_list(tasks):
"""
Returns a specialy sorted list of tasks.
If the tasks will allocate resources in the sorting order of that list
correct balancing is ensured
"""
# first sort the list for attributes
index = 0
balancing_list = [(-t.priority, t.balance, index, t) for index, t in enumerate(tasks)]
balancing_list.sort()
#print
#for p, b, i, t in balancing_list:
# print p, b, i, t.path
balancing_list = [ t for p, b, i, t in balancing_list ]
#now correct the presorted list:
#if task a is dependent on task b, b will be moved before a
done_map = { }
count = len(balancing_list)
while len(done_map) < count:
for i in range(count):
to_inspect = balancing_list[i]
if done_map.has_key(to_inspect):
continue
done_map[to_inspect] = True
break
else:
break
#@ << define inspect_depends_on >>
#@+node:<< define inspect_depends_on >>
inspect_path = to_inspect.path + "."
sources = _get_tasks_of_sources(to_inspect)
sources = [ s + "." for s in sources
if not inspect_path.startswith(s) ]
# the if in the later line ignores assignments like
# like start = up.start (i.e. references to parents)
# this will be handled in the second if of inspect_depends_on
# and can cause errors otherwise
def inspect_depends_on(task):
cmp_path = task.path + "."
for src in sources:
if cmp_path.startswith(src):
#task is a source of to_inspect
return True
if inspect_path.startswith(cmp_path):
#to_inspect is a child of task
return True
return False
#@nonl
#@-node:<< define inspect_depends_on >>
#@nl
for j in range(i + 1, count):
check_task = balancing_list[j]
if done_map.has_key(check_task):
continue
if inspect_depends_on(check_task):
del balancing_list[j]
balancing_list.insert(i, check_task)
i += 1 # to_inspect is now at i + 1
return balancing_list
#@-node:_build_balancing_list
#@+node:_as_string
def _as_string(val):
if isinstance(val, basestring):
return '"""%s"""' % val.replace("\n", "\\n")
if isinstance(val, pcalendar._WorkingDateBase):
return '"%s"' % val.strftime("%Y-%m-%d %H:%M")
if isinstance(val, datetime.datetime):
return '"%s"' % val.strftime("%Y-%m-%d %H:%M")
if isinstance(val, datetime.timedelta):
return '"%id %iM"' % (val.days, val.seconds / 60)
if isinstance(val, tuple):
result = map(_as_string, val)
return "(%s)" % ", ".join(result)
if isinstance(val, list):
result = map(_as_string, val)
return "[%s]" % ", ".join(result)
if isinstance(val, resource.Resource):
return val._as_string()
if isinstance(val, Task):
return val.path
return str(val)
#@-node:_as_string
#@+node:_step_tasks
def _step_tasks(task):
if isinstance(task, Task):
yield task
stack = [iter(task.children)]
while stack:
for task in stack[-1]:
yield task
if task.children:
stack.append(iter(task.children))
break
else:
stack.pop()
#@-node:_step_tasks
#@-node:Utilities
#@+node:Cache
instrumentation_cache = {}
balancing_cache = {}
def clear_cache():
instrumentation_cache.clear()
balancing_cache.clear()
#@nonl
#@-node:Cache
#@+node:Resource Allocators
#@+others
#@+node:VariableLoad
def VariableLoad(limit=0):
"""
Allocates the resource with maximal possible load.
If limit is given, a the load is at least limit or more.
"""
try:
balance = me.balance
except NameError:
balance = SLOPPY
if balance != SLOPPY:
raise RuntimeError("You may specify variable_load only with balance=SLOPPY")
return -limit
#@-node:VariableLoad
#@+node:_calc_load
def _calc_load(task, resource):
#changed at the resource instance
load = resource.__dict__.get("load")
if load is not None: return load
load = task.__dict__.get("load")
if load is not None: return load
#inherited by the task
return min(task.load, task.max_load, resource.max_load or 100.0)
#@-node:_calc_load
#@+node:_calc_maxload
def _calc_maxload(task, resource):
#changed at the resource instance
max_load = resource.__dict__.get("max_load")
if max_load: return max_load
#an explicit load can overwrite max_load
load = max(resource.__dict__.get("load", 0),
task.__dict__.get("load"), 0)
#change at the task
max_load = task.__dict__.get("max_load")
if max_load: return max(max_load, load)
#inherited by the resource
max_load = resource.max_load
if max_load: return max(max_load, load)
#inherited by the task
return max(task.max_load, load)
#@-node:_calc_maxload
#@+node:class AllocationAlgorithm
class AllocationAlgorithm(object):
"""This class is a base for resource allocation algorithms"""
#@ @+others
#@+node:test_allocation
def test_allocation(self, task, resource):
"""This method simulates the allocation of a specific resource.
It returns a list of values representing the state of the allocation.
The task allocator calls test_allocation for every alternative resource.
It compares the first items of all return lists, and allocates the
resource with the minum first item value"""
return (task.end, )
#@-node:test_allocation
#@+node:allocate
def allocate(self, task, state):
"""This method eventually allocates a specific resource.
State is the return list of test_allocation"""
pass
#@-node:allocate
#@-others
#@-node:class AllocationAlgorithm
#@+node:class StrictAllocator
class StrictAllocator(AllocationAlgorithm):
"""This class implements the STRICT resource allocation"""
#@ @+others
#@+node:_distribute_len_loads
def _distribute_len_loads(self, task, resource, effort, length):
# A special load calculation, if effort and length are given.
# and the resources have a defined maxload, the load must be
# individually calculated for each resource.
# Formulars: r=resources, t=task
# effort = length * efficiency(t) * sum[load(r) * effiency(r)]
# ==> sum_load = sum[load(r) * effiency(r)]
# = effort / (length * efficiency(t))
#
sum_load = float(effort) / (task.efficiency * length)
# algorithm:
# The goal is to distribute the load (norm_load) equally
# to all resources. If a resource has a max_load(r) < norm_load
# the load of this resource will be max_load(r), and the other
# resources will have another (higher) norm_load
max_loads = map(lambda r: (_calc_maxload(task, r), r), resource)
max_loads.sort()
efficiency_sum = sum(map(lambda r: r.efficiency, resource))
norm_load = sum_load / efficiency_sum
loads = {}
for max_load, r in max_loads[:-1]:
if max_load < norm_load:
loads[r] = max_load
efficiency_sum -= r.efficiency
sum_load -= max_load * r.efficiency
norm_load = sum_load / efficiency_sum
else:
loads[r] = norm_load
max_load, r = max_loads[-1]
loads[r] = norm_load
return loads
#@-node:_distribute_len_loads
#@+node:test_allocation
def test_allocation(self, task, resource):
effort = task.__dict__.get("effort")
to_start = task._to_start
to_end = task._to_end
to_delta = task._to_delta
if task.performed_end:
start = to_start(max(task.performed_end,
task.root.calendar.now,
task.start))
else:
start = task.start
if task.root.has_actual_data and task.complete == 0:
start = max(start, to_start(task.root.calendar.now))
base_start = to_start(task.performed_start or task.start)
calc_load = lambda r: _calc_load(task, r)
loads = map(lambda r: (r, calc_load(r)), resource)
length = task.__dict__.get("length")
duration = task.__dict__.get("duration")
end = task.__dict__.get("end")
#@ << correct length >>
#@+node:<< correct length >>
if length is not None:
length = to_delta(max(length - (task.start - base_start), 0))
#@nonl
#@-node:<< correct length >>
#@nl
#@ << correct duration >>
#@+node:<< correct duration >>
if duration is not None:
delta = task.start.to_datetime() - base_start.to_datetime()
delta = to_delta(delta, True)
duration = to_delta(max(duration - delta, 0), True)
#@nonl
#@-node:<< correct duration >>
#@nl
#@ << check end >>
#@+node:<< check end >>
if end is not None:
length = end - start
if length <= 0: return False
#@nonl
#@-node:<< check end >>
#@nl
#@ << correct effort and (re)calculate length >>
#@+node:<< correct effort and (re)calculate length >>
if effort is not None:
effort -= task.performed_effort
effort = to_delta(max(effort, 0))
if effort <= 0: return False
if length is not None:
#if length and effort is set, the load will be calculated
length = length or task.calendar.minimum_time_unit
loads = self._distribute_len_loads(task, resource,
effort, length)
def calc_load(res):
return loads[res]
else:
#the length depends on the count of resources
factor = sum(map(lambda a: a[0].efficiency * a[1],
loads)) * task.efficiency
length = effort / factor
#@nonl
#@-node:<< correct effort and (re)calculate length >>
#@nl
#@ << set adjust_date and delta >>
#@+node:<< set adjust_date and delta >>
if length is not None:
adjust_date = lambda date: date
delta = to_delta(length).round()
else:
assert(duration is not None)
adjust_date = _to_datetime
delta = datetime.timedelta(minutes=duration)
#@nonl
#@-node:<< set adjust_date and delta >>
#@nl
# find the earliest start date
start, book_load\
= self.balance(task, start, delta, adjust_date,
calc_load, resource)
end = to_end(start + delta)
start = to_start(start)
if effort is None:
#length is frozen ==> a new effort will be calculated
factor = sum(map(lambda a: a[1], loads))
length = end - start
effort = to_delta(length * factor\
+ task.performed_effort).round()
return (end, book_load), resource, calc_load, start, effort
#@-node:test_allocation
#@+node:allocate
def allocate(self, task, state):
# now really book the resource
end_bl, resource, calc_load, start, effort = state
end = end_bl[0]
cal = task.root.calendar
to_start = task._to_start
to_end = task._to_end
to_delta = task._to_delta
task.start = task.performed_start \
and to_start(task.performed_start) \
or to_start(start)
task.end = end
task._unfreeze("length")
task._unfreeze("duration")
length = end - start
for r in resource:
book_load = calc_load(r)
work_time = to_delta(length * book_load).round()
r.book_task(task, start, end, book_load, work_time, False)
#the following lines are important to be exactly at this
#positions in that order:
# done and todo are dependend on:
# - the existence of effort (if effort was set or not set)
# - book_task (they can only be calculated, if the task is booked)
# - booked_resource (to get the booked tasks)
task.booked_resource = resource
task.done = task.done
task.todo = task.todo
task.length = end - task.start
task.effort = to_delta(effort + task.performed_effort)
#@-node:allocate
#@+node:balance
#now effort exists always
def balance(self, task, start, delta, adjust_date,
calc_load, resource):
book_load = max(map(lambda r: r.get_load(task.start, task.scenario), resource))
return start, book_load
#@-node:balance
#@-others
#@-node:class StrictAllocator
#@+node:class SmartAllocator
class SmartAllocator(StrictAllocator):
#@ @+others
#@+node:balance
def balance(self, task, start, delta, adjust_date,
calc_load, resource):
#find the earliest start date, at which all
#resources in the team are free
cal = task.root.calendar
to_start = task._to_start
start = adjust_date(start)
scenario = task.scenario
while True:
#we have finished, when all resources have the
#same next free start date
for r in resource:
max_load = _calc_maxload(task, r)
load = calc_load(r)
#find the next free time of the resource
s = r.find_free_time(start, delta, load, max_load, scenario)
if s != start:
s = to_start(s)
start = adjust_date(s)
break
else:
#only one resource
break
return start, 1.0
#@-node:balance
#@-others
#@-node:class SmartAllocator
#@+node:class SloppyAllocator
class SloppyAllocator(AllocationAlgorithm):
#@ @+others
#@+node:test_allocation
def test_allocation(self, task, resource):
if task.__dict__.has_key("effort"):
return self.test_allocation_effort(task, resource)
return self.test_allocation_length(task, resource)
#@-node:test_allocation
#@+node:test_allocation_length
def test_allocation_length(self, task, resource):
#length is frozen ==> effort will be calculated
to_start = task._to_start
to_end = task._to_end
to_delta = task._to_delta
end = task.end
if task.performed_end:
start = to_start(max(task.performed_end,
task.root.calendar.now,
start))
else:
start = task.start
base_start = to_start(task.performed_start or task.start)
length = to_delta(max(task.length - (start - base_start), 0))
sum_effort = 0
intervals = []
scenario = task.scenario
for r in resource:
date = start
max_load = _calc_maxload(task, r)
book_load = _calc_load(task, r)
while date < end:
#find free time intervals and add them for booking
endi, load = r.end_of_booking_interval(date, task)
endi = min(endi, end)
endi = to_end(endi)
if book_load <= 0:
#variable book_load ==> calc the maxmimal possible book_load >= (the given book_load)
used_book_load = - book_load
diff_load = max_load - load
if diff_load and diff_load >= book_load:
used_book_load = diff_load
else:
used_book_load = max_load
else:
used_book_load = book_load
if max_load - load >= used_book_load:
intervals.append((r, used_book_load, date, endi))
sum_effort = (endi - date) * used_book_load
date = to_start(endi)
return -sum_effort, end, resource, intervals
#@-node:test_allocation_length
#@+node:test_allocation_effort
def test_allocation_effort(self, task, resource):
#effort is frozen ==> length will be calculated
to_start = task._to_start
to_end = task._to_end
to_delta = task._to_delta
intervals = []
effort = task.__dict__.get("effort")
if task.performed_end:
next_date = to_start(max(task.performed_end,
task.root.calendar.now,
task.start))
else:
next_date = task.start
if task.root.has_actual_data and task.complete == 0:
next_date = max(next_date, to_start(task.root.calendar.now))
#walks chronologicly through the booking
#intervals of each resource, and reduces
#the effort for each free interval
#until it becomes 0
alloc_effort = effort
effort -= task.performed_effort
while effort > 0:
date = next_date
interval_resource = []
interval_end = to_start(sys.maxint)
factor = 0
for r in resource:
max_load = _calc_maxload(task, r)
book_load = _calc_load(task, r)
end, load = r.end_of_booking_interval(date, task)
interval_end = to_start(min(end, interval_end))
if book_load <= 0:
#variable book_load ==> calc the maxmimal possible book_load >= (the given book_load)
book_load = - book_load
diff_load = max_load - load
if diff_load and diff_load >= book_load:
book_load = diff_load
else:
book_load = max_load
if book_load + load <= max_load:
resource_factor = book_load * r.efficiency
interval_resource.append((r, book_load, resource_factor))
factor += resource_factor
next_date = interval_end
if factor:
factor *= task.efficiency
length = to_delta(effort / factor).round()
end = date + length
if interval_end >= end:
next_date = interval_end = end
effort = 0
book_end = end
else:
book_end = interval_end
length = book_end - date
minus_effort = length * factor
effort -= minus_effort
book_end = to_end(book_end)
intervals.append((date, book_end, length, interval_resource))
return next_date, alloc_effort, resource, intervals
#@-node:test_allocation_effort
#@+node:allocate
def allocate(self, task, state):
if task.__dict__.has_key("effort"): self.allocate_effort(task, state)
else: self.allocate_length(task, state)
#@-node:allocate
#@+node:allocate_length
def allocate_length(self, task, state):
# now really book the resource
neg_sum_effort, end, resource, intervals = state
cal = task.root.calendar
to_start = task._to_start
to_end = task._to_end
to_delta = task._to_delta
task.start = to_start(task.performed_start or task.start)
task.end = to_end(end)
task._unfreeze("length")
task._unfreeze("duration")
effort = 0
for r, load, s, e in intervals:
work_time = to_delta((e - s) * load).round()
effort += work_time
r.book_task(task, s, e, load, work_time, False)
#see comment at StrictAllocator.allocate
task.booked_resource = resource
task.done = task.done
task.todo = task.todo
task.effort = to_delta(effort + task.performed_effort).round()
#@-node:allocate_length
#@+node:allocate_effort
def allocate_effort(self, task, state):
# now really book the resource
end, effort, resource, intervals = state
to_start = task._to_start
to_end = task._to_end
to_delta = task._to_delta
task.start = task.performed_start \
and to_start(task.performed_start) \
or to_start(intervals[0][0])
task.end = to_end(end)
task._unfreeze("length")
task._unfreeze("duration")
for start, end, length, resources in intervals:
for r, load, factor in resources:
work_time = to_delta(length * load)
r.book_task(task, start, end, load, work_time, False)
task.booked_resource = resource
task.done = task.done
task.todo = task.todo
task.effort = to_delta(effort)
task.length = task.end - task.start
#@-node:allocate_effort
#@-others
#@-node:class SloppyAllocator
#@-others
_smart_allocator = SmartAllocator()
_sloppy_allocator = SloppyAllocator()
_strict_allocator = StrictAllocator()
_allocators = { SMART: _smart_allocator,
SLOPPY: _sloppy_allocator,
STRICT: _strict_allocator }
_allocator_strings = { SMART: "SMART",
SLOPPY: "SLOPPY",
STRICT: "STRICT" }
#@-node:Resource Allocators
#@+node:Load Calculators
#@+node:YearlyMax
def YearlyMax(value):
"""
Calculates a load parameter with a maximal yearly workload
"""
#@ << calculate calendar and time_diff >>
#@+node:<< calculate calendar and time_diff >>
try:
cal = me.calendar
except NameError:
cal = pcalendar._default_calendar
time_diff = cal.Minutes(value)
#@nonl
#@-node:<< calculate calendar and time_diff >>
#@nl
return float(time_diff) / \
(cal.working_days_per_year \
* cal.working_hours_per_day \
* 60)
#@nonl
#@-node:YearlyMax
#@+node:WeeklyMax
def WeeklyMax(value):
"""
Calculates a load parameter with a maximal weekly workload
"""
#@ << calculate calendar and time_diff >>
#@+node:<< calculate calendar and time_diff >>
try:
cal = me.calendar
except NameError:
cal = pcalendar._default_calendar
time_diff = cal.Minutes(value)
#@nonl
#@-node:<< calculate calendar and time_diff >>
#@nl
return float(time_diff) / \
(cal.working_days_per_week \
* cal.working_hours_per_day \
* 60)
#@-node:WeeklyMax
#@+node:MonthlyMax
def MonthlyMax(value):
"""
Calculates a load parameter with a maximal monthly workload
"""
#@ << calculate calendar and time_diff >>
#@+node:<< calculate calendar and time_diff >>
try:
cal = me.calendar
except NameError:
cal = pcalendar._default_calendar
time_diff = cal.Minutes(value)
#@nonl
#@-node:<< calculate calendar and time_diff >>
#@nl
return float(time_diff) / \
(cal.working_days_per_month \
* cal.working_hours_per_day \
* 60)
#@-node:MonthlyMax
#@+node:DailyMax
def DailyMax(value):
"""
Calculates a load parameter with a maximal daily workload
"""
#@ << calculate calendar and time_diff >>
#@+node:<< calculate calendar and time_diff >>
try:
cal = me.calendar
except NameError:
cal = pcalendar._default_calendar
time_diff = cal.Minutes(value)
#@nonl
#@-node:<< calculate calendar and time_diff >>
#@nl
return float(time_diff) / (cal.working_hours_per_day * 60)
#@-node:DailyMax
#@-node:Load Calculators
#@+node:Task
#@+node:class _TaskProperty
class _TaskProperty(object):
#@ @+others
#@+node:__init__
def __init__(self, method):
self.method = method
#@-node:__init__
#@+node:__get__
def __get__(self, instance, owner):
if not instance:
return None
return instance._wrap_attrib(self.method)
#@-node:__get__
#@-others
#@-node:class _TaskProperty
#@+node:class _RoundingTaskProperty
class _RoundingTaskProperty(object):
#@ @+others
#@+node:__init__
def __init__(self, method, name):
self.method = method
self.name = name
#@-node:__init__
#@+node:__get__
def __get__(self, instance, owner):
if not instance:
return None
result = instance._wrap_attrib(self.method).round()
if instance._is_frozen:
#correct the attrib to the rounded value
setattr(instance, self.name, result)
return result
#@-node:__get__
#@-others
#@-node:class _RoundingTaskProperty
#@+node:class Task
class Task(object):
#@ << description >>
#@+node:<< description >>
"""
This class represents a single task in the project tree. A task
can have other child tasks, or is a leaf of the tree. Resources
will be allocated only to leafes. You will never create task
objects by your self, they are created indirectly by Projects.
@var root:
Returns the root project task.
@var up:
Returns the parent task.
@var title:
Specifies an alternative more descriptive name for the task.
@var start:
The start date of the task. Valid values are expressions and
strings specifing a datatime
@var end:
The end date of the task. Valid values are expressions and
strings.
@var effort:
Specifies the effort needed to complete the task. Valid values
are expressions and strings. (Todo: What happens, in case of
specified performance data...)
@var length:
Specifies the time the task occupies the resources. This is
working time, not calendar time. 7d means 7 working days, not one
week. Whether a day is considered a working day or not depends on
the defined working hours and global vacations.
@var duration:
Specifies the time the task occupies the resources. This is
calendar time, not working time. 7d means one week.
@var buffer:
Specifies the time a task can be delayed, without moving dependend
milestones. A Task with a buffer S{<=} 0d is part of the critical
chain. This attribute is readonly.
@var complete:
Specifies what percentage of the task is already completed.
@var todo:
Specifies the effort, which needs to be done to complete a
task. This is another (indirect) way to specify the ME{complete}
attribute.
@var done:
Specifies the work effort, which has been already done. This
attribute is readonly.
@var estimated_effort:
Specifies the estimated_effort given by setting the effort property.
@var performed:
Specifies a list of actual working times performed on the task.
The format is: C{[ (resource, from, to, time), ... ]}
@var performed_work_time:
Specifies the sum of all working times. This attribute is
readonly.
@var performed_effort:
Specifies the complete effort of all working times. This attribute is
readonly.
@var performed_start:
The start date of the performed data.
@var performed_end:
The end date of the performed data.
@var performed_resource:
The resources who have already performed on the task. This attribute is readonly.
@var balance:
Specifies the resource allocation type. Possible values are
CO{STRICT}, CO{SLOPPY}, CO{SMART}.
@var resource:
Specifies the possible resources, that may be allocated for the
task.
@var booked_resource:
Specifies the allocated resources of a task. This attribute is
readonly.
@var load:
Specifies the daily load of a resource for an allocation of the
specified task. A load of 1.0 (default) means the resource is
allocated for as many hours as specified by
ME{working_hours_per_day}. A load of 0.5 means half that many
hours.
@var max_load:
Specify the maximal allowed load sum of all simultaneously
allocated tasks of a resource. A ME{max_load} of 1.0 (default)
means the resource may be fully allocated. A ME{max_load} of 1.3
means the resource may be allocated with 30% overtime.
@var efficiency:
The efficiency of a resource can be used for two purposes. First
you can use it as a crude way to model a team. A team of 5 people
should have an efficiency of 5.0. Keep in mind that you cannot
track the member of the team individually if you use this
feature. The other use is to model performance variations between
your resources.
@var milestone:
Specified if the task is a milestone. The possible values are
C{True} or "later". If the start date of the milestone is not
a valid working date, the milestone will appear at the previous
working date before the given start date. If "later" is specified
the milestone will appear at the next valid working date.
A milestone has always an effort of 0d.
@var priority:
Specifies a priority between 1 and 1000. A task with higher
priority is more likely to get the requested resources. The
default priority is 500.
@var children:
Specifies a list of all subtasks. A task without children is
called a leaf task index{leaf task} otherwise it is called a
parent task index{parent task}. This attribute is readonly.
@var depth:
Specifies the depth of the task within the hierachy. This
attribute is readonly.
@var index:
Specifies a structural index number. This attribute is readonly.
@var path:
Specifies the path.
@var copy_src:
Specifies the path to an other task. When you set this attribute,
all attributes (except of ME{start} and ME{end}) of copy_src will
be copied to the current task. This is usefull if you want to
define the same task, in diffent project definitions. It acts like
a task link.
@var scenario:
The scenario which is currently evaluated. This attribute is readonly.
@var dont_inherit:
A list of attribute names, which will be not inherited by
subtasks.
@var calendar:
Specifies the task calendar.
@var working_days_per_week:
Specifies the days within a working week. This value is used
internally to convert time differences from weeks to days. The
default value is 5 days.
@var working_days_per_month:
Specifies the days within a working month. This value is used
internally to convert time differences from months to days. The
default value is 20 days.
@var working_days_per_year:
Specifies the days within a working year. This value is used
internally to convert time differences from years to days The
default value is 200 days.
@var working_hours_per_day:
Specifies the hours within a working day. This value is used
internally to convert time differences from are entered in days to
hours. The default value is 8 hours.
@var minimum_time_unit:
Specifies the minimum resolution in minutes for the task
scheduling. The default value is 15 minutes.
@var vacation:
Specifies a public vacation for the calendar. This attribute is
specified as a list of date literals or date literal intervals. Be
aware that the end of an interval is excluded, i.e. it is the
first working date.
@var extra_work:
Specifies additional worktime. This attribute is specified as a
list of date literals or date literal intervals. Be aware that the
end of an interval is excluded, i.e. it is the first working date.
@var working_days:
Specifies the weekly working time within calendar. The format of
this attribute is: [ (day_range, time_range, ...), (day_range, time_range, ...), ... ].
day_range is a comma sperated string of week days. Valid values
are mon, tue, wed, thu, fri, sat, sun.
time_range is string specifing a time interval like
8:00-10:00. You can specified any number of time_ranges, following
the first.
@var now:
Specifies the current daytime and is a date literal. ME{now} is
used to calculate several task attributes.
"""
#@nonl
#@-node:<< description >>
#@nl
#@ << declarations >>
#@+node:<< declarations >>
# Variables for the gui interface
_date_completion = { "Date": 'Date("|")',
"max": "max(|)",
"min": "min(|)",
"Multi" : "Multi(|)" }
_delta_completion = { "Delta" : 'Delta("|")',
"Multi" : "Multi(|)" }
__attrib_completions__ = { \
"def NewTask():" : "def |NewTask():\n",
"milestone": 'milestone = True',
"start": 'start = ',
"end": 'end = ',
"effort": 'effort = "|"',
"duration": 'duration = "|"',
"length": 'length = "|"',
"todo": 'todo = "|"',
"done": 'done = "|"',
"title": 'title = "|"',
"load": 'load = ',
"max_load": 'max_load = ',
"efficiency": 'efficiency = ',
"complete": 'complete = ',
"copy_src": 'copy_src =',
"__constraint__": '__constraint__():\n|"',
"priority": 'priority = ',
"balance" : 'balance = ',
"resource": 'resource = ',
"performed" : 'performed = [(|resource, "2002-02-01", "2002-02-05", "2H"),]',
"add_attrib": "add_attrib(|'name', None)",
"working_days_per_week": 'working_days_per_week = ',
"working_days_per_month": 'working_days_per_month = ',
"working_days_per_year": 'working_days_per_year = ',
"working_hours_per_day": 'working_hours_per_day = ',
"minimum_time_unit": 'minimum_time_unit = ',
"vacation": 'vacation = [("|2002-02-01", "2002-02-05")]',
"extra_work": 'extra_work = [("|2002-02-01", "2002-02-05")]',
"working_days" : 'working_days = ["|mon,tue,wed,thu,fri", "8:00-12:00", "13:00-17:00"]',
"now": 'now = "|"',
"calendar" : 'calendar = ',
"#load": { "YearlyMax": 'YearlyMax("|")',
"WeeklyMax": 'WeeklyMax("|")',
"MonthlyMax": 'MonthlyMax("|")',
"DailyMax": 'DailyMax("|")',
"VariableLoad" : "VariableLoad(|)"},
"#max_load": { "YearlyMax": 'YearlyMax("|")',
"WeeklyMax": 'WeeklyMax("|")',
"MonthlyMax": 'MonthlyMax("|")',
"DailyMax": 'DailyMax("|")' },
"#start": _date_completion,
"#end": _date_completion,
"#effort": _delta_completion,
"#duration": _delta_completion,
"#length": _delta_completion,
"#todo": _delta_completion,
"#done": _delta_completion,
"#resource" : "get_resource_completions",
"#calendar" : "get_calendar_completions",
"#balance": { "STRICT": "STRICT",
"SMART": "SMART",
"SLOPPY": "SLOPPY" } }
formats = { "start" : "%x %H:%M",
"end" : "%x %H:%M",
"performed_start" : "%x %H:%M",
"performed_end" : "%x %H:%M",
"load" : "%.2f",
"length" : "%dd{ %HH}{ %MM}",
"effort" : "%dd{ %HH}{ %MM}",
"estimated_effort" : "%dd{ %HH}{ %MM}",
"performed_effort" : "%dd{ %HH}{ %MM}",
"duration" : "%dd{ %HH}{ %MM}",
"complete" : "%i",
"priority" : "%i",
"todo" : "%dd{ %HH}{ %MM}",
"done" : "%dd{ %HH}{ %MM}",
"efficiency" : "%.2f",
"buffer" : "%dd{ %HH}{ %MM}",
"costs" : "%.2f",
"sum" : "%.2f",
"max" : "%.2f",
"min" : "%.2f",
"milestone" : "%s",
"resource" : "%s",
"booked_resource" : "%s",
"performed_resource" : "%s" }
_constraint = None
_is_frozen = False
_is_compiled = False
_is_parent_referer = False
scenario = None # only for autocompletion
milestone = False
performed = ()
performed_resource = ()
booked_resource = ()
_performed_resource_length = ()
_resource_length = ()
dont_inherit = ()
performed_start = None
performed_end = None
performed_work_time = pcalendar.Minutes(0)
_setting_hooks = {}
#@nonl
#@-node:<< declarations >>
#@nl
#@ @+others
#@+node:__init__
def __init__(self, func, name, parent=None, index=1):
assert(type(func) == types.FunctionType)
func_key = (func.func_code, func.func_closure and id(func.func_closure))
try:
instrumented = instrumentation_cache[func_key]
except KeyError:
instrumented = _instrument(func)
instrumented.org_code = func_key
instrumentation_cache[func_key] = instrumented
func.task_func = instrumented # will be used in the gui
self._function = instrumented
self.name = name
self.up = parent
self.children = []
self._sources = {} # all tasks, I am linked to
self._dependencies = {} # all tasks that link to me
self._original_values = {}
self._properties = {} # a registry of all non standard attributes
self.title = self.name
self.root = parent and parent.root or self
self.scenario = self.root.scenario
self.path = parent and parent.path + "." + name or name
self.depth = len(self.path.split(".")) - 1
self.index = parent and ("%s.%i" % (parent.index, index)) \
or str(index)
if self.formats.has_key(name):
raise AttributeError("Task name '%s' hides attribute of parent." \
% name)
cal = self.calendar
self._to_delta = cal.Minutes
self._to_start = cal.StartDate
self._to_end = cal.EndDate
#@-node:__init__
#@+node:__iter__
def __iter__(self):
return _step_tasks(self)
#@-node:__iter__
#@+node:__repr__
def __repr__(self):
return "<Task %s>" % self.name
#@-node:__repr__
#@+node:__cmp__
def __cmp__(self, other):
try:
return cmp(self.path, other.path)
except Exception:
return cmp(self.path, other)
#@-node:__cmp__
#@+node:__getattr__
def __getattr__(self, name):
try:
if name[0] != "_":
parent = self.up
while parent:
if name not in parent.dont_inherit:
result = getattr(parent, name)
if not (isinstance(result, Task) and result.up == parent):
return result
parent = parent.up
except AttributeError:
pass
except IndexError:
raise AttributeError()
exception = AttributeError("'%s' is not a valid attribute of '%s'."
% (name, self.path))
exception.is_frozen = self._is_frozen
raise exception
#@-node:__getattr__
#@+node:_idendity_
def _idendity_(self): return self.root.id + self.path[4:]
#@-node:_idendity_
#@+node:_set_hook
def _set_hook(cls, attrib_name, function=None):
if function:
cls._setting_hooks[attrib_name] = function
else:
try:
del cls._setting_hooks[attrib_name]
except KeyError: pass
_set_hook = classmethod(_set_hook)
#@nonl
#@-node:_set_hook
#@+node:Public methods
#@+node:to_string
def to_string(self): return _StringConverter(self)
to_string = property(to_string)
#@nonl
#@-node:to_string
#@+node:indent_name
def indent_name(self, ident=" "):
"""
returns a indented name, according to its depth in the hierachy.
"""
return ident * self.depth + self.name
indent_name.attrib_method = True
indent_name.__call_completion__ = "indent_name()"
#@-node:indent_name
#@+node:costs
def costs(self, cost_name, mode="ep"):
"""
calculates the resource costs for the task.
cost_name is the name of a rate attribute of the reosurce
mode is character combination:
e calculates the estimated costs
p calculates the performed costs
==> pe calculates all costs
"""
if self.children:
return sum([ c.costs(cost_name, mode) for c in self.children])
costs = 0
if 'e' in mode:
costs += sum(map(lambda rl: getattr(rl[0], cost_name) * rl[1],
self._resource_length))
if 'p' in mode:
costs += sum(map(lambda rl: getattr(rl[0], cost_name) * rl[1],
self._performed_resource_length))
costs /= (60.0 * self.root.calendar.working_hours_per_day)
return round(costs, 2)
costs.attrib_method = True
costs.__call_completion__ = 'costs("|")'
#@-node:costs
#@+node:sum
def sum(self, attrib_name):
val = 0
if self.children:
val += sum(map(lambda c: c.sum(attrib_name), self.children))
if self.is_inherited(attrib_name):
return val
if attrib_name not in self.dont_inherit:
return val
return val + getattr(self, attrib_name)
sum.attrib_method = True
sum.__call_completion__ = 'sum("|")'
#@-node:sum
#@+node:min
def min(self, attrib_name):
if self.children:
return min(map(lambda c: c.min(attrib_name), self.children))
return getattr(self, attrib_name)
min.attrib_method = True
min.__call_completion__ = 'min("|")'
#@-node:min
#@+node:max
def max(self, attrib_name):
if self.children:
return max(map(lambda c: c.max(attrib_name), self.children))
return getattr(self, attrib_name)
max.attrib_method = True
max.__call_completion__ = 'max("|")'
#@-node:max
#@+node:all_resources
def all_resources(self):
result = self._all_resources_as_dict()
result = result.keys()
result.sort()
return result
#@-node:all_resources
#@+node:get_task
def get_task(self, path=None):
"""
Returns a task with the given path.
"""
if not path:
return self
names = path.split(".")
rest = ".".join(names[1:])
result = getattr(self, names[0], None)
return isinstance(result, Task) and result.get_task(rest) or None
#@-node:get_task
#@+node:snapshot
def snapshot(self, indent="", name=None):
text = indent + "def %s():\n" % (name or self.name)
indent += " "
for name in ("priority", "balance", "complete",
"milestone", "end", "start", "effort", "load"):
val = getattr(self, name, None)
if val is None:
continue
if name[0] == "_":
name = name[1:]
text += "%s%s = %s\n" % (indent, name, _as_string(val))
for name in self._properties:
if name.startswith("performed"): continue
val = getattr(self, name, None)
try:
if issubclass(val, resource.Resource): continue
except TypeError:
pass
text += "%s%s = %s\n" % (indent, name, _as_string(val))
resources = tuple(self._iter_booked_resources())
if resources:
text += "%sresource = \\\n" % indent
def make_resource(res):
return "%s %s" \
% (indent, res.snapshot())
text += "&\\\n".join(map(make_resource, resources)) + "\n"
def make_resource_booking(res):
def make_booking(booking):
return '%s (%s, "%s", "%s", "%sM"),' \
% (indent, res.name,
booking.book_start.strftime("%Y%m%d %H:%M"),
booking.book_end.strftime("%Y%m%d %H:%M"),
booking.work_time)
return "\n".join(map(make_booking, res.get_bookings(self)))
text += "%sperformed = [\n" % indent
text += "\n".join(map(make_resource_booking, resources)) + "]"
child_text = map(lambda c: c.snapshot(indent), self.children)
text += "\n\n"
text += "".join(child_text)
return text
#@-node:snapshot
#@+node:is_inherited
def is_inherited(self, attrib_name):
return not self.__dict__.has_key(attrib_name)
#@-node:is_inherited
#@+node:formatter
def formatter(self, attrib_name, arg=None, format=None):
"""returns a function which is able
to convert the value of the given attrib_name to a string"""
formats = self.formats
format = format or formats.get(attrib_name)
if attrib_name in ("start", "end", "length", "effort",
"done", "todo", "buffer", "estimated_effort",
"performed_effort", "performed_start", "performed_end"):
def save_strftime(v):
try:
return v.strftime(format)
#except AttributeError: some bug avoid catching this exception
except Exception:
return str(v)
return save_strftime
if attrib_name == "duration":
def save_strftime(v):
try:
return v.strftime(format, True)
except AttributeError:
return str(v)
return save_strftime
if attrib_name in ("booked_resource", "performed_resource"):
def get_resource_name(v):
title = getattr(v, "title", None)
if title: return title
return ", ".join([r.title for r in v])
return get_resource_name
if arg and attrib_name in ("costs", "sum", "max", "min"):
format = formats.get("%s(%s)" % (attrib_name, arg), format)
if format:
return lambda v: locale.format(format, v, True)
return str
#@-node:formatter
#@-node:Public methods
#@+node:Resource allocation Methods
#@+node:_all_resources_as_dict
def _all_resources_as_dict(self):
if self.children:
result = {}
for c in self.children:
result.update(c._all_resources_as_dict())
return result
if self.resource:
return dict(map(lambda r: (r, 1), self.resource.all_members()))
return {}
#@-node:_all_resources_as_dict
#@+node:_test_allocation
def _test_allocation(self, resource_state, allocator):
resource = self.resource._get_resources(resource_state)
if not resource:
return False
return allocator.test_allocation(self, resource)
#@-node:_test_allocation
#@+node:_allocate
def _allocate(self, state, allocator):
allocator.allocate(self, state)
#activate cache for done and todo
if self.start.to_datetime() > self.end.to_datetime():
#this can happen when performed effort are
#during non working time
tmp = self.start
self.start = self.end
self.end = tmp
for r in self.performed_resource:
r.correct_bookings(self)
self._resource_length = map(lambda r: (weakref.proxy(r), \
r.length_of(self)),
self._iter_booked_resources())
#@-node:_allocate
#@+node:_convert_performed
def _convert_performed(self, all_resources):
performed = self.performed
if not performed: return False
if not isinstance(performed, (tuple, list)) \
or not isinstance(performed[0], (tuple, list)) \
or not len(performed[0]) >= 3:
self._raise(TypeError("""The format of the performed attribute must be:
[( res_name, start_literal, end_literal, working_time ), ... ].
"""), "performed")
round_down_delta = self.root.calendar.minimum_time_unit / 2
round_down_delta = datetime.timedelta(minutes=round_down_delta)
def convert_item(index):
item = performed[index]
res, start, end = item[:3]
if isinstance(res, str):
found = filter(lambda r: r.name == res, all_resources)
if found: res = found[0]
try:
if not isinstance(res, (resource.Resource,
resource._MetaResource)):
raise ValueError("the resource '%s' is unknown." % res)
start = _to_datetime(start)
end = _to_datetime(end)
if len(item) > 3:
working_time = self._to_delta(item[3]).round()
else:
working_time = self._to_delta(end - start, True)
return ((res, start, end, working_time), index)
except Exception, exc:
self._raise(exc.__class__("Item %i: %s" \
% (index + 1, str(exc))),
"performed")
converted = dict(map(convert_item, range(len(performed))))
converted = converted.items()
converted.sort()
#check for overlapping items
last_res = None
for item, index in converted:
res, start, end, work_time = item
if last_res == res and start < last_end:
self._warn("Items %i, %i: %s and %s are overlapping." \
% (last_index + 1, index + 1,
str(performed[last_index]),
str(performed[index])),
"performed")
last_res = res
last_end = end
last_index = index
self._performed = map(lambda x: x[0], converted)
return True
#@-node:_convert_performed
#@+node:_allocate_performed
def _allocate_performed(self, performed):
if not performed: return
to_delta = self._to_delta
to_start = self._to_start
to_end = self._to_end
last = datetime.datetime.min
first = datetime.datetime.max
effort = 0
work_time_sum = 0
zero_minutes = to_delta(0)
minimum_time_unit = to_delta(self.calendar.minimum_time_unit)
summary = {}
for item in performed:
res, start, end, work_time = item
effort += work_time * self.efficiency * res.efficiency
work_time_sum += work_time
res = res()
ss, es, wts = summary.get(res, (datetime.datetime.max,
datetime.datetime.min,
zero_minutes))
summary[res] = (min(ss, start), max(es, end), wts + work_time)
for r, v in summary.iteritems():
start, end, work_time = v
assert(start.__class__ is datetime.datetime)
assert(end.__class__ is datetime.datetime)
#the booking limits should be inside the workingtime
#to display them correct in resource charts
cstart = to_start(start).to_datetime()
if cstart > start: cstart = to_end(start).to_datetime()
cend = to_end(end).to_datetime()
if cend < end: cend = to_start(end).to_datetime()
if self.root.is_snapshot:
delta = to_end(cend) - to_start(cstart)
else:
delta = to_delta(cend - cstart).round()
if not delta:
delta = minimum_time_unit
book_load = float(work_time) / delta
r().book_task(self, cstart, cend, book_load, work_time, True)
last = max(end, last)
first = min(start, first)
self._performed_resource_length = tuple([ (r, v[2]) for r, v in summary.iteritems() ])
self.performed_resource = tuple(summary.keys())
self.performed_end = last
self.performed_start = first
self.performed_effort = to_delta(effort)
self.performed_work_time = to_delta(work_time_sum)
self._check_completion()
#@-node:_allocate_performed
#@+node:_iter_booked_resources
def _iter_booked_resources(self):
result = dict(map(lambda r: (r, 1), self.performed_resource))
result.update(dict(map(lambda r: (r, 1), self.booked_resource)))
return result.iterkeys()
#@-node:_iter_booked_resources
#@-node:Resource allocation Methods
#@+node:Compile Methods
#@+node:_generate
def _generate(self, deferred=None):
do_raise = False
deferred = deferred or [ self ]
while deferred:
new_deferred = []
for task in deferred:
task._compile(new_deferred, do_raise)
do_raise = deferred == new_deferred
deferred = new_deferred
#@-node:_generate
#@+node:_recalc_properties
def _recalc_properties(self):
if not self._properties: return
self.__compile_function([], False, _MeProxyRecalc(self))
self._is_compiled = True
#@-node:_recalc_properties
#@+node:_compile
def _compile(self, deferred, do_raise):
self.dont_inherit = ()
self._constraint = None
self._original_values.clear()
self._properties.clear()
try:
self.__at_compile
#@ << raise child recursion error >>
#@+node:<< raise child recursion error >>
self._raise(RecursionError("A child defines a "\
"recursive definition at %s" % self.path))
#@-node:<< raise child recursion error >>
#@nl
except AttributeError:
self.__at_compile = self, ""
try:
self.__compile_function(deferred, do_raise, _MeProxy(self))
finally:
del self.__at_compile
for c in self.children:
if not c._is_compiled:
c._compile(deferred, do_raise)
if self._is_compiled:
self.__check_milestone()
self.__check_task()
self.root.has_actual_data |= self.__dict__.has_key("performed")
#@-node:_compile
#@+node:__compile_function
def __compile_function(self, deferred, do_raise, me_instance):
self._is_compiled = self._is_frozen
restore_globals = []
globals_ = self._function.func_globals
#@ << set function global values >>
#@+node:<< set function global values >>
def to_value_wrapper(a):
if isinstance(a, _ValueWrapper):
return a
return _ValueWrapper(a, [(None, None)])
def my_max(*args):
return max(map(to_value_wrapper, args))
def my_min(*args):
return min(map(to_value_wrapper, args))
globals_["me"] = me_instance
if self._is_compiled:
globals_["up"] = self.up
globals_["root"] = self.root
else:
globals_["up"] = _Path(self.up, "up")
globals_["root"] = _Path(self.root, "root")
globals_["Delta"] = self._to_delta
globals_["Date"] = self._to_start
globals_["max"] = my_max
globals_["min"] = my_min
globals_["add_attrib"] = me_instance.add_attrib
#@nonl
#@-node:<< set function global values >>
#@nl
#@ << set me in global functions >>
#@+node:<< set me in global functions >>
#@+at
# Is used for functions like YearlyMax, MonthlyMax, ....
#@-at
#@@code
for name in self._function.global_names:
try:
obj = globals_[name]
if isinstance(obj, types.FunctionType):
fg = obj.func_globals
if not fg.has_key("me") and "me" in obj.func_code.co_names:
restore_globals.append(fg)
fg["me"] = me_instance
except KeyError: continue
#@nonl
#@-node:<< set me in global functions >>
#@nl
try:
#@ << eval function >>
#@+node:<< eval function >>
if do_raise:
try:
self._function()
self._is_compiled = True
except _IncompleteError, e:
src = e.args[1]
if src is not self:
self.__at_compile = e.args[1:]
src._compile([], True)
raise
else:
try:
self._function()
self._is_compiled = True
except AttributeError, e:
#print "AttributeError:", e, self.name, e.is_frozen, do_raise
deferred.append(self)
except _IncompleteError:
#print "_IncompleteError:", id(self), self.name, do_raise
deferred.append(self)
except RecursionError:
self._is_parent_referer = True
deferred.append(self)
#@nonl
#@-node:<< eval function >>
#@nl
finally:
for fg in restore_globals:
del fg["me"]
#@-node:__compile_function
#@-node:Compile Methods
#@+node:Setting methods
#@+node:_set_attrib
def _set_attrib(self, name, value):
if value is _NEVER_USED_: return
try:
value = self._setting_hooks[name](self, name, value)
except KeyError: pass
if name == "__constraint__":
self._constraint = value
return
if type(value) == types.FunctionType:
if value.func_code.co_argcount == 0:
#@ << add child task >>
#@+node:<< add child task >>
try:
task = self.__dict__[value.func_name]
except KeyError:
task = Task(value, value.func_name, self, len(self.children) + 1)
self.children.append(task)
setattr(self, value.func_name, task)
return
#@nonl
#@-node:<< add child task >>
#@nl
if name[0] == "_":
#private vars will not be set
return
if isinstance(value, _Path):
value = value._task
set_method = getattr(self, "_set_" + name, None)
if set_method:
#@ << set standard attribute >>
#@+node:<< set standard attribute >>
if type(value) == types.DictionaryType:
self.root.all_scenarios.update(value.keys())
value = value.get(self.scenario, value["_default"])
self.__set_sources(name, value)
self._original_values[name] = value
set_method(_val(value))
#@nonl
#@-node:<< set standard attribute >>
#@nl
else:
#@ << set userdefined attribute >>
#@+node:<< set userdefined attribute >>
if callable( getattr(self.__class__, name, None)):
raise NameError('You may not use "%s" as attribute' % name)
setattr(self, name, value)
self._properties[name] = True
self.__set_sources(name, value)
#@nonl
#@-node:<< set userdefined attribute >>
#@nl
#@-node:_set_attrib
#@+node:read only attributes
#@+node:_set_name
def _set_name(self, value):
raise AttributeError("The attribute 'name' is readonly.")
#@nonl
#@-node:_set_name
#@+node:_set_done
def _set_done(self, value):
raise AttributeError("The attribute 'done' is readonly.")
#@nonl
#@-node:_set_done
#@+node:_set_performed_work_time
def _set_performed_work_time(self, value):
raise AttributeError("The attribute 'performed_work_time' is readonly.")
#@nonl
#@-node:_set_performed_work_time
#@+node:_set_booked_resource
def _set_booked_resource(self, value):
raise AttributeError("The attribute 'booked_resource' is readonly.")
#@nonl
#@-node:_set_booked_resource
#@+node:_set_performed_effort
def _set_performed_effort(self, value):
raise AttributeError("The attribute 'performed_effort' is readonly.")
#@nonl
#@-node:_set_performed_effort
#@+node:_set_children
def _set_children(self, value):
raise AttributeError("The attribute 'children' is readonly.")
#@nonl
#@-node:_set_children
#@+node:_set_depth
def _set_depth(self, value):
raise AttributeError("The attribute 'depth' is readonly.")
#@nonl
#@-node:_set_depth
#@+node:_set_index
def _set_index(self, value):
raise AttributeError("The attribute 'index' is readonly.")
#@nonl
#@-node:_set_index
#@+node:_set_scenario
def _set_scenario(self, value):
raise AttributeError("The attribute 'scenario' is readonly.")
#@nonl
#@-node:_set_scenario
#@+node:_set_buffer
def _set_buffer(self, value):
raise AttributeError("The attribute 'buffer' is readonly.")
#@nonl
#@-node:_set_buffer
#@-node:read only attributes
#@+node:_set_start
def _set_start(self, value):
self.__start_class = value.__class__
self.start = self._to_start(value).round()
#@-node:_set_start
#@+node:_set_end
def _set_end(self, value):
self.end = self._to_end(value)
#@-node:_set_end
#@+node:_set_max_load
def _set_max_load(self, max_load):
self.max_load = float(max_load)
#@-node:_set_max_load
#@+node:_set_load
def _set_load(self, load):
self.load = float(load)
#@-node:_set_load
#@+node:_set_length
def _set_length(self, value):
self.length = self._to_delta(value).round()
#@-node:_set_length
#@+node:_set_effort
def _set_effort(self, value):
self.effort = self._to_delta(value).round()
#@-node:_set_effort
#@+node:_set_duration
def _set_duration(self, value):
self.duration = self._to_delta(value, True).round()
#@-node:_set_duration
#@+node:_set_complete
def _set_complete(self, value):
self.complete = value
#@-node:_set_complete
#@+node:_set_done
def _set_done(self, value):
self.done = self._to_delta(value).round()
#@-node:_set_done
#@+node:_set_todo
def _set_todo(self, value):
self.todo = self._to_delta(value).round()
#@-node:_set_todo
#@+node:_set_milestone
def _set_milestone(self, value):
self.milestone = value
#@-node:_set_milestone
#@+node:_set_resource
def _set_resource(self, value):
if not value:
self.resource = None
return
if isinstance(value, (tuple, list)):
value = reduce(lambda a, b: a & b, value)
self.resource = value()
#@-node:_set_resource
#@+node:_set_copy_src
def _set_copy_src(self, value):
if isinstance(value, _MeProxy):
raise RuntimeError("Cannot copy me.")
if not value._is_compiled:
raise _IncompleteError(value, "copy_src")
if value.resource and not self.resource:
self.resource = value.resource
if value.balance and not self.balance:
self.balance = value.balance
copy_parms = ("priority", "todo", "complete",
"_constraint", "load", "length",
"effort", "duration")
for p in copy_parms:
v = value.__dict__.get(p)
if v: setattr(self, p, v)
self.copy_src = value
self._properties.update(value._properties)
for k in value._properties.iterkeys():
setattr(self, k, getattr(value, k))
#@-node:_set_copy_src
#@+node:__set_sources
def __set_sources(self, attrib_name, value):
#@ << find references >>
#@+node:<< find references >>
def make_ref(val):
if isinstance(val, _ValueWrapper):
return val._ref
if isinstance(val, Task):
return [(val, "")]
return []
if isinstance(value, (list, tuple)):
sources = _refsum(map(make_ref, value))
else:
sources = make_ref(value)
#@nonl
#@-node:<< find references >>
#@nl
if not sources: return
#track only dependcies within the same project
root = self.root
sources = [ task.path + "." + attrib
for task, attrib in sources
if task and task.root is root ]
self._sources[attrib_name] = tuple(sources)
attr_path = self.path + "." + attrib_name
#set dependencies of my sources
for d in sources:
path, attrib = _split_path(d)
task = self.get_task(path)
r_d = task._dependencies
d_l = r_d.setdefault(attrib, {})
d_l[attr_path] = True
#@-node:__set_sources
#@+node:Calendar Setters
#@+node:_set_calendar
def _set_calendar(self, value):
self.calendar = value
self._to_delta = value.Minutes
self._to_start = value.StartDate
self._to_end = value.EndDate
self.__renew_dates()
#@-node:_set_calendar
#@+node:__renew_dates
def __renew_dates(self):
for attrib in ("effort", "start", "end", "length", "todo"):
try:
self._set_attrib(attrib, self._original_values[attrib])
except KeyError:
pass
#@-node:__renew_dates
#@+node:__make_calendar
def __make_calendar(self):
if not "calendar" in self.__dict__:
cal = self.calendar = self.calendar.clone()
self._to_delta = cal.Minutes
self._to_start = cal.StartDate
self._to_end = cal.EndDate
#@nonl
#@-node:__make_calendar
#@+node:_set_vacation
def _set_vacation(self, value):
self.__make_calendar()
self.calendar.set_vacation(value)
self._properties["vacation"] = True
self.vacation = value
self.__renew_dates()
#@-node:_set_vacation
#@+node:_set_extra_work
def _set_extra_work(self, value):
self.__make_calendar()
self.calendar.set_extra_work(value)
self._properties["extra_work"] = True
self.extra_work = value
self.__renew_dates()
#@-node:_set_extra_work
#@+node:_set_working_days
def _set_working_days(self, value):
if type(value[0]) is str:
value = (value, )
self.working_days = value
self._properties["working_days"] = True
self.__make_calendar()
for v in value:
day_range = v[0]
tranges = tuple(v[1:])
self.calendar.set_working_days(day_range, *tranges)
self.__renew_dates()
#@nonl
#@-node:_set_working_days
#@+node:_set_minimum_time_unit
def _set_minimum_time_unit(self, value):
self.__make_calendar()
self.calendar.minimum_time_unit = value
self._properties["minimum_time_unit"] = True
#@-node:_set_minimum_time_unit
#@+node:_get_minimum_time_unit
def _get_minimum_time_unit(self):
return self.calendar.minimum_time_unit
minimum_time_unit = property(_get_minimum_time_unit)
#@-node:_get_minimum_time_unit
#@+node:_set_working_days_per_week
def _set_working_days_per_week(self, value):
self.__make_calendar()
self.calendar.working_days_per_week = value
self._properties["working_days_per_week"] = True
#@-node:_set_working_days_per_week
#@+node:_get_working_days_per_week
def _get_working_days_per_week(self):
return self.calendar.working_days_per_week
working_days_per_week = property(_get_working_days_per_week)
#@-node:_get_working_days_per_week
#@+node:_set_working_days_per_month
def _set_working_days_per_month(self, value):
self.__make_calendar()
self.calendar.working_days_per_month = value
self._properties["working_days_per_month"] = True
#@-node:_set_working_days_per_month
#@+node:_get_working_days_per_month
def _get_working_days_per_month(self):
return self.calendar.working_days_per_month
working_days_per_month = property(_get_working_days_per_month)
#@-node:_get_working_days_per_month
#@+node:_set_working_days_per_year
def _set_working_days_per_year(self, value):
self.__make_calendar()
self.calendar.working_days_per_year = value
self._properties["working_days_per_year"] = True
#@-node:_set_working_days_per_year
#@+node:_get_working_days_per_year
def _get_working_days_per_year(self):
return self.calendar.working_days_per_year
working_days_per_year = property(_get_working_days_per_year)
#@-node:_get_working_days_per_year
#@+node:_set_working_hours_per_day
def _set_working_hours_per_day(self, value):
self.__make_calendar()
self.calendar.working_hours_per_day = value
self._properties["set_working_hours_per_day"] = True
#@-node:_set_working_hours_per_day
#@+node:_get_working_hours_per_day
def _get_working_hours_per_day(self):
return self.calendar.working_hours_per_day
working_hours_per_day = property(_get_working_hours_per_day)
#@-node:_get_working_hours_per_day
#@+node:_set_now
def _set_now(self, value):
proxy = weakref.proxy
self.calendar.now = _to_datetime(value)
#@-node:_set_now
#@-node:Calendar Setters
#@-node:Setting methods
#@+node:Freezer Methods
#@+node:_unfreeze
def _unfreeze(self, attrib_name):
if self.__dict__.has_key(attrib_name):
del self.__dict__[attrib_name]
#@-node:_unfreeze
#@+node:_wrap_attrib
def _wrap_attrib(self, method):
attrib_name = method.__name__[7:]
recursion_attrib = "_rec" + attrib_name
try:
dest, dattr = self.__at_compile
raise RecursionError("Recursive definition of %s(%s) and %s(%s)." \
% (self.path, attrib_name, dest.path, dattr))
except AttributeError: pass
if not self._is_compiled:
raise _IncompleteError(self, attrib_name)
try:
getattr(self, recursion_attrib)
raise RecursionError(self, attrib_name)
except AttributeError: pass
setattr(self, recursion_attrib, True)
try:
result = method(self)
if self._is_frozen:
setattr(self, attrib_name, result)
return result
finally:
delattr(self, recursion_attrib)
#@-node:_wrap_attrib
#@+node:_find_frozen
def _find_frozen(self, attrib_name, default=None):
value = self.__dict__.get(attrib_name)
if value is not None:
return value
up = self.up
return up and up._find_frozen(attrib_name) or default
#@-node:_find_frozen
#@-node:Freezer Methods
#@+node:Calculation Methods
#@+node:__calc_performed_effort
def __calc_performed_effort(self):
if self.children:
return self._to_delta(sum([ t.performed_effort for t in self.children ]))
return pcalendar.Minutes(0)
performed_effort = _TaskProperty(__calc_performed_effort)
#@-node:__calc_performed_effort
#@+node:__calc_estimated_effort
def __calc_estimated_effort(self):
if self.children:
return self._to_delta(sum([ t.estimated_effort for t in self.children ]))
return self.effort
estimated_effort = _TaskProperty(__calc_estimated_effort)
#@-node:__calc_estimated_effort
#@+node:__calc_start
def __calc_start(self):
to_start = self._to_start
if self.children:
try:
return min([ to_start(t.start) for t in self.children
if not t._is_parent_referer ])
except ValueError:
#@ << raise child recursion error >>
#@+node:<< raise child recursion error >>
self._raise(RecursionError("A child defines a "\
"recursive definition at %s" % self.path))
#@-node:<< raise child recursion error >>
#@nl
try:
end = self.end
duration = self.__dict__.get("duration")
if duration is not None:
start = end.to_datetime() - datetime.timedelta(minutes=duration)
else:
start = end - self.length
return to_start(start)
except RecursionError:
start = self._find_frozen("start")
if start: return to_start(start)
#@ << raise recursion error >>
#@+node:<< raise recursion error >>
raise RecursionError("you have to specify a "\
"start or an end at %s" % self.path)
#@nonl
#@-node:<< raise recursion error >>
#@nl
start = _TaskProperty(__calc_start)
#@-node:__calc_start
#@+node:__calc_end
def __calc_end(self):
to_end = self._to_end
if self.children:
try:
return max([ to_end(t.end) for t in self.children
if not t._is_parent_referer ])
except ValueError:
#@ << raise child recursion error >>
#@+node:<< raise child recursion error >>
self._raise(RecursionError("A child defines a "\
"recursive definition at %s" % self.path))
#@-node:<< raise child recursion error >>
#@nl
try:
start = self.start
duration = self.__dict__.get("duration")
if duration is not None:
end = start.to_datetime() + datetime.timedelta(minutes=duration)
else:
end = start + self.length
return to_end(end)
except RecursionError:
end = self._find_frozen("end")
if end: return to_end(end)
#@ << raise recursion error >>
#@+node:<< raise recursion error >>
raise RecursionError("you have to specify a "\
"start or an end at %s" % self.path)
#@nonl
#@-node:<< raise recursion error >>
#@nl
end = _TaskProperty(__calc_end)
#@-node:__calc_end
#@+node:__calc_load
def __calc_load(self):
length = self.__dict__.get("length")
effort = self.__dict__.get("effort")
if length is not None and effort is not None:
return float(effort) / (float(length) or 1.0)
load = self._find_frozen("load")
if load is not None: return load
return 1.0
load = _TaskProperty(__calc_load)
#@-node:__calc_load
#@+node:__calc_length
def __calc_length(self):
effort = self.__dict__.get("effort")
if effort is None:
return self.end - self.start
return self._to_delta(effort / self.load)
length = _RoundingTaskProperty(__calc_length, "length")
#@-node:__calc_length
#@+node:__calc_duration
def __calc_duration(self):
return self._to_delta(self.end.to_datetime()\
- self.start.to_datetime(), True)
duration = _TaskProperty(__calc_duration)
#@-node:__calc_duration
#@+node:__calc_effort
def __calc_effort(self):
if self.children:
return self._to_delta(sum([ t.effort for t in self.children ]))
return self._to_delta(self.length * self.load)
effort = _RoundingTaskProperty(__calc_effort, "effort")
#@-node:__calc_effort
#@+node:__calc_done
def __calc_done(self):
if self.children:
dones = map(lambda t: t.done, self.children)
return self._to_delta(sum(dones))
res = self._iter_booked_resources()
done = sum(map(lambda r: r.done_of(self), res))
complete = self.__dict__.get("complete")
todo = self.__dict__.get("todo")
if not done and complete == 100 or todo == 0:
#if now is not set
done = self.effort
return self._to_delta(done)
done = _TaskProperty(__calc_done)
#@-node:__calc_done
#@+node:__calc_buffer
def __calc_buffer(self):
if self.children:
return self._to_delta(min(map(lambda t: t.buffer, self.children)))
scenario = self.scenario
end = self.end
old_end = self.__dict__.get("end")
#@ << find all tasks, that depend on my end >>
#@+node:<< find all tasks, that depend on my end >>
deps = { }
task = self
while task:
deps.update(task._dependencies.get("end", {}))
task = task.up
#@nonl
#@-node:<< find all tasks, that depend on my end >>
#@nl
#@ << define unfreeze_parents >>
#@+node:<< define unfreeze_parents >>
def unfreeze_parents():
task = self.up
while task:
task._unfreeze("end")
task = task.up
#@nonl
#@-node:<< define unfreeze_parents >>
#@nl
buffers = [ ]
for d in deps.keys():
path, attrib = _split_path(d)
if attrib != "start":
continue
#@ << calculate buffer to descendant 'd' >>
#@+node:<< calculate buffer to descendant 'd' >>
unfreeze_parents()
# the following code considers a expressione like
# start = predecessor.end + Delta("1d") the buffer
# calculation must be aware of the 1d delay.
# (therefore a simple succ_start - end would be
# incorrect)
# Solution: Simluate a later end and calculate the
# real delay
succ_task = self.get_task(path)
simulated_task = Task(succ_task._function,
succ_task.name,
succ_task.up, 1)
current_start = succ_task.start
simulated_end = current_start
self.end = current_start
simulated_task._generate()
simulated_start = simulated_task.start
unfreeze_parents()
if old_end: self.end = old_end
else: self._unfreeze("end")
del simulated_task
current_delay = current_start - end
simulated_delay = simulated_start - simulated_end
real_delay = current_delay - simulated_delay
try:
buffer_ = real_delay + succ_task.buffer
except RecursionError, err:
self._raise(err)
#@nonl
#@-node:<< calculate buffer to descendant 'd' >>
#@nl
buffers.append(buffer_)
if not buffer_:
break
if buffers:
return self._to_delta(min(buffers))
return not self.milestone \
and self.root.end - end \
or self._to_delta(0)
buffer = _TaskProperty(__calc_buffer)
#@-node:__calc_buffer
#@+node:__calc_complete
def __calc_complete(self):
done = self.done
todo = self.todo
return int(100.0 * done / ((done + todo) or 1))
complete = _TaskProperty(__calc_complete)
#@-node:__calc_complete
#@+node:__calc_todo
def __calc_todo(self):
complete = self.__dict__.get("complete")
if complete:
# effort = done + todo
# done done
# complete = ------ ==> todo = -------- - done
# effort complete
complete = float(complete)
done = self.done
if done:
done = float(done)
return self._to_delta(done * 100.0 / complete - done)
return self._to_delta(self.effort * complete / 100.0)
if self.children:
todos = map(lambda t: t.todo, self.children)
return self._to_delta(sum(todos))
todo = sum(map(lambda r: r.todo_of(self), self.booked_resource))
return self._to_delta(max(todo, self.effort - self.done))
todo = _TaskProperty(__calc_todo)
#@-node:__calc_todo
#@-node:Calculation Methods
#@+node:Check Methods
#@+node:__check_task
def __check_task(self):
if self.children: return
start = self._find_frozen("start")
end = self._find_frozen("end")
if not (start or end):
self._raise(ValueError("You must specify either a"\
" start or an end attribute"))
if start and end: return
length = self.__dict__.get("length")
duration = self.__dict__.get("duration")
effort = self.__dict__.get("effort")
if not (effort or length or duration):
#set a default value
self._set_effort("1d")
#self._raise(ValueError("You must specify either a"\
# " length or a duration or "\
# "an effort attribute"))
#@-node:__check_task
#@+node:__check_milestone
def __check_milestone(self):
if not self.milestone: return
self.length = self._to_delta(0)
start = self.__dict__.get("start")
if not start:
self._raise(ValueError("Milestone must have start attribute"),
"milstone")
if self.__start_class.__name__ == "edt":
#the milestone is probably dependent on the end date of
#an other task (see edt in pcalendar) ==> start at the end date
self.start = self.end = self._to_end(self.start)
else:
self.start = self.end = self._to_start(self.start)
#@-node:__check_milestone
#@+node:_check_completion
def _check_completion(self):
if not self.performed_effort: return
if self.root.is_snapshot: return
# allocation is not done yet ==> self.todo, self.done,
# self.complete cannot be calculated
if self._find_frozen("complete", 0) < 100 \
and self.__dict__.get("todo", 1) > 0:
return
start = self.performed_start
end = self.performed_end
#ensure that self.start.to_datetime() < self.end.to_datetime()
cstart = self._to_start(start)
if cstart.to_datetime() > start: cstart = self._to_end(start)
cend = self._to_end(end)
if cend.to_datetime() < end: cend = self._to_start(end)
self.start = cstart
self.end = cend
if self.performed_effort != self.effort:
self.estimated_effort = self.effort
self.effort = self.performed_effort
#@-node:_check_completion
#@+node:check
def check(self):
if self._constraint and self._is_compiled:
globals_ = self._function.func_globals
globals_["me"] = self
globals_["up"] = self.up
globals_["root"] = self.root
globals_["assert_"] = self.__assert
self._constraint()
#@-node:check
#@-node:Check Methods
#@+node:Error Methods
#@+node:__assert
def __assert(self, value):
if not value:
warnings.warn('Assertion in scenario: "%s".' % self.scenario,
RuntimeWarning, 2)
#@-node:__assert
#@+node:_warn
def _warn(self, message, attrib=None, level=2):
self.__compile_function([], True, _MeProxyWarn(self, attrib, message))
#@-node:_warn
#@+node:_raise
def _raise(self, exc, attrib=None):
self.__compile_function([], True, _MeProxyError(self, attrib, exc))
raise exc
#@-node:_raise
#@-node:Error Methods
#@-others
#@nonl
#@-node:class Task
#@-node:Task
#@+node:Projects
#@+node:class _ProjectBase
class _ProjectBase(Task):
"""
Base class for all projects.
"""
#@ << class _ProjectBase declarations >>
#@+node:<< class _ProjectBase declarations >>
__attrib_completions__ = { }
__attrib_completions__.update(Task.__attrib_completions__)
del __attrib_completions__["milestone"] #project cannot be milestones
priority = 500
efficiency = 1.0
max_load = 1.0
balance = 0
resource = None
copy_src = None
has_actual_data = False
is_snapshot = False
#@-node:<< class _ProjectBase declarations >>
#@nl
#@ @+others
#@+node:__init__
def __init__(self, top_task, scenario="_default", id=""):
self.calendar = pcalendar.Calendar()
Task.__init__(self, top_task, top_task.func_name)
self.id = id or self.name
self.scenario = scenario
self.all_scenarios = set(("_default",))
self.path = "root"
self._globals = top_task.func_globals.copy()
self._generate()
#@-node:__init__
#@+node:_idendity_
def _idendity_(self): return self.id
#@-node:_idendity_
#@+node:_restore_globals
def _restore_globals(self):
self._function.func_globals.clear()
self._function.func_globals.update(self._globals)
del self._globals
#@-node:_restore_globals
#@+node:free
def free(self):
all_resources = self.all_resources()
for r in all_resources:
r().unbook_tasks_of_project(self.id, self.scenario)
for t in self:
t.booked_resource = ()
return all_resources
#@-node:free
#@+node:_get_balancing_list
def _get_balancing_list(self):
try:
cached_list = balancing_cache[self._function.org_code]
if len(cached_list) != len(tuple(self)):
# different scenarios can have different tasks
raise KeyError()
except KeyError:
cached_list = _build_balancing_list(self)
balancing_cache[self._function.org_code] = cached_list
else:
cached_list = [ self.get_task(t.path) for t in cached_list ]
return cached_list
#@-node:_get_balancing_list
#@+node:snapshot
def snapshot(self, indent="", name=None):
text = Task.snapshot(self, indent, name)
lines = text.splitlines(True)
indent += " "
def make_resource(r):
return '%sclass %s(Resource): title = "%s"\n' \
% (indent, r.name, r.title)
now = datetime.datetime.now().strftime("%x %H:%M")
resource_text = map(lambda r: make_resource(r), self.all_resources())
lines.insert(1, "%sfrom faces import Resource\n" % indent)
lines.insert(2, "".join(resource_text) + "\n")
lines.insert(3, '%snow = "%s"\n' % (indent, now))
lines.insert(4, '%sis_snapshot = True\n' % indent)
return "".join(lines)
#@-node:snapshot
#@-others
#@-node:class _ProjectBase
#@+node:class Project
class Project(_ProjectBase):
"""
Generates a Project without allocating resources.
@param top_task: Specifies the highest function of a project definiton.
@param scenario: Specifies the name of the scenario which should be scheduled.
@param id: Specifiess a unique idenfication name to distinguish the project from
other projects in the resource database. The default value for id
is the name of top_task.
"""
#@ << class Project declarations >>
#@+node:<< class Project declarations >>
__call_completion__ = 'Project(|top_task, scenario="_default", id=None)'
#@-node:<< class Project declarations >>
#@nl
#@ @+others
#@+node:__init__
def __init__(self, top_task, scenario="_default", id=None):
_ProjectBase.__init__(self, top_task, scenario, id)
no_snapshot = not self.is_snapshot
for t in self:
t._is_frozen = True
t._recalc_properties()
no_snapshot and t.check()
self._restore_globals()
#@-node:__init__
#@-others
#@-node:class Project
#@+node:class _AllocationPoject
class _AllocationPoject(_ProjectBase):
#@ @+others
#@+node:unfreeze_parents
def unfreeze_parents(self):
if self.has_actual_data:
for t in filter(lambda t: t.children, self):
if not t._original_values.has_key("start"): t._unfreeze("start")
if not t._original_values.has_key("end"): t._unfreeze("end")
#@-node:unfreeze_parents
#@-others
#@-node:class _AllocationPoject
#@+node:class BalancedProject
class BalancedProject(_AllocationPoject):
"""
Generates a project with allocated resources. The tasks are balanced
to fit the resources load conditions.
"""
#@ << class BalancedProject declarations >>
#@+node:<< class BalancedProject declarations >>
__call_completion__ = """BalancedProject(|top_task, scenario="_default",
id=None, balance=SMART, performed=None)"""
#@-node:<< class BalancedProject declarations >>
#@nl
#@ @+others
#@+node:__init__
def __init__(self, top_task, scenario="_default",
id=None, balance=SMART, performed=None):
_AllocationPoject.__init__(self, top_task, scenario, id)
self.balance = balance
if performed:
self._distribute_performed(performed)
self.has_actual_data = True
no_snapshot = not self.is_snapshot
if no_snapshot:
self.allocate()
else:
self.allocate_snapshot()
for t in self:
t._is_frozen = True
t._recalc_properties()
no_snapshot and t.check()
self._restore_globals()
#@nonl
#@-node:__init__
#@+node:allocate_snapshot
def allocate_snapshot(self):
all_resources = self.free()
scenario = self.scenario
has_actual_data = True
for t in self:
if not t.resource or t.milestone or t.children:
continue
t._convert_performed(all_resources)
t._allocate_performed(t._performed)
#@-node:allocate_snapshot
#@+node:allocate
def allocate(self):
all_resources = self.free()
balancing_list = self._get_balancing_list()
scenario = self.scenario
#for t in balancing_list:
# print t.path
for t in balancing_list:
t._compile([], True)
if not t.resource or t.milestone or t.children:
continue
if t._convert_performed(all_resources):
has_actual_data = True
try:
t._allocate_performed(t._performed)
except AttributeError:
pass
allocator = _allocators[t.balance]
min_val = None
min_state = None
for p in range(t.resource._permutation_count()):
state = t._test_allocation(p, allocator)
if not state: continue
to_minimize = state[0]
if not min_val or min_val > to_minimize:
min_val = to_minimize
min_state = state
if min_state:
t._allocate(min_state, allocator)
elif t.performed_start:
# t could not be allocated ==>
# performance data holds all information
t.start = t._to_start(t.performed_start)
t.end = t._to_end(t.performed_end)
self.unfreeze_parents()
#@-node:allocate
#@+node:_distribute_performed
def _distribute_performed(self, performed):
project_id = self._idendity_()
plen = len(project_id)
performed = filter(lambda item: item[0].startswith(project_id),
performed)
performed.sort()
task = None
for item in performed:
path = item[0]
rpath = "root" + path[plen:]
task = self.get_task(rpath)
if not task:
#@ << extract task in activity path >>
#@+node:<< extract task in activity path >>
#@+at
# A performed path can have sub activities appended to the
# task path.
# like:
#
# root.parent1.parent2.task.subactivity
#
# here rhe correct task path is:
#
# root.parent1.parent2.task
#
#@-at
#@@code
orpath = rpath
while not task:
#path can specify a sub module
#find the correct path to the module
try:
last_dot = rpath.rindex(".", 0, len(rpath))
except ValueError:
break
rpath = rpath[:last_dot]
task = self.get_task(rpath)
item = list(item)
item.append(orpath[len(rpath):])
#@nonl
#@-node:<< extract task in activity path >>
#@nl
if not task or task.children:
self._warn("The performance data contain "
"a task with id '%s'. But such "
"a task does not exist in your "
"project." % path)
continue
if not isinstance(task.performed, list):
task.performed = list(task.performed)
task.performed.append(item[1:])
#@nonl
#@-node:_distribute_performed
#@-others
#@-node:class BalancedProject
#@+node:class AdjustedProject
class AdjustedProject(_AllocationPoject):
"""
Generates a project with allocated resources. The tasks are
adjusted to the actual tracking data and balanced to fit the
resources load conditions.
"""
#@ << class AdjustedProject declarations >>
#@+node:<< class AdjustedProject declarations >>
__call_completion__ = 'AdjustedProject(|base_project)'
#@-node:<< class AdjustedProject declarations >>
#@nl
#@ @+others
#@+node:__init__
def __init__(self, base_project):
_AllocationPoject.__init__(self, base_project._function,
base_project.scenario,
base_project.id)
self.balance = base_project.balance
self.has_actual_data = base_project.has_actual_data
self.allocate(base_project)
for t in self:
t._is_frozen = True
t._recalc_properties()
t.check()
self._restore_globals()
#@-node:__init__
#@+node:allocate
def allocate(self, base):
balancing_list = self._get_balancing_list()
scenario = self.scenario
cal = self.calendar
now = cal.now
#for t in balancing_list:
# print t.path
#@ << free the resources, we have to rebook >>
#@+node:<< free the resources, we have to rebook >>
for t in balancing_list:
src = base.get_task(t.path)
if src.end > now or src.complete < 100:
for r in src._iter_booked_resources():
r.unbook_task(src)
#@nonl
#@-node:<< free the resources, we have to rebook >>
#@nl
for t in balancing_list:
src = base.get_task(t.path)
if src.end <= now and src.complete == 100:
#@ << copy the attribs of complete tasks >>
#@+node:<< copy the attribs of complete tasks >>
t.effort = src.effort
t.load = src.load
t.start = src.start
t.end = src.end
t.done = src.done
t.todo = src.todo
t.booked_resource = src.booked_resource
t.performed_resource = src.performed_resource
t._unfreeze("length")
t._unfreeze("duration")
#@nonl
#@-node:<< copy the attribs of complete tasks >>
#@nl
continue
t._compile([], True)
if not t.resource or t.milestone or t.children:
continue
# now allocate the uncomplete tasks
#@ << allocate performed data >>
#@+node:<< allocate performed data >>
try:
t._performed = src._performed
t._allocate_performed(t._performed)
except AttributeError:
pass
#@nonl
#@-node:<< allocate performed data >>
#@nl
allocator = _allocators[t.balance]
if src.start >= now:
#@ << allocate tasks, that have not begun yet >>
#@+node:<< allocate tasks, that have not begun yet >>
min_val = None
min_state = None
for p in range(t.resource._permutation_count()):
state = t._test_allocation(p, allocator)
if not state: continue
to_minimize = state[0]
if not min_val or min_val > to_minimize:
min_val = to_minimize
min_state = state
if min_state:
t._allocate(min_state, allocator)
elif t.performed_start:
t.start = t._to_start(t.performed_start)
t.end = t._to_end(t.performed_end)
#@-node:<< allocate tasks, that have not begun yet >>
#@nl
else:
#@ << allocate tasks, that are allready at work >>
#@+node:<< allocate tasks, that are allready at work >>
if t.__dict__.has_key("effort"):
t.effort = t._to_delta(src.done + src.todo).round()
resource = src.booked_resource or src.performed_resource
state = allocator.test_allocation(t, resource)
if state:
t._allocate(state, allocator)
#@nonl
#@-node:<< allocate tasks, that are allready at work >>
#@nl
self.unfreeze_parents()
#@nonl
#@-node:allocate
#@-others
#@-node:class AdjustedProject
#@-node:Projects
#@-others
"""
Atttribute mit Bedeutung:
calendar
--------
minimum_time_unit |int in minutes|
working_days_per_week |int in days |
working_days_per_month|int in days |
working_days_per_year |int in days |
working_hours_per_day |int in hours |
vacation | [ one_day, (from, to), .. ] |
working_days
now
Task
-----
load
start
end
length
effort
duration
resource
booked_resource
milestone
complete
done
todo
priority
efficiency
buffer
children
depth
index
path
dont_inherit
performed_effort
performed_end
performed_start
sum()
min()
max()
costs()
indent_name()
max_load
copy_src (set: copy all attributes of another task
get: reference of copy)
balance
for gantt
-----
line
accumulate
Resource
----------
efficiency
load
vacation
max_load
"""
#@-node:@file task.py
#@-leo
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
agpl-3.0
|
mjfarmer/scada_py
|
env/lib/python2.7/site-packages/twisted/internet/_win32serialport.py
|
19
|
4617
|
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Serial port support for Windows.
Requires PySerial and pywin32.
"""
from __future__ import division, absolute_import
# system imports
from serial import PARITY_NONE
from serial import STOPBITS_ONE
from serial import EIGHTBITS
import win32file, win32event
# twisted imports
from twisted.internet import abstract
# sibling imports
from twisted.internet.serialport import BaseSerialPort
class SerialPort(BaseSerialPort, abstract.FileDescriptor):
"""A serial device, acting as a transport, that uses a win32 event."""
connected = 1
def __init__(self, protocol, deviceNameOrPortNumber, reactor,
baudrate = 9600, bytesize = EIGHTBITS, parity = PARITY_NONE,
stopbits = STOPBITS_ONE, xonxoff = 0, rtscts = 0):
self._serial = self._serialFactory(
deviceNameOrPortNumber, baudrate=baudrate, bytesize=bytesize,
parity=parity, stopbits=stopbits, timeout=None,
xonxoff=xonxoff, rtscts=rtscts)
self.flushInput()
self.flushOutput()
self.reactor = reactor
self.protocol = protocol
self.outQueue = []
self.closed = 0
self.closedNotifies = 0
self.writeInProgress = 0
self.protocol = protocol
self._overlappedRead = win32file.OVERLAPPED()
self._overlappedRead.hEvent = win32event.CreateEvent(None, 1, 0, None)
self._overlappedWrite = win32file.OVERLAPPED()
self._overlappedWrite.hEvent = win32event.CreateEvent(None, 0, 0, None)
self.reactor.addEvent(self._overlappedRead.hEvent, self, 'serialReadEvent')
self.reactor.addEvent(self._overlappedWrite.hEvent, self, 'serialWriteEvent')
self.protocol.makeConnection(self)
self._finishPortSetup()
def _finishPortSetup(self):
"""
Finish setting up the serial port.
This is a separate method to facilitate testing.
"""
flags, comstat = win32file.ClearCommError(self._serial.hComPort)
rc, self.read_buf = win32file.ReadFile(self._serial.hComPort,
win32file.AllocateReadBuffer(1),
self._overlappedRead)
def serialReadEvent(self):
#get that character we set up
n = win32file.GetOverlappedResult(self._serial.hComPort, self._overlappedRead, 0)
if n:
first = str(self.read_buf[:n])
#now we should get everything that is already in the buffer
flags, comstat = win32file.ClearCommError(self._serial.hComPort)
if comstat.cbInQue:
win32event.ResetEvent(self._overlappedRead.hEvent)
rc, buf = win32file.ReadFile(self._serial.hComPort,
win32file.AllocateReadBuffer(comstat.cbInQue),
self._overlappedRead)
n = win32file.GetOverlappedResult(self._serial.hComPort, self._overlappedRead, 1)
#handle all the received data:
self.protocol.dataReceived(first + str(buf[:n]))
else:
#handle all the received data:
self.protocol.dataReceived(first)
#set up next one
win32event.ResetEvent(self._overlappedRead.hEvent)
rc, self.read_buf = win32file.ReadFile(self._serial.hComPort,
win32file.AllocateReadBuffer(1),
self._overlappedRead)
def write(self, data):
if data:
if self.writeInProgress:
self.outQueue.append(data)
else:
self.writeInProgress = 1
win32file.WriteFile(self._serial.hComPort, data, self._overlappedWrite)
def serialWriteEvent(self):
try:
dataToWrite = self.outQueue.pop(0)
except IndexError:
self.writeInProgress = 0
return
else:
win32file.WriteFile(self._serial.hComPort, dataToWrite, self._overlappedWrite)
def connectionLost(self, reason):
"""
Called when the serial port disconnects.
Will call C{connectionLost} on the protocol that is handling the
serial data.
"""
self.reactor.removeEvent(self._overlappedRead.hEvent)
self.reactor.removeEvent(self._overlappedWrite.hEvent)
abstract.FileDescriptor.connectionLost(self, reason)
self._serial.close()
self.protocol.connectionLost(reason)
|
gpl-3.0
|
digris/openbroadcast.org
|
website/tools/l10n/models.py
|
2
|
5224
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
from django.conf import settings
CONTINENTS = (
("AF", _("Africa")),
("NA", _("North America")),
("EU", _("Europe")),
("AS", _("Asia")),
("OC", _("Oceania")),
("SA", _("South America")),
("AN", _("Antarctica")),
("WX", _("Worldwide")),
)
AREAS = (
("a", _("Another")),
("i", _("Island")),
("ar", _("Arrondissement")),
("at", _("Atoll")),
("ai", _("Autonomous island")),
("ca", _("Canton")),
("cm", _("Commune")),
("co", _("County")),
("dp", _("Department")),
("de", _("Dependency")),
("dt", _("District")),
("dv", _("Division")),
("em", _("Emirate")),
("gv", _("Governorate")),
("ic", _("Island council")),
("ig", _("Island group")),
("ir", _("Island region")),
("kd", _("Kingdom")),
("mu", _("Municipality")),
("pa", _("Parish")),
("pf", _("Prefecture")),
("pr", _("Province")),
("rg", _("Region")),
("rp", _("Republic")),
("sh", _("Sheading")),
("st", _("State")),
("sd", _("Subdivision")),
("sj", _("Subject")),
("ty", _("Territory")),
)
@python_2_unicode_compatible
class Country(models.Model):
"""
International Organization for Standardization (ISO) 3166-1 Country list
"""
iso2_code = models.CharField(_("ISO alpha-2"), max_length=2, unique=True)
name = models.CharField(_("Official name (CAPS)"), max_length=128)
printable_name = models.CharField(_("Country name"), max_length=128)
iso3_code = models.CharField(_("ISO alpha-3"), max_length=3, unique=True)
numcode = models.PositiveSmallIntegerField(_("ISO numeric"), null=True, blank=True)
active = models.BooleanField(_("Country is active"), default=True)
continent = models.CharField(_("Continent"), choices=CONTINENTS, max_length=2)
admin_area = models.CharField(
_("Administrative Area"), choices=AREAS, max_length=2, null=True, blank=True
)
class Meta:
verbose_name = _("Country")
verbose_name_plural = _("Countries")
ordering = ("printable_name",)
def __str__(self):
return "{} ({})".format(self.printable_name, self.iso2_code)
@python_2_unicode_compatible
class AdminArea(models.Model):
"""
Administrative Area level 1 for a country. For the US, this would be the
states
"""
country = models.ForeignKey(Country)
name = models.CharField(_("Admin Area name"), max_length=60)
abbrev = models.CharField(
_("Postal Abbreviation"), max_length=3, null=True, blank=True
)
active = models.BooleanField(_("Area is active"), default=True)
class Meta:
verbose_name = _("Administrative Area")
verbose_name_plural = _("Administrative Areas")
ordering = ("name",)
def __str__(self):
return self.name
BASE_ADDRESS_TEMPLATE = _(
"""
Name: %(name)s,
Address: %(address)s,
Zip-Code: %(zipcode)s,
City: %(city)s,
State: %(state)s,
Country: %(country)s,
"""
)
BASE_ADDRESS_TEMPLATE = _(
"""Name: %(name)s
Address:
%(address)s
Zip-Code: %(zipcode)s
City: %(city)s
Country: %(country)s
Email: %(email)s"""
)
ADDRESS_TEMPLATE = getattr(settings, "SHOP_ADDRESS_TEMPLATE", BASE_ADDRESS_TEMPLATE)
@python_2_unicode_compatible
class Address(models.Model):
user_shipping = models.OneToOneField(
settings.AUTH_USER_MODEL, related_name="shipping_address", blank=True, null=True
)
user_billing = models.OneToOneField(
settings.AUTH_USER_MODEL, related_name="billing_address", blank=True, null=True
)
name = models.CharField(_("Name"), max_length=255)
address = models.CharField(_("Address"), max_length=255)
address2 = models.CharField(_("Address2"), max_length=255, blank=True)
zip_code = models.CharField(_("Zip Code"), max_length=20)
city = models.CharField(_("City"), max_length=20)
state = models.ForeignKey(AdminArea, verbose_name=_("state"), null=True, blank=True)
country = models.ForeignKey(
Country, limit_choices_to={"active": True}, verbose_name=_("country")
)
# additional fields
email = models.EmailField(_("EMail"), max_length=255)
# company = models.CharField(_('Company'), max_length=255, null=True, blank=True)
class Meta(object):
abstract = True
verbose_name = _("Address")
verbose_name_plural = _("Addresses")
def __str__(self):
return "%s (%s, %s)" % (self.name, self.zip_code, self.city)
def clone(self):
new_kwargs = dict(
[
(fld.name, getattr(self, fld.name))
for fld in self._meta.fields
if fld.name != "id"
]
)
return self.__class__.objects.create(**new_kwargs)
def as_text(self):
return ADDRESS_TEMPLATE % {
"name": self.name,
"address": "%s\n%s" % (self.address, self.address2),
"zipcode": self.zip_code,
"city": self.city,
"country": self.country,
"email": self.email,
}
|
gpl-3.0
|
tiagofrepereira2012/tensorflow
|
tensorflow/contrib/keras/python/keras/losses_test.py
|
27
|
3551
|
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for Keras loss functions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.contrib.keras.python import keras
from tensorflow.python.platform import test
ALL_LOSSES = [keras.losses.mean_squared_error,
keras.losses.mean_absolute_error,
keras.losses.mean_absolute_percentage_error,
keras.losses.mean_squared_logarithmic_error,
keras.losses.squared_hinge,
keras.losses.hinge,
keras.losses.categorical_crossentropy,
keras.losses.binary_crossentropy,
keras.losses.kullback_leibler_divergence,
keras.losses.poisson,
keras.losses.cosine_proximity,
keras.losses.logcosh,
keras.losses.categorical_hinge]
class KerasLossesTest(test.TestCase):
def test_objective_shapes_3d(self):
with self.test_session():
y_a = keras.backend.variable(np.random.random((5, 6, 7)))
y_b = keras.backend.variable(np.random.random((5, 6, 7)))
for obj in ALL_LOSSES:
objective_output = obj(y_a, y_b)
self.assertListEqual(objective_output.get_shape().as_list(), [5, 6])
def test_objective_shapes_2d(self):
with self.test_session():
y_a = keras.backend.variable(np.random.random((6, 7)))
y_b = keras.backend.variable(np.random.random((6, 7)))
for obj in ALL_LOSSES:
objective_output = obj(y_a, y_b)
self.assertListEqual(objective_output.get_shape().as_list(), [6,])
def test_cce_one_hot(self):
with self.test_session():
y_a = keras.backend.variable(np.random.randint(0, 7, (5, 6)))
y_b = keras.backend.variable(np.random.random((5, 6, 7)))
objective_output = keras.losses.sparse_categorical_crossentropy(y_a, y_b)
assert keras.backend.eval(objective_output).shape == (5, 6)
y_a = keras.backend.variable(np.random.randint(0, 7, (6,)))
y_b = keras.backend.variable(np.random.random((6, 7)))
objective_output = keras.losses.sparse_categorical_crossentropy(y_a, y_b)
assert keras.backend.eval(objective_output).shape == (6,)
def test_serialization(self):
fn = keras.losses.get('mse')
config = keras.losses.serialize(fn)
new_fn = keras.losses.deserialize(config)
self.assertEqual(fn, new_fn)
def test_categorical_hinge(self):
y_pred = keras.backend.variable(np.array([[0.3, 0.2, 0.1],
[0.1, 0.2, 0.7]]))
y_true = keras.backend.variable(np.array([[0, 1, 0], [1, 0, 0]]))
expected_loss = ((0.3 - 0.2 + 1) + (0.7 - 0.1 + 1)) / 2.0
loss = keras.backend.eval(keras.losses.categorical_hinge(y_true, y_pred))
self.assertAllClose(expected_loss, np.mean(loss))
if __name__ == '__main__':
test.main()
|
apache-2.0
|
pauloschilling/sentry
|
src/sentry/models/releasefile.py
|
20
|
1259
|
"""
sentry.models.releasefile
~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2015 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from django.db import models
from hashlib import sha1
from sentry.db.models import FlexibleForeignKey, Model, sane_repr
class ReleaseFile(Model):
"""
A ReleaseFile is an association between a Release and a File.
The ident of the file should be sha1(name) and must be unique per release.
"""
__core__ = False
project = FlexibleForeignKey('sentry.Project')
release = FlexibleForeignKey('sentry.Release')
file = FlexibleForeignKey('sentry.File')
ident = models.CharField(max_length=40)
name = models.TextField()
__repr__ = sane_repr('release', 'ident')
class Meta:
unique_together = (('release', 'ident'),)
app_label = 'sentry'
db_table = 'sentry_releasefile'
def save(self, *args, **kwargs):
if not self.ident and self.name:
self.ident = type(self).get_ident(self.name)
return super(ReleaseFile, self).save(*args, **kwargs)
@classmethod
def get_ident(cls, name):
return sha1(name.encode('utf-8')).hexdigest()
|
bsd-3-clause
|
kobejean/tensorflow
|
tensorflow/contrib/distribute/python/input_ops_test.py
|
7
|
9593
|
# Copyright 2018 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.
# ==============================================================================
"""Tests for input pipeline modifications for distribution strategies."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from tensorflow.contrib.distribute.python import input_ops
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.data.ops import readers
from tensorflow.python.framework import errors
from tensorflow.python.lib.io import python_io
from tensorflow.python.platform import test
from tensorflow.python.util import compat
class AutoShardDatasetTest(test.TestCase):
def setUp(self):
super(AutoShardDatasetTest, self).setUp()
self._num_files = 10
self._num_records = 4
self._num_shards = 2
self._shard_index = 0
self._record_bytes = 10
def _record(self, r, f):
return compat.as_bytes("Record %d of file %d" % (r, f))
def _text_line(self, r, f):
return compat.as_bytes("Text line %d of file %d" % (r, f))
def _fixed_length_record(self, r, f):
return compat.as_bytes(str((r * f) % 10) * self._record_bytes)
def _createTFRecordFiles(self):
filenames = []
for i in range(self._num_files):
fn = os.path.join(self.get_temp_dir(), "tf_record.%d.txt" % i)
filenames.append(fn)
writer = python_io.TFRecordWriter(fn)
for j in range(self._num_records):
record = self._record(j, i)
writer.write(record)
writer.close()
return filenames
def _createTextFiles(self):
filenames = []
for i in range(self._num_files):
fn = os.path.join(self.get_temp_dir(), "text_line.%d.txt" % i)
filenames.append(fn)
contents = []
for j in range(self._num_records):
contents.append(self._text_line(j, i))
if j + 1 != self._num_records or i == 0:
contents.append(b"\r\n")
contents = b"".join(contents)
with open(fn, "wb") as f:
f.write(contents)
return filenames
def _createFixedLengthRecordFiles(self):
filenames = []
for i in range(self._num_files):
fn = os.path.join(self.get_temp_dir(), "fixed_length_record.%d.txt" % i)
filenames.append(fn)
with open(fn, "wb") as f:
for j in range(self._num_records):
f.write(self._fixed_length_record(j, i))
return filenames
def _verifySimpleShardingOutput(self, dataset, record_fn):
iterator = dataset.make_one_shot_iterator()
next_element = iterator.get_next()
with self.cached_session() as sess:
for f in range(self._shard_index, self._num_files, self._num_shards):
for r in range(self._num_records):
self.assertAllEqual(record_fn(r, f), sess.run(next_element))
with self.assertRaises(errors.OutOfRangeError):
sess.run(next_element)
def testTFRecordDataset(self):
dataset = readers.TFRecordDataset(self._createTFRecordFiles())
dataset = input_ops.auto_shard_dataset(
dataset, self._num_shards, self._shard_index)
self._verifySimpleShardingOutput(dataset, self._record)
def testFlatMap(self):
dataset = dataset_ops.Dataset.from_tensor_slices(
self._createTFRecordFiles())
dataset = dataset.flat_map(readers.TFRecordDataset)
dataset = input_ops.auto_shard_dataset(
dataset, self._num_shards, self._shard_index)
self._verifySimpleShardingOutput(dataset, self._record)
def testInterleave(self):
dataset = dataset_ops.Dataset.from_tensor_slices(
self._createTFRecordFiles())
dataset = dataset.interleave(
readers.TFRecordDataset, cycle_length=4, block_length=self._num_records)
dataset = input_ops.auto_shard_dataset(
dataset, self._num_shards, self._shard_index)
# Since block_length == num records in each file, the output will still
# contain records in order of files.
self._verifySimpleShardingOutput(dataset, self._record)
def testListfiles(self):
filenames = self._createTFRecordFiles()
file_pattern = filenames[0].rsplit("/", 1)[0] + "/tf_record.*.txt"
dataset = dataset_ops.Dataset.list_files(file_pattern, shuffle=False)
dataset = dataset.flat_map(readers.TFRecordDataset)
dataset = input_ops.auto_shard_dataset(
dataset, self._num_shards, self._shard_index)
iterator = dataset.make_one_shot_iterator()
next_element = iterator.get_next()
with self.cached_session() as sess:
actual, expected = [], []
for f in range(self._shard_index, self._num_files, self._num_shards):
for r in range(self._num_records):
actual.append(sess.run(next_element))
expected.append(self._record(r, f))
with self.assertRaises(errors.OutOfRangeError):
sess.run(next_element)
self.assertAllEqual(expected, actual)
def testComplexPipeline(self):
# Setup a complex input pipeline.
batch_size = 2
num_epochs = 5
dataset = dataset_ops.Dataset.from_tensor_slices(
self._createTFRecordFiles())
dataset = dataset.shuffle(buffer_size=self._num_files)
dataset = dataset.flat_map(readers.TFRecordDataset)
dataset = dataset.prefetch(buffer_size=batch_size)
dataset = dataset.shuffle(2 * self._num_files * self._num_records)
dataset = dataset.repeat(num_epochs)
dataset = dataset.map(lambda x: x)
dataset = dataset.batch(batch_size)
dataset = dataset.prefetch(buffer_size=None)
# Auto shard.
dataset = input_ops.auto_shard_dataset(
dataset, self._num_shards, self._shard_index)
# Verify output.
iterator = dataset.make_one_shot_iterator()
next_element = iterator.get_next()
with self.cached_session() as sess:
actual = []
num_iterations = (self._num_files * self._num_records * num_epochs) // (
self._num_shards * batch_size)
for _ in range(num_iterations):
actual.extend(sess.run(next_element))
with self.assertRaises(errors.OutOfRangeError):
sess.run(next_element)
expected = []
for f in range(0, self._num_files, self._num_shards):
for r in range(self._num_records):
expected.append(self._record(r, f))
expected *= num_epochs
self.assertAllEqual(sorted(expected), sorted(actual))
def testZip(self):
dataset1 = readers.TFRecordDataset(self._createTFRecordFiles())
dataset2 = readers.TextLineDataset(self._createTextFiles())
dataset = dataset_ops.Dataset.zip((dataset1, dataset2))
dataset = input_ops.auto_shard_dataset(
dataset, self._num_shards, self._shard_index)
record_fn = lambda r, f: (self._record(r, f), self._text_line(r, f))
self._verifySimpleShardingOutput(dataset, record_fn)
def testConcat(self):
dataset1 = readers.TFRecordDataset(self._createTFRecordFiles())
dataset2 = readers.TextLineDataset(self._createTextFiles())
dataset = dataset1.concatenate(dataset2)
dataset = input_ops.auto_shard_dataset(
dataset, self._num_shards, self._shard_index)
iterator = dataset.make_one_shot_iterator()
next_element = iterator.get_next()
with self.cached_session() as sess:
for f in range(self._shard_index, self._num_files, self._num_shards):
for r in range(self._num_records):
self.assertAllEqual(self._record(r, f), sess.run(next_element))
for f in range(self._shard_index, self._num_files, self._num_shards):
for r in range(self._num_records):
self.assertAllEqual(self._text_line(r, f), sess.run(next_element))
with self.assertRaises(errors.OutOfRangeError):
sess.run(next_element)
def testTextLineReader(self):
dataset = readers.TextLineDataset(self._createTextFiles())
dataset = input_ops.auto_shard_dataset(
dataset, self._num_shards, self._shard_index)
self._verifySimpleShardingOutput(dataset, self._text_line)
def testTextLineReaderWithFlatMap(self):
dataset = dataset_ops.Dataset.from_tensor_slices(self._createTextFiles())
dataset = dataset.flat_map(readers.TextLineDataset)
dataset = input_ops.auto_shard_dataset(
dataset, self._num_shards, self._shard_index)
self._verifySimpleShardingOutput(dataset, self._text_line)
def testFixedLengthReader(self):
dataset = readers.FixedLengthRecordDataset(
self._createFixedLengthRecordFiles(), self._record_bytes)
dataset = input_ops.auto_shard_dataset(
dataset, self._num_shards, self._shard_index)
self._verifySimpleShardingOutput(dataset, self._fixed_length_record)
def testFixedLengthReaderWithFlatMap(self):
dataset = dataset_ops.Dataset.from_tensor_slices(
self._createFixedLengthRecordFiles())
dataset = dataset.flat_map(
lambda f: readers.FixedLengthRecordDataset(f, self._record_bytes))
dataset = input_ops.auto_shard_dataset(
dataset, self._num_shards, self._shard_index)
self._verifySimpleShardingOutput(dataset, self._fixed_length_record)
if __name__ == "__main__":
test.main()
|
apache-2.0
|
jarshwah/django
|
django/contrib/contenttypes/migrations/0002_remove_content_type_name.py
|
582
|
1168
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
def add_legacy_name(apps, schema_editor):
ContentType = apps.get_model('contenttypes', 'ContentType')
for ct in ContentType.objects.all():
try:
ct.name = apps.get_model(ct.app_label, ct.model)._meta.object_name
except LookupError:
ct.name = ct.model
ct.save()
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='contenttype',
options={'verbose_name': 'content type', 'verbose_name_plural': 'content types'},
),
migrations.AlterField(
model_name='contenttype',
name='name',
field=models.CharField(max_length=100, null=True),
),
migrations.RunPython(
migrations.RunPython.noop,
add_legacy_name,
hints={'model_name': 'contenttype'},
),
migrations.RemoveField(
model_name='contenttype',
name='name',
),
]
|
bsd-3-clause
|
scrollback/kuma
|
vendor/lib/python/taggit/models.py
|
12
|
5092
|
import django
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.generic import GenericForeignKey
from django.db import models, IntegrityError, transaction
from django.template.defaultfilters import slugify as default_slugify
from django.utils.translation import ugettext_lazy as _, ugettext
class TagBase(models.Model):
name = models.CharField(verbose_name=_('Name'), max_length=100)
slug = models.SlugField(verbose_name=_('Slug'), unique=True, max_length=100)
def __unicode__(self):
return self.name
class Meta:
abstract = True
def save(self, *args, **kwargs):
if not self.pk and not self.slug:
self.slug = self.slugify(self.name)
if django.VERSION >= (1, 2):
from django.db import router
using = kwargs.get("using") or router.db_for_write(
type(self), instance=self)
# Make sure we write to the same db for all attempted writes,
# with a multi-master setup, theoretically we could try to
# write and rollback on different DBs
kwargs["using"] = using
trans_kwargs = {"using": using}
else:
trans_kwargs = {}
i = 0
while True:
i += 1
try:
sid = transaction.savepoint(**trans_kwargs)
res = super(TagBase, self).save(*args, **kwargs)
transaction.savepoint_commit(sid, **trans_kwargs)
return res
except IntegrityError:
transaction.savepoint_rollback(sid, **trans_kwargs)
self.slug = self.slugify(self.name, i)
else:
return super(TagBase, self).save(*args, **kwargs)
def slugify(self, tag, i=None):
slug = default_slugify(tag)
if i is not None:
slug += "_%d" % i
return slug
class Tag(TagBase):
class Meta:
verbose_name = _("Tag")
verbose_name_plural = _("Tags")
class ItemBase(models.Model):
def __unicode__(self):
return ugettext("%(object)s tagged with %(tag)s") % {
"object": self.content_object,
"tag": self.tag
}
class Meta:
abstract = True
@classmethod
def tag_model(cls):
return cls._meta.get_field_by_name("tag")[0].rel.to
@classmethod
def tag_relname(cls):
return cls._meta.get_field_by_name('tag')[0].rel.related_name
@classmethod
def lookup_kwargs(cls, instance):
return {
'content_object': instance
}
@classmethod
def bulk_lookup_kwargs(cls, instances):
return {
"content_object__in": instances,
}
class TaggedItemBase(ItemBase):
if django.VERSION < (1, 2):
tag = models.ForeignKey(Tag, related_name="%(class)s_items")
else:
tag = models.ForeignKey(Tag, related_name="%(app_label)s_%(class)s_items")
class Meta:
abstract = True
@classmethod
def tags_for(cls, model, instance=None):
if instance is not None:
return cls.tag_model().objects.filter(**{
'%s__content_object' % cls.tag_relname(): instance
})
return cls.tag_model().objects.filter(**{
'%s__content_object__isnull' % cls.tag_relname(): False
}).distinct()
class GenericTaggedItemBase(ItemBase):
object_id = models.IntegerField(verbose_name=_('Object id'), db_index=True)
if django.VERSION < (1, 2):
content_type = models.ForeignKey(
ContentType,
verbose_name=_('Content type'),
related_name="%(class)s_tagged_items"
)
else:
content_type = models.ForeignKey(
ContentType,
verbose_name=_('Content type'),
related_name="%(app_label)s_%(class)s_tagged_items"
)
content_object = GenericForeignKey()
class Meta:
abstract=True
@classmethod
def lookup_kwargs(cls, instance):
return {
'object_id': instance.pk,
'content_type': ContentType.objects.get_for_model(instance)
}
@classmethod
def bulk_lookup_kwargs(cls, instances):
# TODO: instances[0], can we assume there are instances.
return {
"object_id__in": [instance.pk for instance in instances],
"content_type": ContentType.objects.get_for_model(instances[0]),
}
@classmethod
def tags_for(cls, model, instance=None):
ct = ContentType.objects.get_for_model(model)
kwargs = {
"%s__content_type" % cls.tag_relname(): ct
}
if instance is not None:
kwargs["%s__object_id" % cls.tag_relname()] = instance.pk
return cls.tag_model().objects.filter(**kwargs).distinct()
class TaggedItem(GenericTaggedItemBase, TaggedItemBase):
class Meta:
verbose_name = _("Tagged Item")
verbose_name_plural = _("Tagged Items")
|
mpl-2.0
|
enriclluelles/ansible-modules-extras
|
notification/sns.py
|
8
|
5738
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2014, Michael J. Schultz <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
DOCUMENTATION = """
module: sns
short_description: Send Amazon Simple Notification Service (SNS) messages
description:
- The M(sns) module sends notifications to a topic on your Amazon SNS account
version_added: 1.6
author: '"Michael J. Schultz (@mjschultz)" <[email protected]>'
options:
msg:
description:
- Default message to send.
required: true
aliases: [ "default" ]
subject:
description:
- Subject line for email delivery.
required: false
topic:
description:
- The topic you want to publish to.
required: true
email:
description:
- Message to send to email-only subscription
required: false
sqs:
description:
- Message to send to SQS-only subscription
required: false
sms:
description:
- Message to send to SMS-only subscription
required: false
http:
description:
- Message to send to HTTP-only subscription
required: false
https:
description:
- Message to send to HTTPS-only subscription
required: false
aws_secret_key:
description:
- AWS secret key. If not set then the value of the AWS_SECRET_KEY environment variable is used.
required: false
default: None
aliases: ['ec2_secret_key', 'secret_key']
aws_access_key:
description:
- AWS access key. If not set then the value of the AWS_ACCESS_KEY environment variable is used.
required: false
default: None
aliases: ['ec2_access_key', 'access_key']
region:
description:
- The AWS region to use. If not specified then the value of the EC2_REGION environment variable, if any, is used.
required: false
aliases: ['aws_region', 'ec2_region']
requirements: [ "boto" ]
author: Michael J. Schultz
"""
EXAMPLES = """
- name: Send default notification message via SNS
local_action:
module: sns
msg: "{{ inventory_hostname }} has completed the play."
subject: "Deploy complete!"
topic: "deploy"
- name: Send notification messages via SNS with short message for SMS
local_action:
module: sns
msg: "{{ inventory_hostname }} has completed the play."
sms: "deployed!"
subject: "Deploy complete!"
topic: "deploy"
"""
import sys
from ansible.module_utils.basic import *
from ansible.module_utils.ec2 import *
try:
import boto
import boto.ec2
import boto.sns
except ImportError:
print "failed=True msg='boto required for this module'"
sys.exit(1)
def arn_topic_lookup(connection, short_topic):
response = connection.get_all_topics()
result = response[u'ListTopicsResponse'][u'ListTopicsResult']
# topic names cannot have colons, so this captures the full topic name
lookup_topic = ':{}'.format(short_topic)
for topic in result[u'Topics']:
if topic[u'TopicArn'].endswith(lookup_topic):
return topic[u'TopicArn']
return None
def main():
argument_spec = ec2_argument_spec()
argument_spec.update(
dict(
msg=dict(type='str', required=True, aliases=['default']),
subject=dict(type='str', default=None),
topic=dict(type='str', required=True),
email=dict(type='str', default=None),
sqs=dict(type='str', default=None),
sms=dict(type='str', default=None),
http=dict(type='str', default=None),
https=dict(type='str', default=None),
)
)
module = AnsibleModule(argument_spec=argument_spec)
msg = module.params['msg']
subject = module.params['subject']
topic = module.params['topic']
email = module.params['email']
sqs = module.params['sqs']
sms = module.params['sms']
http = module.params['http']
https = module.params['https']
region, ec2_url, aws_connect_params = get_aws_connection_info(module)
if not region:
module.fail_json(msg="region must be specified")
try:
connection = connect_to_aws(boto.sns, region, **aws_connect_params)
except boto.exception.NoAuthHandlerFound, e:
module.fail_json(msg=str(e))
# .publish() takes full ARN topic id, but I'm lazy and type shortnames
# so do a lookup (topics cannot contain ':', so thats the decider)
if ':' in topic:
arn_topic = topic
else:
arn_topic = arn_topic_lookup(connection, topic)
if not arn_topic:
module.fail_json(msg='Could not find topic: {}'.format(topic))
dict_msg = {'default': msg}
if email:
dict_msg.update(email=email)
if sqs:
dict_msg.update(sqs=sqs)
if sms:
dict_msg.update(sms=sms)
if http:
dict_msg.update(http=http)
if https:
dict_msg.update(https=https)
json_msg = json.dumps(dict_msg)
try:
connection.publish(topic=arn_topic, subject=subject,
message_structure='json', message=json_msg)
except boto.exception.BotoServerError, e:
module.fail_json(msg=str(e))
module.exit_json(msg="OK")
main()
|
gpl-3.0
|
packages/psutil
|
examples/nettop.py
|
11
|
4712
|
#!/usr/bin/env python
#
# $Id: iotop.py 1160 2011-10-14 18:50:36Z [email protected] $
#
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Shows real-time network statistics.
Author: Giampaolo Rodola' <[email protected]>
$ python examples/nettop.py
-----------------------------------------------------------
total bytes: sent: 1.49 G received: 4.82 G
total packets: sent: 7338724 received: 8082712
wlan0 TOTAL PER-SEC
-----------------------------------------------------------
bytes-sent 1.29 G 0.00 B/s
bytes-recv 3.48 G 0.00 B/s
pkts-sent 7221782 0
pkts-recv 6753724 0
eth1 TOTAL PER-SEC
-----------------------------------------------------------
bytes-sent 131.77 M 0.00 B/s
bytes-recv 1.28 G 0.00 B/s
pkts-sent 0 0
pkts-recv 1214470 0
"""
import atexit
import time
import sys
try:
import curses
except ImportError:
sys.exit('platform not supported')
import psutil
# --- curses stuff
def tear_down():
win.keypad(0)
curses.nocbreak()
curses.echo()
curses.endwin()
win = curses.initscr()
atexit.register(tear_down)
curses.endwin()
lineno = 0
def print_line(line, highlight=False):
"""A thin wrapper around curses's addstr()."""
global lineno
try:
if highlight:
line += " " * (win.getmaxyx()[1] - len(line))
win.addstr(lineno, 0, line, curses.A_REVERSE)
else:
win.addstr(lineno, 0, line, 0)
except curses.error:
lineno = 0
win.refresh()
raise
else:
lineno += 1
# --- curses stuff
def bytes2human(n):
"""
>>> bytes2human(10000)
'9.8 K'
>>> bytes2human(100001221)
'95.4 M'
"""
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i + 1) * 10
for s in reversed(symbols):
if n >= prefix[s]:
value = float(n) / prefix[s]
return '%.2f %s' % (value, s)
return '%.2f B' % (n)
def poll(interval):
"""Retrieve raw stats within an interval window."""
tot_before = psutil.net_io_counters()
pnic_before = psutil.net_io_counters(pernic=True)
# sleep some time
time.sleep(interval)
tot_after = psutil.net_io_counters()
pnic_after = psutil.net_io_counters(pernic=True)
return (tot_before, tot_after, pnic_before, pnic_after)
def refresh_window(tot_before, tot_after, pnic_before, pnic_after):
"""Print stats on screen."""
global lineno
# totals
print_line("total bytes: sent: %-10s received: %s" % (
bytes2human(tot_after.bytes_sent),
bytes2human(tot_after.bytes_recv))
)
print_line("total packets: sent: %-10s received: %s" % (
tot_after.packets_sent, tot_after.packets_recv))
# per-network interface details: let's sort network interfaces so
# that the ones which generated more traffic are shown first
print_line("")
nic_names = list(pnic_after.keys())
nic_names.sort(key=lambda x: sum(pnic_after[x]), reverse=True)
for name in nic_names:
stats_before = pnic_before[name]
stats_after = pnic_after[name]
templ = "%-15s %15s %15s"
print_line(templ % (name, "TOTAL", "PER-SEC"), highlight=True)
print_line(templ % (
"bytes-sent",
bytes2human(stats_after.bytes_sent),
bytes2human(
stats_after.bytes_sent - stats_before.bytes_sent) + '/s',
))
print_line(templ % (
"bytes-recv",
bytes2human(stats_after.bytes_recv),
bytes2human(
stats_after.bytes_recv - stats_before.bytes_recv) + '/s',
))
print_line(templ % (
"pkts-sent",
stats_after.packets_sent,
stats_after.packets_sent - stats_before.packets_sent,
))
print_line(templ % (
"pkts-recv",
stats_after.packets_recv,
stats_after.packets_recv - stats_before.packets_recv,
))
print_line("")
win.refresh()
lineno = 0
def main():
try:
interval = 0
while True:
args = poll(interval)
refresh_window(*args)
interval = 1
except (KeyboardInterrupt, SystemExit):
pass
if __name__ == '__main__':
main()
|
bsd-3-clause
|
nanolearning/edx-platform
|
lms/djangoapps/certificates/migrations/0001_added_generatedcertificates.py
|
188
|
6863
|
# -*- coding: 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):
# Adding model 'GeneratedCertificate'
db.create_table('certificates_generatedcertificate', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'])),
('certificate_id', self.gf('django.db.models.fields.CharField')(max_length=32)),
))
db.send_create_signal('certificates', ['GeneratedCertificate'])
def backwards(self, orm):
# Deleting model 'GeneratedCertificate'
db.delete_table('certificates_generatedcertificate')
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'})
},
'certificates.generatedcertificate': {
'Meta': {'object_name': 'GeneratedCertificate'},
'certificate_id': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'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'})
}
}
complete_apps = ['certificates']
|
agpl-3.0
|
yamila-moreno/nikola
|
nikola/plugins/command/install_theme.py
|
9
|
6202
|
# -*- coding: utf-8 -*-
# Copyright © 2012-2015 Roberto Alsina and others.
# Permission is hereby granted, free of charge, to any
# person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the
# Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the
# Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice
# shall be included in all copies or substantial portions of
# the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
# OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""Install a theme."""
from __future__ import print_function
import os
import io
import time
import requests
import pygments
from pygments.lexers import PythonLexer
from pygments.formatters import TerminalFormatter
from nikola.plugin_categories import Command
from nikola import utils
LOGGER = utils.get_logger('install_theme', utils.STDERR_HANDLER)
class CommandInstallTheme(Command):
"""Install a theme."""
name = "install_theme"
doc_usage = "[[-u] theme_name] | [[-u] -l]"
doc_purpose = "install theme into current site"
output_dir = 'themes'
cmd_options = [
{
'name': 'list',
'short': 'l',
'long': 'list',
'type': bool,
'default': False,
'help': 'Show list of available themes.'
},
{
'name': 'url',
'short': 'u',
'long': 'url',
'type': str,
'help': "URL for the theme repository (default: "
"https://themes.getnikola.com/v7/themes.json)",
'default': 'https://themes.getnikola.com/v7/themes.json'
},
{
'name': 'getpath',
'short': 'g',
'long': 'get-path',
'type': bool,
'default': False,
'help': "Print the path for installed theme",
},
]
def _execute(self, options, args):
"""Install theme into current site."""
listing = options['list']
url = options['url']
if args:
name = args[0]
else:
name = None
if options['getpath'] and name:
path = utils.get_theme_path(name)
if path:
print(path)
else:
print('not installed')
return 0
if name is None and not listing:
LOGGER.error("This command needs either a theme name or the -l option.")
return False
try:
data = requests.get(url).json()
except requests.exceptions.SSLError:
LOGGER.warning("SSL error, using http instead of https (press ^C to abort)")
time.sleep(1)
url = url.replace('https', 'http', 1)
data = requests.get(url).json()
if listing:
print("Themes:")
print("-------")
for theme in sorted(data.keys()):
print(theme)
return True
else:
# `name` may be modified by the while loop.
origname = name
installstatus = self.do_install(name, data)
# See if the theme's parent is available. If not, install it
while True:
parent_name = utils.get_parent_theme_name(name)
if parent_name is None:
break
try:
utils.get_theme_path(parent_name)
break
except: # Not available
self.do_install(parent_name, data)
name = parent_name
if installstatus:
LOGGER.notice('Remember to set THEME="{0}" in conf.py to use this theme.'.format(origname))
def do_install(self, name, data):
"""Download and install a theme."""
if name in data:
utils.makedirs(self.output_dir)
url = data[name]
LOGGER.info("Downloading '{0}'".format(url))
try:
zip_data = requests.get(url).content
except requests.exceptions.SSLError:
LOGGER.warning("SSL error, using http instead of https (press ^C to abort)")
time.sleep(1)
url = url.replace('https', 'http', 1)
zip_data = requests.get(url).content
zip_file = io.BytesIO()
zip_file.write(zip_data)
LOGGER.info("Extracting '{0}' into themes/".format(name))
utils.extract_all(zip_file)
dest_path = os.path.join(self.output_dir, name)
else:
dest_path = os.path.join(self.output_dir, name)
try:
theme_path = utils.get_theme_path(name)
LOGGER.error("Theme '{0}' is already installed in {1}".format(name, theme_path))
except Exception:
LOGGER.error("Can't find theme {0}".format(name))
return False
confpypath = os.path.join(dest_path, 'conf.py.sample')
if os.path.exists(confpypath):
LOGGER.notice('This theme has a sample config file. Integrate it with yours in order to make this theme work!')
print('Contents of the conf.py.sample file:\n')
with io.open(confpypath, 'r', encoding='utf-8') as fh:
if self.site.colorful:
print(utils.indent(pygments.highlight(
fh.read(), PythonLexer(), TerminalFormatter()),
4 * ' '))
else:
print(utils.indent(fh.read(), 4 * ' '))
return True
|
mit
|
trishnaguha/ansible
|
lib/ansible/modules/network/fortios/fortios_system_sdn_connector.py
|
7
|
18926
|
#!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
# Copyright 2018 Fortinet, Inc.
#
# 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 <https://www.gnu.org/licenses/>.
#
# the lib use python logging can get it if the following is set in your
# Ansible config.
__metaclass__ = type
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'metadata_version': '1.1'}
DOCUMENTATION = '''
---
module: fortios_system_sdn_connector
short_description: Configure connection to SDN Connector.
description:
- This module is able to configure a FortiGate or FortiOS by
allowing the user to configure system feature and sdn_connector category.
Examples includes all options and need to be adjusted to datasources before usage.
Tested with FOS v6.0.2
version_added: "2.8"
author:
- Miguel Angel Munoz (@mamunozgonzalez)
- Nicolas Thomas (@thomnico)
notes:
- Requires fortiosapi library developed by Fortinet
- Run as a local_action in your playbook
requirements:
- fortiosapi>=0.9.8
options:
host:
description:
- FortiOS or FortiGate ip adress.
required: true
username:
description:
- FortiOS or FortiGate username.
required: true
password:
description:
- FortiOS or FortiGate password.
default: ""
vdom:
description:
- Virtual domain, among those defined previously. A vdom is a
virtual instance of the FortiGate that can be configured and
used as a different unit.
default: root
https:
description:
- Indicates if the requests towards FortiGate must use HTTPS
protocol
type: bool
default: false
system_sdn_connector:
description:
- Configure connection to SDN Connector.
default: null
suboptions:
state:
description:
- Indicates whether to create or remove the object
choices:
- present
- absent
access-key:
description:
- AWS access key ID.
azure-region:
description:
- Azure server region.
choices:
- global
- china
- germany
- usgov
client-id:
description:
- Azure client ID (application ID).
client-secret:
description:
- Azure client secret (application key).
compartment-id:
description:
- Compartment ID.
external-ip:
description:
- Configure GCP external IP.
suboptions:
name:
description:
- External IP name.
required: true
gcp-project:
description:
- GCP project name.
key-passwd:
description:
- Private key password.
name:
description:
- SDN connector name.
required: true
nic:
description:
- Configure Azure network interface.
suboptions:
ip:
description:
- Configure IP configuration.
suboptions:
name:
description:
- IP configuration name.
required: true
public-ip:
description:
- Public IP name.
name:
description:
- Network interface name.
required: true
oci-cert:
description:
- OCI certificate. Source certificate.local.name.
oci-fingerprint:
description:
- OCI pubkey fingerprint.
oci-region:
description:
- OCI server region.
choices:
- phoenix
- ashburn
- frankfurt
- london
password:
description:
- Password of the remote SDN connector as login credentials.
private-key:
description:
- Private key of GCP service account.
region:
description:
- AWS region name.
resource-group:
description:
- Azure resource group.
route:
description:
- Configure GCP route.
suboptions:
name:
description:
- Route name.
required: true
route-table:
description:
- Configure Azure route table.
suboptions:
name:
description:
- Route table name.
required: true
route:
description:
- Configure Azure route.
suboptions:
name:
description:
- Route name.
required: true
next-hop:
description:
- Next hop address.
secret-key:
description:
- AWS secret access key.
server:
description:
- Server address of the remote SDN connector.
server-port:
description:
- Port number of the remote SDN connector.
service-account:
description:
- GCP service account email.
status:
description:
- Enable/disable connection to the remote SDN connector.
choices:
- disable
- enable
subscription-id:
description:
- Azure subscription ID.
tenant-id:
description:
- Tenant ID (directory ID).
type:
description:
- Type of SDN connector.
choices:
- aci
- aws
- azure
- nsx
- nuage
- oci
- gcp
update-interval:
description:
- Dynamic object update interval (0 - 3600 sec, 0 means disabled, default = 60).
use-metadata-iam:
description:
- Enable/disable using IAM role from metadata to call API.
choices:
- disable
- enable
user-id:
description:
- User ID.
username:
description:
- Username of the remote SDN connector as login credentials.
vpc-id:
description:
- AWS VPC ID.
'''
EXAMPLES = '''
- hosts: localhost
vars:
host: "192.168.122.40"
username: "admin"
password: ""
vdom: "root"
tasks:
- name: Configure connection to SDN Connector.
fortios_system_sdn_connector:
host: "{{ host }}"
username: "{{ username }}"
password: "{{ password }}"
vdom: "{{ vdom }}"
system_sdn_connector:
state: "present"
access-key: "<your_own_value>"
azure-region: "global"
client-id: "<your_own_value>"
client-secret: "<your_own_value>"
compartment-id: "<your_own_value>"
external-ip:
-
name: "default_name_9"
gcp-project: "<your_own_value>"
key-passwd: "<your_own_value>"
name: "default_name_12"
nic:
-
ip:
-
name: "default_name_15"
public-ip: "<your_own_value>"
name: "default_name_17"
oci-cert: "<your_own_value> (source certificate.local.name)"
oci-fingerprint: "<your_own_value>"
oci-region: "phoenix"
password: "<your_own_value>"
private-key: "<your_own_value>"
region: "<your_own_value>"
resource-group: "<your_own_value>"
route:
-
name: "default_name_26"
route-table:
-
name: "default_name_28"
route:
-
name: "default_name_30"
next-hop: "<your_own_value>"
secret-key: "<your_own_value>"
server: "192.168.100.40"
server-port: "34"
service-account: "<your_own_value>"
status: "disable"
subscription-id: "<your_own_value>"
tenant-id: "<your_own_value>"
type: "aci"
update-interval: "40"
use-metadata-iam: "disable"
user-id: "<your_own_value>"
username: "<your_own_value>"
vpc-id: "<your_own_value>"
'''
RETURN = '''
build:
description: Build number of the fortigate image
returned: always
type: str
sample: '1547'
http_method:
description: Last method used to provision the content into FortiGate
returned: always
type: str
sample: 'PUT'
http_status:
description: Last result given by FortiGate on last operation applied
returned: always
type: str
sample: "200"
mkey:
description: Master key (id) used in the last call to FortiGate
returned: success
type: str
sample: "key1"
name:
description: Name of the table used to fulfill the request
returned: always
type: str
sample: "urlfilter"
path:
description: Path of the table used to fulfill the request
returned: always
type: str
sample: "webfilter"
revision:
description: Internal revision number
returned: always
type: str
sample: "17.0.2.10658"
serial:
description: Serial number of the unit
returned: always
type: str
sample: "FGVMEVYYQT3AB5352"
status:
description: Indication of the operation's result
returned: always
type: str
sample: "success"
vdom:
description: Virtual domain used
returned: always
type: str
sample: "root"
version:
description: Version of the FortiGate
returned: always
type: str
sample: "v5.6.3"
'''
from ansible.module_utils.basic import AnsibleModule
fos = None
def login(data):
host = data['host']
username = data['username']
password = data['password']
fos.debug('on')
if 'https' in data and not data['https']:
fos.https('off')
else:
fos.https('on')
fos.login(host, username, password)
def filter_system_sdn_connector_data(json):
option_list = ['access-key', 'azure-region', 'client-id',
'client-secret', 'compartment-id', 'external-ip',
'gcp-project', 'key-passwd', 'name',
'nic', 'oci-cert', 'oci-fingerprint',
'oci-region', 'password', 'private-key',
'region', 'resource-group', 'route',
'route-table', 'secret-key', 'server',
'server-port', 'service-account', 'status',
'subscription-id', 'tenant-id', 'type',
'update-interval', 'use-metadata-iam', 'user-id',
'username', 'vpc-id']
dictionary = {}
for attribute in option_list:
if attribute in json:
dictionary[attribute] = json[attribute]
return dictionary
def system_sdn_connector(data, fos):
vdom = data['vdom']
system_sdn_connector_data = data['system_sdn_connector']
filtered_data = filter_system_sdn_connector_data(system_sdn_connector_data)
if system_sdn_connector_data['state'] == "present":
return fos.set('system',
'sdn-connector',
data=filtered_data,
vdom=vdom)
elif system_sdn_connector_data['state'] == "absent":
return fos.delete('system',
'sdn-connector',
mkey=filtered_data['name'],
vdom=vdom)
def fortios_system(data, fos):
login(data)
methodlist = ['system_sdn_connector']
for method in methodlist:
if data[method]:
resp = eval(method)(data, fos)
break
fos.logout()
return not resp['status'] == "success", resp['status'] == "success", resp
def main():
fields = {
"host": {"required": True, "type": "str"},
"username": {"required": True, "type": "str"},
"password": {"required": False, "type": "str", "no_log": True},
"vdom": {"required": False, "type": "str", "default": "root"},
"https": {"required": False, "type": "bool", "default": "False"},
"system_sdn_connector": {
"required": False, "type": "dict",
"options": {
"state": {"required": True, "type": "str",
"choices": ["present", "absent"]},
"access-key": {"required": False, "type": "str"},
"azure-region": {"required": False, "type": "str",
"choices": ["global", "china", "germany",
"usgov"]},
"client-id": {"required": False, "type": "str"},
"client-secret": {"required": False, "type": "str"},
"compartment-id": {"required": False, "type": "str"},
"external-ip": {"required": False, "type": "list",
"options": {
"name": {"required": True, "type": "str"}
}},
"gcp-project": {"required": False, "type": "str"},
"key-passwd": {"required": False, "type": "str"},
"name": {"required": True, "type": "str"},
"nic": {"required": False, "type": "list",
"options": {
"ip": {"required": False, "type": "list",
"options": {
"name": {"required": True, "type": "str"},
"public-ip": {"required": False, "type": "str"}
}},
"name": {"required": True, "type": "str"}
}},
"oci-cert": {"required": False, "type": "str"},
"oci-fingerprint": {"required": False, "type": "str"},
"oci-region": {"required": False, "type": "str",
"choices": ["phoenix", "ashburn", "frankfurt",
"london"]},
"password": {"required": False, "type": "str"},
"private-key": {"required": False, "type": "str"},
"region": {"required": False, "type": "str"},
"resource-group": {"required": False, "type": "str"},
"route": {"required": False, "type": "list",
"options": {
"name": {"required": True, "type": "str"}
}},
"route-table": {"required": False, "type": "list",
"options": {
"name": {"required": True, "type": "str"},
"route": {"required": False, "type": "list",
"options": {
"name": {"required": True, "type": "str"},
"next-hop": {"required": False, "type": "str"}
}}
}},
"secret-key": {"required": False, "type": "str"},
"server": {"required": False, "type": "str"},
"server-port": {"required": False, "type": "int"},
"service-account": {"required": False, "type": "str"},
"status": {"required": False, "type": "str",
"choices": ["disable", "enable"]},
"subscription-id": {"required": False, "type": "str"},
"tenant-id": {"required": False, "type": "str"},
"type": {"required": False, "type": "str",
"choices": ["aci", "aws", "azure",
"nsx", "nuage", "oci",
"gcp"]},
"update-interval": {"required": False, "type": "int"},
"use-metadata-iam": {"required": False, "type": "str",
"choices": ["disable", "enable"]},
"user-id": {"required": False, "type": "str"},
"username": {"required": False, "type": "str"},
"vpc-id": {"required": False, "type": "str"}
}
}
}
module = AnsibleModule(argument_spec=fields,
supports_check_mode=False)
try:
from fortiosapi import FortiOSAPI
except ImportError:
module.fail_json(msg="fortiosapi module is required")
global fos
fos = FortiOSAPI()
is_error, has_changed, result = fortios_system(module.params, fos)
if not is_error:
module.exit_json(changed=has_changed, meta=result)
else:
module.fail_json(msg="Error in repo", meta=result)
if __name__ == '__main__':
main()
|
gpl-3.0
|
resba/gnuradio
|
gnuradio-core/src/python/gnuradio/gr/qa_bin_statistics.py
|
11
|
7437
|
#!/usr/bin/env python
#
# Copyright 2006,2007,2010 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at your option)
# any later version.
#
# GNU Radio 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 GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
from gnuradio import gr, gr_unittest
import random
import struct
#import os
#print "pid =", os.getpid()
#raw_input("Attach gdb and press return...")
"""
Note: The QA tests below have been disabled by renaming them from test_*
to xtest_*. See ticket:199 on http://gnuradio.org/trac/ticket/199
"""
class counter(gr.feval_dd):
def __init__(self, step_size=1):
gr.feval_dd.__init__(self)
self.step_size = step_size
self.count = 0
def eval(self, input):
#print "eval: self.count =", self.count
t = self.count
self.count = self.count + self.step_size
return t
class counter3(gr.feval_dd):
def __init__(self, f, step_size):
gr.feval_dd.__init__(self)
self.f = f
self.step_size = step_size
self.count = 0
def eval(self, input):
try:
#print "eval: self.count =", self.count
t = self.count
self.count = self.count + self.step_size
self.f(self.count)
except Exception, e:
print "Exception: ", e
return t
def foobar3(new_t):
#print "foobar3: new_t =", new_t
pass
class counter4(gr.feval_dd):
def __init__(self, obj_instance, step_size):
gr.feval_dd.__init__(self)
self.obj_instance = obj_instance
self.step_size = step_size
self.count = 0
def eval(self, input):
try:
#print "eval: self.count =", self.count
t = self.count
self.count = self.count + self.step_size
self.obj_instance.foobar4(self.count)
except Exception, e:
print "Exception: ", e
return t
class parse_msg(object):
def __init__(self, msg):
self.center_freq = msg.arg1()
self.vlen = int(msg.arg2())
assert(msg.length() == self.vlen * gr.sizeof_float)
self.data = struct.unpack('%df' % (self.vlen,), msg.to_string())
# FIXME: see ticket:199
class xtest_bin_statistics(gr_unittest.TestCase):
def setUp(self):
self.tb = gr.top_block ()
def tearDown(self):
self.tb = None
def xtest_001(self):
vlen = 4
tune = counter(1)
tune_delay = 0
dwell_delay = 1
msgq = gr.msg_queue()
src_data = tuple([float(x) for x in
( 1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12,
13, 14, 15, 16
)])
expected_results = tuple([float(x) for x in
( 1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12,
13, 14, 15, 16
)])
src = gr.vector_source_f(src_data, False)
s2v = gr.stream_to_vector(gr.sizeof_float, vlen)
stats = gr.bin_statistics_f(vlen, msgq, tune, tune_delay, dwell_delay)
self.tb.connect(src, s2v, stats)
self.tb.run()
self.assertEqual(4, msgq.count())
for i in range(4):
m = parse_msg(msgq.delete_head())
#print "m =", m.center_freq, m.data
self.assertEqual(expected_results[vlen*i:vlen*i + vlen], m.data)
def xtest_002(self):
vlen = 4
tune = counter(1)
tune_delay = 1
dwell_delay = 2
msgq = gr.msg_queue()
src_data = tuple([float(x) for x in
( 1, 2, 3, 4,
9, 6, 11, 8,
5, 10, 7, 12,
13, 14, 15, 16
)])
expected_results = tuple([float(x) for x in
( 9, 10, 11, 12)])
src = gr.vector_source_f(src_data, False)
s2v = gr.stream_to_vector(gr.sizeof_float, vlen)
stats = gr.bin_statistics_f(vlen, msgq, tune, tune_delay, dwell_delay)
self.tb.connect(src, s2v, stats)
self.tb.run()
self.assertEqual(1, msgq.count())
for i in range(1):
m = parse_msg(msgq.delete_head())
#print "m =", m.center_freq, m.data
self.assertEqual(expected_results[vlen*i:vlen*i + vlen], m.data)
def xtest_003(self):
vlen = 4
tune = counter3(foobar3, 1)
tune_delay = 1
dwell_delay = 2
msgq = gr.msg_queue()
src_data = tuple([float(x) for x in
( 1, 2, 3, 4,
9, 6, 11, 8,
5, 10, 7, 12,
13, 14, 15, 16
)])
expected_results = tuple([float(x) for x in
( 9, 10, 11, 12)])
src = gr.vector_source_f(src_data, False)
s2v = gr.stream_to_vector(gr.sizeof_float, vlen)
stats = gr.bin_statistics_f(vlen, msgq, tune, tune_delay, dwell_delay)
self.tb.connect(src, s2v, stats)
self.tb.run()
self.assertEqual(1, msgq.count())
for i in range(1):
m = parse_msg(msgq.delete_head())
#print "m =", m.center_freq, m.data
self.assertEqual(expected_results[vlen*i:vlen*i + vlen], m.data)
def foobar4(self, new_t):
#print "foobar4: new_t =", new_t
pass
def xtest_004(self):
vlen = 4
tune = counter4(self, 1)
tune_delay = 1
dwell_delay = 2
msgq = gr.msg_queue()
src_data = tuple([float(x) for x in
( 1, 2, 3, 4,
9, 6, 11, 8,
5, 10, 7, 12,
13, 14, 15, 16
)])
expected_results = tuple([float(x) for x in
( 9, 10, 11, 12)])
src = gr.vector_source_f(src_data, False)
s2v = gr.stream_to_vector(gr.sizeof_float, vlen)
stats = gr.bin_statistics_f(vlen, msgq, tune, tune_delay, dwell_delay)
self.tb.connect(src, s2v, stats)
self.tb.run()
self.assertEqual(1, msgq.count())
for i in range(1):
m = parse_msg(msgq.delete_head())
#print "m =", m.center_freq, m.data
self.assertEqual(expected_results[vlen*i:vlen*i + vlen], m.data)
if __name__ == '__main__':
gr_unittest.run(xtest_bin_statistics, "test_bin_statistics.xml")
|
gpl-3.0
|
Oliver2213/NVDAYoutube-dl
|
addon/globalPlugins/nvdaYoutubeDL/youtube_dl/extractor/senateisvp.py
|
19
|
6075
|
# coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
ExtractorError,
unsmuggle_url,
)
from ..compat import (
compat_parse_qs,
compat_urlparse,
)
class SenateISVPIE(InfoExtractor):
_COMM_MAP = [
["ag", "76440", "http://ag-f.akamaihd.net"],
["aging", "76442", "http://aging-f.akamaihd.net"],
["approps", "76441", "http://approps-f.akamaihd.net"],
["armed", "76445", "http://armed-f.akamaihd.net"],
["banking", "76446", "http://banking-f.akamaihd.net"],
["budget", "76447", "http://budget-f.akamaihd.net"],
["cecc", "76486", "http://srs-f.akamaihd.net"],
["commerce", "80177", "http://commerce1-f.akamaihd.net"],
["csce", "75229", "http://srs-f.akamaihd.net"],
["dpc", "76590", "http://dpc-f.akamaihd.net"],
["energy", "76448", "http://energy-f.akamaihd.net"],
["epw", "76478", "http://epw-f.akamaihd.net"],
["ethics", "76449", "http://ethics-f.akamaihd.net"],
["finance", "76450", "http://finance-f.akamaihd.net"],
["foreign", "76451", "http://foreign-f.akamaihd.net"],
["govtaff", "76453", "http://govtaff-f.akamaihd.net"],
["help", "76452", "http://help-f.akamaihd.net"],
["indian", "76455", "http://indian-f.akamaihd.net"],
["intel", "76456", "http://intel-f.akamaihd.net"],
["intlnarc", "76457", "http://intlnarc-f.akamaihd.net"],
["jccic", "85180", "http://jccic-f.akamaihd.net"],
["jec", "76458", "http://jec-f.akamaihd.net"],
["judiciary", "76459", "http://judiciary-f.akamaihd.net"],
["rpc", "76591", "http://rpc-f.akamaihd.net"],
["rules", "76460", "http://rules-f.akamaihd.net"],
["saa", "76489", "http://srs-f.akamaihd.net"],
["smbiz", "76461", "http://smbiz-f.akamaihd.net"],
["srs", "75229", "http://srs-f.akamaihd.net"],
["uscc", "76487", "http://srs-f.akamaihd.net"],
["vetaff", "76462", "http://vetaff-f.akamaihd.net"],
["arch", "", "http://ussenate-f.akamaihd.net/"]
]
_IE_NAME = 'senate.gov'
_VALID_URL = r'http://www\.senate\.gov/isvp/?\?(?P<qs>.+)'
_TESTS = [{
'url': 'http://www.senate.gov/isvp/?comm=judiciary&type=live&stt=&filename=judiciary031715&auto_play=false&wmode=transparent&poster=http%3A%2F%2Fwww.judiciary.senate.gov%2Fthemes%2Fjudiciary%2Fimages%2Fvideo-poster-flash-fit.png',
'info_dict': {
'id': 'judiciary031715',
'ext': 'flv',
'title': 'Integrated Senate Video Player',
'thumbnail': 're:^https?://.*\.(?:jpg|png)$',
}
}, {
'url': 'http://www.senate.gov/isvp/?type=live&comm=commerce&filename=commerce011514.mp4&auto_play=false',
'info_dict': {
'id': 'commerce011514',
'ext': 'flv',
'title': 'Integrated Senate Video Player'
}
}, {
'url': 'http://www.senate.gov/isvp/?type=arch&comm=intel&filename=intel090613&hc_location=ufi',
# checksum differs each time
'info_dict': {
'id': 'intel090613',
'ext': 'mp4',
'title': 'Integrated Senate Video Player'
}
}, {
# From http://www.c-span.org/video/?96791-1
'url': 'http://www.senate.gov/isvp?type=live&comm=banking&filename=banking012715',
'only_matching': True,
}]
@staticmethod
def _search_iframe_url(webpage):
mobj = re.search(
r"<iframe[^>]+src=['\"](?P<url>http://www\.senate\.gov/isvp/?\?[^'\"]+)['\"]",
webpage)
if mobj:
return mobj.group('url')
def _get_info_for_comm(self, committee):
for entry in self._COMM_MAP:
if entry[0] == committee:
return entry[1:]
def _real_extract(self, url):
url, smuggled_data = unsmuggle_url(url, {})
qs = compat_parse_qs(re.match(self._VALID_URL, url).group('qs'))
if not qs.get('filename') or not qs.get('type') or not qs.get('comm'):
raise ExtractorError('Invalid URL', expected=True)
video_id = re.sub(r'.mp4$', '', qs['filename'][0])
webpage = self._download_webpage(url, video_id)
if smuggled_data.get('force_title'):
title = smuggled_data['force_title']
else:
title = self._html_search_regex(r'<title>([^<]+)</title>', webpage, video_id)
poster = qs.get('poster')
thumbnail = poster[0] if poster else None
video_type = qs['type'][0]
committee = video_type if video_type == 'arch' else qs['comm'][0]
stream_num, domain = self._get_info_for_comm(committee)
formats = []
if video_type == 'arch':
filename = video_id if '.' in video_id else video_id + '.mp4'
formats = [{
# All parameters in the query string are necessary to prevent a 403 error
'url': compat_urlparse.urljoin(domain, filename) + '?v=3.1.0&fp=&r=&g=',
}]
else:
hdcore_sign = 'hdcore=3.1.0'
url_params = (domain, video_id, stream_num)
f4m_url = '%s/z/%s_1@%s/manifest.f4m?' % url_params + hdcore_sign
m3u8_url = '%s/i/%s_1@%s/master.m3u8' % url_params
for entry in self._extract_f4m_formats(f4m_url, video_id, f4m_id='f4m'):
# URLs without the extra param induce an 404 error
entry.update({'extra_param_to_segment_url': hdcore_sign})
formats.append(entry)
for entry in self._extract_m3u8_formats(m3u8_url, video_id, ext='mp4', m3u8_id='m3u8'):
mobj = re.search(r'(?P<tag>(?:-p|-b)).m3u8', entry['url'])
if mobj:
entry['format_id'] += mobj.group('tag')
formats.append(entry)
self._sort_formats(formats)
return {
'id': video_id,
'title': title,
'formats': formats,
'thumbnail': thumbnail,
}
|
gpl-2.0
|
sylvan5/PRML
|
ch5/digits.py
|
2
|
2415
|
#coding:utf-8
import numpy as np
from mlp import MultiLayerPerceptron
from sklearn.datasets import load_digits
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import LabelBinarizer
from sklearn.metrics import confusion_matrix, classification_report
"""
簡易手書き数字データの認識
scikit-learnのインストールが必要
http://scikit-learn.org/
"""
if __name__ == "__main__":
# scikit-learnの簡易数字データをロード
# 1797サンプル, 8x8ピクセル
digits = load_digits()
# 訓練データを作成
X = digits.data
y = digits.target
# ピクセルの値を0.0-1.0に正規化
X /= X.max()
# 多層パーセプトロン
mlp = MultiLayerPerceptron(64, 100, 10, act1="tanh", act2="sigmoid")
# 訓練データ(90%)とテストデータ(10%)に分解
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1)
# 教師信号の数字を1-of-K表記に変換
# 0 => [1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
# 1 => [0, 1, 0, 0, 0, 0, 0, 0, 0, 0]
# ...
# 9 => [0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
labels_train = LabelBinarizer().fit_transform(y_train)
labels_test = LabelBinarizer().fit_transform(y_test)
# 訓練データを用いてニューラルネットの重みを学習
mlp.fit(X_train, labels_train, learning_rate=0.01, epochs=10000)
# テストデータを用いて予測精度を計算
predictions = []
for i in range(X_test.shape[0]):
o = mlp.predict(X_test[i])
# 最大の出力を持つクラスに分類
predictions.append(np.argmax(o))
print confusion_matrix(y_test, predictions)
print classification_report(y_test, predictions)
# 誤認識したデータのみ描画
# 誤認識データ数と誤っているテストデータのidxを収集
cnt = 0
error_idx = []
for idx in range(len(y_test)):
if y_test[idx] != predictions[idx]:
print "error: %d : %d => %d" % (idx, y_test[idx], predictions[idx])
error_idx.append(idx)
cnt += 1
# 描画
import pylab
for i, idx in enumerate(error_idx):
pylab.subplot(cnt/5 + 1, 5, i + 1)
pylab.axis('off')
pylab.imshow(X_test[idx].reshape((8, 8)), cmap=pylab.cm.gray_r)
pylab.title('%d : %i => %i' % (idx, y_test[idx], predictions[idx]))
pylab.show()
|
mit
|
alexryndin/ambari
|
ambari-server/src/main/resources/stacks/BIGTOP/0.8/services/PIG/package/scripts/pig_client.py
|
4
|
1154
|
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Ambari Agent
"""
import sys
from resource_management import *
from pig import pig
class PigClient(Script):
def install(self, env):
self.install_packages(env)
self.configure(env)
def configure(self, env):
import params
env.set_params(params)
pig()
def status(self, env):
raise ClientComponentHasNoStatus()
if __name__ == "__main__":
PigClient().execute()
|
apache-2.0
|
shsingh/ansible
|
test/support/network-integration/collections/ansible_collections/ansible/netcommon/plugins/action/net_get.py
|
47
|
6707
|
# (c) 2018, Ansible Inc,
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import os
import re
import uuid
import hashlib
from ansible.errors import AnsibleError
from ansible.module_utils._text import to_text, to_bytes
from ansible.module_utils.connection import Connection, ConnectionError
from ansible.plugins.action import ActionBase
from ansible.module_utils.six.moves.urllib.parse import urlsplit
from ansible.utils.display import Display
display = Display()
class ActionModule(ActionBase):
def run(self, tmp=None, task_vars=None):
socket_path = None
self._get_network_os(task_vars)
persistent_connection = self._play_context.connection.split(".")[-1]
result = super(ActionModule, self).run(task_vars=task_vars)
if persistent_connection != "network_cli":
# It is supported only with network_cli
result["failed"] = True
result["msg"] = (
"connection type %s is not valid for net_get module,"
" please use fully qualified name of network_cli connection type"
% self._play_context.connection
)
return result
try:
src = self._task.args["src"]
except KeyError as exc:
return {
"failed": True,
"msg": "missing required argument: %s" % exc,
}
# Get destination file if specified
dest = self._task.args.get("dest")
if dest is None:
dest = self._get_default_dest(src)
else:
dest = self._handle_dest_path(dest)
# Get proto
proto = self._task.args.get("protocol")
if proto is None:
proto = "scp"
if socket_path is None:
socket_path = self._connection.socket_path
conn = Connection(socket_path)
sock_timeout = conn.get_option("persistent_command_timeout")
try:
changed = self._handle_existing_file(
conn, src, dest, proto, sock_timeout
)
if changed is False:
result["changed"] = changed
result["destination"] = dest
return result
except Exception as exc:
result["msg"] = (
"Warning: %s idempotency check failed. Check dest" % exc
)
try:
conn.get_file(
source=src, destination=dest, proto=proto, timeout=sock_timeout
)
except Exception as exc:
result["failed"] = True
result["msg"] = "Exception received: %s" % exc
result["changed"] = changed
result["destination"] = dest
return result
def _handle_dest_path(self, dest):
working_path = self._get_working_path()
if os.path.isabs(dest) or urlsplit("dest").scheme:
dst = dest
else:
dst = self._loader.path_dwim_relative(working_path, "", dest)
return dst
def _get_src_filename_from_path(self, src_path):
filename_list = re.split("/|:", src_path)
return filename_list[-1]
def _get_default_dest(self, src_path):
dest_path = self._get_working_path()
src_fname = self._get_src_filename_from_path(src_path)
filename = "%s/%s" % (dest_path, src_fname)
return filename
def _handle_existing_file(self, conn, source, dest, proto, timeout):
"""
Determines whether the source and destination file match.
:return: False if source and dest both exist and have matching sha1 sums, True otherwise.
"""
if not os.path.exists(dest):
return True
cwd = self._loader.get_basedir()
filename = str(uuid.uuid4())
tmp_dest_file = os.path.join(cwd, filename)
try:
conn.get_file(
source=source,
destination=tmp_dest_file,
proto=proto,
timeout=timeout,
)
except ConnectionError as exc:
error = to_text(exc)
if error.endswith("No such file or directory"):
if os.path.exists(tmp_dest_file):
os.remove(tmp_dest_file)
return True
try:
with open(tmp_dest_file, "r") as f:
new_content = f.read()
with open(dest, "r") as f:
old_content = f.read()
except (IOError, OSError):
os.remove(tmp_dest_file)
raise
sha1 = hashlib.sha1()
old_content_b = to_bytes(old_content, errors="surrogate_or_strict")
sha1.update(old_content_b)
checksum_old = sha1.digest()
sha1 = hashlib.sha1()
new_content_b = to_bytes(new_content, errors="surrogate_or_strict")
sha1.update(new_content_b)
checksum_new = sha1.digest()
os.remove(tmp_dest_file)
if checksum_old == checksum_new:
return False
return True
def _get_working_path(self):
cwd = self._loader.get_basedir()
if self._task._role is not None:
cwd = self._task._role._role_path
return cwd
def _get_network_os(self, task_vars):
if "network_os" in self._task.args and self._task.args["network_os"]:
display.vvvv("Getting network OS from task argument")
network_os = self._task.args["network_os"]
elif self._play_context.network_os:
display.vvvv("Getting network OS from inventory")
network_os = self._play_context.network_os
elif (
"network_os" in task_vars.get("ansible_facts", {})
and task_vars["ansible_facts"]["network_os"]
):
display.vvvv("Getting network OS from fact")
network_os = task_vars["ansible_facts"]["network_os"]
else:
raise AnsibleError(
"ansible_network_os must be specified on this host"
)
return network_os
|
gpl-3.0
|
tareqalayan/ansible
|
lib/ansible/modules/cloud/cloudstack/cs_disk_offering.py
|
24
|
11291
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (c) 2018, David Passante <@dpassante>
# (c) 2017, René Moser <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: cs_disk_offering
description:
- Create and delete disk offerings for guest VMs.
- Update display_text or display_offering of existing disk offering.
short_description: Manages disk offerings on Apache CloudStack based clouds.
version_added: "2.7"
author:
- "David Passante (@dpassante)"
- "René Moser(@resmo)"
options:
disk_size:
description:
- Size of the disk offering in GB (1GB = 1,073,741,824 bytes).
bytes_read_rate:
description:
- Bytes read rate of the disk offering.
bytes_write_rate:
description:
- Bytes write rate of the disk offering.
display_text:
description:
- Display text of the disk offering.
- If not set, C(name) will be used as C(display_text) while creating.
domain:
description:
- Domain the disk offering is related to.
- Public for all domains and subdomains if not set.
hypervisor_snapshot_reserve:
description:
- Hypervisor snapshot reserve space as a percent of a volume.
- Only for managed storage using Xen or VMware.
customized:
description:
- Whether disk offering iops is custom or not.
type: bool
default: false
iops_read_rate:
description:
- IO requests read rate of the disk offering.
iops_write_rate:
description:
- IO requests write rate of the disk offering.
iops_max:
description:
- Max. iops of the disk offering.
iops_min:
description:
- Min. iops of the disk offering.
name:
description:
- Name of the disk offering.
required: true
provisioning_type:
description:
- Provisioning type used to create volumes.
choices:
- thin
- sparse
- fat
state:
description:
- State of the disk offering.
choices:
- present
- absent
default: present
storage_type:
description:
- The storage type of the disk offering.
choices:
- local
- shared
storage_tags:
description:
- The storage tags for this disk offering.
aliases:
- storage_tag
display_offering:
description:
- An optional field, whether to display the offering to the end user or not.
type: bool
extends_documentation_fragment: cloudstack
'''
EXAMPLES = '''
- name: Create a disk offering with local storage
local_action:
module: cs_disk_offering
name: small
display_text: Small 10GB
disk_size: 10
storage_type: local
- name: Create or update a disk offering with shared storage
local_action:
module: cs_disk_offering
name: small
display_text: Small 10GB
disk_size: 10
storage_type: shared
storage_tags: SAN01
- name: Remove a disk offering
local_action:
module: cs_disk_offering
name: small
state: absent
'''
RETURN = '''
---
id:
description: UUID of the disk offering
returned: success
type: string
sample: a6f7a5fc-43f8-11e5-a151-feff819cdc9f
disk_size:
description: Size of the disk offering in GB
returned: success
type: int
sample: 10
iops_max:
description: Max iops of the disk offering
returned: success
type: int
sample: 1000
iops_min:
description: Min iops of the disk offering
returned: success
type: int
sample: 500
bytes_read_rate:
description: Bytes read rate of the disk offering
returned: success
type: int
sample: 1000
bytes_write_rate:
description: Bytes write rate of the disk offering
returned: success
type: int
sample: 1000
iops_read_rate:
description: IO requests per second read rate of the disk offering
returned: success
type: int
sample: 1000
iops_write_rate:
description: IO requests per second write rate of the disk offering
returned: success
type: int
sample: 1000
created:
description: Date the offering was created
returned: success
type: string
sample: 2017-11-19T10:48:59+0000
display_text:
description: Display text of the offering
returned: success
type: string
sample: Small 10GB
domain:
description: Domain the offering is into
returned: success
type: string
sample: ROOT
storage_tags:
description: List of storage tags
returned: success
type: list
sample: [ 'eco' ]
customized:
description: Whether the offering uses custom IOPS or not
returned: success
type: bool
sample: false
name:
description: Name of the system offering
returned: success
type: string
sample: Micro
provisioning_type:
description: Provisioning type used to create volumes
returned: success
type: string
sample: thin
storage_type:
description: Storage type used to create volumes
returned: success
type: string
sample: shared
display_offering:
description: Whether to display the offering to the end user or not.
returned: success
type: bool
sample: false
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.cloudstack import (
AnsibleCloudStack,
cs_argument_spec,
cs_required_together,
)
class AnsibleCloudStackDiskOffering(AnsibleCloudStack):
def __init__(self, module):
super(AnsibleCloudStackDiskOffering, self).__init__(module)
self.returns = {
'disksize': 'disk_size',
'diskBytesReadRate': 'bytes_read_rate',
'diskBytesWriteRate': 'bytes_write_rate',
'diskIopsReadRate': 'iops_read_rate',
'diskIopsWriteRate': 'iops_write_rate',
'maxiops': 'iops_max',
'miniops': 'iops_min',
'hypervisorsnapshotreserve': 'hypervisor_snapshot_reserve',
'customized': 'customized',
'provisioningtype': 'provisioning_type',
'storagetype': 'storage_type',
'tags': 'storage_tags',
'displayoffering': 'display_offering',
}
self.disk_offering = None
def get_disk_offering(self):
args = {
'name': self.module.params.get('name'),
'domainid': self.get_domain(key='id'),
}
disk_offerings = self.query_api('listDiskOfferings', **args)
if disk_offerings:
for disk_offer in disk_offerings['diskoffering']:
if args['name'] == disk_offer['name']:
self.disk_offering = disk_offer
return self.disk_offering
def present_disk_offering(self):
disk_offering = self.get_disk_offering()
if not disk_offering:
disk_offering = self._create_offering(disk_offering)
else:
disk_offering = self._update_offering(disk_offering)
return disk_offering
def absent_disk_offering(self):
disk_offering = self.get_disk_offering()
if disk_offering:
self.result['changed'] = True
if not self.module.check_mode:
args = {
'id': disk_offering['id'],
}
self.query_api('deleteDiskOffering', **args)
return disk_offering
def _create_offering(self, disk_offering):
self.result['changed'] = True
args = {
'name': self.module.params.get('name'),
'displaytext': self.get_or_fallback('display_text', 'name'),
'disksize': self.module.params.get('disk_size'),
'bytesreadrate': self.module.params.get('bytes_read_rate'),
'byteswriterate': self.module.params.get('bytes_write_rate'),
'customized': self.module.params.get('customized'),
'domainid': self.get_domain(key='id'),
'hypervisorsnapshotreserve': self.module.params.get('hypervisor_snapshot_reserve'),
'iopsreadrate': self.module.params.get('iops_read_rate'),
'iopswriterate': self.module.params.get('iops_write_rate'),
'maxiops': self.module.params.get('iops_max'),
'miniops': self.module.params.get('iops_min'),
'provisioningtype': self.module.params.get('provisioning_type'),
'diskofferingdetails': self.module.params.get('disk_offering_details'),
'storagetype': self.module.params.get('storage_type'),
'tags': self.module.params.get('storage_tags'),
'displayoffering': self.module.params.get('display_offering'),
}
if not self.module.check_mode:
res = self.query_api('createDiskOffering', **args)
disk_offering = res['diskoffering']
return disk_offering
def _update_offering(self, disk_offering):
args = {
'id': disk_offering['id'],
'name': self.module.params.get('name'),
'displaytext': self.get_or_fallback('display_text', 'name'),
'displayoffering': self.module.params.get('display_offering'),
}
if self.has_changed(args, disk_offering):
self.result['changed'] = True
if not self.module.check_mode:
res = self.query_api('updateDiskOffering', **args)
disk_offering = res['diskoffering']
return disk_offering
def get_result(self, disk_offering):
super(AnsibleCloudStackDiskOffering, self).get_result(disk_offering)
if disk_offering:
# Prevent confusion, the api returns a tags key for storage tags.
if 'tags' in disk_offering:
self.result['storage_tags'] = disk_offering['tags'].split(',') or [disk_offering['tags']]
if 'tags' in self.result:
del self.result['tags']
return self.result
def main():
argument_spec = cs_argument_spec()
argument_spec.update(dict(
name=dict(required=True),
display_text=dict(),
domain=dict(),
disk_size=dict(type='int'),
display_offering=dict(type='bool'),
hypervisor_snapshot_reserve=dict(type='int'),
bytes_read_rate=dict(type='int'),
bytes_write_rate=dict(type='int'),
customized=dict(type='bool'),
iops_read_rate=dict(type='int'),
iops_write_rate=dict(type='int'),
iops_max=dict(type='int'),
iops_min=dict(type='int'),
provisioning_type=dict(choices=['thin', 'sparse', 'fat']),
storage_type=dict(choices=['local', 'shared']),
storage_tags=dict(type='list', aliases=['storage_tag']),
state=dict(choices=['present', 'absent'], default='present'),
))
module = AnsibleModule(
argument_spec=argument_spec,
required_together=cs_required_together(),
supports_check_mode=True
)
acs_do = AnsibleCloudStackDiskOffering(module)
state = module.params.get('state')
if state == "absent":
disk_offering = acs_do.absent_disk_offering()
else:
disk_offering = acs_do.present_disk_offering()
result = acs_do.get_result(disk_offering)
module.exit_json(**result)
if __name__ == '__main__':
main()
|
gpl-3.0
|
dendisuhubdy/tensorflow
|
tensorflow/contrib/distributions/python/ops/vector_laplace_diag.py
|
3
|
8336
|
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Distribution of a vectorized Laplace, with uncorrelated components."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.distributions.python.ops import distribution_util
from tensorflow.contrib.distributions.python.ops import vector_laplace_linear_operator as vector_laplace_linop
from tensorflow.python.framework import ops
__all__ = [
"VectorLaplaceDiag",
]
class VectorLaplaceDiag(
vector_laplace_linop.VectorLaplaceLinearOperator):
"""The vectorization of the Laplace distribution on `R^k`.
The vector laplace distribution is defined over `R^k`, and parameterized by
a (batch of) length-`k` `loc` vector (the means) and a (batch of) `k x k`
`scale` matrix: `covariance = 2 * scale @ scale.T`, where `@` denotes
matrix-multiplication.
#### Mathematical Details
The probability density function (pdf) is,
```none
pdf(x; loc, scale) = exp(-||y||_1) / Z,
y = inv(scale) @ (x - loc),
Z = 2**k |det(scale)|,
```
where:
* `loc` is a vector in `R^k`,
* `scale` is a linear operator in `R^{k x k}`, `cov = scale @ scale.T`,
* `Z` denotes the normalization constant, and,
* `||y||_1` denotes the `l1` norm of `y`, `sum_i |y_i|.
A (non-batch) `scale` matrix is:
```none
scale = diag(scale_diag + scale_identity_multiplier * ones(k))
```
where:
* `scale_diag.shape = [k]`, and,
* `scale_identity_multiplier.shape = []`.
Additional leading dimensions (if any) will index batches.
If both `scale_diag` and `scale_identity_multiplier` are `None`, then
`scale` is the Identity matrix.
The VectorLaplace distribution is a member of the [location-scale
family](https://en.wikipedia.org/wiki/Location-scale_family), i.e., it can be
constructed as,
```none
X = (X_1, ..., X_k), each X_i ~ Laplace(loc=0, scale=1)
Y = (Y_1, ...,Y_k) = scale @ X + loc
```
#### About `VectorLaplace` and `Vector` distributions in TensorFlow.
The `VectorLaplace` is a non-standard distribution that has useful properties.
The marginals `Y_1, ..., Y_k` are *not* Laplace random variables, due to
the fact that the sum of Laplace random variables is not Laplace.
Instead, `Y` is a vector whose components are linear combinations of Laplace
random variables. Thus, `Y` lives in the vector space generated by `vectors`
of Laplace distributions. This allows the user to decide the mean and
covariance (by setting `loc` and `scale`), while preserving some properties of
the Laplace distribution. In particular, the tails of `Y_i` will be (up to
polynomial factors) exponentially decaying.
To see this last statement, note that the pdf of `Y_i` is the convolution of
the pdf of `k` independent Laplace random variables. One can then show by
induction that distributions with exponential (up to polynomial factors) tails
are closed under convolution.
#### Examples
```python
tfd = tf.contrib.distributions
# Initialize a single 2-variate VectorLaplace.
vla = tfd.VectorLaplaceDiag(
loc=[1., -1],
scale_diag=[1, 2.])
vla.mean().eval()
# ==> [1., -1]
vla.stddev().eval()
# ==> [1., 2] * sqrt(2)
# Evaluate this on an observation in `R^2`, returning a scalar.
vla.prob([-1., 0]).eval() # shape: []
# Initialize a 3-batch, 2-variate scaled-identity VectorLaplace.
vla = tfd.VectorLaplaceDiag(
loc=[1., -1],
scale_identity_multiplier=[1, 2., 3])
vla.mean().eval() # shape: [3, 2]
# ==> [[1., -1]
# [1, -1],
# [1, -1]]
vla.stddev().eval() # shape: [3, 2]
# ==> sqrt(2) * [[1., 1],
# [2, 2],
# [3, 3]]
# Evaluate this on an observation in `R^2`, returning a length-3 vector.
vla.prob([-1., 0]).eval() # shape: [3]
# Initialize a 2-batch of 3-variate VectorLaplace's.
vla = tfd.VectorLaplaceDiag(
loc=[[1., 2, 3],
[11, 22, 33]] # shape: [2, 3]
scale_diag=[[1., 2, 3],
[0.5, 1, 1.5]]) # shape: [2, 3]
# Evaluate this on a two observations, each in `R^3`, returning a length-2
# vector.
x = [[-1., 0, 1],
[-11, 0, 11.]] # shape: [2, 3].
vla.prob(x).eval() # shape: [2]
```
"""
def __init__(self,
loc=None,
scale_diag=None,
scale_identity_multiplier=None,
validate_args=False,
allow_nan_stats=True,
name="VectorLaplaceDiag"):
"""Construct Vector Laplace distribution on `R^k`.
The `batch_shape` is the broadcast shape between `loc` and `scale`
arguments.
The `event_shape` is given by last dimension of the matrix implied by
`scale`. The last dimension of `loc` (if provided) must broadcast with this.
Recall that `covariance = 2 * scale @ scale.T`.
```none
scale = diag(scale_diag + scale_identity_multiplier * ones(k))
```
where:
* `scale_diag.shape = [k]`, and,
* `scale_identity_multiplier.shape = []`.
Additional leading dimensions (if any) will index batches.
If both `scale_diag` and `scale_identity_multiplier` are `None`, then
`scale` is the Identity matrix.
Args:
loc: Floating-point `Tensor`. If this is set to `None`, `loc` is
implicitly `0`. When specified, may have shape `[B1, ..., Bb, k]` where
`b >= 0` and `k` is the event size.
scale_diag: Non-zero, floating-point `Tensor` representing a diagonal
matrix added to `scale`. May have shape `[B1, ..., Bb, k]`, `b >= 0`,
and characterizes `b`-batches of `k x k` diagonal matrices added to
`scale`. When both `scale_identity_multiplier` and `scale_diag` are
`None` then `scale` is the `Identity`.
scale_identity_multiplier: Non-zero, floating-point `Tensor` representing
a scaled-identity-matrix added to `scale`. May have shape
`[B1, ..., Bb]`, `b >= 0`, and characterizes `b`-batches of scaled
`k x k` identity matrices added to `scale`. When both
`scale_identity_multiplier` and `scale_diag` are `None` then `scale` is
the `Identity`.
validate_args: Python `bool`, default `False`. When `True` distribution
parameters are checked for validity despite possibly degrading runtime
performance. When `False` invalid inputs may silently render incorrect
outputs.
allow_nan_stats: Python `bool`, default `True`. When `True`,
statistics (e.g., mean, mode, variance) use the value "`NaN`" to
indicate the result is undefined. When `False`, an exception is raised
if one or more of the statistic's batch members are undefined.
name: Python `str` name prefixed to Ops created by this class.
Raises:
ValueError: if at most `scale_identity_multiplier` is specified.
"""
parameters = dict(locals())
with ops.name_scope(name):
with ops.name_scope("init", values=[
loc, scale_diag, scale_identity_multiplier]):
# No need to validate_args while making diag_scale. The returned
# LinearOperatorDiag has an assert_non_singular method that is called by
# the Bijector.
scale = distribution_util.make_diag_scale(
loc=loc,
scale_diag=scale_diag,
scale_identity_multiplier=scale_identity_multiplier,
validate_args=False,
assert_positive=False)
super(VectorLaplaceDiag, self).__init__(
loc=loc,
scale=scale,
validate_args=validate_args,
allow_nan_stats=allow_nan_stats,
name=name)
self._parameters = parameters
|
apache-2.0
|
mrquim/repository.mrquim
|
plugin.video.mrpiracy/resources/lib/js2py/legecy_translators/nodevisitor.py
|
54
|
15965
|
from jsparser import *
from utils import *
import re
from utils import *
#Note all white space sent to this module must be ' ' so no '\n'
REPL = {}
#PROBLEMS
# <<=, >>=, >>>=
# they are unusual so I will not fix that now. a++ +b works fine and a+++++b (a++ + ++b) does not work even in V8
ASSIGNMENT_MATCH = '(?<!=|!|<|>)=(?!=)'
def unary_validitator(keyword, before, after):
if keyword[-1] in IDENTIFIER_PART:
if not after or after[0] in IDENTIFIER_PART:
return False
if before and before[-1] in IDENTIFIER_PART: # I am not sure here...
return False
return True
def comb_validitator(keyword, before, after):
if keyword=='instanceof' or keyword=='in':
if before and before[-1] in IDENTIFIER_PART:
return False
elif after and after[0] in IDENTIFIER_PART:
return False
return True
def bracket_replace(code):
new = ''
for e in bracket_split(code, ['()','[]'], False):
if e[0]=='[':
name = '#PYJSREPL'+str(len(REPL))+'{'
new+= name
REPL[name] = e
elif e[0]=='(': # can be a function call
name = '@PYJSREPL'+str(len(REPL))+'}'
new+= name
REPL[name] = e
else:
new+=e
return new
class NodeVisitor:
def __init__(self, code):
self.code = code
def rl(self, lis, op):
"""performs this operation on a list from *right to left*
op must take 2 args
a,b,c => op(a, op(b, c))"""
it = reversed(lis)
res = trans(it.next())
for e in it:
e = trans(e)
res = op(e, res)
return res
def lr(self, lis, op):
"""performs this operation on a list from *left to right*
op must take 2 args
a,b,c => op(op(a, b), c)"""
it = iter(lis)
res = trans(it.next())
for e in it:
e = trans(e)
res = op(res, e)
return res
def translate(self):
"""Translates outer operation and calls translate on inner operation.
Returns fully translated code."""
if not self.code:
return ''
new = bracket_replace(self.code)
#Check comma operator:
cand = new.split(',') #every comma in new must be an operator
if len(cand)>1: #LR
return self.lr(cand, js_comma)
#Check = operator:
# dont split at != or !== or == or === or <= or >=
#note <<=, >>= or this >>> will NOT be supported
# maybe I will change my mind later
# Find this crappy ?:
if '?' in new:
cond_ind = new.find('?')
tenary_start = 0
for ass in re.finditer(ASSIGNMENT_MATCH, new):
cand = ass.span()[1]
if cand < cond_ind:
tenary_start = cand
else:
break
actual_tenary = new[tenary_start:]
spl = ''.join(split_at_any(new, [':', '?'], translate=trans))
tenary_translation = transform_crap(spl)
assignment = new[:tenary_start] + ' PyJsConstantTENARY'
return trans(assignment).replace('PyJsConstantTENARY', tenary_translation)
cand = list(split_at_single(new, '=', ['!', '=','<','>'], ['=']))
if len(cand)>1: # RL
it = reversed(cand)
res = trans(it.next())
for e in it:
e = e.strip()
if not e:
raise SyntaxError('Missing left-hand in assignment!')
op = ''
if e[-2:] in OP_METHODS:
op = ','+e[-2:].__repr__()
e = e[:-2]
elif e[-1:] in OP_METHODS:
op = ','+e[-1].__repr__()
e = e[:-1]
e = trans(e)
#Now replace last get method with put and change args
c = list(bracket_split(e, ['()']))
beg, arglist = ''.join(c[:-1]).strip(), c[-1].strip() #strips just to make sure... I will remove it later
if beg[-4:]!='.get':
raise SyntaxError('Invalid left-hand side in assignment')
beg = beg[0:-3]+'put'
arglist = arglist[0:-1]+', '+res+op+')'
res = beg+arglist
return res
#Now check remaining 2 arg operators that are not handled by python
#They all have Left to Right (LR) associativity
order = [OR, AND, BOR, BXOR, BAND, EQS, COMPS, BSHIFTS, ADDS, MULTS]
# actually we dont need OR and AND because they can be handled easier. But just for fun
dangerous = ['<', '>']
for typ in order:
#we have to use special method for ADDS since they can be also unary operation +/++ or -/-- FUCK
if '+' in typ:
cand = list(split_add_ops(new))
else:
#dont translate. cant start or end on dangerous op.
cand = list(split_at_any(new, typ.keys(), False, dangerous, dangerous,validitate=comb_validitator))
if not len(cand)>1:
continue
n = 1
res = trans(cand[0])
if not res:
raise SyntaxError("Missing operand!")
while n<len(cand):
e = cand[n]
if not e:
raise SyntaxError("Missing operand!")
if n%2:
op = typ[e]
else:
res = op(res, trans(e))
n+=1
return res
#Now replace unary operators - only they are left
cand = list(split_at_any(new, UNARY.keys(), False, validitate=unary_validitator))
if len(cand)>1: #contains unary operators
if '++' in cand or '--' in cand: #it cant contain both ++ and --
if '--' in cand:
op = '--'
meths = js_post_dec, js_pre_dec
else:
op = '++'
meths = js_post_inc, js_pre_inc
pos = cand.index(op)
if cand[pos-1].strip(): # post increment
a = cand[pos-1]
meth = meths[0]
elif cand[pos+1].strip(): #pre increment
a = cand[pos+1]
meth = meths[1]
else:
raise SyntaxError('Invalid use of ++ operator')
if cand[pos+2:]:
raise SyntaxError('Too many operands')
operand = meth(trans(a))
cand = cand[:pos-1]
# now last cand should be operand and every other odd element should be empty
else:
operand = trans(cand[-1])
del cand[-1]
for i, e in enumerate(reversed(cand)):
if i%2:
if e.strip():
raise SyntaxError('Too many operands')
else:
operand = UNARY[e](operand)
return operand
#Replace brackets
if new[0]=='@' or new[0]=='#':
if len(list(bracket_split(new, ('#{','@}')))) ==1: # we have only one bracket, otherwise pseudobracket like @@....
assert new in REPL
if new[0]=='#':
raise SyntaxError('[] cant be used as brackets! Use () instead.')
return '('+trans(REPL[new][1:-1])+')'
#Replace function calls and prop getters
# 'now' must be a reference like: a or b.c.d but it can have also calls or getters ( for example a["b"](3))
#From here @@ means a function call and ## means get operation (note they dont have to present)
it = bracket_split(new, ('#{','@}'))
res = []
for e in it:
if e[0]!='#' and e[0]!='@':
res += [x.strip() for x in e.split('.')]
else:
res += [e.strip()]
# res[0] can be inside @@ (name)...
res = filter(lambda x: x, res)
if is_internal(res[0]):
out = res[0]
elif res[0][0] in {'#', '@'}:
out = '('+trans(REPL[res[0]][1:-1])+')'
elif is_valid_lval(res[0]) or res[0] in {'this', 'false', 'true', 'null'}:
out = 'var.get('+res[0].__repr__()+')'
else:
if is_reserved(res[0]):
raise SyntaxError('Unexpected reserved word: "%s"'%res[0])
raise SyntaxError('Invalid identifier: "%s"'%res[0])
if len(res)==1:
return out
n = 1
while n<len(res): #now every func call is a prop call
e = res[n]
if e[0]=='@': # direct call
out += trans_args(REPL[e])
n += 1
continue
args = False #assume not prop call
if n+1<len(res) and res[n+1][0]=='@': #prop call
args = trans_args(REPL[res[n+1]])[1:]
if args!=')':
args = ','+args
if e[0]=='#':
prop = trans(REPL[e][1:-1])
else:
if not is_lval(e):
raise SyntaxError('Invalid identifier: "%s"'%e)
prop = e.__repr__()
if args: # prop call
n+=1
out += '.callprop('+prop+args
else: #prop get
out += '.get('+prop+')'
n+=1
return out
def js_comma(a, b):
return 'PyJsComma('+a+','+b+')'
def js_or(a, b):
return '('+a+' or '+b+')'
def js_bor(a, b):
return '('+a+'|'+b+')'
def js_bxor(a, b):
return '('+a+'^'+b+')'
def js_band(a, b):
return '('+a+'&'+b+')'
def js_and(a, b):
return '('+a+' and '+b+')'
def js_strict_eq(a, b):
return 'PyJsStrictEq('+a+','+b+')'
def js_strict_neq(a, b):
return 'PyJsStrictNeq('+a+','+b+')'
#Not handled by python in the same way like JS. For example 2==2==True returns false.
# In JS above would return true so we need brackets.
def js_abstract_eq(a, b):
return '('+a+'=='+b+')'
#just like ==
def js_abstract_neq(a, b):
return '('+a+'!='+b+')'
def js_lt(a, b):
return '('+a+'<'+b+')'
def js_le(a, b):
return '('+a+'<='+b+')'
def js_ge(a, b):
return '('+a+'>='+b+')'
def js_gt(a, b):
return '('+a+'>'+b+')'
def js_in(a, b):
return b+'.contains('+a+')'
def js_instanceof(a, b):
return a+'.instanceof('+b+')'
def js_lshift(a, b):
return '('+a+'<<'+b+')'
def js_rshift(a, b):
return '('+a+'>>'+b+')'
def js_shit(a, b):
return 'PyJsBshift('+a+','+b+')'
def js_add(a, b): # To simplify later process of converting unary operators + and ++
return '(%s+%s)'%(a, b)
def js_sub(a, b): # To simplify
return '(%s-%s)'%(a, b)
def js_mul(a, b):
return '('+a+'*'+b+')'
def js_div(a, b):
return '('+a+'/'+b+')'
def js_mod(a, b):
return '('+a+'%'+b+')'
def js_typeof(a):
cand = list(bracket_split(a, ('()',)))
if len(cand)==2 and cand[0]=='var.get':
return cand[0]+cand[1][:-1]+',throw=False).typeof()'
return a+'.typeof()'
def js_void(a):
return '('+a+')'
def js_new(a):
cands = list(bracket_split(a, ('()',)))
lim = len(cands)
if lim < 2:
return a + '.create()'
n = 0
while n < lim:
c = cands[n]
if c[0]=='(':
if cands[n-1].endswith('.get') and n+1>=lim: # last get operation.
return a + '.create()'
elif cands[n-1][0]=='(':
return ''.join(cands[:n])+'.create' + c + ''.join(cands[n+1:])
elif cands[n-1]=='.callprop':
beg = ''.join(cands[:n-1])
args = argsplit(c[1:-1],',')
prop = args[0]
new_args = ','.join(args[1:])
create = '.get(%s).create(%s)' % (prop, new_args)
return beg + create + ''.join(cands[n+1:])
n+=1
return a + '.create()'
def js_delete(a):
#replace last get with delete.
c = list(bracket_split(a, ['()']))
beg, arglist = ''.join(c[:-1]).strip(), c[-1].strip() #strips just to make sure... I will remove it later
if beg[-4:]!='.get':
raise SyntaxError('Invalid delete operation')
return beg[:-3]+'delete'+arglist
def js_neg(a):
return '(-'+a+')'
def js_pos(a):
return '(+'+a+')'
def js_inv(a):
return '(~'+a+')'
def js_not(a):
return a+'.neg()'
def postfix(a, inc, post):
bra = list(bracket_split(a, ('()',)))
meth = bra[-2]
if not meth.endswith('get'):
raise SyntaxError('Invalid ++ or -- operation.')
bra[-2] = bra[-2][:-3] + 'put'
bra[-1] = '(%s,%s%sJs(1))' % (bra[-1][1:-1], a, '+' if inc else '-')
res = ''.join(bra)
return res if not post else '(%s%sJs(1))' % (res, '-' if inc else '+')
def js_pre_inc(a):
return postfix(a, True, False)
def js_post_inc(a):
return postfix(a, True, True)
def js_pre_dec(a):
return postfix(a, False, False)
def js_post_dec(a):
return postfix(a, False, True)
OR = {'||': js_or}
AND = {'&&': js_and}
BOR = {'|': js_bor}
BXOR = {'^': js_bxor}
BAND = {'&': js_band}
EQS = {'===': js_strict_eq,
'!==': js_strict_neq,
'==': js_abstract_eq, # we need == and != too. Read a note above method
'!=': js_abstract_neq}
#Since JS does not have chained comparisons we need to implement all cmp methods.
COMPS = {'<': js_lt,
'<=': js_le,
'>=': js_ge,
'>': js_gt,
'instanceof': js_instanceof, #todo change to validitate
'in': js_in}
BSHIFTS = {'<<': js_lshift,
'>>': js_rshift,
'>>>': js_shit}
ADDS = {'+': js_add,
'-': js_sub}
MULTS = {'*': js_mul,
'/': js_div,
'%': js_mod}
#Note they dont contain ++ and -- methods because they both have 2 different methods
# correct method will be found automatically in translate function
UNARY = {'typeof': js_typeof,
'void': js_void,
'new': js_new,
'delete': js_delete,
'!': js_not,
'-': js_neg,
'+': js_pos,
'~': js_inv,
'++': None,
'--': None
}
def transform_crap(code): #needs some more tests
"""Transforms this ?: crap into if else python syntax"""
ind = code.rfind('?')
if ind==-1:
return code
sep = code.find(':', ind)
if sep==-1:
raise SyntaxError('Invalid ?: syntax (probably missing ":" )')
beg = max(code.rfind(':', 0, ind), code.find('?', 0, ind))+1
end = code.find(':',sep+1)
end = len(code) if end==-1 else end
formula = '('+code[ind+1:sep]+' if '+code[beg:ind]+' else '+code[sep+1:end]+')'
return transform_crap(code[:beg]+formula+code[end:])
from code import InteractiveConsole
#e = InteractiveConsole(globals()).interact()
import traceback
def trans(code):
return NodeVisitor(code.strip()).translate().strip()
#todo finish this trans args
def trans_args(code):
new = bracket_replace(code.strip()[1:-1])
args = ','.join(trans(e) for e in new.split(','))
return '(%s)'%args
EXP = 0
def exp_translator(code):
global REPL, EXP
EXP += 1
REPL = {}
#print EXP, code
code = code.replace('\n', ' ')
assert '@' not in code
assert ';' not in code
assert '#' not in code
#if not code.strip(): #?
# return 'var.get("undefined")'
try:
return trans(code)
except:
#print '\n\ntrans failed on \n\n' + code
#raw_input('\n\npress enter')
raise
if __name__=='__main__':
#print 'Here', trans('(eee ) . ii [ PyJsMarker ] [ jkj ] ( j , j ) .
# jiji (h , ji , i)(non )( )()()()')
for e in xrange(3):
print exp_translator('jk = kk.ik++')
#First line translated with PyJs: PyJsStrictEq(PyJsAdd((Js(100)*Js(50)),Js(30)), Js("5030")), yay!
print exp_translator('delete a.f')
|
gpl-2.0
|
bluemurder/mlfl
|
config.py
|
1
|
3279
|
version = "1.0"
start_date = '2009-01-01' # Start date for all the computations
ref_symbol = 'ETFMIB.MI' # Symbol used to map main market (SPY, ETFMIB,...)
test_portfolio = ['STS.MI', 'ENEL.MI', 'SFER.MI']
ftsemib_symbols = ['A2A.MI', 'ATL.MI', 'BMPS.MI', 'BAMI.MI',
'BMED.MI', 'BPE.MI',
'BRE.MI', 'BZU.MI', 'CPR.MI', 'CNHI.MI', 'ENEL.MI', 'ENI.MI',
'EXO.MI', 'SFER.MI', 'RACE.MI', 'FCA.MI', 'FBK.MI', 'G.MI',
'ISP.MI', 'IG.MI', 'LDO.MI', 'LUX.MI', 'MS.MI', 'MB.MI',
'MONC.MI', 'PST.MI', 'PRY.MI', 'REC.MI', 'SPM.MI', 'SRG.MI',
'STM.MI', 'TIT.MI', 'TEN.MI', 'TRN.MI', 'UBI.MI', 'UCG.MI',
'UNI.MI', 'US.MI', 'YNAP.MI']
ftsemib_allshare_symbols = ['A2A.MI', 'ACE.MI', 'ACO.MI',
'ACS.MI', 'AE.MI', 'AEF.MI',
'ADB.MI', 'ARN.MI', 'AZA.MI', 'ATH.MI', 'AMP.MI', 'ANIM.MI',
'STS.MI', 'ASR.MI', 'ASC.MI', 'AST.MI', 'AT.MI', 'ATL.MI',
'AGL.MI', 'AUTME.MI', 'AZM.MI', 'BEC.MI', 'CRG.MI', 'CRGR.MI',
'BFE.MI', 'BGN.MI', 'IF.MI', 'BMPS.MI', 'PRO.MI', 'BST.MI',
'BAMI.MI', 'SANT.MI', 'BANZ.MI', 'BAN.MI', 'B.MI', 'BB.MI',
'BIM.MI', 'BMED.MI', 'PEL.MI', 'BPSO.MI', 'SPO.MI', 'BDBR.MI',
'BDB.MI', 'BSRP.MI', 'BET.MI', 'BE.MI', 'BNS.MI', 'BEST.MI',
'BIA.MI', 'BCM.MI', 'BSS.MI', 'BIE.MI', 'BOE.MI', 'BF.MI',
'BO.MI', 'BOR.MI', 'BPE.MI', 'BRE.MI', 'BRI.MI', 'BC.MI',
'BZU.MI', 'BZUR.MI', 'CAD.MI', 'CAI.MI', 'CLF.MI', 'CALT.MI',
'CED.MI', 'CPR.MI', 'CARR.MI', 'CASS.MI', 'CMB.MI', 'CEM.MI',
'CLT.MI', 'RIC.MI', 'CERV.MI', 'CHL.MI', 'CIA.MI', 'CC.MI',
'CIR.MI', 'CLE.MI', 'CNHI.MI', 'COF.MI', 'CRES.MI', 'CNP.MI',
'CVAL.MI', 'CE.MI', 'CSP.MI', 'CTIC.MI', 'DA.MI', 'DMN.MI',
'DIS.MI', 'DAN.MI', 'DANR.MI', 'DAL.MI', 'DLG.MI', 'DEA.MI',
'DIA.MI', 'DIB.MI', 'DMA.MI', 'EDNR.MI', 'EEMS.MI', 'EIT.MI',
'ELN.MI', 'ELC.MI', 'EM.MI', 'ENAV.MI', 'ENAV_D.MI', 'ENEL.MI',
'ENV.MI', 'ENI.MI', 'ERG.MI', 'PRT.MI', 'EUK.MI', 'ETH.MI',
'EXO.MI', 'XPR.MI', 'FKR.MI', 'SFER.MI', 'RACE.MI', 'FCA.MI',
'FDA.MI', 'FM.MI', 'FILA.MI', 'FCT.MI', 'FCT_D.MI', 'FBK.MI',
'FNM.MI', 'FUL.MI', 'GAB.MI', 'GSP.MI', 'GE.MI', 'G.MI',
'GEO.MI', 'GEQ.MI', 'ES.MI', 'WIG.MI', 'IGV.MI', 'GCN.MI',
'HER.MI', 'IMA.MI', 'IGD.MI', 'S24.MI', 'IMS.MI', 'IIN.MI',
'IKG.MI', 'IKGR.MI', 'IP.MI', 'ISP.MI', 'ISPR.MI', 'INW.MI',
'IRC.MI', 'IRE.MI', 'ISGS.MI', 'ISG.MI', 'ITW.MI', 'IG.MI',
'IOL.MI', 'ITM.MI', 'IVS.MI', 'JUVE.MI', 'KRE.MI', 'LD.MI',
'LR.MI', 'LDO.MI', 'LUX.MI', 'LVEN.MI', 'MT.MI', 'MARR.MI',
'MZB.MI', 'MCH.MI', 'MS.MI', 'MB.MI', 'MIT.MI', 'MSK.MI',
'MLM.MI', 'MONC.MI', 'MN.MI', 'MTV.MI', 'MON.MI', 'MOL.MI',
'NICE.MI', 'NR.MI', 'OLI.MI', 'OJM.MI', 'OVS.MI', 'PAN.MI',
'PLT.MI', 'PIA.MI', 'PRL.MI', 'PINF.MI', 'PQ.MI', 'PSF.MI',
'POL.MI', 'PST_D.MI', 'PST.MI', 'PRS.MI', 'PR.MI', 'PRI.MI',
'PRY.MI', 'RWAY.MI', 'RWAY_D.MI', 'RAT.MI', 'RCS.MI', 'REC.MI',
'RM.MI', 'REY.MI', 'LIT.MI', 'RN.MI', 'ROS.MI', 'SSL.MI',
'SAB.MI', 'SG.MI', 'SGR.MI', 'SFL.MI', 'SPM.MI', 'SALR.MI',
'SAL.MI', 'SRS.MI', 'SAVE.MI', 'SRI.MI', 'SES.MI', 'SIS.MI',
'SII.MI', 'SNA.MI', 'SRG.MI', 'SO.MI', 'SOL.MI', 'STEF.MI',
'STM.MI', 'TIP.MI', 'TAS.MI', 'TGYM.MI', 'TECN.MI', 'TIT.MI',
'TITR.MI', 'TEN.MI', 'TRN.MI', 'TER.MI', 'TES.MI', 'TIS.MI',
'TOD.MI', 'TYA.MI', 'TFI.MI', 'TXT.MI', 'UBI.MI', 'UCG.MI',
'UCGR.MI', 'UNI.MI', 'US.MI', 'VLS.MI', 'VIA.MI', 'VAS.MI',
'YNAP.MI', 'ZV.MI', 'ZUC.MI', 'ZUCR.MI']
|
mit
|
jeffery-do/Vizdoombot
|
doom/lib/python3.5/site-packages/theano/scan_module/scan.py
|
3
|
48450
|
"""
This module provides the Scan Op.
Scanning is a general form of recurrence, which can be used for looping.
The idea is that you *scan* a function along some input sequence, producing
an output at each time-step that can be seen (but not modified) by the
function at the next time-step. (Technically, the function can see the
previous K time-steps of your outputs and L time steps (from past and
future) of your inputs.
So for example, ``sum()`` could be computed by scanning the ``z+x_i``
function over a list, given an initial state of ``z=0``.
Special cases:
* A *reduce* operation can be performed by using only the last
output of a ``scan``.
* A *map* operation can be performed by applying a function that
ignores previous steps of the outputs.
Often a for-loop or while-loop can be expressed as a ``scan()`` operation,
and ``scan`` is the closest that theano comes to looping. The advantages
of using ``scan`` over `for` loops in python (amongs other) are:
* it allows the number of iterations to be part of the symbolic graph
* it allows computing gradients through the for loop
* there exist a bunch of optimizations that help re-write your loop
such that less memory is used and that it runs faster
* it ensures that data is not copied from host to gpu and gpu to
host at each step
The Scan Op should typically be used by calling any of the following
functions: ``scan()``, ``map()``, ``reduce()``, ``foldl()``,
``foldr()``.
"""
__docformat__ = 'restructedtext en'
__authors__ = ("Razvan Pascanu "
"Frederic Bastien "
"James Bergstra "
"Pascal Lamblin ")
__copyright__ = "(c) 2010, Universite de Montreal"
__contact__ = "Razvan Pascanu <r.pascanu@gmail>"
import logging
import numpy
import warnings
from theano.compat import ifilter, izip
from six import iteritems, integer_types
from six.moves import xrange
from theano.compile import SharedVariable, function
from theano import compile
from theano import gof
from theano.tensor import opt
from theano import tensor
from theano import config
from theano.updates import OrderedUpdates
from theano.compile import ops
from theano.compat import OrderedDict
from theano.scan_module import scan_op
from theano.scan_module import scan_utils
from theano.scan_module.scan_utils import safe_new, traverse
# Logging function for sending warning or info
_logger = logging.getLogger('theano.scan_module.scan')
def scan(fn,
sequences=None,
outputs_info=None,
non_sequences=None,
n_steps=None,
truncate_gradient=-1,
go_backwards=False,
mode=None,
name=None,
profile=False,
allow_gc=None,
strict=False):
"""
This function constructs and applies a Scan op to the provided
arguments.
Parameters
----------
fn
``fn`` is a function that describes the operations involved in one
step of ``scan``. ``fn`` should construct variables describing the
output of one iteration step. It should expect as input theano
variables representing all the slices of the input sequences
and previous values of the outputs, as well as all other arguments
given to scan as ``non_sequences``. The order in which scan passes
these variables to ``fn`` is the following :
* all time slices of the first sequence
* all time slices of the second sequence
* ...
* all time slices of the last sequence
* all past slices of the first output
* all past slices of the second otuput
* ...
* all past slices of the last output
* all other arguments (the list given as `non_sequences` to
scan)
The order of the sequences is the same as the one in the list
`sequences` given to scan. The order of the outputs is the same
as the order of ``outputs_info``. For any sequence or output the
order of the time slices is the same as the one in which they have
been given as taps. For example if one writes the following :
.. code-block:: python
scan(fn, sequences = [ dict(input= Sequence1, taps = [-3,2,-1])
, Sequence2
, dict(input = Sequence3, taps = 3) ]
, outputs_info = [ dict(initial = Output1, taps = [-3,-5])
, dict(initial = Output2, taps = None)
, Output3 ]
, non_sequences = [ Argument1, Argument2])
``fn`` should expect the following arguments in this given order:
#. ``Sequence1[t-3]``
#. ``Sequence1[t+2]``
#. ``Sequence1[t-1]``
#. ``Sequence2[t]``
#. ``Sequence3[t+3]``
#. ``Output1[t-3]``
#. ``Output1[t-5]``
#. ``Output3[t-1]``
#. ``Argument1``
#. ``Argument2``
The list of ``non_sequences`` can also contain shared variables
used in the function, though ``scan`` is able to figure those
out on its own so they can be skipped. For the clarity of the
code we recommend though to provide them to scan. To some extend
``scan`` can also figure out other ``non sequences`` (not shared)
even if not passed to scan (but used by `fn`). A simple example of
this would be :
.. code-block:: python
import theano.tensor as TT
W = TT.matrix()
W_2 = W**2
def f(x):
return TT.dot(x,W_2)
The function is expected to return two things. One is a list of
outputs ordered in the same order as ``outputs_info``, with the
difference that there should be only one output variable per
output initial state (even if no tap value is used). Secondly
`fn` should return an update dictionary (that tells how to
update any shared variable after each iteration step). The
dictionary can optionally be given as a list of tuples. There is
no constraint on the order of these two list, ``fn`` can return
either ``(outputs_list, update_dictionary)`` or
``(update_dictionary, outputs_list)`` or just one of the two (in
case the other is empty).
To use ``scan`` as a while loop, the user needs to change the
function ``fn`` such that also a stopping condition is returned.
To do so, he/she needs to wrap the condition in an ``until`` class.
The condition should be returned as a third element, for example:
.. code-block:: python
...
return [y1_t, y2_t], {x:x+1}, theano.scan_module.until(x < 50)
Note that a number of steps (considered in here as the maximum
number of steps ) is still required even though a condition is
passed (and it is used to allocate memory if needed). = {}):
sequences
``sequences`` is the list of Theano variables or dictionaries
describing the sequences ``scan`` has to iterate over. If a
sequence is given as wrapped in a dictionary, then a set of optional
information can be provided about the sequence. The dictionary
should have the following keys:
* ``input`` (*mandatory*) -- Theano variable representing the
sequence.
* ``taps`` -- Temporal taps of the sequence required by ``fn``.
They are provided as a list of integers, where a value ``k``
impiles that at iteration step ``t`` scan will pass to ``fn``
the slice ``t+k``. Default value is ``[0]``
Any Theano variable in the list ``sequences`` is automatically
wrapped into a dictionary where ``taps`` is set to ``[0]``
outputs_info
``outputs_info`` is the list of Theano variables or dictionaries
describing the initial state of the outputs computed
recurrently. When this initial states are given as dictionary
optional information can be provided about the output corresponding
to these initial states. The dictionary should have the following
keys:
* ``initial`` -- Theano variable that represents the initial
state of a given output. In case the output is not computed
recursively (think of a map) and does not require an initial
state this field can be skipped. Given that (only) the previous
time step of the output is used by ``fn``, the initial state
**should have the same shape** as the output and **should not
involve a downcast** of the data type of the output. If multiple
time taps are used, the initial state should have one extra
dimension that should cover all the possible taps. For example
if we use ``-5``, ``-2`` and ``-1`` as past taps, at step 0,
``fn`` will require (by an abuse of notation) ``output[-5]``,
``output[-2]`` and ``output[-1]``. This will be given by
the initial state, which in this case should have the shape
(5,)+output.shape. If this variable containing the initial
state is called ``init_y`` then ``init_y[0]`` *corresponds to*
``output[-5]``. ``init_y[1]`` *correponds to* ``output[-4]``,
``init_y[2]`` corresponds to ``output[-3]``, ``init_y[3]``
coresponds to ``output[-2]``, ``init_y[4]`` corresponds to
``output[-1]``. While this order might seem strange, it comes
natural from splitting an array at a given point. Assume that
we have a array ``x``, and we choose ``k`` to be time step
``0``. Then our initial state would be ``x[:k]``, while the
output will be ``x[k:]``. Looking at this split, elements in
``x[:k]`` are ordered exactly like those in ``init_y``.
* ``taps`` -- Temporal taps of the output that will be pass to
``fn``. They are provided as a list of *negative* integers,
where a value ``k`` implies that at iteration step ``t`` scan
will pass to ``fn`` the slice ``t+k``.
``scan`` will follow this logic if partial information is given:
* If an output is not wrapped in a dictionary, ``scan`` will wrap
it in one assuming that you use only the last step of the output
(i.e. it makes your tap value list equal to [-1]).
* If you wrap an output in a dictionary and you do not provide any
taps but you provide an initial state it will assume that you are
using only a tap value of -1.
* If you wrap an output in a dictionary but you do not provide any
initial state, it assumes that you are not using any form of
taps.
* If you provide a ``None`` instead of a variable or a empty
dictionary ``scan`` assumes that you will not use any taps for
this output (like for example in case of a map)
If ``outputs_info`` is an empty list or None, ``scan`` assumes
that no tap is used for any of the outputs. If information is
provided just for a subset of the outputs an exception is
raised (because there is no convention on how scan should map
the provided information to the outputs of ``fn``)
non_sequences
``non_sequences`` is the list of arguments that are passed to
``fn`` at each steps. One can opt to exclude variable
used in ``fn`` from this list as long as they are part of the
computational graph, though for clarity we encourage not to do so.
n_steps
``n_steps`` is the number of steps to iterate given as an int
or Theano scalar. If any of the input sequences do not have
enough elements, scan will raise an error. If the *value is 0* the
outputs will have *0 rows*. If the value is negative, ``scan``
will run backwards in time. If the ``go_backwards`` flag is already
set and also ``n_steps`` is negative, ``scan`` will run forward
in time. If n_steps is not provided, ``scan`` will figure
out the amount of steps it should run given its input sequences.
truncate_gradient
``truncate_gradient`` is the number of steps to use in truncated
BPTT. If you compute gradients through a scan op, they are
computed using backpropagation through time. By providing a
different value then -1, you choose to use truncated BPTT instead
of classical BPTT, where you go for only ``truncate_gradient``
number of steps back in time.
go_backwards
``go_backwards`` is a flag indicating if ``scan`` should go
backwards through the sequences. If you think of each sequence
as indexed by time, making this flag True would mean that
``scan`` goes back in time, namely that for any sequence it
starts from the end and goes towards 0.
name
When profiling ``scan``, it is crucial to provide a name for any
instance of ``scan``. The profiler will produce an overall
profile of your code as well as profiles for the computation of
one step of each instance of ``scan``. The ``name`` of the instance
appears in those profiles and can greatly help to disambiguate
information.
mode
It is recommended to leave this argument to None, especially
when profiling ``scan`` (otherwise the results are not going to
be accurate). If you prefer the computations of one step of
``scan`` to be done differently then the entire function, you
can use this parameter to describe how the computations in this
loop are done (see ``theano.function`` for details about
possible values and their meaning).
profile
Flag or string. If true, or different from the empty string, a
profile object will be created and attached to the inner graph of
scan. In case ``profile`` is True, the profile object will have the
name of the scan instance, otherwise it will have the passed string.
Profile object collect (and print) information only when running the
inner graph with the new cvm linker ( with default modes,
other linkers this argument is useless)
allow_gc
Set the value of allow gc for the internal graph of scan. If
set to None, this will use the value of config.scan.allow_gc.
strict
If true, all the shared variables used in ``fn`` must be provided as a
part of ``non_sequences`` or ``sequences``.
Returns
-------
tuple
Tuple of the form (outputs, updates); ``outputs`` is either a
Theano variable or a list of Theano variables representing the
outputs of ``scan`` (in the same order as in ``outputs_info``).
``updates`` is a subclass of dictionary specifying the update rules for
all shared variables used in scan.
This dictionary should be passed to ``theano.function`` when you compile
your function. The change compared to a normal dictionary is that we
validate that keys are SharedVariable and addition of those dictionary
are validated to be consistent.
"""
# General observation : this code is executed only once, at creation
# of the computational graph, so we don't yet need to be smart about
# anything (to speed things up)
##
# Step 1. Wrap all inputs in dictionaries and add default values
##
# check if inputs are just single variables instead of lists
def wrap_into_list(x):
"""
Wrap the input into a list if it is not already a list.
"""
if x is None:
return []
elif not isinstance(x, (list, tuple)):
return [x]
else:
return list(x)
seqs = wrap_into_list(sequences)
outs_info = wrap_into_list(outputs_info)
# Make sure we get rid of numpy arrays or ints or anything like that
# passed as inputs to scan
non_seqs = []
for elem in wrap_into_list(non_sequences):
if not isinstance(elem, gof.Variable):
non_seqs.append(tensor.as_tensor_variable(elem))
else:
non_seqs.append(elem)
# If we provided a known number of steps ( before compilation)
# and if that number is 1 or -1, then we can skip the Scan Op,
# and just apply the inner function once
# To do that we check here to see the nature of n_steps
n_fixed_steps = None
if isinstance(n_steps, (float, integer_types)):
n_fixed_steps = int(n_steps)
else:
try:
n_fixed_steps = opt.get_scalar_constant_value(n_steps)
except tensor.basic.NotScalarConstantError:
n_fixed_steps = None
# Check n_steps is an int
if (hasattr(n_steps, 'dtype') and
str(n_steps.dtype)[:3] not in ('uin', 'int')):
raise ValueError(' n_steps must be an int. dtype provided '
'is %s' % n_steps.dtype)
# compute number of sequences and number of outputs
n_seqs = len(seqs)
n_outs = len(outs_info)
return_steps = OrderedDict()
# wrap sequences in a dictionary if they are not already dictionaries
for i in xrange(n_seqs):
if not isinstance(seqs[i], dict):
seqs[i] = OrderedDict([('input', seqs[i]), ('taps', [0])])
elif seqs[i].get('taps', None) is not None:
seqs[i]['taps'] = wrap_into_list(seqs[i]['taps'])
elif seqs[i].get('taps', None) is None:
# seqs dictionary does not have the ``taps`` key
seqs[i]['taps'] = [0]
# wrap outputs info in a dictionary if they are not already in one
for i in xrange(n_outs):
if outs_info[i] is not None:
if isinstance(outs_info[i], dict):
# DEPRECATED :
if outs_info[i].get('return_steps', None) is not None:
raise ValueError(
"Using `return_steps` has been deprecated. "
"Simply select the entries you need using a "
"subtensor. Scan will optimize memory "
"consumption, so do not worry about that.")
# END
if not isinstance(outs_info[i], dict):
# by default any output has a tap value of -1
outs_info[i] = OrderedDict([('initial', outs_info[i]), ('taps', [-1])])
elif (outs_info[i].get('initial', None) is None and
outs_info[i].get('taps', None) is not None):
# ^ no initial state but taps provided
raise ValueError(('If you are using slices of an output '
'you need to provide a initial state '
'for it'), outs_info[i])
elif (outs_info[i].get('initial', None) is not None and
outs_info[i].get('taps', None) is None):
# ^ initial state but taps not provided
if 'taps' in outs_info[i]:
# ^ explicitly provided a None for taps
_logger.warning('Output %s ( index %d) has a initial '
'state but taps is explicitly set to None ',
getattr(outs_info[i]['initial'], 'name', 'None'),
i)
outs_info[i]['taps'] = [-1]
else:
# if a None is provided as the output info we replace it
# with an empty OrdereDict() to simplify handling
outs_info[i] = OrderedDict()
##
# Step 2. Generate inputs and outputs of the inner functions
# for compiling a dummy function (Iteration #1)
##
# create theano inputs for the recursive function
# note : this is a first batch of possible inputs that will
# be compiled in a dummy function; we used this dummy
# function to detect shared variables and their updates
# and to construct a new and complete list of inputs and
# outputs
n_seqs = 0
scan_seqs = [] # Variables passed as inputs to the scan op
inner_seqs = [] # Variables passed as inputs to the inner function
inner_slices = [] # Actual slices if scan is removed from the picture
# go through sequences picking up time slices as needed
for i, seq in enumerate(seqs):
# Note that you can have something like no taps for
# a sequence, though is highly unlikely in practice
if 'taps' in seq:
# go through the indicated slice
mintap = numpy.min(seq['taps'])
maxtap = numpy.max(seq['taps'])
for k in seq['taps']:
# create one slice of the input
# Later on, if we decide not to use scan because we are
# going for just one step, it makes things easier if we
# compute the correct outputs here. This way we can use
# the output of the lambda expression directly to replace
# the output of scan.
# If not we need to use copies, that will be replaced at
# each frame by the corresponding slice
actual_slice = seq['input'][k - mintap]
_seq_val = tensor.as_tensor_variable(seq['input'])
_seq_val_slice = _seq_val[k - mintap]
nw_slice = _seq_val_slice.type()
# Try to transfer test_value to the new variable
if config.compute_test_value != 'off':
try:
nw_slice.tag.test_value = gof.Op._get_test_value(
_seq_val_slice)
except AttributeError as e:
if config.compute_test_value != 'ignore':
# No need to print a warning or raise an error now,
# it will be done when fn will be called.
_logger.info(('Cannot compute test value for '
'the inner function of scan, input value '
'missing %s'), e)
# Add names to slices for debugging and pretty printing ..
# that is if the input already has a name
if getattr(seq['input'], 'name', None) is not None:
if k > 0:
nw_name = seq['input'].name + '[t+%d]' % k
elif k == 0:
nw_name = seq['input'].name + '[t]'
else:
nw_name = seq['input'].name + '[t%d]' % k
nw_slice.name = nw_name
# We cut the sequence such that seq[i] to correspond to
# seq[i-k]. For the purposes of cutting the sequences, we
# need to pretend tap 0 is used to avoid cutting the sequences
# too long if the taps are all lower or all higher than 0.
maxtap_proxy = max(maxtap, 0)
mintap_proxy = min(mintap, 0)
start = (k - mintap_proxy)
if k == maxtap_proxy:
nw_seq = seq['input'][start:]
else:
end = -(maxtap_proxy - k)
nw_seq = seq['input'][start:end]
if go_backwards:
nw_seq = nw_seq[::-1]
scan_seqs.append(nw_seq)
inner_seqs.append(nw_slice)
inner_slices.append(actual_slice)
n_seqs += 1
# Since we've added all sequences now we need to level them up based on
# n_steps or their different shapes
lengths_vec = []
for seq in scan_seqs:
lengths_vec.append(seq.shape[0])
if not scan_utils.isNaN_or_Inf_or_None(n_steps):
# ^ N_steps should also be considered
lengths_vec.append(tensor.as_tensor(n_steps))
if len(lengths_vec) == 0:
# ^ No information about the number of steps
raise ValueError('No information about the number of steps '
'provided. Either provide a value for '
'n_steps argument of scan or provide an input '
'sequence')
# If the user has provided the number of steps, do that regardless ( and
# raise an error if the sequences are not long enough )
if scan_utils.isNaN_or_Inf_or_None(n_steps):
actual_n_steps = lengths_vec[0]
for contestant in lengths_vec[1:]:
actual_n_steps = tensor.minimum(actual_n_steps, contestant)
else:
actual_n_steps = tensor.as_tensor(n_steps)
# Add names -- it helps a lot when debugging
for (nw_seq, seq) in zip(scan_seqs, seqs):
if getattr(seq['input'], 'name', None) is not None:
nw_seq.name = seq['input'].name + '[%d:]' % k
scan_seqs = [seq[:actual_n_steps] for seq in scan_seqs]
# Conventions :
# mit_mot = multiple input taps, multiple output taps ( only provided
# by the gradient function )
# mit_sot = multiple input taps, single output tap (t + 0)
# sit_sot = single input tap, single output tap (t + 0)
# nit_sot = no input tap, single output tap (t + 0)
# MIT_MOT -- not provided by the user only by the grad function
n_mit_mot = 0
n_mit_mot_outs = 0
mit_mot_scan_inputs = []
mit_mot_inner_inputs = []
mit_mot_inner_outputs = []
mit_mot_out_slices = []
mit_mot_rightOrder = []
# SIT_SOT -- provided by the user
n_mit_sot = 0
mit_sot_scan_inputs = []
mit_sot_inner_inputs = []
mit_sot_inner_slices = []
mit_sot_inner_outputs = []
mit_sot_return_steps = OrderedDict()
mit_sot_tap_array = []
mit_sot_rightOrder = []
n_sit_sot = 0
sit_sot_scan_inputs = []
sit_sot_inner_inputs = []
sit_sot_inner_slices = []
sit_sot_inner_outputs = []
sit_sot_return_steps = OrderedDict()
sit_sot_rightOrder = []
# go through outputs picking up time slices as needed
for i, init_out in enumerate(outs_info):
# Note that our convention dictates that if an output uses
# just the previous time step, as a initial state we will only
# provide a tensor of the same dimension as one time step; This
# makes code much cleaner for those who do not use taps. Otherwise
# they would always had to shape_padleft the initial state ..
# which is ugly
if init_out.get('taps', None) == [-1]:
actual_arg = init_out['initial']
if not isinstance(actual_arg, tensor.Variable):
actual_arg = tensor.as_tensor_variable(actual_arg)
arg = safe_new(actual_arg)
if isinstance(arg, tensor.Constant):
# safe new returns a clone of the constants, but that is not
# what we need for initial states
arg = arg.type()
# Try to transfer test_value to the new variable
if config.compute_test_value != 'off':
try:
arg.tag.test_value = gof.Op._get_test_value(actual_arg)
except AttributeError as e:
if config.compute_test_value != 'ignore':
# No need to print a warning or raise an error now,
# it will be done when fn will be called.
_logger.info(('Cannot compute test value for the '
'inner function of scan, input value missing %s'),
e)
if getattr(init_out['initial'], 'name', None) is not None:
arg.name = init_out['initial'].name + '[t-1]'
# We need now to allocate space for storing the output and copy
# the initial state over. We do this using the expand function
# defined in scan utils
sit_sot_scan_inputs.append(
scan_utils.expand_empty(
tensor.unbroadcast(
tensor.shape_padleft(actual_arg), 0),
actual_n_steps
))
sit_sot_inner_slices.append(actual_arg)
if i in return_steps:
sit_sot_return_steps[n_sit_sot] = return_steps[i]
sit_sot_inner_inputs.append(arg)
sit_sot_rightOrder.append(i)
n_sit_sot += 1
elif init_out.get('taps', None):
if numpy.any(numpy.array(init_out.get('taps', [])) > 0):
# Make sure we do not have requests for future values of a
# sequence we can not provide such values
raise ValueError('Can not use future taps of outputs',
init_out)
# go through the taps
mintap = abs(numpy.min(init_out['taps']))
mit_sot_tap_array.append(init_out['taps'])
idx_offset = abs(numpy.min(init_out['taps']))
# Sequence
mit_sot_scan_inputs.append(
scan_utils.expand_empty(init_out['initial'][:mintap],
actual_n_steps))
if i in return_steps:
mit_sot_return_steps[n_mit_sot] = return_steps[i]
mit_sot_rightOrder.append(i)
n_mit_sot += 1
for k in init_out['taps']:
# create a new slice
actual_nw_slice = init_out['initial'][k + mintap]
_init_out_var = tensor.as_tensor_variable(init_out['initial'])
_init_out_var_slice = _init_out_var[k + mintap]
nw_slice = _init_out_var_slice.type()
# Try to transfer test_value to the new variable
if config.compute_test_value != 'off':
try:
nw_slice.tag.test_value = gof.Op._get_test_value(
_init_out_var_slice)
except AttributeError as e:
if config.compute_test_value != 'ignore':
# No need to print a warning or raise an error now,
# it will be done when fn will be called.
_logger.info(('Cannot compute test value for '
'the inner function of scan, input value '
'missing. %s'), e)
# give it a name or debugging and pretty printing
if getattr(init_out['initial'], 'name', None) is not None:
if k > 0:
nw_slice.name = (init_out['initial'].name +
'[t+%d]' % k)
elif k == 0:
nw_slice.name = init_out['initial'].name + '[t]'
else:
nw_slice.name = (init_out['initial'].name +
'[t%d]' % k)
mit_sot_inner_inputs.append(nw_slice)
mit_sot_inner_slices.append(actual_nw_slice)
# NOTE: there is another case, in which we do not want to provide
# any previous value of the output to the inner function (i.e.
# a map); in that case we do not have to do anything ..
# Re-order args
max_mit_sot = numpy.max([-1] + mit_sot_rightOrder) + 1
max_sit_sot = numpy.max([-1] + sit_sot_rightOrder) + 1
n_elems = numpy.max([max_mit_sot, max_sit_sot])
_ordered_args = [[] for x in xrange(n_elems)]
offset = 0
for idx in xrange(n_mit_sot):
n_inputs = len(mit_sot_tap_array[idx])
if n_fixed_steps in [1, -1]:
_ordered_args[mit_sot_rightOrder[idx]] = \
mit_sot_inner_slices[offset:offset + n_inputs]
else:
_ordered_args[mit_sot_rightOrder[idx]] = \
mit_sot_inner_inputs[offset:offset + n_inputs]
offset += n_inputs
for idx in xrange(n_sit_sot):
if n_fixed_steps in [1, -1]:
_ordered_args[sit_sot_rightOrder[idx]] = \
[sit_sot_inner_slices[idx]]
else:
_ordered_args[sit_sot_rightOrder[idx]] = \
[sit_sot_inner_inputs[idx]]
ordered_args = []
for ls in _ordered_args:
ordered_args += ls
if n_fixed_steps in [1, -1]:
args = (inner_slices +
ordered_args +
non_seqs)
else:
args = (inner_seqs +
ordered_args +
non_seqs)
# add only the non-shared variables and non-constants to the arguments of
# the dummy function [ a function should not get shared variables or
# constants as input ]
dummy_args = [arg for arg in args
if (not isinstance(arg, SharedVariable) and
not isinstance(arg, tensor.Constant))]
# when we apply the lambda expression we get a mixture of update rules
# and outputs that needs to be separated
condition, outputs, updates = scan_utils.get_updates_and_outputs(fn(*args))
if condition is not None:
as_while = True
else:
as_while = False
##
# Step 3. Check if we actually need scan and remove it if we don't
##
if n_fixed_steps in [1, -1]:
# We do not need to use the scan op anymore, so we can just return
# the outputs and updates we have
if condition is not None:
_logger.warning(('When the number of steps is fixed and equal '
'to 1, the provided stopping condition, ',
str(condition), ' is ignored'))
for pos, inner_out in enumerate(outputs):
# we need to see if we need to pad our sequences with an
# unbroadcastable dimension; case example : we return an
# output for which we want all intermediate. If n_steps is 1
# then, if we return the output as given by the innner function
# this will represent only a slice and it will have one
# dimension less.
if (isinstance(inner_out.type, tensor.TensorType) and
return_steps.get(pos, 0) != 1):
outputs[pos] = tensor.unbroadcast(
tensor.shape_padleft(inner_out), 0)
if len(outputs) == 1:
outputs = outputs[0]
return (outputs, updates)
##
# Step 4. Compile the dummy function
##
# We can now compile a dummy function just to see what shared variable
# we have and what are their update rules (note that the user has
# the option not to pass the shared variable to scan, so we need to
# pick them manually and add them to scan)
# make the compilation as fast as possible by not applying any
# optimization or conversion to C [ note this region is not important
# for performance so we can do stuff as unoptimal as we wish ]
# extract still missing inputs (there still might be so) and add them
# as non sequences at the end of our args
fake_nonseqs = [x.type() for x in non_seqs]
fake_outputs = scan_utils.clone(outputs,
replace=OrderedDict(izip(non_seqs,
fake_nonseqs)))
all_inputs = ifilter(
lambda x: (isinstance(x, gof.Variable) and
not isinstance(x, SharedVariable) and
not isinstance(x, gof.Constant)),
gof.graph.inputs(fake_outputs))
extra_inputs = [x for x in all_inputs if x not in args + fake_nonseqs]
non_seqs += extra_inputs
# Note we do not use all_inputs directly since the order of variables
# in args is quite important
dummy_args += extra_inputs
dummy_outs = outputs
if condition is not None:
dummy_outs.append(condition)
dummy_f = function(dummy_args,
dummy_outs,
updates=updates,
mode=compile.mode.Mode(linker='py',
optimizer=None),
on_unused_input='ignore',
profile=False)
##
# Step 5. Re-arange inputs of scan into a more strict order
##
# Step 5.0 Check the outputs of the dummy function to see if they
# match with user provided data
# if the number of outputs to the function does not match the number of
# assumed outputs until now (provided by the user) there can be
# only one explanation: No information is provided for any of the
# outputs (i.e. we are dealing with a map)
tmp_dummy_f_outs = len(dummy_f.maker.outputs)
if as_while:
tmp_dummy_f_outs -= 1
if not (tmp_dummy_f_outs == n_outs or outs_info == []):
raise ValueError('Please provide None as outputs_info for '
'any output that does not feed back into '
'scan (i.e. it behaves like a map) ')
if outs_info == []:
n_outs = len(dummy_f.maker.outputs)
if as_while:
n_outs = n_outs - 1
outs_info = [OrderedDict() for x in xrange(n_outs)]
# Step 5.1 Outputs with taps different then -1
for i, out in enumerate(outs_info):
if 'taps' in out and out['taps'] != [-1]:
mit_sot_inner_outputs.append(outputs[i])
# Step 5.2 Outputs with tap equal to -1
for i, out in enumerate(outs_info):
if 'taps' in out and out['taps'] == [-1]:
sit_sot_inner_outputs.append(outputs[i])
# Step 5.3 Outputs that correspond to update rules of shared variables
givens = OrderedDict()
n_shared_outs = 0
shared_scan_inputs = []
shared_inner_inputs = []
shared_inner_outputs = []
sit_sot_shared = []
for input in dummy_f.maker.expanded_inputs:
if isinstance(input.variable, SharedVariable) and input.update:
new_var = safe_new(input.variable)
if getattr(input.variable, 'name', None) is not None:
new_var.name = input.variable.name + '_copy'
if isinstance(new_var.type, ops.expandable_types):
sit_sot_inner_inputs.append(new_var)
sit_sot_scan_inputs.append(
scan_utils.expand_empty(
tensor.unbroadcast(
tensor.shape_padleft(input.variable), 0),
actual_n_steps))
tensor_update = tensor.as_tensor_variable(input.update)
sit_sot_inner_outputs.append(tensor_update)
# Not that pos is not a negative index. The sign of pos is used
# as a flag to indicate if this output should be part of the
# update rules or part of the standard outputs of scan.
# If `pos` is positive than it corresponds to the standard
# outputs of scan and it refers to output of index `pos`. If `pos`
# is negative that it corresponds to update rules of scan and it
# refers to update rule of index -1 - `pos`.
sit_sot_rightOrder.append(-1 - len(sit_sot_shared))
sit_sot_shared.append(input.variable)
givens[input.variable] = new_var
else:
shared_inner_inputs.append(new_var)
shared_scan_inputs.append(input.variable)
shared_inner_outputs.append(input.update)
givens[input.variable] = new_var
n_shared_outs += 1
n_sit_sot = len(sit_sot_inner_inputs)
# Step 5.4 Outputs with no taps used in the input
n_nit_sot = 0
nit_sot_inner_outputs = []
nit_sot_return_steps = OrderedDict()
nit_sot_rightOrder = []
for i, out in enumerate(outs_info):
if not 'taps' in out:
nit_sot_inner_outputs.append(outputs[i])
if i in return_steps:
nit_sot_return_steps[n_nit_sot] = return_steps[i]
nit_sot_rightOrder.append(i)
n_nit_sot += 1
# Step 5.5 all other arguments including extra inputs
other_scan_args = []
other_inner_args = []
other_scan_args += [arg for arg in non_seqs
if (not isinstance(arg, SharedVariable) and
not isinstance(arg, tensor.Constant))]
# Step 5.6 all shared variables with no update rules
other_inner_args += [safe_new(arg, '_copy') for arg in non_seqs
if (not isinstance(arg, SharedVariable) and
not isinstance(arg, tensor.Constant))]
givens.update(OrderedDict(izip(other_scan_args, other_inner_args)))
if strict:
non_seqs_set = set(non_sequences if non_sequences is not None else [])
other_shared_scan_args = [arg.variable for arg
in dummy_f.maker.expanded_inputs
if (isinstance(arg.variable, SharedVariable) and
not arg.update and
arg.variable in non_seqs_set)]
other_shared_inner_args = [safe_new(arg.variable, '_copy') for arg
in dummy_f.maker.expanded_inputs
if (isinstance(arg.variable, SharedVariable) and
not arg.update and
arg.variable in non_seqs_set)]
else:
other_shared_scan_args = [arg.variable for arg
in dummy_f.maker.expanded_inputs
if (isinstance(arg.variable, SharedVariable) and
not arg.update)]
other_shared_inner_args = [safe_new(arg.variable, '_copy') for arg
in dummy_f.maker.expanded_inputs
if (isinstance(arg.variable, SharedVariable) and
not arg.update)]
givens.update(OrderedDict(izip(other_shared_scan_args,
other_shared_inner_args)))
##
# Step 6. Re-order the outputs and clone them replacing things
# using the givens
##
inner_inputs = (inner_seqs +
mit_mot_inner_inputs +
mit_sot_inner_inputs +
sit_sot_inner_inputs +
shared_inner_inputs +
other_shared_inner_args +
other_inner_args)
inner_outs = (mit_mot_inner_outputs +
mit_sot_inner_outputs +
sit_sot_inner_outputs +
nit_sot_inner_outputs +
shared_inner_outputs)
if condition is not None:
inner_outs.append(condition)
# Cuda and Gpuarray are imported here, instead of being imported on top of
# the file because that would force on the user some dependencies that we
# might do not want to. Currently we are working on removing the
# dependencies on sandbox code completeley.
from theano.sandbox import cuda, gpuarray
if cuda.cuda_available or gpuarray.pygpu_activated:
# very often we end up in this situation when we want to
# replace w with w_copy, where w is a GPU variable
# and w_copy is TensorType. This is caused because shared
# variables are put on GPU right aways >:| ,
new_givens = OrderedDict()
for w, w_copy in iteritems(givens):
if ((isinstance(w.type, cuda.CudaNdarrayType) or
isinstance(w.type, gpuarray.GpuArrayType)) and
isinstance(w_copy.type, tensor.TensorType)):
for o in inner_outs:
new_givens = traverse(o, w, w_copy, new_givens)
else:
new_givens[w] = w_copy
else:
new_givens = givens
new_outs = scan_utils.clone(inner_outs, replace=new_givens)
##
# Step 7. Create the Scan Op
##
tap_array = mit_sot_tap_array + [[-1] for x in xrange(n_sit_sot)]
if allow_gc is None:
allow_gc = config.scan.allow_gc
info = OrderedDict()
info['tap_array'] = tap_array
info['n_seqs'] = n_seqs
info['n_mit_mot'] = n_mit_mot
info['n_mit_mot_outs'] = n_mit_mot_outs
info['mit_mot_out_slices'] = mit_mot_out_slices
info['n_mit_sot'] = n_mit_sot
info['n_sit_sot'] = n_sit_sot
info['n_shared_outs'] = n_shared_outs
info['n_nit_sot'] = n_nit_sot
info['truncate_gradient'] = truncate_gradient
info['name'] = name
info['mode'] = mode
info['destroy_map'] = OrderedDict()
info['gpu'] = False
info['as_while'] = as_while
info['profile'] = profile
info['allow_gc'] = allow_gc
info['strict'] = strict
local_op = scan_op.Scan(inner_inputs, new_outs, info)
##
# Step 8. Compute the outputs using the scan op
##
_scan_inputs = (scan_seqs +
mit_mot_scan_inputs +
mit_sot_scan_inputs +
sit_sot_scan_inputs +
shared_scan_inputs +
[actual_n_steps for x in xrange(n_nit_sot)] +
other_shared_scan_args +
other_scan_args)
scan_inputs = []
for arg in [actual_n_steps] + _scan_inputs:
try:
arg = tensor.as_tensor_variable(arg)
except TypeError:
# This happens for Random States for e.g. but it is a good way
# to make sure no input is a cuda ndarrays
pass
scan_inputs += [arg]
scan_outs = local_op(*scan_inputs)
if type(scan_outs) not in (list, tuple):
scan_outs = [scan_outs]
##
# Step 9. Figure out which outs are update rules for shared variables
# and so on ...
##
update_map = OrderedUpdates()
def remove_dimensions(outs, steps_return, offsets=None):
out_ls = []
for idx, out in enumerate(outs):
if idx in steps_return:
if steps_return[idx] > 1:
out_ls.append(out[-steps_return[idx]:])
else:
out_ls.append(out[-1])
else:
if offsets is None:
out_ls.append(out)
else:
out_ls.append(out[offsets[idx]:])
return out_ls
offset = n_mit_mot
offsets = [abs(numpy.min(x)) for x in mit_sot_tap_array]
mit_sot_outs = remove_dimensions(
scan_outs[offset:offset + n_mit_sot],
mit_sot_return_steps,
offsets)
offset += n_mit_sot
offsets = [1 for x in xrange(n_sit_sot)]
sit_sot_outs = remove_dimensions(
scan_outs[offset:offset + n_sit_sot],
sit_sot_return_steps,
offsets)
offset += n_sit_sot
nit_sot_outs = remove_dimensions(
scan_outs[offset:offset + n_nit_sot],
nit_sot_return_steps)
offset += n_nit_sot
for idx, update_rule in enumerate(
scan_outs[offset:offset + n_shared_outs]):
update_map[shared_scan_inputs[idx]] = update_rule
_scan_out_list = (mit_sot_outs +
sit_sot_outs +
nit_sot_outs)
# Step 10. I need to reorder the outputs to be in the order expected by
# the user
rightOrder = (mit_sot_rightOrder +
sit_sot_rightOrder +
nit_sot_rightOrder)
scan_out_list = [None] * len(rightOrder)
for idx, pos in enumerate(rightOrder):
if pos >= 0:
scan_out_list[pos] = _scan_out_list[idx]
else:
# Not that pos is not a negative index. The sign of pos is used
# as a flag to indicate if this output should be part of the
# update rules or part of the standard outputs of scan.
# If `pos` is positive than it corresponds to the standard
# outputs of scan and it refers to output of index `pos`. If `pos`
# is negative that it corresponds to update rules of scan and it
# refers to update rule of index -1 - `pos`.
update_map[sit_sot_shared[abs(pos) - 1]] = _scan_out_list[idx][-1]
scan_out_list = [x for x in scan_out_list if x is not None]
if len(scan_out_list) == 1:
scan_out_list = scan_out_list[0]
elif len(scan_out_list) == 0:
scan_out_list = None
return (scan_out_list, update_map)
|
mit
|
noroutine/ansible
|
lib/ansible/modules/cloud/google/gce_snapshot.py
|
122
|
6781
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright: Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: gce_snapshot
version_added: "2.3"
short_description: Create or destroy snapshots for GCE storage volumes
description:
- Manages snapshots for GCE instances. This module manages snapshots for
the storage volumes of a GCE compute instance. If there are multiple
volumes, each snapshot will be prepended with the disk name
options:
instance_name:
description:
- The GCE instance to snapshot
required: True
snapshot_name:
description:
- The name of the snapshot to manage
disks:
description:
- A list of disks to create snapshots for. If none is provided,
all of the volumes will be snapshotted
default: all
required: False
state:
description:
- Whether a snapshot should be C(present) or C(absent)
required: false
default: present
choices: [present, absent]
service_account_email:
description:
- GCP service account email for the project where the instance resides
required: true
credentials_file:
description:
- The path to the credentials file associated with the service account
required: true
project_id:
description:
- The GCP project ID to use
required: true
requirements:
- "python >= 2.6"
- "apache-libcloud >= 0.19.0"
author: Rob Wagner (@robwagner33)
'''
EXAMPLES = '''
- name: Create gce snapshot
gce_snapshot:
instance_name: example-instance
snapshot_name: example-snapshot
state: present
service_account_email: [email protected]
credentials_file: /path/to/credentials
project_id: project_name
delegate_to: localhost
- name: Delete gce snapshot
gce_snapshot:
instance_name: example-instance
snapshot_name: example-snapshot
state: absent
service_account_email: [email protected]
credentials_file: /path/to/credentials
project_id: project_name
delegate_to: localhost
# This example creates snapshots for only two of the available disks as
# disk0-example-snapshot and disk1-example-snapshot
- name: Create snapshots of specific disks
gce_snapshot:
instance_name: example-instance
snapshot_name: example-snapshot
state: present
disks:
- disk0
- disk1
service_account_email: [email protected]
credentials_file: /path/to/credentials
project_id: project_name
delegate_to: localhost
'''
RETURN = '''
snapshots_created:
description: List of newly created snapshots
returned: When snapshots are created
type: list
sample: "[disk0-example-snapshot, disk1-example-snapshot]"
snapshots_deleted:
description: List of destroyed snapshots
returned: When snapshots are deleted
type: list
sample: "[disk0-example-snapshot, disk1-example-snapshot]"
snapshots_existing:
description: List of snapshots that already existed (no-op)
returned: When snapshots were already present
type: list
sample: "[disk0-example-snapshot, disk1-example-snapshot]"
snapshots_absent:
description: List of snapshots that were already absent (no-op)
returned: When snapshots were already absent
type: list
sample: "[disk0-example-snapshot, disk1-example-snapshot]"
'''
try:
from libcloud.compute.types import Provider
_ = Provider.GCE
HAS_LIBCLOUD = True
except ImportError:
HAS_LIBCLOUD = False
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.gce import gce_connect
def find_snapshot(volume, name):
'''
Check if there is a snapshot already created with the given name for
the passed in volume.
Args:
volume: A gce StorageVolume object to manage
name: The name of the snapshot to look for
Returns:
The VolumeSnapshot object if one is found
'''
found_snapshot = None
snapshots = volume.list_snapshots()
for snapshot in snapshots:
if name == snapshot.name:
found_snapshot = snapshot
return found_snapshot
def main():
module = AnsibleModule(
argument_spec=dict(
instance_name=dict(required=True),
snapshot_name=dict(required=True),
state=dict(choices=['present', 'absent'], default='present'),
disks=dict(default=None, type='list'),
service_account_email=dict(type='str'),
credentials_file=dict(type='path'),
project_id=dict(type='str')
)
)
if not HAS_LIBCLOUD:
module.fail_json(msg='libcloud with GCE support (0.19.0+) is required for this module')
gce = gce_connect(module)
instance_name = module.params.get('instance_name')
snapshot_name = module.params.get('snapshot_name')
disks = module.params.get('disks')
state = module.params.get('state')
json_output = dict(
changed=False,
snapshots_created=[],
snapshots_deleted=[],
snapshots_existing=[],
snapshots_absent=[]
)
snapshot = None
instance = gce.ex_get_node(instance_name, 'all')
instance_disks = instance.extra['disks']
for instance_disk in instance_disks:
disk_snapshot_name = snapshot_name
device_name = instance_disk['deviceName']
if disks is None or device_name in disks:
volume_obj = gce.ex_get_volume(device_name)
# If we have more than one disk to snapshot, prepend the disk name
if len(instance_disks) > 1:
disk_snapshot_name = device_name + "-" + disk_snapshot_name
snapshot = find_snapshot(volume_obj, disk_snapshot_name)
if snapshot and state == 'present':
json_output['snapshots_existing'].append(disk_snapshot_name)
elif snapshot and state == 'absent':
snapshot.destroy()
json_output['changed'] = True
json_output['snapshots_deleted'].append(disk_snapshot_name)
elif not snapshot and state == 'present':
volume_obj.snapshot(disk_snapshot_name)
json_output['changed'] = True
json_output['snapshots_created'].append(disk_snapshot_name)
elif not snapshot and state == 'absent':
json_output['snapshots_absent'].append(disk_snapshot_name)
module.exit_json(**json_output)
if __name__ == '__main__':
main()
|
gpl-3.0
|
myself659/linux
|
tools/perf/scripts/python/check-perf-trace.py
|
1997
|
2539
|
# perf script event handlers, generated by perf script -g python
# (c) 2010, Tom Zanussi <[email protected]>
# Licensed under the terms of the GNU GPL License version 2
#
# This script tests basic functionality such as flag and symbol
# strings, common_xxx() calls back into perf, begin, end, unhandled
# events, etc. Basically, if this script runs successfully and
# displays expected results, Python scripting support should be ok.
import os
import sys
sys.path.append(os.environ['PERF_EXEC_PATH'] + \
'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')
from Core import *
from perf_trace_context import *
unhandled = autodict()
def trace_begin():
print "trace_begin"
pass
def trace_end():
print_unhandled()
def irq__softirq_entry(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
common_callchain, vec):
print_header(event_name, common_cpu, common_secs, common_nsecs,
common_pid, common_comm)
print_uncommon(context)
print "vec=%s\n" % \
(symbol_str("irq__softirq_entry", "vec", vec)),
def kmem__kmalloc(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
common_callchain, call_site, ptr, bytes_req, bytes_alloc,
gfp_flags):
print_header(event_name, common_cpu, common_secs, common_nsecs,
common_pid, common_comm)
print_uncommon(context)
print "call_site=%u, ptr=%u, bytes_req=%u, " \
"bytes_alloc=%u, gfp_flags=%s\n" % \
(call_site, ptr, bytes_req, bytes_alloc,
flag_str("kmem__kmalloc", "gfp_flags", gfp_flags)),
def trace_unhandled(event_name, context, event_fields_dict):
try:
unhandled[event_name] += 1
except TypeError:
unhandled[event_name] = 1
def print_header(event_name, cpu, secs, nsecs, pid, comm):
print "%-20s %5u %05u.%09u %8u %-20s " % \
(event_name, cpu, secs, nsecs, pid, comm),
# print trace fields not included in handler args
def print_uncommon(context):
print "common_preempt_count=%d, common_flags=%s, common_lock_depth=%d, " \
% (common_pc(context), trace_flag_str(common_flags(context)), \
common_lock_depth(context))
def print_unhandled():
keys = unhandled.keys()
if not keys:
return
print "\nunhandled events:\n\n",
print "%-40s %10s\n" % ("event", "count"),
print "%-40s %10s\n" % ("----------------------------------------", \
"-----------"),
for event_name in keys:
print "%-40s %10d\n" % (event_name, unhandled[event_name])
|
gpl-2.0
|
MaralAfris/wasp-summer-school-team6
|
drone/bebop_controller/src/PID.py
|
2
|
1594
|
from copy import deepcopy
import numpy
from PIDParameters import *
class PID(object):
def __init__(self):
p = PIDParameters()
p.Beta = 1.0
p.H = 0.05
p.integratorOn = False
p.K = 0.25 # start 0.1 # used to be 0.20
p.N = 10
p.Td = 0.0 # start 0.1
p.Ti = 30 # used to be 10
p.Tr = 30 # used to be 10
self.p = deepcopy(p)
self.I = 0.0
self.D = 0.0
self.v = 0.0
self.e = 0.0
self.y = 0.0
self.yold = 0.0
self.ad = self.p.Td / (self.p.Td + self.p.N*self.p.H)
self.bd = self.p.K * self.ad * self.p.N
def calculate_output(self, y, yref):
self.y = deepcopy(y)
self.yref = deepcopy(yref)
self.e = yref - y
self.D = self.ad*self.D - self.bd * (y - self.yold)
self.v = self.p.K*(self.p.Beta*yref - y) + self.I + self.D
return deepcopy(self.v)
def update_state(self, u):
if self.p.integratorOn:
self.I = self.I + (self.p.K*self.p.H/self.p.Ti)*self.e + (self.p.H/self.p.Tr)*(self.u - self.v)
else:
self.I = 0.0
self.yold = self.y
def set_parameters(self, param):
self.p = deepcopy(param)
self.ad = self.p.Td / (self.p.Td + self.p.N*self.p.H)
self.bd = self.p.K * self.ad * self.p.N
if not self.p.integratorOn:
self.I = 0.0
def reset(self):
self.I = 0.0
self.D = 0.0
self.yold = 0.0
def get_parameters(self):
return deepcopy(self.p)
|
gpl-3.0
|
NeuralSpaz/Arduino
|
arduino-core/src/processing/app/i18n/python/requests/packages/charade/codingstatemachine.py
|
2931
|
2318
|
######################## BEGIN LICENSE BLOCK ########################
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Mark Pilgrim - port to Python
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
from .constants import eStart
from .compat import wrap_ord
class CodingStateMachine:
def __init__(self, sm):
self._mModel = sm
self._mCurrentBytePos = 0
self._mCurrentCharLen = 0
self.reset()
def reset(self):
self._mCurrentState = eStart
def next_state(self, c):
# for each byte we get its class
# if it is first byte, we also get byte length
# PY3K: aBuf is a byte stream, so c is an int, not a byte
byteCls = self._mModel['classTable'][wrap_ord(c)]
if self._mCurrentState == eStart:
self._mCurrentBytePos = 0
self._mCurrentCharLen = self._mModel['charLenTable'][byteCls]
# from byte's class and stateTable, we get its next state
curr_state = (self._mCurrentState * self._mModel['classFactor']
+ byteCls)
self._mCurrentState = self._mModel['stateTable'][curr_state]
self._mCurrentBytePos += 1
return self._mCurrentState
def get_current_charlen(self):
return self._mCurrentCharLen
def get_coding_state_machine(self):
return self._mModel['name']
|
lgpl-2.1
|
HBEE/odoo-addons
|
sale_require_purchase_order_number/__openerp__.py
|
2
|
1599
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar)
# All Rights Reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Sale Require Purchase Order Number',
'version': '8.0.0.1.0',
'category': 'Projects & Services',
'sequence': 14,
'summary': '',
'description': """
Sale Require Purchase Order Number
==================================
""",
'author': 'ADHOC SA',
'website': 'www.adhoc.com.ar',
'images': [
],
'depends': [
'sale_stock'
],
'data': [
'sale_view.xml',
'partner_view.xml',
'account_view.xml',
'stock_view.xml'
],
'demo': [
],
'test': [
],
'installable': True,
'auto_install': False,
'application': False,
}
|
agpl-3.0
|
MalloyDelacroix/DownloaderForReddit
|
Tests/unittests/core/test_content_filter.py
|
1
|
5834
|
from unittest import TestCase
from unittest.mock import MagicMock
from DownloaderForReddit.core.content_filter import ContentFilter
from DownloaderForReddit.database.database_handler import DatabaseHandler
from DownloaderForReddit.utils import injector
from Tests.mockobjects.mock_objects import (get_user, get_post, get_content, get_mock_reddit_video_post,
get_mock_reddit_uploads_post)
class TestContentFilter(TestCase):
@classmethod
def setUpClass(cls):
cls.mock_settings_manager = MagicMock()
injector.settings_manager = cls.mock_settings_manager
def setUp(self):
self.content_filter = ContentFilter()
def test_filter_duplicate_url_already_in_db_avoid_duplicates(self):
db = DatabaseHandler(in_memory=True)
with db.get_scoped_session() as session:
content = get_content()
post = content.post
session.add(content, post)
session.commit()
f = self.content_filter.filter_duplicate(post, content.url)
self.assertFalse(f)
def test_filter_duplicate_new_url_avoid_duplicates(self):
added_url = 'https://www.fakesite.com/323sds9sd9wn3lk23.jpg'
new_url = 'https://www.realsite.com/2340sdfilnj23lk324kj.png'
db = DatabaseHandler(in_memory=True)
with db.get_scoped_session() as session:
content = get_content(url=added_url)
post = content.post
session.add(content, post)
session.commit()
f = self.content_filter.filter_duplicate(post, new_url)
self.assertTrue(f)
def test_filter_duplicate_url_already_in_db_do_not_avoid_duplicates(self):
db = DatabaseHandler(in_memory=True)
with db.get_scoped_session() as session:
user = get_user(avoid_duplicates=False)
content = get_content(user=user)
post = content.post
session.add(content)
session.commit()
self.assertEqual(post.significant_reddit_object, user)
f = self.content_filter.filter_duplicate(post, content.url)
self.assertTrue(f)
def test_filter_reddit_video_allowed_in_settings(self):
self.mock_settings_manager.download_reddit_hosted_videos = True
post = get_mock_reddit_video_post()
f = self.content_filter.filter_reddit_video(post)
self.assertTrue(f)
def test_filter_reddit_video_not_allowed_in_settings(self):
self.mock_settings_manager.download_reddit_hosted_videos = False
post = get_mock_reddit_video_post()
f = self.content_filter.filter_reddit_video(post)
self.assertFalse(f)
def test_filter_non_reddit_video_not_allowed_in_settings(self):
self.mock_settings_manager.download_reddit_hosted_videos = False
post = get_mock_reddit_uploads_post()
f = self.content_filter.filter_reddit_video(post)
self.assertTrue(f)
def test_filter_file_type_image_not_allowed(self):
user = get_user(download_images=False)
post = get_post(author=user, significant=user)
ext = 'jpg'
f = self.content_filter.filter_file_type(post, ext)
self.assertFalse(f)
def test_filter_file_type_image_allowed(self):
user = get_user(download_images=True)
post = get_post(author=user, significant=user)
ext = 'jpg'
f = self.content_filter.filter_file_type(post, ext)
self.assertTrue(f)
def test_filter_file_type_gifs_not_allowed(self):
user = get_user(download_gifs=False)
post = get_post(author=user, significant=user)
ext = 'webm'
f = self.content_filter.filter_file_type(post, ext)
self.assertFalse(f)
def test_filter_file_type_gifs_allowed(self):
user = get_user(download_gifs=True)
post = get_post(author=user, significant=user)
ext = 'webm'
f = self.content_filter.filter_file_type(post, ext)
self.assertTrue(f)
def test_filter_file_type_videos_not_allowed(self):
user = get_user(download_videos=False)
post = get_post(author=user, significant=user)
ext = 'mp4'
f = self.content_filter.filter_file_type(post, ext)
self.assertFalse(f)
def test_filter_file_type_videos_allowed(self):
user = get_user(download_videos=True)
post = get_post(author=user, significant=user)
ext = 'mp4'
f = self.content_filter.filter_file_type(post, ext)
self.assertTrue(f)
def test_filter_file_type_image_cross_contamination(self):
user = get_user(download_images=False)
post = get_post(author=user, significant=user)
ext = 'jpg'
f = self.content_filter.filter_file_type(post, ext)
self.assertFalse(f)
self.assertTrue(self.content_filter.filter_file_type(post, 'mp4'))
self.assertTrue(self.content_filter.filter_file_type(post, 'webm'))
def test_filter_file_type_gifs_cross_contamination(self):
user = get_user(download_gifs=False)
post = get_post(author=user, significant=user)
ext = 'webm'
f = self.content_filter.filter_file_type(post, ext)
self.assertFalse(f)
self.assertTrue(self.content_filter.filter_file_type(post, 'jpg'))
self.assertTrue(self.content_filter.filter_file_type(post, 'mp4'))
def test_filter_file_type_video_cross_contamination(self):
user = get_user(download_videos=False)
post = get_post(author=user, significant=user)
ext = 'mp4'
f = self.content_filter.filter_file_type(post, ext)
self.assertFalse(f)
self.assertTrue(self.content_filter.filter_file_type(post, 'jpg'))
self.assertTrue(self.content_filter.filter_file_type(post, 'webm'))
|
gpl-3.0
|
JamesAng/oe
|
lib/oe/types.py
|
25
|
3409
|
import re
class OEList(list):
"""OpenEmbedded 'list' type
Acts as an ordinary list, but is constructed from a string value and a
separator (optional), and re-joins itself when converted to a string with
str(). Set the variable type flag to 'list' to use this type, and the
'separator' flag may be specified (defaulting to whitespace)."""
name = "list"
def __init__(self, value, separator = None):
if value is not None:
list.__init__(self, value.split(separator))
else:
list.__init__(self)
if separator is None:
self.separator = " "
else:
self.separator = separator
def __str__(self):
return self.separator.join(self)
def choice(value, choices):
"""OpenEmbedded 'choice' type
Acts as a multiple choice for the user. To use this, set the variable
type flag to 'choice', and set the 'choices' flag to a space separated
list of valid values."""
if not isinstance(value, basestring):
raise TypeError("choice accepts a string, not '%s'" % type(value))
value = value.lower()
choices = choices.lower()
if value not in choices.split():
raise ValueError("Invalid choice '%s'. Valid choices: %s" %
(value, choices))
return value
def regex(value, regexflags=None):
"""OpenEmbedded 'regex' type
Acts as a regular expression, returning the pre-compiled regular
expression pattern object. To use this type, set the variable type flag
to 'regex', and optionally, set the 'regexflags' type to a space separated
list of the flags to control the regular expression matching (e.g.
FOO[regexflags] += 'ignorecase'). See the python documentation on the
're' module for a list of valid flags."""
flagval = 0
if regexflags:
for flag in regexflags.split():
flag = flag.upper()
try:
flagval |= getattr(re, flag)
except AttributeError:
raise ValueError("Invalid regex flag '%s'" % flag)
try:
return re.compile(value, flagval)
except re.error, exc:
raise ValueError("Invalid regex value '%s': %s" %
(value, exc.args[0]))
def boolean(value):
"""OpenEmbedded 'boolean' type
Valid values for true: 'yes', 'y', 'true', 't', '1'
Valid values for false: 'no', 'n', 'false', 'f', '0'
"""
if not isinstance(value, basestring):
raise TypeError("boolean accepts a string, not '%s'" % type(value))
value = value.lower()
if value in ('yes', 'y', 'true', 't', '1'):
return True
elif value in ('no', 'n', 'false', 'f', '0'):
return False
raise ValueError("Invalid boolean value '%s'" % value)
def integer(value, numberbase=10):
"""OpenEmbedded 'integer' type
Defaults to base 10, but this can be specified using the optional
'numberbase' flag."""
return int(value, int(numberbase))
_float = float
def float(value, fromhex='false'):
"""OpenEmbedded floating point type
To use this type, set the type flag to 'float', and optionally set the
'fromhex' flag to a true value (obeying the same rules as for the
'boolean' type) if the value is in base 16 rather than base 10."""
if boolean(fromhex):
return _float.fromhex(value)
else:
return _float(value)
|
mit
|
13xforever/webserver
|
qa/141-FastCGI-EmptyVars.py
|
8
|
1608
|
import os
from base import *
DIR = "/FCGI-EmptyVars/"
MAGIC = "Cherokee and FastCGI rocks!"
PORT = get_free_port()
PYTHON = look_for_python()
SCRIPT = """
from fcgi import *
def app (environ, start_response):
start_response('200 OK', [("Content-Type", "text/plain")])
resp = ""
for k in environ:
resp += '%%s: %%s\\n' %% (k, environ[k])
return [resp]
WSGIServer(app, bindAddress=("localhost",%d)).run()
""" % (PORT)
source = get_next_source()
CONF = """
vserver!1!rule!1410!match = directory
vserver!1!rule!1410!match!directory = %(DIR)s
vserver!1!rule!1410!handler = fcgi
vserver!1!rule!1410!handler!check_file = 0
vserver!1!rule!1410!handler!balancer = round_robin
vserver!1!rule!1410!handler!balancer!source!1 = %(source)d
source!%(source)d!type = interpreter
source!%(source)d!host = localhost:%(PORT)d
source!%(source)d!interpreter = %(PYTHON)s %(fcgi_file)s
"""
class Test (TestBase):
def __init__ (self):
TestBase.__init__ (self, __file__)
self.name = "FastCGI: Variables"
self.request = "GET %s HTTP/1.0\r\n" % (DIR)
self.expected_error = 200
self.expected_content = ['PATH_INFO:', 'QUERY_STRING:']
self.forbidden_content = ['from fcgi', 'start_response']
def Prepare (self, www):
fcgi_file = self.WriteFile (www, "fcgi_test_vbles.fcgi", 0444, SCRIPT)
fcgi = os.path.join (www, 'fcgi.py')
if not os.path.exists (fcgi):
self.CopyFile ('fcgi.py', fcgi)
vars = globals()
vars['fcgi_file'] = fcgi_file
self.conf = CONF % (vars)
|
gpl-2.0
|
alanjw/GreenOpenERP-Win-X86
|
openerp/addons/crm_todo/__init__.py
|
66
|
1071
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import crm_todo
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
agpl-3.0
|
ApuliaSoftware/odoo
|
openerp/addons/base/tests/test_basecase.py
|
379
|
3895
|
# -*- coding: utf-8 -*-
import unittest2
from openerp.tests import common
class test_single_transaction_case(common.SingleTransactionCase):
"""
Check the whole-class transaction behavior of SingleTransactionCase.
"""
def test_00(self):
"""Create a partner."""
cr, uid = self.cr, self.uid
self.registry('res.partner').create(cr, uid, {'name': 'test_per_class_teardown_partner'})
ids = self.registry('res.partner').search(cr, uid, [('name', '=', 'test_per_class_teardown_partner')])
self.assertEqual(1, len(ids), "Test partner not found.")
def test_01(self):
"""Find the created partner."""
cr, uid = self.cr, self.uid
ids = self.registry('res.partner').search(cr, uid, [('name', '=', 'test_per_class_teardown_partner')])
self.assertEqual(1, len(ids), "Test partner not found.")
def test_20a(self):
""" Create a partner with a XML ID """
cr, uid = self.cr, self.uid
res_partner = self.registry('res.partner')
ir_model_data = self.registry('ir.model.data')
pid, _ = res_partner.name_create(cr, uid, 'Mr Blue')
ir_model_data.create(cr, uid, {'name': 'test_partner_blue',
'module': 'base',
'model': 'res.partner',
'res_id': pid})
def test_20b(self):
""" Resolve xml id with ref() and browse_ref() """
cr, uid = self.cr, self.uid
res_partner = self.registry('res.partner')
xid = 'base.test_partner_blue'
p_ref = self.ref(xid)
self.assertTrue(p_ref, "ref() should resolve xid to database ID")
partner = res_partner.browse(cr, uid, p_ref)
p_browse_ref = self.browse_ref(xid)
self.assertEqual(partner, p_browse_ref, "browse_ref() should resolve xid to browse records")
class test_transaction_case(common.TransactionCase):
"""
Check the per-method transaction behavior of TransactionCase.
"""
def test_00(self):
"""Create a partner."""
cr, uid = self.cr, self.uid
ids = self.registry('res.partner').search(cr, uid, [('name', '=', 'test_per_class_teardown_partner')])
self.assertEqual(0, len(ids), "Test partner found.")
self.registry('res.partner').create(cr, uid, {'name': 'test_per_class_teardown_partner'})
ids = self.registry('res.partner').search(cr, uid, [('name', '=', 'test_per_class_teardown_partner')])
self.assertEqual(1, len(ids), "Test partner not found.")
def test_01(self):
"""Don't find the created partner."""
cr, uid = self.cr, self.uid
ids = self.registry('res.partner').search(cr, uid, [('name', '=', 'test_per_class_teardown_partner')])
self.assertEqual(0, len(ids), "Test partner found.")
def test_20a(self):
""" Create a partner with a XML ID then resolve xml id with ref() and browse_ref() """
cr, uid = self.cr, self.uid
res_partner = self.registry('res.partner')
ir_model_data = self.registry('ir.model.data')
pid, _ = res_partner.name_create(cr, uid, 'Mr Yellow')
ir_model_data.create(cr, uid, {'name': 'test_partner_yellow',
'module': 'base',
'model': 'res.partner',
'res_id': pid})
xid = 'base.test_partner_yellow'
p_ref = self.ref(xid)
self.assertEquals(p_ref, pid, "ref() should resolve xid to database ID")
partner = res_partner.browse(cr, uid, pid)
p_browse_ref = self.browse_ref(xid)
self.assertEqual(partner, p_browse_ref, "browse_ref() should resolve xid to browse records")
if __name__ == '__main__':
unittest2.main()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
agpl-3.0
|
krieger-od/nwjs_chromium.src
|
third_party/pycoverage/coverage/bytecode.py
|
209
|
2036
|
"""Bytecode manipulation for coverage.py"""
import opcode, types
from coverage.backward import byte_to_int
class ByteCode(object):
"""A single bytecode."""
def __init__(self):
# The offset of this bytecode in the code object.
self.offset = -1
# The opcode, defined in the `opcode` module.
self.op = -1
# The argument, a small integer, whose meaning depends on the opcode.
self.arg = -1
# The offset in the code object of the next bytecode.
self.next_offset = -1
# The offset to jump to.
self.jump_to = -1
class ByteCodes(object):
"""Iterator over byte codes in `code`.
Returns `ByteCode` objects.
"""
# pylint: disable=R0924
def __init__(self, code):
self.code = code
def __getitem__(self, i):
return byte_to_int(self.code[i])
def __iter__(self):
offset = 0
while offset < len(self.code):
bc = ByteCode()
bc.op = self[offset]
bc.offset = offset
next_offset = offset+1
if bc.op >= opcode.HAVE_ARGUMENT:
bc.arg = self[offset+1] + 256*self[offset+2]
next_offset += 2
label = -1
if bc.op in opcode.hasjrel:
label = next_offset + bc.arg
elif bc.op in opcode.hasjabs:
label = bc.arg
bc.jump_to = label
bc.next_offset = offset = next_offset
yield bc
class CodeObjects(object):
"""Iterate over all the code objects in `code`."""
def __init__(self, code):
self.stack = [code]
def __iter__(self):
while self.stack:
# We're going to return the code object on the stack, but first
# push its children for later returning.
code = self.stack.pop()
for c in code.co_consts:
if isinstance(c, types.CodeType):
self.stack.append(c)
yield code
|
bsd-3-clause
|
kai11/ansible-modules-core
|
cloud/amazon/ec2_vol.py
|
50
|
15330
|
#!/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/>.
DOCUMENTATION = '''
---
module: ec2_vol
short_description: create and attach a volume, return volume id and device map
description:
- creates an EBS volume and optionally attaches it to an instance. If both an instance ID and a device name is given and the instance has a device at the device name, then no volume is created and no attachment is made. This module has a dependency on python-boto.
version_added: "1.1"
options:
instance:
description:
- instance ID if you wish to attach the volume. Since 1.9 you can set to None to detach.
required: false
default: null
aliases: []
name:
description:
- volume Name tag if you wish to attach an existing volume (requires instance)
required: false
default: null
aliases: []
version_added: "1.6"
id:
description:
- volume id if you wish to attach an existing volume (requires instance) or remove an existing volume
required: false
default: null
aliases: []
version_added: "1.6"
volume_size:
description:
- size of volume (in GB) to create.
required: false
default: null
aliases: []
volume_type:
description:
- Type of EBS volume; standard (magnetic), gp2 (SSD), io1 (Provisioned IOPS). "Standard" is the old EBS default
and continues to remain the Ansible default for backwards compatibility.
required: false
default: standard
aliases: []
version_added: "1.9"
iops:
description:
- the provisioned IOPs you want to associate with this volume (integer).
required: false
default: 100
aliases: []
version_added: "1.3"
encrypted:
description:
- Enable encryption at rest for this volume.
default: false
version_added: "1.8"
device_name:
description:
- device id to override device mapping. Assumes /dev/sdf for Linux/UNIX and /dev/xvdf for Windows.
required: false
default: null
aliases: []
region:
description:
- The AWS region to use. If not specified then the value of the EC2_REGION environment variable, if any, is used.
required: false
default: null
aliases: ['aws_region', 'ec2_region']
zone:
description:
- zone in which to create the volume, if unset uses the zone the instance is in (if set)
required: false
default: null
aliases: ['aws_zone', 'ec2_zone']
snapshot:
description:
- snapshot ID on which to base the volume
required: false
default: null
version_added: "1.5"
validate_certs:
description:
- When set to "no", SSL certificates will not be validated for boto versions >= 2.6.0.
required: false
default: "yes"
choices: ["yes", "no"]
aliases: []
version_added: "1.5"
state:
description:
- whether to ensure the volume is present or absent, or to list existing volumes (The C(list) option was added in version 1.8).
required: false
default: present
choices: ['absent', 'present', 'list']
version_added: "1.6"
author: "Lester Wade (@lwade)"
extends_documentation_fragment: aws
'''
EXAMPLES = '''
# Simple attachment action
- ec2_vol:
instance: XXXXXX
volume_size: 5
device_name: sdd
# Example using custom iops params
- ec2_vol:
instance: XXXXXX
volume_size: 5
iops: 200
device_name: sdd
# Example using snapshot id
- ec2_vol:
instance: XXXXXX
snapshot: "{{ snapshot }}"
# Playbook example combined with instance launch
- ec2:
keypair: "{{ keypair }}"
image: "{{ image }}"
wait: yes
count: 3
register: ec2
- ec2_vol:
instance: "{{ item.id }} "
volume_size: 5
with_items: ec2.instances
register: ec2_vol
# Example: Launch an instance and then add a volume if not already attached
# * Volume will be created with the given name if not already created.
# * Nothing will happen if the volume is already attached.
# * Requires Ansible 2.0
- ec2:
keypair: "{{ keypair }}"
image: "{{ image }}"
zone: YYYYYY
id: my_instance
wait: yes
count: 1
register: ec2
- ec2_vol:
instance: "{{ item.id }}"
name: my_existing_volume_Name_tag
device_name: /dev/xvdf
with_items: ec2.instances
register: ec2_vol
# Remove a volume
- ec2_vol:
id: vol-XXXXXXXX
state: absent
# Detach a volume (since 1.9)
- ec2_vol:
id: vol-XXXXXXXX
instance: None
# List volumes for an instance
- ec2_vol:
instance: i-XXXXXX
state: list
# Create new volume using SSD storage
- ec2_vol:
instance: XXXXXX
volume_size: 50
volume_type: gp2
device_name: /dev/xvdf
'''
import time
from distutils.version import LooseVersion
try:
import boto.ec2
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
def get_volume(module, ec2):
name = module.params.get('name')
id = module.params.get('id')
zone = module.params.get('zone')
filters = {}
volume_ids = None
if zone:
filters['availability_zone'] = zone
if name:
filters = {'tag:Name': name}
if id:
volume_ids = [id]
try:
vols = ec2.get_all_volumes(volume_ids=volume_ids, filters=filters)
except boto.exception.BotoServerError, e:
module.fail_json(msg = "%s: %s" % (e.error_code, e.error_message))
if not vols:
if id:
msg = "Could not find the volume with id: %s" % id
if name:
msg += (" and name: %s" % name)
module.fail_json(msg=msg)
else:
return None
if len(vols) > 1:
module.fail_json(msg="Found more than one volume in zone (if specified) with name: %s" % name)
return vols[0]
def get_volumes(module, ec2):
instance = module.params.get('instance')
if not instance:
module.fail_json(msg = "Instance must be specified to get volumes")
try:
vols = ec2.get_all_volumes(filters={'attachment.instance-id': instance})
except boto.exception.BotoServerError, e:
module.fail_json(msg = "%s: %s" % (e.error_code, e.error_message))
return vols
def delete_volume(module, ec2):
volume_id = module.params['id']
try:
ec2.delete_volume(volume_id)
module.exit_json(changed=True)
except boto.exception.EC2ResponseError as ec2_error:
if ec2_error.code == 'InvalidVolume.NotFound':
module.exit_json(changed=False)
module.fail_json(msg=ec2_error.message)
def boto_supports_volume_encryption():
"""
Check if Boto library supports encryption of EBS volumes (added in 2.29.0)
Returns:
True if boto library has the named param as an argument on the request_spot_instances method, else False
"""
return hasattr(boto, 'Version') and LooseVersion(boto.Version) >= LooseVersion('2.29.0')
def create_volume(module, ec2, zone):
name = module.params.get('name')
id = module.params.get('id')
instance = module.params.get('instance')
iops = module.params.get('iops')
encrypted = module.params.get('encrypted')
volume_size = module.params.get('volume_size')
volume_type = module.params.get('volume_type')
snapshot = module.params.get('snapshot')
# If custom iops is defined we use volume_type "io1" rather than the default of "standard"
if iops:
volume_type = 'io1'
if instance == 'None' or instance == '':
instance = None
volume = get_volume(module, ec2)
if volume:
if volume.attachment_state() is not None:
if instance is None:
return volume
adata = volume.attach_data
if adata.instance_id != instance:
module.fail_json(msg = "Volume %s is already attached to another instance: %s"
% (name or id, adata.instance_id))
else:
module.exit_json(msg="Volume %s is already mapped on instance %s: %s" %
(name or id, adata.instance_id, adata.device),
volume_id=id,
device=adata.device,
changed=False)
else:
try:
if boto_supports_volume_encryption():
volume = ec2.create_volume(volume_size, zone, snapshot, volume_type, iops, encrypted)
else:
volume = ec2.create_volume(volume_size, zone, snapshot, volume_type, iops)
while volume.status != 'available':
time.sleep(3)
volume.update()
if name:
ec2.create_tags([volume.id], {"Name": name})
except boto.exception.BotoServerError, e:
module.fail_json(msg = "%s: %s" % (e.error_code, e.error_message))
return volume
def attach_volume(module, ec2, volume, instance):
device_name = module.params.get('device_name')
if device_name and instance:
try:
attach = volume.attach(instance.id, device_name)
while volume.attachment_state() != 'attached':
time.sleep(3)
volume.update()
except boto.exception.BotoServerError, e:
module.fail_json(msg = "%s: %s" % (e.error_code, e.error_message))
# If device_name isn't set, make a choice based on best practices here:
# http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html
# In future this needs to be more dynamic but combining block device mapping best practices
# (bounds for devices, as above) with instance.block_device_mapping data would be tricky. For me ;)
# Use password data attribute to tell whether the instance is Windows or Linux
if device_name is None and instance:
try:
if not ec2.get_password_data(instance.id):
device_name = '/dev/sdf'
attach = volume.attach(instance.id, device_name)
while volume.attachment_state() != 'attached':
time.sleep(3)
volume.update()
else:
device_name = '/dev/xvdf'
attach = volume.attach(instance.id, device_name)
while volume.attachment_state() != 'attached':
time.sleep(3)
volume.update()
except boto.exception.BotoServerError, e:
module.fail_json(msg = "%s: %s" % (e.error_code, e.error_message))
def detach_volume(module, ec2):
vol = get_volume(module, ec2)
if not vol or vol.attachment_state() is None:
module.exit_json(changed=False)
else:
vol.detach()
module.exit_json(changed=True)
def main():
argument_spec = ec2_argument_spec()
argument_spec.update(dict(
instance = dict(),
id = dict(),
name = dict(),
volume_size = dict(),
volume_type = dict(choices=['standard', 'gp2', 'io1'], default='standard'),
iops = dict(),
encrypted = dict(),
device_name = dict(),
zone = dict(aliases=['availability_zone', 'aws_zone', 'ec2_zone']),
snapshot = dict(),
state = dict(choices=['absent', 'present', 'list'], default='present')
)
)
module = AnsibleModule(argument_spec=argument_spec)
if not HAS_BOTO:
module.fail_json(msg='boto required for this module')
id = module.params.get('id')
name = module.params.get('name')
instance = module.params.get('instance')
volume_size = module.params.get('volume_size')
volume_type = module.params.get('volume_type')
iops = module.params.get('iops')
encrypted = module.params.get('encrypted')
device_name = module.params.get('device_name')
zone = module.params.get('zone')
snapshot = module.params.get('snapshot')
state = module.params.get('state')
if instance == 'None' or instance == '':
instance = None
ec2 = ec2_connect(module)
if state == 'list':
returned_volumes = []
vols = get_volumes(module, ec2)
for v in vols:
attachment = v.attach_data
returned_volumes.append({
'create_time': v.create_time,
'id': v.id,
'iops': v.iops,
'size': v.size,
'snapshot_id': v.snapshot_id,
'status': v.status,
'type': v.type,
'zone': v.zone,
'attachment_set': {
'attach_time': attachment.attach_time,
'device': attachment.device,
'status': attachment.status
}
})
module.exit_json(changed=False, volumes=returned_volumes)
if encrypted and not boto_supports_volume_encryption():
module.fail_json(msg="You must use boto >= v2.29.0 to use encrypted volumes")
# Here we need to get the zone info for the instance. This covers situation where
# instance is specified but zone isn't.
# Useful for playbooks chaining instance launch with volume create + attach and where the
# zone doesn't matter to the user.
if instance:
reservation = ec2.get_all_instances(instance_ids=instance)
inst = reservation[0].instances[0]
zone = inst.placement
# Check if there is a volume already mounted there.
if device_name:
if device_name in inst.block_device_mapping:
module.exit_json(msg="Volume mapping for %s already exists on instance %s" % (device_name, instance),
volume_id=inst.block_device_mapping[device_name].volume_id,
device=device_name,
changed=False)
# Delaying the checks until after the instance check allows us to get volume ids for existing volumes
# without needing to pass an unused volume_size
if not volume_size and not (id or name or snapshot):
module.fail_json(msg="You must specify volume_size or identify an existing volume by id, name, or snapshot")
if volume_size and (id or snapshot):
module.fail_json(msg="Cannot specify volume_size together with id or snapshot")
if state == 'absent':
delete_volume(module, ec2)
if state == 'present':
volume = create_volume(module, ec2, zone)
if instance:
attach_volume(module, ec2, volume, inst)
else:
detach_volume(module, ec2)
module.exit_json(volume_id=volume.id, device=device_name, volume_type=volume.type)
# import module snippets
from ansible.module_utils.basic import *
from ansible.module_utils.ec2 import *
main()
|
gpl-3.0
|
dkodnik/Ant
|
addons/l10n_gt/__openerp__.py
|
170
|
2385
|
# -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2009-2010 Soluciones Tecnologócias Prisma S.A. All Rights Reserved.
# José Rodrigo Fernández Menegazzo, Soluciones Tecnologócias Prisma S.A.
# (http://www.solucionesprisma.com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
#
# This module provides a minimal Guatemalan chart of accounts that can be use
# to build upon a more complex one. It also includes a chart of taxes and
# the Quetzal currency.
#
# This module is based on the UK minimal chart of accounts:
# Copyright (c) 2004-2009 Seath Solutions Ltd. All Rights Reserved.
# Geoff Gardiner, Seath Solutions Ltd (http://www.seathsolutions.com/)
#
# This module works with OpenERP 6.0
#
{
'name': 'Guatemala - Accounting',
'version': '3.0',
'category': 'Localization/Account Charts',
'description': """
This is the base module to manage the accounting chart for Guatemala.
=====================================================================
Agrega una nomenclatura contable para Guatemala. También icluye impuestos y
la moneda del Quetzal. -- Adds accounting chart for Guatemala. It also includes
taxes and the Quetzal currency.""",
'author': 'José Rodrigo Fernández Menegazzo',
'website': 'http://solucionesprisma.com/',
'depends': ['base', 'account', 'account_chart'],
'data': [
'account_types.xml',
'account_chart.xml',
'account_tax.xml',
'l10n_gt_base.xml',
],
'demo': [],
'installable': True,
'images': ['images/config_chart_l10n_gt.jpeg','images/l10n_gt_chart.jpeg'],
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
agpl-3.0
|
goodfeli/pylearn2
|
pylearn2/datasets/vector_spaces_dataset.py
|
41
|
6009
|
"""TODO: module-level docstring."""
__authors__ = "Pascal Lamblin and Razvan Pascanu"
__copyright__ = "Copyright 2010-2013, Universite de Montreal"
__credits__ = ["Pascal Lamblin", "Razvan Pascanu", "Ian Goodfellow",
"Mehdi Mirza"]
__license__ = "3-clause BSD"
__maintainer__ = "Pascal Lamblin"
__email__ = "lamblinp@iro"
import functools
import numpy as np
from pylearn2.datasets.dataset import Dataset
from pylearn2.utils import wraps
from pylearn2.utils.iteration import (
FiniteDatasetIterator,
resolve_iterator_class
)
from pylearn2.utils.data_specs import is_flat_specs
from pylearn2.utils.rng import make_np_rng
from pylearn2.utils import contains_nan
class VectorSpacesDataset(Dataset):
"""
A class representing datasets being stored as a number of VectorSpaces.
This can be seen as a generalization of DenseDesignMatrix where
there can be any number of sources, not just X and possibly y.
Parameters
----------
data : ndarray, or tuple of ndarrays, containing the data.
It is formatted as specified in `data_specs`. For instance, if
`data_specs` is (VectorSpace(nfeat), 'features'), then `data` has to be
a 2-d ndarray, of shape (nb examples, nfeat), that defines an unlabeled
dataset. If `data_specs` is (CompositeSpace(Conv2DSpace(...),
VectorSpace(1)), ('features', 'target')), then `data` has to be an
(X, y) pair, with X being an ndarray containing images stored in the
topological view specified by the `Conv2DSpace`, and y being a 2-D
ndarray of width 1, containing the labels or targets for each example.
data_specs : (space, source) pair
space is an instance of `Space` (possibly a `CompositeSpace`),
and `source` is a string (or tuple of strings, if `space` is a
`CompositeSpace`), defining the format and labels associated
to `data`.
rng : object, optional
A random number generator used for picking random indices into the
design matrix when choosing minibatches.
preprocessor: WRITEME
fit_preprocessor: WRITEME
"""
_default_seed = (17, 2, 946)
def __init__(self, data=None, data_specs=None, rng=_default_seed,
preprocessor=None, fit_preprocessor=False):
# data_specs should be flat, and there should be no
# duplicates in source, as we keep only one version
assert is_flat_specs(data_specs)
if isinstance(data_specs[1], tuple):
assert sorted(set(data_specs[1])) == sorted(data_specs[1])
space, source = data_specs
if isinstance(data, list):
data = tuple(data)
space.np_validate(data)
assert len(set(elem.shape[0] for elem in list(data))) <= 1
self.data = data
self.data_specs = data_specs
self.num_examples = list(data)[0].shape[0]
self.compress = False
self.design_loc = None
self.rng = make_np_rng(rng, which_method='random_integers')
# Defaults for iterators
self._iter_mode = resolve_iterator_class('sequential')
if preprocessor:
preprocessor.apply(self, can_fit=fit_preprocessor)
self.preprocessor = preprocessor
@functools.wraps(Dataset.iterator)
def iterator(self, mode=None, batch_size=None, num_batches=None,
rng=None, data_specs=None,
return_tuple=False):
if mode is None:
if hasattr(self, '_iter_subset_class'):
mode = self._iter_subset_class
else:
raise ValueError('iteration mode not provided and no default '
'mode set for %s' % str(self))
else:
mode = resolve_iterator_class(mode)
if batch_size is None:
batch_size = getattr(self, '_iter_batch_size', None)
if num_batches is None:
num_batches = getattr(self, '_iter_num_batches', None)
if rng is None and mode.stochastic:
rng = self.rng
if data_specs is None:
data_specs = self.data_specs
return FiniteDatasetIterator(
self,
mode(self.get_num_examples(),
batch_size, num_batches, rng),
data_specs=data_specs, return_tuple=return_tuple
)
def get_data_specs(self):
"""
Returns the data_specs specifying how the data is internally stored.
This is the format the data returned by `self.get_data()` will be.
"""
return self.data_specs
def get_data(self):
"""
.. todo::
WRITEME
"""
return self.data
def set_data(self, data, data_specs):
"""
.. todo::
WRITEME
"""
# data is organized as data_specs
# keep self.data_specs, and convert data
data_specs[0].np_validate(data)
assert not [contains_nan(X) for X in data]
raise NotImplementedError()
def get_source(self, name):
"""
.. todo::
WRITEME
"""
raise NotImplementedError()
@wraps(Dataset.get_num_examples)
def get_num_examples(self):
return self.num_examples
def get_batch(self, batch_size, data_specs=None):
"""
.. todo::
WRITEME
"""
raise NotImplementedError()
"""
try:
idx = self.rng.randint(self.X.shape[0] - batch_size + 1)
except ValueError:
if batch_size > self.X.shape[0]:
raise ValueError("Requested "+str(batch_size)+" examples"
"from a dataset containing only "+str(self.X.shape[0]))
raise
rx = self.X[idx:idx + batch_size, :]
if include_labels:
if self.y is None:
return rx, None
ry = self.y[idx:idx + batch_size]
return rx, ry
rx = np.cast[config.floatX](rx)
return rx
"""
|
bsd-3-clause
|
kkoksvik/FreeCAD
|
src/Mod/Ship/shipCapacityCurve/PlotAux.py
|
8
|
5494
|
#***************************************************************************
#* *
#* Copyright (c) 2011, 2016 *
#* Jose Luis Cercos Pita <[email protected]> *
#* *
#* This program is free software; you can redistribute it and/or modify *
#* it under the terms of the GNU Lesser General Public License (LGPL) *
#* as published by the Free Software Foundation; either version 2 of *
#* the License, or (at your option) any later version. *
#* for detail see the LICENCE text file. *
#* *
#* 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 Library General Public License for more details. *
#* *
#* You should have received a copy of the GNU Library 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 *
#* *
#***************************************************************************
import os
from PySide import QtGui, QtCore
import FreeCAD
import FreeCADGui
from FreeCAD import Base
import Spreadsheet
import matplotlib.ticker as mtick
class Plot(object):
def __init__(self, l, z, v, tank):
""" Constructor. performs the plot and shows it.
@param l Percentages of filling level.
@param z Level z coordinates.
@param v Volume of fluid.
@param tank Active tank instance.
"""
self.plot(l, z, v, tank)
self.spreadSheet(l, z, v, tank)
def plot(self, l, z, v, tank):
""" Perform the areas curve plot.
@param l Percentages of filling level.
@param z Level z coordinates.
@param v Volume of fluid.
@param tank Active tank instance.
@return True if error happens.
"""
try:
import Plot
plt = Plot.figure('Capacity curve')
except ImportError:
msg = QtGui.QApplication.translate(
"ship_console",
"Plot module is disabled, so I cannot perform the plot",
None,
QtGui.QApplication.UnicodeUTF8)
FreeCAD.Console.PrintWarning(msg + '\n')
return True
# Plot the volume as a function of the level percentage
vols = Plot.plot(l, v, 'Capacity')
vols.line.set_linestyle('-')
vols.line.set_linewidth(2.0)
vols.line.set_color((0.0, 0.0, 0.0))
Plot.xlabel(r'$\mathrm{level}$')
Plot.ylabel(r'$V \; [\mathrm{m}^3]$')
plt.axes.xaxis.label.set_fontsize(20)
plt.axes.yaxis.label.set_fontsize(20)
Plot.grid(True)
# Special percentage formatter for the x axis
fmt = '%.0f%%'
xticks = mtick.FormatStrFormatter(fmt)
plt.axes.xaxis.set_major_formatter(xticks)
# Now duplicate the axes
ax = Plot.addNewAxes()
# Y axis can be placed at right
ax.yaxis.tick_right()
ax.spines['right'].set_color((0.0, 0.0, 0.0))
ax.spines['left'].set_color('none')
ax.yaxis.set_ticks_position('right')
ax.yaxis.set_label_position('right')
# And X axis can be placed at top
ax.xaxis.tick_top()
ax.spines['top'].set_color((0.0, 0.0, 1.0))
ax.spines['bottom'].set_color('none')
ax.xaxis.set_ticks_position('top')
ax.xaxis.set_label_position('top')
# Plot the volume as a function of the level z coordinate
vols = Plot.plot(z, v, 'level')
vols.line.set_linestyle('-')
vols.line.set_linewidth(2.0)
vols.line.set_color((0.0, 0.0, 1.0))
Plot.xlabel(r'$z \; [\mathrm{m}]$')
Plot.ylabel(r'$V \; [\mathrm{m}^3]$')
ax.xaxis.label.set_fontsize(20)
ax.yaxis.label.set_fontsize(20)
ax.xaxis.label.set_color((0.0, 0.0, 1.0))
ax.tick_params(axis='x', colors=(0.0, 0.0, 1.0))
Plot.grid(True)
# End
plt.update()
return False
def spreadSheet(self, l, z, v, tank):
""" Write the output data file.
@param l Percentages of filling level.
@param z Level z coordinates.
@param v Volume of fluid.
@param tank Active tank instance.
"""
s = FreeCAD.activeDocument().addObject('Spreadsheet::Sheet',
'Capacity curve')
# Print the header
s.set("A1", "Percentage of filling level")
s.set("B1", "Level [m]")
s.set("C1", "Volume [m^3]")
# Print the data
for i in range(len(l)):
s.set("A{}".format(i + 2), str(l[i]))
s.set("B{}".format(i + 2), str(z[i]))
s.set("C{}".format(i + 2), str(v[i]))
# Recompute
FreeCAD.activeDocument().recompute()
|
lgpl-2.1
|
eusi/MissionPlanerHM
|
Lib/site-packages/scipy/optimize/linesearch.py
|
55
|
17394
|
from scipy.optimize import minpack2
import numpy as np
from numpy.compat import asbytes
__all__ = ['line_search_wolfe1', 'line_search_wolfe2',
'scalar_search_wolfe1', 'scalar_search_wolfe2',
'line_search_armijo']
#------------------------------------------------------------------------------
# Minpack's Wolfe line and scalar searches
#------------------------------------------------------------------------------
def line_search_wolfe1(f, fprime, xk, pk, gfk=None,
old_fval=None, old_old_fval=None,
args=(), c1=1e-4, c2=0.9, amax=50, amin=1e-8,
xtol=1e-14):
"""
As `scalar_search_wolfe1` but do a line search to direction `pk`
Parameters
----------
f : callable
Function `f(x)`
fprime : callable
Gradient of `f`
xk : array-like
Current point
pk : array-like
Search direction
gfk : array-like, optional
Gradient of `f` at point `xk`
old_fval : float, optional
Value of `f` at point `xk`
old_old_fval : float, optional
Value of `f` at point preceding `xk`
The rest of the parameters are the same as for `scalar_search_wolfe1`.
Returns
-------
stp, f_count, g_count, fval, old_fval
As in `line_search_wolfe1`
gval : array
Gradient of `f` at the final point
"""
if gfk is None:
gfk = fprime(xk)
if isinstance(fprime, tuple):
eps = fprime[1]
fprime = fprime[0]
newargs = (f, eps) + args
gradient = False
else:
newargs = args
gradient = True
gval = [gfk]
gc = [0]
fc = [0]
def phi(s):
fc[0] += 1
return f(xk + s*pk, *args)
def derphi(s):
gval[0] = fprime(xk + s*pk, *newargs)
if gradient:
gc[0] += 1
else:
fc[0] += len(xk) + 1
return np.dot(gval[0], pk)
derphi0 = np.dot(gfk, pk)
stp, fval, old_fval = scalar_search_wolfe1(
phi, derphi, old_fval, old_old_fval, derphi0,
c1=c1, c2=c2, amax=amax, amin=amin, xtol=xtol)
return stp, fc[0], gc[0], fval, old_fval, gval[0]
def scalar_search_wolfe1(phi, derphi, phi0=None, old_phi0=None, derphi0=None,
c1=1e-4, c2=0.9,
amax=50, amin=1e-8, xtol=1e-14):
"""
Scalar function search for alpha that satisfies strong Wolfe conditions
alpha > 0 is assumed to be a descent direction.
Parameters
----------
phi : callable phi(alpha)
Function at point `alpha`
derphi : callable dphi(alpha)
Derivative `d phi(alpha)/ds`. Returns a scalar.
phi0 : float, optional
Value of `f` at 0
old_phi0 : float, optional
Value of `f` at the previous point
derphi0 : float, optional
Value `derphi` at 0
amax : float, optional
Maximum step size
c1, c2 : float, optional
Wolfe parameters
Returns
-------
alpha : float
Step size, or None if no suitable step was found
phi : float
Value of `phi` at the new point `alpha`
phi0 : float
Value of `phi` at `alpha=0`
Notes
-----
Uses routine DCSRCH from MINPACK.
"""
if phi0 is None:
phi0 = phi(0.)
if derphi0 is None:
derphi0 = derphi(0.)
if old_phi0 is not None:
alpha1 = min(1.0, 1.01*2*(phi0 - old_phi0)/derphi0)
if alpha1 < 0:
alpha1 = 1.0
else:
alpha1 = 1.0
phi1 = phi0
derphi1 = derphi0
isave = np.zeros((2,), np.intc)
dsave = np.zeros((13,), float)
task = asbytes('START')
while 1:
stp, phi1, derphi1, task = minpack2.dcsrch(alpha1, phi1, derphi1,
c1, c2, xtol, task,
amin, amax, isave, dsave)
if task[:2] == asbytes('FG'):
alpha1 = stp
phi1 = phi(stp)
derphi1 = derphi(stp)
else:
break
if task[:5] == asbytes('ERROR') or task[:4] == asbytes('WARN'):
stp = None # failed
return stp, phi1, phi0
line_search = line_search_wolfe1
#------------------------------------------------------------------------------
# Pure-Python Wolfe line and scalar searches
#------------------------------------------------------------------------------
def line_search_wolfe2(f, myfprime, xk, pk, gfk=None, old_fval=None,
old_old_fval=None, args=(), c1=1e-4, c2=0.9, amax=50):
"""Find alpha that satisfies strong Wolfe conditions.
Parameters
----------
f : callable f(x,*args)
Objective function.
myfprime : callable f'(x,*args)
Objective function gradient (can be None).
xk : ndarray
Starting point.
pk : ndarray
Search direction.
gfk : ndarray, optional
Gradient value for x=xk (xk being the current parameter
estimate). Will be recomputed if omitted.
old_fval : float, optional
Function value for x=xk. Will be recomputed if omitted.
old_old_fval : float, optional
Function value for the point preceding x=xk
args : tuple, optional
Additional arguments passed to objective function.
c1 : float, optional
Parameter for Armijo condition rule.
c2 : float, optional
Parameter for curvature condition rule.
Returns
-------
alpha0 : float
Alpha for which ``x_new = x0 + alpha * pk``.
fc : int
Number of function evaluations made.
gc : int
Number of gradient evaluations made.
Notes
-----
Uses the line search algorithm to enforce strong Wolfe
conditions. See Wright and Nocedal, 'Numerical Optimization',
1999, pg. 59-60.
For the zoom phase it uses an algorithm by [...].
"""
fc = [0]
gc = [0]
gval = [None]
def phi(alpha):
fc[0] += 1
return f(xk + alpha * pk, *args)
if isinstance(myfprime, tuple):
def derphi(alpha):
fc[0] += len(xk)+1
eps = myfprime[1]
fprime = myfprime[0]
newargs = (f,eps) + args
gval[0] = fprime(xk+alpha*pk, *newargs) # store for later use
return np.dot(gval[0], pk)
else:
fprime = myfprime
def derphi(alpha):
gc[0] += 1
gval[0] = fprime(xk+alpha*pk, *args) # store for later use
return np.dot(gval[0], pk)
derphi0 = np.dot(gfk, pk)
alpha_star, phi_star, old_fval, derphi_star = \
scalar_search_wolfe2(phi, derphi, old_fval, old_old_fval,
derphi0, c1, c2, amax)
if derphi_star is not None:
# derphi_star is a number (derphi) -- so use the most recently
# calculated gradient used in computing it derphi = gfk*pk
# this is the gradient at the next step no need to compute it
# again in the outer loop.
derphi_star = gval[0]
return alpha_star, fc[0], gc[0], phi_star, old_fval, derphi_star
def scalar_search_wolfe2(phi, derphi=None, phi0=None,
old_phi0=None, derphi0=None,
c1=1e-4, c2=0.9, amax=50):
"""Find alpha that satisfies strong Wolfe conditions.
alpha > 0 is assumed to be a descent direction.
Parameters
----------
phi : callable f(x,*args)
Objective scalar function.
derphi : callable f'(x,*args), optional
Objective function derivative (can be None)
phi0 : float, optional
Value of phi at s=0
old_phi0 : float, optional
Value of phi at previous point
derphi0 : float, optional
Value of derphi at s=0
args : tuple
Additional arguments passed to objective function.
c1 : float
Parameter for Armijo condition rule.
c2 : float
Parameter for curvature condition rule.
Returns
-------
alpha_star : float
Best alpha
phi_star
phi at alpha_star
phi0
phi at 0
derphi_star
derphi at alpha_star
Notes
-----
Uses the line search algorithm to enforce strong Wolfe
conditions. See Wright and Nocedal, 'Numerical Optimization',
1999, pg. 59-60.
For the zoom phase it uses an algorithm by [...].
"""
if phi0 is None:
phi0 = phi(0.)
if derphi0 is None and derphi is not None:
derphi0 = derphi(0.)
alpha0 = 0
if old_phi0 is not None:
alpha1 = min(1.0, 1.01*2*(phi0 - old_phi0)/derphi0)
else:
alpha1 = 1.0
if alpha1 < 0:
alpha1 = 1.0
if alpha1 == 0:
# This shouldn't happen. Perhaps the increment has slipped below
# machine precision? For now, set the return variables skip the
# useless while loop, and raise warnflag=2 due to possible imprecision.
alpha_star = None
phi_star = phi0
phi0 = old_phi0
derphi_star = None
phi_a1 = phi(alpha1)
#derphi_a1 = derphi(alpha1) evaluated below
phi_a0 = phi0
derphi_a0 = derphi0
i = 1
maxiter = 10
while 1: # bracketing phase
if alpha1 == 0:
break
if (phi_a1 > phi0 + c1*alpha1*derphi0) or \
((phi_a1 >= phi_a0) and (i > 1)):
alpha_star, phi_star, derphi_star = \
_zoom(alpha0, alpha1, phi_a0,
phi_a1, derphi_a0, phi, derphi,
phi0, derphi0, c1, c2)
break
derphi_a1 = derphi(alpha1)
if (abs(derphi_a1) <= -c2*derphi0):
alpha_star = alpha1
phi_star = phi_a1
derphi_star = derphi_a1
break
if (derphi_a1 >= 0):
alpha_star, phi_star, derphi_star = \
_zoom(alpha1, alpha0, phi_a1,
phi_a0, derphi_a1, phi, derphi,
phi0, derphi0, c1, c2)
break
alpha2 = 2 * alpha1 # increase by factor of two on each iteration
i = i + 1
alpha0 = alpha1
alpha1 = alpha2
phi_a0 = phi_a1
phi_a1 = phi(alpha1)
derphi_a0 = derphi_a1
# stopping test if lower function not found
if i > maxiter:
alpha_star = alpha1
phi_star = phi_a1
derphi_star = None
break
return alpha_star, phi_star, phi0, derphi_star
def _cubicmin(a,fa,fpa,b,fb,c,fc):
"""
Finds the minimizer for a cubic polynomial that goes through the
points (a,fa), (b,fb), and (c,fc) with derivative at a of fpa.
If no minimizer can be found return None
"""
# f(x) = A *(x-a)^3 + B*(x-a)^2 + C*(x-a) + D
C = fpa
D = fa
db = b-a
dc = c-a
if (db == 0) or (dc == 0) or (b==c): return None
denom = (db*dc)**2 * (db-dc)
d1 = np.empty((2,2))
d1[0,0] = dc**2
d1[0,1] = -db**2
d1[1,0] = -dc**3
d1[1,1] = db**3
[A,B] = np.dot(d1, np.asarray([fb-fa-C*db,fc-fa-C*dc]).flatten())
A /= denom
B /= denom
radical = B*B-3*A*C
if radical < 0: return None
if (A == 0): return None
xmin = a + (-B + np.sqrt(radical))/(3*A)
return xmin
def _quadmin(a,fa,fpa,b,fb):
"""
Finds the minimizer for a quadratic polynomial that goes through
the points (a,fa), (b,fb) with derivative at a of fpa,
"""
# f(x) = B*(x-a)^2 + C*(x-a) + D
D = fa
C = fpa
db = b-a*1.0
if (db==0): return None
B = (fb-D-C*db)/(db*db)
if (B <= 0): return None
xmin = a - C / (2.0*B)
return xmin
def _zoom(a_lo, a_hi, phi_lo, phi_hi, derphi_lo,
phi, derphi, phi0, derphi0, c1, c2):
"""
Part of the optimization algorithm in `scalar_search_wolfe2`.
"""
maxiter = 10
i = 0
delta1 = 0.2 # cubic interpolant check
delta2 = 0.1 # quadratic interpolant check
phi_rec = phi0
a_rec = 0
while 1:
# interpolate to find a trial step length between a_lo and
# a_hi Need to choose interpolation here. Use cubic
# interpolation and then if the result is within delta *
# dalpha or outside of the interval bounded by a_lo or a_hi
# then use quadratic interpolation, if the result is still too
# close, then use bisection
dalpha = a_hi-a_lo;
if dalpha < 0: a,b = a_hi,a_lo
else: a,b = a_lo, a_hi
# minimizer of cubic interpolant
# (uses phi_lo, derphi_lo, phi_hi, and the most recent value of phi)
#
# if the result is too close to the end points (or out of the
# interval) then use quadratic interpolation with phi_lo,
# derphi_lo and phi_hi if the result is stil too close to the
# end points (or out of the interval) then use bisection
if (i > 0):
cchk = delta1*dalpha
a_j = _cubicmin(a_lo, phi_lo, derphi_lo, a_hi, phi_hi, a_rec, phi_rec)
if (i==0) or (a_j is None) or (a_j > b-cchk) or (a_j < a+cchk):
qchk = delta2*dalpha
a_j = _quadmin(a_lo, phi_lo, derphi_lo, a_hi, phi_hi)
if (a_j is None) or (a_j > b-qchk) or (a_j < a+qchk):
a_j = a_lo + 0.5*dalpha
# Check new value of a_j
phi_aj = phi(a_j)
if (phi_aj > phi0 + c1*a_j*derphi0) or (phi_aj >= phi_lo):
phi_rec = phi_hi
a_rec = a_hi
a_hi = a_j
phi_hi = phi_aj
else:
derphi_aj = derphi(a_j)
if abs(derphi_aj) <= -c2*derphi0:
a_star = a_j
val_star = phi_aj
valprime_star = derphi_aj
break
if derphi_aj*(a_hi - a_lo) >= 0:
phi_rec = phi_hi
a_rec = a_hi
a_hi = a_lo
phi_hi = phi_lo
else:
phi_rec = phi_lo
a_rec = a_lo
a_lo = a_j
phi_lo = phi_aj
derphi_lo = derphi_aj
i += 1
if (i > maxiter):
a_star = a_j
val_star = phi_aj
valprime_star = None
break
return a_star, val_star, valprime_star
#------------------------------------------------------------------------------
# Armijo line and scalar searches
#------------------------------------------------------------------------------
def line_search_armijo(f, xk, pk, gfk, old_fval, args=(), c1=1e-4, alpha0=1):
"""Minimize over alpha, the function ``f(xk+alpha pk)``.
Uses the interpolation algorithm (Armijo backtracking) as suggested by
Wright and Nocedal in 'Numerical Optimization', 1999, pg. 56-57
Returns
-------
alpha
f_count
f_val_at_alpha
"""
xk = np.atleast_1d(xk)
fc = [0]
def phi(alpha1):
fc[0] += 1
return f(xk + alpha1*pk, *args)
if old_fval is None:
phi0 = phi(0.)
else:
phi0 = old_fval # compute f(xk) -- done in past loop
derphi0 = np.dot(gfk, pk)
alpha, phi1 = scalar_search_armijo(phi, phi0, derphi0, c1=c1, alpha0=alpha0)
return alpha, fc[0], phi1
def line_search_BFGS(f, xk, pk, gfk, old_fval, args=(), c1=1e-4, alpha0=1):
"""
Compatibility wrapper for `line_search_armijo`
"""
r = line_search_armijo(f, xk, pk, gfk, old_fval, args=args, c1=c1,
alpha0=alpha0)
return r[0], r[1], 0, r[2]
def scalar_search_armijo(phi, phi0, derphi0, c1=1e-4, alpha0=1, amin=0):
"""Minimize over alpha, the function ``phi(alpha)``.
Uses the interpolation algorithm (Armijo backtracking) as suggested by
Wright and Nocedal in 'Numerical Optimization', 1999, pg. 56-57
alpha > 0 is assumed to be a descent direction.
Returns
-------
alpha
phi1
"""
phi_a0 = phi(alpha0)
if phi_a0 <= phi0 + c1*alpha0*derphi0:
return alpha0, phi_a0
# Otherwise compute the minimizer of a quadratic interpolant:
alpha1 = -(derphi0) * alpha0**2 / 2.0 / (phi_a0 - phi0 - derphi0 * alpha0)
phi_a1 = phi(alpha1)
if (phi_a1 <= phi0 + c1*alpha1*derphi0):
return alpha1, phi_a1
# Otherwise loop with cubic interpolation until we find an alpha which
# satifies the first Wolfe condition (since we are backtracking, we will
# assume that the value of alpha is not too small and satisfies the second
# condition.
while alpha1 > amin: # we are assuming alpha>0 is a descent direction
factor = alpha0**2 * alpha1**2 * (alpha1-alpha0)
a = alpha0**2 * (phi_a1 - phi0 - derphi0*alpha1) - \
alpha1**2 * (phi_a0 - phi0 - derphi0*alpha0)
a = a / factor
b = -alpha0**3 * (phi_a1 - phi0 - derphi0*alpha1) + \
alpha1**3 * (phi_a0 - phi0 - derphi0*alpha0)
b = b / factor
alpha2 = (-b + np.sqrt(abs(b**2 - 3 * a * derphi0))) / (3.0*a)
phi_a2 = phi(alpha2)
if (phi_a2 <= phi0 + c1*alpha2*derphi0):
return alpha2, phi_a2
if (alpha1 - alpha2) > alpha1 / 2.0 or (1 - alpha2/alpha1) < 0.96:
alpha2 = alpha1 / 2.0
alpha0 = alpha1
alpha1 = alpha2
phi_a0 = phi_a1
phi_a1 = phi_a2
# Failed to find a suitable step length
return None, phi_a1
|
gpl-3.0
|
DarkPurpleShadow/ConnectFour
|
urwid/main_loop.py
|
2
|
41354
|
#!/usr/bin/python
#
# Urwid main loop code
# Copyright (C) 2004-2012 Ian Ward
# Copyright (C) 2008 Walter Mundt
# Copyright (C) 2009 Andrew Psaltis
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Urwid web site: http://excess.org/urwid/
import time
import heapq
import select
import fcntl
import os
from functools import wraps
from weakref import WeakKeyDictionary
from urwid.util import is_mouse_event
from urwid.compat import PYTHON3
from urwid.command_map import command_map, REDRAW_SCREEN
from urwid.wimp import PopUpTarget
from urwid import signals
from urwid.display_common import INPUT_DESCRIPTORS_CHANGED
PIPE_BUFFER_READ_SIZE = 4096 # can expect this much on Linux, so try for that
class ExitMainLoop(Exception):
"""
When this exception is raised within a main loop the main loop
will exit cleanly.
"""
pass
class MainLoop(object):
"""
This is the standard main loop implementation for a single interactive
session.
:param widget: the topmost widget used for painting the screen, stored as
:attr:`widget` and may be modified. Must be a box widget.
:type widget: widget instance
:param palette: initial palette for screen
:type palette: iterable of palette entries
:param screen: screen to use, default is a new :class:`raw_display.Screen`
instance; stored as :attr:`screen`
:type screen: display module screen instance
:param handle_mouse: ``True`` to ask :attr:`.screen` to process mouse events
:type handle_mouse: bool
:param input_filter: a function to filter input before sending it to
:attr:`.widget`, called from :meth:`.input_filter`
:type input_filter: callable
:param unhandled_input: a function called when input is not handled by
:attr:`.widget`, called from :meth:`.unhandled_input`
:type unhandled_input: callable
:param event_loop: if :attr:`.screen` supports external an event loop it may be
given here, default is a new :class:`SelectEventLoop` instance;
stored as :attr:`.event_loop`
:type event_loop: event loop instance
:param pop_ups: `True` to wrap :attr:`.widget` with a :class:`PopUpTarget`
instance to allow any widget to open a pop-up anywhere on the screen
:type pop_ups: boolean
.. attribute:: screen
The screen object this main loop uses for screen updates and reading input
.. attribute:: event_loop
The event loop object this main loop uses for waiting on alarms and IO
"""
def __init__(self, widget, palette=(), screen=None,
handle_mouse=True, input_filter=None, unhandled_input=None,
event_loop=None, pop_ups=False):
self._widget = widget
self.handle_mouse = handle_mouse
self.pop_ups = pop_ups # triggers property setting side-effect
if not screen:
from urwid import raw_display
screen = raw_display.Screen()
if palette:
screen.register_palette(palette)
self.screen = screen
self.screen_size = None
self._unhandled_input = unhandled_input
self._input_filter = input_filter
if not hasattr(screen, 'get_input_descriptors'
) and event_loop is not None:
raise NotImplementedError("screen object passed "
"%r does not support external event loops" % (screen,))
if event_loop is None:
event_loop = SelectEventLoop()
self.event_loop = event_loop
self._input_timeout = None
self._watch_pipes = {}
def _set_widget(self, widget):
self._widget = widget
if self.pop_ups:
self._topmost_widget.original_widget = self._widget
else:
self._topmost_widget = self._widget
widget = property(lambda self:self._widget, _set_widget, doc=
"""
Property for the topmost widget used to draw the screen.
This must be a box widget.
""")
def _set_pop_ups(self, pop_ups):
self._pop_ups = pop_ups
if pop_ups:
self._topmost_widget = PopUpTarget(self._widget)
else:
self._topmost_widget = self._widget
pop_ups = property(lambda self:self._pop_ups, _set_pop_ups)
def set_alarm_in(self, sec, callback, user_data=None):
"""
Schedule an alarm in *sec* seconds that will call *callback* from the
within the :meth:`run` method.
:param sec: seconds until alarm
:type sec: float
:param callback: function to call with two parameters: this main loop
object and *user_data*
:type callback: callable
"""
def cb():
callback(self, user_data)
return self.event_loop.alarm(sec, cb)
def set_alarm_at(self, tm, callback, user_data=None):
"""
Schedule an alarm at *tm* time that will call *callback* from the
within the :meth:`run` function. Returns a handle that may be passed to
:meth:`remove_alarm`.
:param tm: time to call callback e.g. ``time.time() + 5``
:type tm: float
:param callback: function to call with two parameters: this main loop
object and *user_data*
:type callback: callable
"""
def cb():
callback(self, user_data)
return self.event_loop.alarm(tm - time.time(), cb)
def remove_alarm(self, handle):
"""
Remove an alarm. Return ``True`` if *handle* was found, ``False``
otherwise.
"""
return self.event_loop.remove_alarm(handle)
def watch_pipe(self, callback):
"""
Create a pipe for use by a subprocess or thread to trigger a callback
in the process/thread running the main loop.
:param callback: function taking one parameter to call from within
the process/thread running the main loop
:type callback: callable
This method returns a file descriptor attached to the write end of a
pipe. The read end of the pipe is added to the list of files
:attr:`event_loop` is watching. When data is written to the pipe the
callback function will be called and passed a single value containing
data read from the pipe.
This method may be used any time you want to update widgets from
another thread or subprocess.
Data may be written to the returned file descriptor with
``os.write(fd, data)``. Ensure that data is less than 512 bytes (or 4K
on Linux) so that the callback will be triggered just once with the
complete value of data passed in.
If the callback returns ``False`` then the watch will be removed from
:attr:`event_loop` and the read end of the pipe will be closed. You
are responsible for closing the write end of the pipe with
``os.close(fd)``.
"""
pipe_rd, pipe_wr = os.pipe()
fcntl.fcntl(pipe_rd, fcntl.F_SETFL, os.O_NONBLOCK)
watch_handle = None
def cb():
data = os.read(pipe_rd, PIPE_BUFFER_READ_SIZE)
rval = callback(data)
if rval is False:
self.event_loop.remove_watch_file(watch_handle)
os.close(pipe_rd)
watch_handle = self.event_loop.watch_file(pipe_rd, cb)
self._watch_pipes[pipe_wr] = (watch_handle, pipe_rd)
return pipe_wr
def remove_watch_pipe(self, write_fd):
"""
Close the read end of the pipe and remove the watch created by
:meth:`watch_pipe`. You are responsible for closing the write end of
the pipe.
Returns ``True`` if the watch pipe exists, ``False`` otherwise
"""
try:
watch_handle, pipe_rd = self._watch_pipes.pop(write_fd)
except KeyError:
return False
if not self.event_loop.remove_watch_file(watch_handle):
return False
os.close(pipe_rd)
return True
def watch_file(self, fd, callback):
"""
Call *callback* when *fd* has some data to read. No parameters are
passed to callback.
Returns a handle that may be passed to :meth:`remove_watch_file`.
"""
return self.event_loop.watch_file(fd, callback)
def remove_watch_file(self, handle):
"""
Remove a watch file. Returns ``True`` if the watch file
exists, ``False`` otherwise.
"""
return self.event_loop.remove_watch_file(handle)
def run(self):
"""
Start the main loop handling input events and updating the screen. The
loop will continue until an :exc:`ExitMainLoop` exception is raised.
This method will use :attr:`screen`'s run_wrapper() method if
:attr:`screen`'s start() method has not already been called.
"""
try:
if self.screen.started:
self._run()
else:
self.screen.run_wrapper(self._run)
except ExitMainLoop:
pass
def _test_run(self):
"""
>>> w = _refl("widget") # _refl prints out function calls
>>> w.render_rval = "fake canvas" # *_rval is used for return values
>>> scr = _refl("screen")
>>> scr.get_input_descriptors_rval = [42]
>>> scr.get_cols_rows_rval = (20, 10)
>>> scr.started = True
>>> scr._urwid_signals = {}
>>> evl = _refl("event_loop")
>>> evl.enter_idle_rval = 1
>>> evl.watch_file_rval = 2
>>> ml = MainLoop(w, [], scr, event_loop=evl)
>>> ml.run() # doctest:+ELLIPSIS
screen.set_mouse_tracking()
screen.get_cols_rows()
widget.render((20, 10), focus=True)
screen.draw_screen((20, 10), 'fake canvas')
screen.get_input_descriptors()
event_loop.watch_file(42, <bound method ...>)
event_loop.enter_idle(<bound method ...>)
event_loop.run()
event_loop.remove_enter_idle(1)
event_loop.remove_watch_file(2)
>>> scr.started = False
>>> ml.run() # doctest:+ELLIPSIS
screen.run_wrapper(<bound method ...>)
"""
def _run(self):
if self.handle_mouse:
self.screen.set_mouse_tracking()
if not hasattr(self.screen, 'get_input_descriptors'):
return self._run_screen_event_loop()
self.draw_screen()
fd_handles = []
def reset_input_descriptors(only_remove=False):
for handle in fd_handles:
self.event_loop.remove_watch_file(handle)
if only_remove:
del fd_handles[:]
else:
fd_handles[:] = [
self.event_loop.watch_file(fd, self._update)
for fd in self.screen.get_input_descriptors()]
if not fd_handles and self._input_timeout is not None:
self.event_loop.remove_alarm(self._input_timeout)
try:
signals.connect_signal(self.screen, INPUT_DESCRIPTORS_CHANGED,
reset_input_descriptors)
except NameError:
pass
# watch our input descriptors
reset_input_descriptors()
idle_handle = self.event_loop.enter_idle(self.entering_idle)
# Go..
self.event_loop.run()
# tidy up
self.event_loop.remove_enter_idle(idle_handle)
reset_input_descriptors(True)
signals.disconnect_signal(self.screen, INPUT_DESCRIPTORS_CHANGED,
reset_input_descriptors)
def _update(self, timeout=False):
"""
>>> w = _refl("widget")
>>> w.selectable_rval = True
>>> w.mouse_event_rval = True
>>> scr = _refl("screen")
>>> scr.get_cols_rows_rval = (15, 5)
>>> scr.get_input_nonblocking_rval = 1, ['y'], [121]
>>> evl = _refl("event_loop")
>>> ml = MainLoop(w, [], scr, event_loop=evl)
>>> ml._input_timeout = "old timeout"
>>> ml._update() # doctest:+ELLIPSIS
event_loop.remove_alarm('old timeout')
screen.get_input_nonblocking()
event_loop.alarm(1, <function ...>)
screen.get_cols_rows()
widget.selectable()
widget.keypress((15, 5), 'y')
>>> scr.get_input_nonblocking_rval = None, [("mouse press", 1, 5, 4)
... ], []
>>> ml._update()
screen.get_input_nonblocking()
widget.mouse_event((15, 5), 'mouse press', 1, 5, 4, focus=True)
>>> scr.get_input_nonblocking_rval = None, [], []
>>> ml._update()
screen.get_input_nonblocking()
"""
if self._input_timeout is not None and not timeout:
# cancel the timeout, something else triggered the update
self.event_loop.remove_alarm(self._input_timeout)
self._input_timeout = None
max_wait, keys, raw = self.screen.get_input_nonblocking()
if max_wait is not None:
# if get_input_nonblocking wants to be called back
# make sure it happens with an alarm
self._input_timeout = self.event_loop.alarm(max_wait,
lambda: self._update(timeout=True))
keys = self.input_filter(keys, raw)
if keys:
self.process_input(keys)
if 'window resize' in keys:
self.screen_size = None
def _run_screen_event_loop(self):
"""
This method is used when the screen does not support using
external event loops.
The alarms stored in the SelectEventLoop in :attr:`event_loop`
are modified by this method.
"""
next_alarm = None
while True:
self.draw_screen()
if not next_alarm and self.event_loop._alarms:
next_alarm = heapq.heappop(self.event_loop._alarms)
keys = None
while not keys:
if next_alarm:
sec = max(0, next_alarm[0] - time.time())
self.screen.set_input_timeouts(sec)
else:
self.screen.set_input_timeouts(None)
keys, raw = self.screen.get_input(True)
if not keys and next_alarm:
sec = next_alarm[0] - time.time()
if sec <= 0:
break
keys = self.input_filter(keys, raw)
if keys:
self.process_input(keys)
while next_alarm:
sec = next_alarm[0] - time.time()
if sec > 0:
break
tm, callback = next_alarm
callback()
if self.event_loop._alarms:
next_alarm = heapq.heappop(self.event_loop._alarms)
else:
next_alarm = None
if 'window resize' in keys:
self.screen_size = None
def _test_run_screen_event_loop(self):
"""
>>> w = _refl("widget")
>>> scr = _refl("screen")
>>> scr.get_cols_rows_rval = (10, 5)
>>> scr.get_input_rval = [], []
>>> ml = MainLoop(w, screen=scr)
>>> def stop_now(loop, data):
... raise ExitMainLoop()
>>> handle = ml.set_alarm_in(0, stop_now)
>>> try:
... ml._run_screen_event_loop()
... except ExitMainLoop:
... pass
screen.get_cols_rows()
widget.render((10, 5), focus=True)
screen.draw_screen((10, 5), None)
screen.set_input_timeouts(0)
screen.get_input(True)
"""
def process_input(self, keys):
"""
This method will pass keyboard input and mouse events to :attr:`widget`.
This method is called automatically from the :meth:`run` method when
there is input, but may also be called to simulate input from the user.
*keys* is a list of input returned from :attr:`screen`'s get_input()
or get_input_nonblocking() methods.
Returns ``True`` if any key was handled by a widget or the
:meth:`unhandled_input` method.
"""
if not self.screen_size:
self.screen_size = self.screen.get_cols_rows()
something_handled = False
for k in keys:
if k == 'window resize':
continue
if is_mouse_event(k):
event, button, col, row = k
if self._topmost_widget.mouse_event(self.screen_size,
event, button, col, row, focus=True ):
k = None
elif self._topmost_widget.selectable():
k = self._topmost_widget.keypress(self.screen_size, k)
if k:
if command_map[k] == REDRAW_SCREEN:
self.screen.clear()
something_handled = True
else:
something_handled |= bool(self.unhandled_input(k))
else:
something_handled = True
return something_handled
def _test_process_input(self):
"""
>>> w = _refl("widget")
>>> w.selectable_rval = True
>>> scr = _refl("screen")
>>> scr.get_cols_rows_rval = (10, 5)
>>> ml = MainLoop(w, [], scr)
>>> ml.process_input(['enter', ('mouse drag', 1, 14, 20)])
screen.get_cols_rows()
widget.selectable()
widget.keypress((10, 5), 'enter')
widget.mouse_event((10, 5), 'mouse drag', 1, 14, 20, focus=True)
True
"""
def input_filter(self, keys, raw):
"""
This function is passed each all the input events and raw keystroke
values. These values are passed to the *input_filter* function
passed to the constructor. That function must return a list of keys to
be passed to the widgets to handle. If no *input_filter* was
defined this implementation will return all the input events.
"""
if self._input_filter:
return self._input_filter(keys, raw)
return keys
def unhandled_input(self, input):
"""
This function is called with any input that was not handled by the
widgets, and calls the *unhandled_input* function passed to the
constructor. If no *unhandled_input* was defined then the input
will be ignored.
*input* is the keyboard or mouse input.
The *unhandled_input* function should return ``True`` if it handled
the input.
"""
if self._unhandled_input:
return self._unhandled_input(input)
def entering_idle(self):
"""
This method is called whenever the event loop is about to enter the
idle state. :meth:`draw_screen` is called here to update the
screen when anything has changed.
"""
if self.screen.started:
self.draw_screen()
def draw_screen(self):
"""
Render the widgets and paint the screen. This method is called
automatically from :meth:`entering_idle`.
If you modify the widgets displayed outside of handling input or
responding to an alarm you will need to call this method yourself
to repaint the screen.
"""
if not self.screen_size:
self.screen_size = self.screen.get_cols_rows()
canvas = self._topmost_widget.render(self.screen_size, focus=True)
self.screen.draw_screen(self.screen_size, canvas)
class SelectEventLoop(object):
"""
Event loop based on :func:`select.select`
"""
def __init__(self):
self._alarms = []
self._watch_files = {}
self._idle_handle = 0
self._idle_callbacks = {}
def alarm(self, seconds, callback):
"""
Call callback() given time from from now. No parameters are
passed to callback.
Returns a handle that may be passed to remove_alarm()
seconds -- floating point time to wait before calling callback
callback -- function to call from event loop
"""
tm = time.time() + seconds
heapq.heappush(self._alarms, (tm, callback))
return (tm, callback)
def remove_alarm(self, handle):
"""
Remove an alarm.
Returns True if the alarm exists, False otherwise
"""
try:
self._alarms.remove(handle)
heapq.heapify(self._alarms)
return True
except ValueError:
return False
def watch_file(self, fd, callback):
"""
Call callback() when fd has some data to read. No parameters
are passed to callback.
Returns a handle that may be passed to remove_watch_file()
fd -- file descriptor to watch for input
callback -- function to call when input is available
"""
self._watch_files[fd] = callback
return fd
def remove_watch_file(self, handle):
"""
Remove an input file.
Returns True if the input file exists, False otherwise
"""
if handle in self._watch_files:
del self._watch_files[handle]
return True
return False
def enter_idle(self, callback):
"""
Add a callback for entering idle.
Returns a handle that may be passed to remove_idle()
"""
self._idle_handle += 1
self._idle_callbacks[self._idle_handle] = callback
return self._idle_handle
def remove_enter_idle(self, handle):
"""
Remove an idle callback.
Returns True if the handle was removed.
"""
try:
del self._idle_callbacks[handle]
except KeyError:
return False
return True
def _entering_idle(self):
"""
Call all the registered idle callbacks.
"""
for callback in list(self._idle_callbacks.values()):
callback()
def run(self):
"""
Start the event loop. Exit the loop when any callback raises
an exception. If ExitMainLoop is raised, exit cleanly.
"""
try:
self._did_something = True
while True:
try:
self._loop()
except select.error as e:
if e.args[0] != 4:
# not just something we need to retry
raise
except ExitMainLoop:
pass
def _loop(self):
"""
A single iteration of the event loop
"""
fds = list(self._watch_files.keys())
if self._alarms or self._did_something:
if self._alarms:
tm = self._alarms[0][0]
timeout = max(0, tm - time.time())
if self._did_something and (not self._alarms or
(self._alarms and timeout > 0)):
timeout = 0
tm = 'idle'
ready, w, err = select.select(fds, [], fds, timeout)
else:
tm = None
ready, w, err = select.select(fds, [], fds)
if not ready:
if tm == 'idle':
self._entering_idle()
self._did_something = False
elif tm is not None:
# must have been a timeout
tm, alarm_callback = self._alarms.pop(0)
alarm_callback()
self._did_something = True
for fd in ready:
self._watch_files[fd]()
self._did_something = True
class GLibEventLoop(object):
"""
Event loop based on GLib.MainLoop
"""
def __init__(self):
from gi.repository import GLib
self.GLib = GLib
self._alarms = []
self._watch_files = {}
self._idle_handle = 0
self._glib_idle_enabled = False # have we called glib.idle_add?
self._idle_callbacks = {}
self._loop = GLib.MainLoop()
self._exc_info = None
self._enable_glib_idle()
def alarm(self, seconds, callback):
"""
Call callback() given time from from now. No parameters are
passed to callback.
Returns a handle that may be passed to remove_alarm()
seconds -- floating point time to wait before calling callback
callback -- function to call from event loop
"""
@self.handle_exit
def ret_false():
callback()
self._enable_glib_idle()
return False
fd = self.GLib.timeout_add(int(seconds*1000), ret_false)
self._alarms.append(fd)
return (fd, callback)
def remove_alarm(self, handle):
"""
Remove an alarm.
Returns True if the alarm exists, False otherwise
"""
try:
self._alarms.remove(handle[0])
self.GLib.source_remove(handle[0])
return True
except ValueError:
return False
def watch_file(self, fd, callback):
"""
Call callback() when fd has some data to read. No parameters
are passed to callback.
Returns a handle that may be passed to remove_watch_file()
fd -- file descriptor to watch for input
callback -- function to call when input is available
"""
@self.handle_exit
def io_callback(source, cb_condition):
callback()
self._enable_glib_idle()
return True
self._watch_files[fd] = \
self.GLib.io_add_watch(fd,self.GLib.IO_IN,io_callback)
return fd
def remove_watch_file(self, handle):
"""
Remove an input file.
Returns True if the input file exists, False otherwise
"""
if handle in self._watch_files:
self.GLib.source_remove(self._watch_files[handle])
del self._watch_files[handle]
return True
return False
def enter_idle(self, callback):
"""
Add a callback for entering idle.
Returns a handle that may be passed to remove_enter_idle()
"""
self._idle_handle += 1
self._idle_callbacks[self._idle_handle] = callback
return self._idle_handle
def _enable_glib_idle(self):
if self._glib_idle_enabled:
return
self.GLib.idle_add(self._glib_idle_callback)
self._glib_idle_enabled = True
def _glib_idle_callback(self):
for callback in list(self._idle_callbacks.values()):
callback()
self._glib_idle_enabled = False
return False # ask glib not to call again (or we would be called
def remove_enter_idle(self, handle):
"""
Remove an idle callback.
Returns True if the handle was removed.
"""
try:
del self._idle_callbacks[handle]
except KeyError:
return False
return True
def run(self):
"""
Start the event loop. Exit the loop when any callback raises
an exception. If ExitMainLoop is raised, exit cleanly.
"""
try:
self._loop.run()
finally:
if self._loop.is_running():
self._loop.quit()
if self._exc_info:
# An exception caused us to exit, raise it now
exc_info = self._exc_info
self._exc_info = None
raise exc_info[0](exc_info[1]).with_traceback(exc_info[2])
def handle_exit(self,f):
"""
Decorator that cleanly exits the :class:`GLibEventLoop` if
:exc:`ExitMainLoop` is thrown inside of the wrapped function. Store the
exception info if some other exception occurs, it will be reraised after
the loop quits.
*f* -- function to be wrapped
"""
def wrapper(*args,**kargs):
try:
return f(*args,**kargs)
except ExitMainLoop:
self._loop.quit()
except:
import sys
self._exc_info = sys.exc_info()
if self._loop.is_running():
self._loop.quit()
return False
return wrapper
class TornadoEventLoop(object):
""" This is an Urwid-specific event loop to plug into its MainLoop.
It acts as an adaptor for Tornado's IOLoop which does all
heavy lifting except idle-callbacks.
Notice, since Tornado has no concept of idle callbacks we
monkey patch ioloop._impl.poll() function to be able to detect
potential idle periods.
"""
_ioloop_registry = WeakKeyDictionary() # {<ioloop> : {<handle> : <idle_func>}}
_max_idle_handle = 0
class PollProxy(object):
""" A simple proxy for a Python's poll object that wraps the .poll() method
in order to detect idle periods and call Urwid callbacks
"""
def __init__(self, poll_obj, idle_map):
self.__poll_obj = poll_obj
self.__idle_map = idle_map
self._idle_done = False
self._prev_timeout = 0
def __getattr__(self, name):
return getattr(self.__poll_obj, name)
def poll(self, timeout):
if timeout > self._prev_timeout:
# if timeout increased we assume a timer event was handled
self._idle_done = False
self._prev_timeout = timeout
start = time.time()
# any IO pending wins
events = self.__poll_obj.poll(0)
if events:
self._idle_done = False
return events
# our chance to enter idle
if not self._idle_done:
for callback in list(self.__idle_map.values()):
callback()
self._idle_done = True
# then complete the actual request (adjusting timeout)
timeout = max(0, min(timeout, timeout + start - time.time()))
events = self.__poll_obj.poll(timeout)
if events:
self._idle_done = False
return events
@classmethod
def _patch_poll_impl(cls, ioloop):
""" Wraps original poll object in the IOLoop's poll object
"""
if ioloop in cls._ioloop_registry:
return # we already patched this instance
cls._ioloop_registry[ioloop] = idle_map = {}
ioloop._impl = cls.PollProxy(ioloop._impl, idle_map)
def __init__(self, ioloop=None):
if not ioloop:
from tornado.ioloop import IOLoop
ioloop = IOLoop.instance()
self._ioloop = ioloop
self._patch_poll_impl(ioloop)
self._pending_alarms = {}
self._watch_handles = {} # {<watch_handle> : <file_descriptor>}
self._max_watch_handle = 0
self._exception = None
def alarm(self, secs, callback):
ioloop = self._ioloop
def wrapped():
try:
del self._pending_alarms[handle]
except KeyError:
pass
self.handle_exit(callback)()
handle = ioloop.add_timeout(ioloop.time() + secs, wrapped)
self._pending_alarms[handle] = 1
return handle
def remove_alarm(self, handle):
self._ioloop.remove_timeout(handle)
try:
del self._pending_alarms[handle]
except KeyError:
return False
else:
return True
def watch_file(self, fd, callback):
from tornado.ioloop import IOLoop
handler = lambda fd,events: self.handle_exit(callback)()
self._ioloop.add_handler(fd, handler, IOLoop.READ)
self._max_watch_handle += 1
handle = self._max_watch_handle
self._watch_handles[handle] = fd
return handle
def remove_watch_file(self, handle):
fd = self._watch_handles.pop(handle, None)
if fd is None:
return False
else:
self._ioloop.remove_handler(fd)
return True
def enter_idle(self, callback):
self._max_idle_handle += 1
handle = self._max_idle_handle
idle_map = self._ioloop_registry[self._ioloop]
idle_map[handle] = callback
return handle
def remove_enter_idle(self, handle):
idle_map = self._ioloop_registry[self._ioloop]
cb = idle_map.pop(handle, None)
return cb is not None
def handle_exit(self, func):
@wraps(func)
def wrapper(*args, **kw):
try:
return func(*args, **kw)
except ExitMainLoop:
self._ioloop.stop()
except Exception as exc:
self._exception = exc
self._ioloop.stop()
return False
return wrapper
def run(self):
self._ioloop.start()
if self._exception:
exc, self._exception = self._exception, None
raise exc
try:
from twisted.internet.abstract import FileDescriptor
except ImportError:
FileDescriptor = object
class TwistedInputDescriptor(FileDescriptor):
def __init__(self, reactor, fd, cb):
self._fileno = fd
self.cb = cb
FileDescriptor.__init__(self, reactor)
def fileno(self):
return self._fileno
def doRead(self):
return self.cb()
class TwistedEventLoop(object):
"""
Event loop based on Twisted_
"""
_idle_emulation_delay = 1.0/256 # a short time (in seconds)
def __init__(self, reactor=None, manage_reactor=True):
"""
:param reactor: reactor to use
:type reactor: :class:`twisted.internet.reactor`.
:param: manage_reactor: `True` if you want this event loop to run
and stop the reactor.
:type manage_reactor: boolean
.. WARNING::
Twisted's reactor doesn't like to be stopped and run again. If you
need to stop and run your :class:`MainLoop`, consider setting
``manage_reactor=False`` and take care of running/stopping the reactor
at the beginning/ending of your program yourself.
.. _Twisted: http://twistedmatrix.com/trac/
"""
if reactor is None:
import twisted.internet.reactor
reactor = twisted.internet.reactor
self.reactor = reactor
self._alarms = []
self._watch_files = {}
self._idle_handle = 0
self._twisted_idle_enabled = False
self._idle_callbacks = {}
self._exc_info = None
self.manage_reactor = manage_reactor
self._enable_twisted_idle()
def alarm(self, seconds, callback):
"""
Call callback() given time from from now. No parameters are
passed to callback.
Returns a handle that may be passed to remove_alarm()
seconds -- floating point time to wait before calling callback
callback -- function to call from event loop
"""
handle = self.reactor.callLater(seconds, self.handle_exit(callback))
return handle
def remove_alarm(self, handle):
"""
Remove an alarm.
Returns True if the alarm exists, False otherwise
"""
from twisted.internet.error import AlreadyCancelled, AlreadyCalled
try:
handle.cancel()
return True
except AlreadyCancelled:
return False
except AlreadyCalled:
return False
def watch_file(self, fd, callback):
"""
Call callback() when fd has some data to read. No parameters
are passed to callback.
Returns a handle that may be passed to remove_watch_file()
fd -- file descriptor to watch for input
callback -- function to call when input is available
"""
ind = TwistedInputDescriptor(self.reactor, fd,
self.handle_exit(callback))
self._watch_files[fd] = ind
self.reactor.addReader(ind)
return fd
def remove_watch_file(self, handle):
"""
Remove an input file.
Returns True if the input file exists, False otherwise
"""
if handle in self._watch_files:
self.reactor.removeReader(self._watch_files[handle])
del self._watch_files[handle]
return True
return False
def enter_idle(self, callback):
"""
Add a callback for entering idle.
Returns a handle that may be passed to remove_enter_idle()
"""
self._idle_handle += 1
self._idle_callbacks[self._idle_handle] = callback
return self._idle_handle
def _enable_twisted_idle(self):
"""
Twisted's reactors don't have an idle or enter-idle callback
so the best we can do for now is to set a timer event in a very
short time to approximate an enter-idle callback.
.. WARNING::
This will perform worse than the other event loops until we can find a
fix or workaround
"""
if self._twisted_idle_enabled:
return
self.reactor.callLater(self._idle_emulation_delay,
self.handle_exit(self._twisted_idle_callback, enable_idle=False))
self._twisted_idle_enabled = True
def _twisted_idle_callback(self):
for callback in list(self._idle_callbacks.values()):
callback()
self._twisted_idle_enabled = False
def remove_enter_idle(self, handle):
"""
Remove an idle callback.
Returns True if the handle was removed.
"""
try:
del self._idle_callbacks[handle]
except KeyError:
return False
return True
def run(self):
"""
Start the event loop. Exit the loop when any callback raises
an exception. If ExitMainLoop is raised, exit cleanly.
"""
if not self.manage_reactor:
return
self.reactor.run()
if self._exc_info:
# An exception caused us to exit, raise it now
exc_info = self._exc_info
self._exc_info = None
raise exc_info[0](exc_info[1]).with_traceback(exc_info[2])
def handle_exit(self, f, enable_idle=True):
"""
Decorator that cleanly exits the :class:`TwistedEventLoop` if
:class:`ExitMainLoop` is thrown inside of the wrapped function. Store the
exception info if some other exception occurs, it will be reraised after
the loop quits.
*f* -- function to be wrapped
"""
def wrapper(*args,**kargs):
rval = None
try:
rval = f(*args,**kargs)
except ExitMainLoop:
if self.manage_reactor:
self.reactor.stop()
except:
import sys
print(sys.exc_info())
self._exc_info = sys.exc_info()
if self.manage_reactor:
self.reactor.crash()
if enable_idle:
self._enable_twisted_idle()
return rval
return wrapper
def _refl(name, rval=None, exit=False):
"""
This function is used to test the main loop classes.
>>> scr = _refl("screen")
>>> scr.function("argument")
screen.function('argument')
>>> scr.callme(when="now")
screen.callme(when='now')
>>> scr.want_something_rval = 42
>>> x = scr.want_something()
screen.want_something()
>>> x
42
"""
class Reflect(object):
def __init__(self, name, rval=None):
self._name = name
self._rval = rval
def __call__(self, *argl, **argd):
args = ", ".join([repr(a) for a in argl])
if args and argd:
args = args + ", "
args = args + ", ".join([k+"="+repr(v) for k,v in list(argd.items())])
print(self._name+"("+args+")")
if exit:
raise ExitMainLoop()
return self._rval
def __getattr__(self, attr):
if attr.endswith("_rval"):
raise AttributeError()
#print self._name+"."+attr
if hasattr(self, attr+"_rval"):
return Reflect(self._name+"."+attr, getattr(self, attr+"_rval"))
return Reflect(self._name+"."+attr)
return Reflect(name)
def _test():
import doctest
doctest.testmod()
if __name__=='__main__':
_test()
|
bsd-3-clause
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.