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 |
---|---|---|---|---|---|
Syrcon/servo | tests/wpt/web-platform-tests/tools/pywebsocket/src/test/test_util.py | 449 | 7538 | #!/usr/bin/env python
#
# Copyright 2011, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Tests for util module."""
import os
import random
import sys
import unittest
import set_sys_path # Update sys.path to locate mod_pywebsocket module.
from mod_pywebsocket import util
_TEST_DATA_DIR = os.path.join(os.path.split(__file__)[0], 'testdata')
class UtilTest(unittest.TestCase):
"""A unittest for util module."""
def test_get_stack_trace(self):
self.assertEqual('None\n', util.get_stack_trace())
try:
a = 1 / 0 # Intentionally raise exception.
except Exception:
trace = util.get_stack_trace()
self.failUnless(trace.startswith('Traceback'))
self.failUnless(trace.find('ZeroDivisionError') != -1)
def test_prepend_message_to_exception(self):
exc = Exception('World')
self.assertEqual('World', str(exc))
util.prepend_message_to_exception('Hello ', exc)
self.assertEqual('Hello World', str(exc))
def test_get_script_interp(self):
cygwin_path = 'c:\\cygwin\\bin'
cygwin_perl = os.path.join(cygwin_path, 'perl')
self.assertEqual(None, util.get_script_interp(
os.path.join(_TEST_DATA_DIR, 'README')))
self.assertEqual(None, util.get_script_interp(
os.path.join(_TEST_DATA_DIR, 'README'), cygwin_path))
self.assertEqual('/usr/bin/perl -wT', util.get_script_interp(
os.path.join(_TEST_DATA_DIR, 'hello.pl')))
self.assertEqual(cygwin_perl + ' -wT', util.get_script_interp(
os.path.join(_TEST_DATA_DIR, 'hello.pl'), cygwin_path))
def test_hexify(self):
self.assertEqual('61 7a 41 5a 30 39 20 09 0d 0a 00 ff',
util.hexify('azAZ09 \t\r\n\x00\xff'))
class RepeatedXorMaskerTest(unittest.TestCase):
"""A unittest for RepeatedXorMasker class."""
def test_mask(self):
# Sample input e6,97,a5 is U+65e5 in UTF-8
masker = util.RepeatedXorMasker('\xff\xff\xff\xff')
result = masker.mask('\xe6\x97\xa5')
self.assertEqual('\x19\x68\x5a', result)
masker = util.RepeatedXorMasker('\x00\x00\x00\x00')
result = masker.mask('\xe6\x97\xa5')
self.assertEqual('\xe6\x97\xa5', result)
masker = util.RepeatedXorMasker('\xe6\x97\xa5\x20')
result = masker.mask('\xe6\x97\xa5')
self.assertEqual('\x00\x00\x00', result)
def test_mask_twice(self):
masker = util.RepeatedXorMasker('\x00\x7f\xff\x20')
# mask[0], mask[1], ... will be used.
result = masker.mask('\x00\x00\x00\x00\x00')
self.assertEqual('\x00\x7f\xff\x20\x00', result)
# mask[2], mask[0], ... will be used for the next call.
result = masker.mask('\x00\x00\x00\x00\x00')
self.assertEqual('\x7f\xff\x20\x00\x7f', result)
def test_mask_large_data(self):
masker = util.RepeatedXorMasker('mASk')
original = ''.join([chr(i % 256) for i in xrange(1000)])
result = masker.mask(original)
expected = ''.join(
[chr((i % 256) ^ ord('mASk'[i % 4])) for i in xrange(1000)])
self.assertEqual(expected, result)
masker = util.RepeatedXorMasker('MaSk')
first_part = 'The WebSocket Protocol enables two-way communication.'
result = masker.mask(first_part)
self.assertEqual(
'\x19\t6K\x1a\x0418"\x028\x0e9A\x03\x19"\x15<\x08"\rs\x0e#'
'\x001\x07(\x12s\x1f:\x0e~\x1c,\x18s\x08"\x0c>\x1e#\x080\n9'
'\x08<\x05c',
result)
second_part = 'It has two parts: a handshake and the data transfer.'
result = masker.mask(second_part)
self.assertEqual(
"('K%\x00 K9\x16<K=\x00!\x1f>[s\nm\t2\x05)\x12;\n&\x04s\n#"
"\x05s\x1f%\x04s\x0f,\x152K9\x132\x05>\x076\x19c",
result)
def get_random_section(source, min_num_chunks):
chunks = []
bytes_chunked = 0
while bytes_chunked < len(source):
chunk_size = random.randint(
1,
min(len(source) / min_num_chunks, len(source) - bytes_chunked))
chunk = source[bytes_chunked:bytes_chunked + chunk_size]
chunks.append(chunk)
bytes_chunked += chunk_size
return chunks
class InflaterDeflaterTest(unittest.TestCase):
"""A unittest for _Inflater and _Deflater class."""
def test_inflate_deflate_default(self):
input = b'hello' + '-' * 30000 + b'hello'
inflater15 = util._Inflater(15)
deflater15 = util._Deflater(15)
inflater8 = util._Inflater(8)
deflater8 = util._Deflater(8)
compressed15 = deflater15.compress_and_finish(input)
compressed8 = deflater8.compress_and_finish(input)
inflater15.append(compressed15)
inflater8.append(compressed8)
self.assertNotEqual(compressed15, compressed8)
self.assertEqual(input, inflater15.decompress(-1))
self.assertEqual(input, inflater8.decompress(-1))
def test_random_section(self):
random.seed(a=0)
source = ''.join(
[chr(random.randint(0, 255)) for i in xrange(100 * 1024)])
chunked_input = get_random_section(source, 10)
print "Input chunk sizes: %r" % [len(c) for c in chunked_input]
deflater = util._Deflater(15)
compressed = []
for chunk in chunked_input:
compressed.append(deflater.compress(chunk))
compressed.append(deflater.compress_and_finish(''))
chunked_expectation = get_random_section(source, 10)
print ("Expectation chunk sizes: %r" %
[len(c) for c in chunked_expectation])
inflater = util._Inflater(15)
inflater.append(''.join(compressed))
for chunk in chunked_expectation:
decompressed = inflater.decompress(len(chunk))
self.assertEqual(chunk, decompressed)
self.assertEqual('', inflater.decompress(-1))
if __name__ == '__main__':
unittest.main()
# vi:sts=4 sw=4 et
| mpl-2.0 |
sankhesh/VTK | Filters/Modeling/Testing/Python/Hyper.py | 9 | 5170 | #!/usr/bin/env python
import os
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
# Create the RenderWindow, Renderer and interactive renderer
#
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.SetMultiSamples(0)
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
VTK_INTEGRATE_BOTH_DIRECTIONS = 2
#
# generate tensors
ptLoad = vtk.vtkPointLoad()
ptLoad.SetLoadValue(100.0)
ptLoad.SetSampleDimensions(20, 20, 20)
ptLoad.ComputeEffectiveStressOn()
ptLoad.SetModelBounds(-10, 10, -10, 10, -10, 10)
#
# If the current directory is writable, then test the writers
#
try:
channel = open("wSP.vtk", "wb")
channel.close()
wSP = vtk.vtkDataSetWriter()
wSP.SetInputConnection(ptLoad.GetOutputPort())
wSP.SetFileName("wSP.vtk")
wSP.SetTensorsName("pointload")
wSP.SetScalarsName("effective_stress")
wSP.Write()
rSP = vtk.vtkDataSetReader()
rSP.SetFileName("wSP.vtk")
rSP.SetTensorsName("pointload")
rSP.SetScalarsName("effective_stress")
rSP.Update()
input = rSP.GetOutput()
# cleanup
#
try:
os.remove("wSP.vtk")
except OSError:
pass
except IOError:
print("Unable to test the writer/reader.")
input = ptLoad.GetOutput()
# Generate hyperstreamlines
s1 = vtk.vtkHyperStreamline()
s1.SetInputData(input)
s1.SetStartPosition(9, 9, -9)
s1.IntegrateMinorEigenvector()
s1.SetMaximumPropagationDistance(18.0)
s1.SetIntegrationStepLength(0.1)
s1.SetStepLength(0.01)
s1.SetRadius(0.25)
s1.SetNumberOfSides(18)
s1.SetIntegrationDirection(VTK_INTEGRATE_BOTH_DIRECTIONS)
s1.Update()
# Map hyperstreamlines
lut = vtk.vtkLogLookupTable()
lut.SetHueRange(.6667, 0.0)
s1Mapper = vtk.vtkPolyDataMapper()
s1Mapper.SetInputConnection(s1.GetOutputPort())
s1Mapper.SetLookupTable(lut)
# force update for scalar range
ptLoad.Update()
s1Mapper.SetScalarRange(ptLoad.GetOutput().GetScalarRange())
s1Actor = vtk.vtkActor()
s1Actor.SetMapper(s1Mapper)
s2 = vtk.vtkHyperStreamline()
s2.SetInputData(input)
s2.SetStartPosition(-9, -9, -9)
s2.IntegrateMinorEigenvector()
s2.SetMaximumPropagationDistance(18.0)
s2.SetIntegrationStepLength(0.1)
s2.SetStepLength(0.01)
s2.SetRadius(0.25)
s2.SetNumberOfSides(18)
s2.SetIntegrationDirection(VTK_INTEGRATE_BOTH_DIRECTIONS)
s2.Update()
s2Mapper = vtk.vtkPolyDataMapper()
s2Mapper.SetInputConnection(s2.GetOutputPort())
s2Mapper.SetLookupTable(lut)
s2Mapper.SetScalarRange(input.GetScalarRange())
s2Actor = vtk.vtkActor()
s2Actor.SetMapper(s2Mapper)
s3 = vtk.vtkHyperStreamline()
s3.SetInputData(input)
s3.SetStartPosition(9, -9, -9)
s3.IntegrateMinorEigenvector()
s3.SetMaximumPropagationDistance(18.0)
s3.SetIntegrationStepLength(0.1)
s3.SetStepLength(0.01)
s3.SetRadius(0.25)
s3.SetNumberOfSides(18)
s3.SetIntegrationDirection(VTK_INTEGRATE_BOTH_DIRECTIONS)
s3.Update()
s3Mapper = vtk.vtkPolyDataMapper()
s3Mapper.SetInputConnection(s3.GetOutputPort())
s3Mapper.SetLookupTable(lut)
s3Mapper.SetScalarRange(input.GetScalarRange())
s3Actor = vtk.vtkActor()
s3Actor.SetMapper(s3Mapper)
s4 = vtk.vtkHyperStreamline()
s4.SetInputData(input)
s4.SetStartPosition(-9, 9, -9)
s4.IntegrateMinorEigenvector()
s4.SetMaximumPropagationDistance(18.0)
s4.SetIntegrationStepLength(0.1)
s4.SetStepLength(0.01)
s4.SetRadius(0.25)
s4.SetNumberOfSides(18)
s4.SetIntegrationDirection(VTK_INTEGRATE_BOTH_DIRECTIONS)
s4.Update()
s4Mapper = vtk.vtkPolyDataMapper()
s4Mapper.SetInputConnection(s4.GetOutputPort())
s4Mapper.SetLookupTable(lut)
s4Mapper.SetScalarRange(input.GetScalarRange())
s4Actor = vtk.vtkActor()
s4Actor.SetMapper(s4Mapper)
# plane for context
#
g = vtk.vtkImageDataGeometryFilter()
g.SetInputData(input)
g.SetExtent(0, 100, 0, 100, 0, 0)
g.Update()
# for scalar range
gm = vtk.vtkPolyDataMapper()
gm.SetInputConnection(g.GetOutputPort())
gm.SetScalarRange(g.GetOutput().GetScalarRange())
ga = vtk.vtkActor()
ga.SetMapper(gm)
# Create outline around data
#
outline = vtk.vtkOutlineFilter()
outline.SetInputData(input)
outlineMapper = vtk.vtkPolyDataMapper()
outlineMapper.SetInputConnection(outline.GetOutputPort())
outlineActor = vtk.vtkActor()
outlineActor.SetMapper(outlineMapper)
outlineActor.GetProperty().SetColor(0, 0, 0)
# Create cone indicating application of load
#
coneSrc = vtk.vtkConeSource()
coneSrc.SetRadius(.5)
coneSrc.SetHeight(2)
coneMap = vtk.vtkPolyDataMapper()
coneMap.SetInputConnection(coneSrc.GetOutputPort())
coneActor = vtk.vtkActor()
coneActor.SetMapper(coneMap)
coneActor.SetPosition(0, 0, 11)
coneActor.RotateY(90)
coneActor.GetProperty().SetColor(1, 0, 0)
camera = vtk.vtkCamera()
camera.SetFocalPoint(0.113766, -1.13665, -1.01919)
camera.SetPosition(-29.4886, -63.1488, 26.5807)
camera.SetViewAngle(24.4617)
camera.SetViewUp(0.17138, 0.331163, 0.927879)
camera.SetClippingRange(1, 100)
ren1.AddActor(s1Actor)
ren1.AddActor(s2Actor)
ren1.AddActor(s3Actor)
ren1.AddActor(s4Actor)
ren1.AddActor(outlineActor)
ren1.AddActor(coneActor)
ren1.AddActor(ga)
ren1.SetBackground(1.0, 1.0, 1.0)
ren1.SetActiveCamera(camera)
renWin.SetSize(300, 300)
renWin.Render()
iren.Initialize()
#iren.Start()
| bsd-3-clause |
sss-freshbyte/blog | node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings.py | 1361 | 45045 | # 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.
r"""Code to validate and convert settings of the Microsoft build tools.
This file contains code to validate and convert settings of the Microsoft
build tools. The function ConvertToMSBuildSettings(), ValidateMSVSSettings(),
and ValidateMSBuildSettings() are the entry points.
This file was created by comparing the projects created by Visual Studio 2008
and Visual Studio 2010 for all available settings through the user interface.
The MSBuild schemas were also considered. They are typically found in the
MSBuild install directory, e.g. c:\Program Files (x86)\MSBuild
"""
import sys
import re
# Dictionaries of settings validators. The key is the tool name, the value is
# a dictionary mapping setting names to validation functions.
_msvs_validators = {}
_msbuild_validators = {}
# A dictionary of settings converters. The key is the tool name, the value is
# a dictionary mapping setting names to conversion functions.
_msvs_to_msbuild_converters = {}
# Tool name mapping from MSVS to MSBuild.
_msbuild_name_of_tool = {}
class _Tool(object):
"""Represents a tool used by MSVS or MSBuild.
Attributes:
msvs_name: The name of the tool in MSVS.
msbuild_name: The name of the tool in MSBuild.
"""
def __init__(self, msvs_name, msbuild_name):
self.msvs_name = msvs_name
self.msbuild_name = msbuild_name
def _AddTool(tool):
"""Adds a tool to the four dictionaries used to process settings.
This only defines the tool. Each setting also needs to be added.
Args:
tool: The _Tool object to be added.
"""
_msvs_validators[tool.msvs_name] = {}
_msbuild_validators[tool.msbuild_name] = {}
_msvs_to_msbuild_converters[tool.msvs_name] = {}
_msbuild_name_of_tool[tool.msvs_name] = tool.msbuild_name
def _GetMSBuildToolSettings(msbuild_settings, tool):
"""Returns an MSBuild tool dictionary. Creates it if needed."""
return msbuild_settings.setdefault(tool.msbuild_name, {})
class _Type(object):
"""Type of settings (Base class)."""
def ValidateMSVS(self, value):
"""Verifies that the value is legal for MSVS.
Args:
value: the value to check for this type.
Raises:
ValueError if value is not valid for MSVS.
"""
def ValidateMSBuild(self, value):
"""Verifies that the value is legal for MSBuild.
Args:
value: the value to check for this type.
Raises:
ValueError if value is not valid for MSBuild.
"""
def ConvertToMSBuild(self, value):
"""Returns the MSBuild equivalent of the MSVS value given.
Args:
value: the MSVS value to convert.
Returns:
the MSBuild equivalent.
Raises:
ValueError if value is not valid.
"""
return value
class _String(_Type):
"""A setting that's just a string."""
def ValidateMSVS(self, value):
if not isinstance(value, basestring):
raise ValueError('expected string; got %r' % value)
def ValidateMSBuild(self, value):
if not isinstance(value, basestring):
raise ValueError('expected string; got %r' % value)
def ConvertToMSBuild(self, value):
# Convert the macros
return ConvertVCMacrosToMSBuild(value)
class _StringList(_Type):
"""A settings that's a list of strings."""
def ValidateMSVS(self, value):
if not isinstance(value, basestring) and not isinstance(value, list):
raise ValueError('expected string list; got %r' % value)
def ValidateMSBuild(self, value):
if not isinstance(value, basestring) and not isinstance(value, list):
raise ValueError('expected string list; got %r' % value)
def ConvertToMSBuild(self, value):
# Convert the macros
if isinstance(value, list):
return [ConvertVCMacrosToMSBuild(i) for i in value]
else:
return ConvertVCMacrosToMSBuild(value)
class _Boolean(_Type):
"""Boolean settings, can have the values 'false' or 'true'."""
def _Validate(self, value):
if value != 'true' and value != 'false':
raise ValueError('expected bool; got %r' % value)
def ValidateMSVS(self, value):
self._Validate(value)
def ValidateMSBuild(self, value):
self._Validate(value)
def ConvertToMSBuild(self, value):
self._Validate(value)
return value
class _Integer(_Type):
"""Integer settings."""
def __init__(self, msbuild_base=10):
_Type.__init__(self)
self._msbuild_base = msbuild_base
def ValidateMSVS(self, value):
# Try to convert, this will raise ValueError if invalid.
self.ConvertToMSBuild(value)
def ValidateMSBuild(self, value):
# Try to convert, this will raise ValueError if invalid.
int(value, self._msbuild_base)
def ConvertToMSBuild(self, value):
msbuild_format = (self._msbuild_base == 10) and '%d' or '0x%04x'
return msbuild_format % int(value)
class _Enumeration(_Type):
"""Type of settings that is an enumeration.
In MSVS, the values are indexes like '0', '1', and '2'.
MSBuild uses text labels that are more representative, like 'Win32'.
Constructor args:
label_list: an array of MSBuild labels that correspond to the MSVS index.
In the rare cases where MSVS has skipped an index value, None is
used in the array to indicate the unused spot.
new: an array of labels that are new to MSBuild.
"""
def __init__(self, label_list, new=None):
_Type.__init__(self)
self._label_list = label_list
self._msbuild_values = set(value for value in label_list
if value is not None)
if new is not None:
self._msbuild_values.update(new)
def ValidateMSVS(self, value):
# Try to convert. It will raise an exception if not valid.
self.ConvertToMSBuild(value)
def ValidateMSBuild(self, value):
if value not in self._msbuild_values:
raise ValueError('unrecognized enumerated value %s' % value)
def ConvertToMSBuild(self, value):
index = int(value)
if index < 0 or index >= len(self._label_list):
raise ValueError('index value (%d) not in expected range [0, %d)' %
(index, len(self._label_list)))
label = self._label_list[index]
if label is None:
raise ValueError('converted value for %s not specified.' % value)
return label
# Instantiate the various generic types.
_boolean = _Boolean()
_integer = _Integer()
# For now, we don't do any special validation on these types:
_string = _String()
_file_name = _String()
_folder_name = _String()
_file_list = _StringList()
_folder_list = _StringList()
_string_list = _StringList()
# Some boolean settings went from numerical values to boolean. The
# mapping is 0: default, 1: false, 2: true.
_newly_boolean = _Enumeration(['', 'false', 'true'])
def _Same(tool, name, setting_type):
"""Defines a setting that has the same name in MSVS and MSBuild.
Args:
tool: a dictionary that gives the names of the tool for MSVS and MSBuild.
name: the name of the setting.
setting_type: the type of this setting.
"""
_Renamed(tool, name, name, setting_type)
def _Renamed(tool, msvs_name, msbuild_name, setting_type):
"""Defines a setting for which the name has changed.
Args:
tool: a dictionary that gives the names of the tool for MSVS and MSBuild.
msvs_name: the name of the MSVS setting.
msbuild_name: the name of the MSBuild setting.
setting_type: the type of this setting.
"""
def _Translate(value, msbuild_settings):
msbuild_tool_settings = _GetMSBuildToolSettings(msbuild_settings, tool)
msbuild_tool_settings[msbuild_name] = setting_type.ConvertToMSBuild(value)
_msvs_validators[tool.msvs_name][msvs_name] = setting_type.ValidateMSVS
_msbuild_validators[tool.msbuild_name][msbuild_name] = (
setting_type.ValidateMSBuild)
_msvs_to_msbuild_converters[tool.msvs_name][msvs_name] = _Translate
def _Moved(tool, settings_name, msbuild_tool_name, setting_type):
_MovedAndRenamed(tool, settings_name, msbuild_tool_name, settings_name,
setting_type)
def _MovedAndRenamed(tool, msvs_settings_name, msbuild_tool_name,
msbuild_settings_name, setting_type):
"""Defines a setting that may have moved to a new section.
Args:
tool: a dictionary that gives the names of the tool for MSVS and MSBuild.
msvs_settings_name: the MSVS name of the setting.
msbuild_tool_name: the name of the MSBuild tool to place the setting under.
msbuild_settings_name: the MSBuild name of the setting.
setting_type: the type of this setting.
"""
def _Translate(value, msbuild_settings):
tool_settings = msbuild_settings.setdefault(msbuild_tool_name, {})
tool_settings[msbuild_settings_name] = setting_type.ConvertToMSBuild(value)
_msvs_validators[tool.msvs_name][msvs_settings_name] = (
setting_type.ValidateMSVS)
validator = setting_type.ValidateMSBuild
_msbuild_validators[msbuild_tool_name][msbuild_settings_name] = validator
_msvs_to_msbuild_converters[tool.msvs_name][msvs_settings_name] = _Translate
def _MSVSOnly(tool, name, setting_type):
"""Defines a setting that is only found in MSVS.
Args:
tool: a dictionary that gives the names of the tool for MSVS and MSBuild.
name: the name of the setting.
setting_type: the type of this setting.
"""
def _Translate(unused_value, unused_msbuild_settings):
# Since this is for MSVS only settings, no translation will happen.
pass
_msvs_validators[tool.msvs_name][name] = setting_type.ValidateMSVS
_msvs_to_msbuild_converters[tool.msvs_name][name] = _Translate
def _MSBuildOnly(tool, name, setting_type):
"""Defines a setting that is only found in MSBuild.
Args:
tool: a dictionary that gives the names of the tool for MSVS and MSBuild.
name: the name of the setting.
setting_type: the type of this setting.
"""
def _Translate(value, msbuild_settings):
# Let msbuild-only properties get translated as-is from msvs_settings.
tool_settings = msbuild_settings.setdefault(tool.msbuild_name, {})
tool_settings[name] = value
_msbuild_validators[tool.msbuild_name][name] = setting_type.ValidateMSBuild
_msvs_to_msbuild_converters[tool.msvs_name][name] = _Translate
def _ConvertedToAdditionalOption(tool, msvs_name, flag):
"""Defines a setting that's handled via a command line option in MSBuild.
Args:
tool: a dictionary that gives the names of the tool for MSVS and MSBuild.
msvs_name: the name of the MSVS setting that if 'true' becomes a flag
flag: the flag to insert at the end of the AdditionalOptions
"""
def _Translate(value, msbuild_settings):
if value == 'true':
tool_settings = _GetMSBuildToolSettings(msbuild_settings, tool)
if 'AdditionalOptions' in tool_settings:
new_flags = '%s %s' % (tool_settings['AdditionalOptions'], flag)
else:
new_flags = flag
tool_settings['AdditionalOptions'] = new_flags
_msvs_validators[tool.msvs_name][msvs_name] = _boolean.ValidateMSVS
_msvs_to_msbuild_converters[tool.msvs_name][msvs_name] = _Translate
def _CustomGeneratePreprocessedFile(tool, msvs_name):
def _Translate(value, msbuild_settings):
tool_settings = _GetMSBuildToolSettings(msbuild_settings, tool)
if value == '0':
tool_settings['PreprocessToFile'] = 'false'
tool_settings['PreprocessSuppressLineNumbers'] = 'false'
elif value == '1': # /P
tool_settings['PreprocessToFile'] = 'true'
tool_settings['PreprocessSuppressLineNumbers'] = 'false'
elif value == '2': # /EP /P
tool_settings['PreprocessToFile'] = 'true'
tool_settings['PreprocessSuppressLineNumbers'] = 'true'
else:
raise ValueError('value must be one of [0, 1, 2]; got %s' % value)
# Create a bogus validator that looks for '0', '1', or '2'
msvs_validator = _Enumeration(['a', 'b', 'c']).ValidateMSVS
_msvs_validators[tool.msvs_name][msvs_name] = msvs_validator
msbuild_validator = _boolean.ValidateMSBuild
msbuild_tool_validators = _msbuild_validators[tool.msbuild_name]
msbuild_tool_validators['PreprocessToFile'] = msbuild_validator
msbuild_tool_validators['PreprocessSuppressLineNumbers'] = msbuild_validator
_msvs_to_msbuild_converters[tool.msvs_name][msvs_name] = _Translate
fix_vc_macro_slashes_regex_list = ('IntDir', 'OutDir')
fix_vc_macro_slashes_regex = re.compile(
r'(\$\((?:%s)\))(?:[\\/]+)' % "|".join(fix_vc_macro_slashes_regex_list)
)
# Regular expression to detect keys that were generated by exclusion lists
_EXCLUDED_SUFFIX_RE = re.compile('^(.*)_excluded$')
def _ValidateExclusionSetting(setting, settings, error_msg, stderr=sys.stderr):
"""Verify that 'setting' is valid if it is generated from an exclusion list.
If the setting appears to be generated from an exclusion list, the root name
is checked.
Args:
setting: A string that is the setting name to validate
settings: A dictionary where the keys are valid settings
error_msg: The message to emit in the event of error
stderr: The stream receiving the error messages.
"""
# This may be unrecognized because it's an exclusion list. If the
# setting name has the _excluded suffix, then check the root name.
unrecognized = True
m = re.match(_EXCLUDED_SUFFIX_RE, setting)
if m:
root_setting = m.group(1)
unrecognized = root_setting not in settings
if unrecognized:
# We don't know this setting. Give a warning.
print >> stderr, error_msg
def FixVCMacroSlashes(s):
"""Replace macros which have excessive following slashes.
These macros are known to have a built-in trailing slash. Furthermore, many
scripts hiccup on processing paths with extra slashes in the middle.
This list is probably not exhaustive. Add as needed.
"""
if '$' in s:
s = fix_vc_macro_slashes_regex.sub(r'\1', s)
return s
def ConvertVCMacrosToMSBuild(s):
"""Convert the the MSVS macros found in the string to the MSBuild equivalent.
This list is probably not exhaustive. Add as needed.
"""
if '$' in s:
replace_map = {
'$(ConfigurationName)': '$(Configuration)',
'$(InputDir)': '%(RelativeDir)',
'$(InputExt)': '%(Extension)',
'$(InputFileName)': '%(Filename)%(Extension)',
'$(InputName)': '%(Filename)',
'$(InputPath)': '%(Identity)',
'$(ParentName)': '$(ProjectFileName)',
'$(PlatformName)': '$(Platform)',
'$(SafeInputName)': '%(Filename)',
}
for old, new in replace_map.iteritems():
s = s.replace(old, new)
s = FixVCMacroSlashes(s)
return s
def ConvertToMSBuildSettings(msvs_settings, stderr=sys.stderr):
"""Converts MSVS settings (VS2008 and earlier) to MSBuild settings (VS2010+).
Args:
msvs_settings: A dictionary. The key is the tool name. The values are
themselves dictionaries of settings and their values.
stderr: The stream receiving the error messages.
Returns:
A dictionary of MSBuild settings. The key is either the MSBuild tool name
or the empty string (for the global settings). The values are themselves
dictionaries of settings and their values.
"""
msbuild_settings = {}
for msvs_tool_name, msvs_tool_settings in msvs_settings.iteritems():
if msvs_tool_name in _msvs_to_msbuild_converters:
msvs_tool = _msvs_to_msbuild_converters[msvs_tool_name]
for msvs_setting, msvs_value in msvs_tool_settings.iteritems():
if msvs_setting in msvs_tool:
# Invoke the translation function.
try:
msvs_tool[msvs_setting](msvs_value, msbuild_settings)
except ValueError, e:
print >> stderr, ('Warning: while converting %s/%s to MSBuild, '
'%s' % (msvs_tool_name, msvs_setting, e))
else:
_ValidateExclusionSetting(msvs_setting,
msvs_tool,
('Warning: unrecognized setting %s/%s '
'while converting to MSBuild.' %
(msvs_tool_name, msvs_setting)),
stderr)
else:
print >> stderr, ('Warning: unrecognized tool %s while converting to '
'MSBuild.' % msvs_tool_name)
return msbuild_settings
def ValidateMSVSSettings(settings, stderr=sys.stderr):
"""Validates that the names of the settings are valid for MSVS.
Args:
settings: A dictionary. The key is the tool name. The values are
themselves dictionaries of settings and their values.
stderr: The stream receiving the error messages.
"""
_ValidateSettings(_msvs_validators, settings, stderr)
def ValidateMSBuildSettings(settings, stderr=sys.stderr):
"""Validates that the names of the settings are valid for MSBuild.
Args:
settings: A dictionary. The key is the tool name. The values are
themselves dictionaries of settings and their values.
stderr: The stream receiving the error messages.
"""
_ValidateSettings(_msbuild_validators, settings, stderr)
def _ValidateSettings(validators, settings, stderr):
"""Validates that the settings are valid for MSBuild or MSVS.
We currently only validate the names of the settings, not their values.
Args:
validators: A dictionary of tools and their validators.
settings: A dictionary. The key is the tool name. The values are
themselves dictionaries of settings and their values.
stderr: The stream receiving the error messages.
"""
for tool_name in settings:
if tool_name in validators:
tool_validators = validators[tool_name]
for setting, value in settings[tool_name].iteritems():
if setting in tool_validators:
try:
tool_validators[setting](value)
except ValueError, e:
print >> stderr, ('Warning: for %s/%s, %s' %
(tool_name, setting, e))
else:
_ValidateExclusionSetting(setting,
tool_validators,
('Warning: unrecognized setting %s/%s' %
(tool_name, setting)),
stderr)
else:
print >> stderr, ('Warning: unrecognized tool %s' % tool_name)
# MSVS and MBuild names of the tools.
_compile = _Tool('VCCLCompilerTool', 'ClCompile')
_link = _Tool('VCLinkerTool', 'Link')
_midl = _Tool('VCMIDLTool', 'Midl')
_rc = _Tool('VCResourceCompilerTool', 'ResourceCompile')
_lib = _Tool('VCLibrarianTool', 'Lib')
_manifest = _Tool('VCManifestTool', 'Manifest')
_masm = _Tool('MASM', 'MASM')
_AddTool(_compile)
_AddTool(_link)
_AddTool(_midl)
_AddTool(_rc)
_AddTool(_lib)
_AddTool(_manifest)
_AddTool(_masm)
# Add sections only found in the MSBuild settings.
_msbuild_validators[''] = {}
_msbuild_validators['ProjectReference'] = {}
_msbuild_validators['ManifestResourceCompile'] = {}
# Descriptions of the compiler options, i.e. VCCLCompilerTool in MSVS and
# ClCompile in MSBuild.
# See "c:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\1033\cl.xml" for
# the schema of the MSBuild ClCompile settings.
# Options that have the same name in MSVS and MSBuild
_Same(_compile, 'AdditionalIncludeDirectories', _folder_list) # /I
_Same(_compile, 'AdditionalOptions', _string_list)
_Same(_compile, 'AdditionalUsingDirectories', _folder_list) # /AI
_Same(_compile, 'AssemblerListingLocation', _file_name) # /Fa
_Same(_compile, 'BrowseInformationFile', _file_name)
_Same(_compile, 'BufferSecurityCheck', _boolean) # /GS
_Same(_compile, 'DisableLanguageExtensions', _boolean) # /Za
_Same(_compile, 'DisableSpecificWarnings', _string_list) # /wd
_Same(_compile, 'EnableFiberSafeOptimizations', _boolean) # /GT
_Same(_compile, 'EnablePREfast', _boolean) # /analyze Visible='false'
_Same(_compile, 'ExpandAttributedSource', _boolean) # /Fx
_Same(_compile, 'FloatingPointExceptions', _boolean) # /fp:except
_Same(_compile, 'ForceConformanceInForLoopScope', _boolean) # /Zc:forScope
_Same(_compile, 'ForcedIncludeFiles', _file_list) # /FI
_Same(_compile, 'ForcedUsingFiles', _file_list) # /FU
_Same(_compile, 'GenerateXMLDocumentationFiles', _boolean) # /doc
_Same(_compile, 'IgnoreStandardIncludePath', _boolean) # /X
_Same(_compile, 'MinimalRebuild', _boolean) # /Gm
_Same(_compile, 'OmitDefaultLibName', _boolean) # /Zl
_Same(_compile, 'OmitFramePointers', _boolean) # /Oy
_Same(_compile, 'PreprocessorDefinitions', _string_list) # /D
_Same(_compile, 'ProgramDataBaseFileName', _file_name) # /Fd
_Same(_compile, 'RuntimeTypeInfo', _boolean) # /GR
_Same(_compile, 'ShowIncludes', _boolean) # /showIncludes
_Same(_compile, 'SmallerTypeCheck', _boolean) # /RTCc
_Same(_compile, 'StringPooling', _boolean) # /GF
_Same(_compile, 'SuppressStartupBanner', _boolean) # /nologo
_Same(_compile, 'TreatWChar_tAsBuiltInType', _boolean) # /Zc:wchar_t
_Same(_compile, 'UndefineAllPreprocessorDefinitions', _boolean) # /u
_Same(_compile, 'UndefinePreprocessorDefinitions', _string_list) # /U
_Same(_compile, 'UseFullPaths', _boolean) # /FC
_Same(_compile, 'WholeProgramOptimization', _boolean) # /GL
_Same(_compile, 'XMLDocumentationFileName', _file_name)
_Same(_compile, 'AssemblerOutput',
_Enumeration(['NoListing',
'AssemblyCode', # /FA
'All', # /FAcs
'AssemblyAndMachineCode', # /FAc
'AssemblyAndSourceCode'])) # /FAs
_Same(_compile, 'BasicRuntimeChecks',
_Enumeration(['Default',
'StackFrameRuntimeCheck', # /RTCs
'UninitializedLocalUsageCheck', # /RTCu
'EnableFastChecks'])) # /RTC1
_Same(_compile, 'BrowseInformation',
_Enumeration(['false',
'true', # /FR
'true'])) # /Fr
_Same(_compile, 'CallingConvention',
_Enumeration(['Cdecl', # /Gd
'FastCall', # /Gr
'StdCall', # /Gz
'VectorCall'])) # /Gv
_Same(_compile, 'CompileAs',
_Enumeration(['Default',
'CompileAsC', # /TC
'CompileAsCpp'])) # /TP
_Same(_compile, 'DebugInformationFormat',
_Enumeration(['', # Disabled
'OldStyle', # /Z7
None,
'ProgramDatabase', # /Zi
'EditAndContinue'])) # /ZI
_Same(_compile, 'EnableEnhancedInstructionSet',
_Enumeration(['NotSet',
'StreamingSIMDExtensions', # /arch:SSE
'StreamingSIMDExtensions2', # /arch:SSE2
'AdvancedVectorExtensions', # /arch:AVX (vs2012+)
'NoExtensions', # /arch:IA32 (vs2012+)
# This one only exists in the new msbuild format.
'AdvancedVectorExtensions2', # /arch:AVX2 (vs2013r2+)
]))
_Same(_compile, 'ErrorReporting',
_Enumeration(['None', # /errorReport:none
'Prompt', # /errorReport:prompt
'Queue'], # /errorReport:queue
new=['Send'])) # /errorReport:send"
_Same(_compile, 'ExceptionHandling',
_Enumeration(['false',
'Sync', # /EHsc
'Async'], # /EHa
new=['SyncCThrow'])) # /EHs
_Same(_compile, 'FavorSizeOrSpeed',
_Enumeration(['Neither',
'Speed', # /Ot
'Size'])) # /Os
_Same(_compile, 'FloatingPointModel',
_Enumeration(['Precise', # /fp:precise
'Strict', # /fp:strict
'Fast'])) # /fp:fast
_Same(_compile, 'InlineFunctionExpansion',
_Enumeration(['Default',
'OnlyExplicitInline', # /Ob1
'AnySuitable'], # /Ob2
new=['Disabled'])) # /Ob0
_Same(_compile, 'Optimization',
_Enumeration(['Disabled', # /Od
'MinSpace', # /O1
'MaxSpeed', # /O2
'Full'])) # /Ox
_Same(_compile, 'RuntimeLibrary',
_Enumeration(['MultiThreaded', # /MT
'MultiThreadedDebug', # /MTd
'MultiThreadedDLL', # /MD
'MultiThreadedDebugDLL'])) # /MDd
_Same(_compile, 'StructMemberAlignment',
_Enumeration(['Default',
'1Byte', # /Zp1
'2Bytes', # /Zp2
'4Bytes', # /Zp4
'8Bytes', # /Zp8
'16Bytes'])) # /Zp16
_Same(_compile, 'WarningLevel',
_Enumeration(['TurnOffAllWarnings', # /W0
'Level1', # /W1
'Level2', # /W2
'Level3', # /W3
'Level4'], # /W4
new=['EnableAllWarnings'])) # /Wall
# Options found in MSVS that have been renamed in MSBuild.
_Renamed(_compile, 'EnableFunctionLevelLinking', 'FunctionLevelLinking',
_boolean) # /Gy
_Renamed(_compile, 'EnableIntrinsicFunctions', 'IntrinsicFunctions',
_boolean) # /Oi
_Renamed(_compile, 'KeepComments', 'PreprocessKeepComments', _boolean) # /C
_Renamed(_compile, 'ObjectFile', 'ObjectFileName', _file_name) # /Fo
_Renamed(_compile, 'OpenMP', 'OpenMPSupport', _boolean) # /openmp
_Renamed(_compile, 'PrecompiledHeaderThrough', 'PrecompiledHeaderFile',
_file_name) # Used with /Yc and /Yu
_Renamed(_compile, 'PrecompiledHeaderFile', 'PrecompiledHeaderOutputFile',
_file_name) # /Fp
_Renamed(_compile, 'UsePrecompiledHeader', 'PrecompiledHeader',
_Enumeration(['NotUsing', # VS recognized '' for this value too.
'Create', # /Yc
'Use'])) # /Yu
_Renamed(_compile, 'WarnAsError', 'TreatWarningAsError', _boolean) # /WX
_ConvertedToAdditionalOption(_compile, 'DefaultCharIsUnsigned', '/J')
# MSVS options not found in MSBuild.
_MSVSOnly(_compile, 'Detect64BitPortabilityProblems', _boolean)
_MSVSOnly(_compile, 'UseUnicodeResponseFiles', _boolean)
# MSBuild options not found in MSVS.
_MSBuildOnly(_compile, 'BuildingInIDE', _boolean)
_MSBuildOnly(_compile, 'CompileAsManaged',
_Enumeration([], new=['false',
'true'])) # /clr
_MSBuildOnly(_compile, 'CreateHotpatchableImage', _boolean) # /hotpatch
_MSBuildOnly(_compile, 'MultiProcessorCompilation', _boolean) # /MP
_MSBuildOnly(_compile, 'PreprocessOutputPath', _string) # /Fi
_MSBuildOnly(_compile, 'ProcessorNumber', _integer) # the number of processors
_MSBuildOnly(_compile, 'TrackerLogDirectory', _folder_name)
_MSBuildOnly(_compile, 'TreatSpecificWarningsAsErrors', _string_list) # /we
_MSBuildOnly(_compile, 'UseUnicodeForAssemblerListing', _boolean) # /FAu
# Defines a setting that needs very customized processing
_CustomGeneratePreprocessedFile(_compile, 'GeneratePreprocessedFile')
# Directives for converting MSVS VCLinkerTool to MSBuild Link.
# See "c:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\1033\link.xml" for
# the schema of the MSBuild Link settings.
# Options that have the same name in MSVS and MSBuild
_Same(_link, 'AdditionalDependencies', _file_list)
_Same(_link, 'AdditionalLibraryDirectories', _folder_list) # /LIBPATH
# /MANIFESTDEPENDENCY:
_Same(_link, 'AdditionalManifestDependencies', _file_list)
_Same(_link, 'AdditionalOptions', _string_list)
_Same(_link, 'AddModuleNamesToAssembly', _file_list) # /ASSEMBLYMODULE
_Same(_link, 'AllowIsolation', _boolean) # /ALLOWISOLATION
_Same(_link, 'AssemblyLinkResource', _file_list) # /ASSEMBLYLINKRESOURCE
_Same(_link, 'BaseAddress', _string) # /BASE
_Same(_link, 'CLRUnmanagedCodeCheck', _boolean) # /CLRUNMANAGEDCODECHECK
_Same(_link, 'DelayLoadDLLs', _file_list) # /DELAYLOAD
_Same(_link, 'DelaySign', _boolean) # /DELAYSIGN
_Same(_link, 'EmbedManagedResourceFile', _file_list) # /ASSEMBLYRESOURCE
_Same(_link, 'EnableUAC', _boolean) # /MANIFESTUAC
_Same(_link, 'EntryPointSymbol', _string) # /ENTRY
_Same(_link, 'ForceSymbolReferences', _file_list) # /INCLUDE
_Same(_link, 'FunctionOrder', _file_name) # /ORDER
_Same(_link, 'GenerateDebugInformation', _boolean) # /DEBUG
_Same(_link, 'GenerateMapFile', _boolean) # /MAP
_Same(_link, 'HeapCommitSize', _string)
_Same(_link, 'HeapReserveSize', _string) # /HEAP
_Same(_link, 'IgnoreAllDefaultLibraries', _boolean) # /NODEFAULTLIB
_Same(_link, 'IgnoreEmbeddedIDL', _boolean) # /IGNOREIDL
_Same(_link, 'ImportLibrary', _file_name) # /IMPLIB
_Same(_link, 'KeyContainer', _file_name) # /KEYCONTAINER
_Same(_link, 'KeyFile', _file_name) # /KEYFILE
_Same(_link, 'ManifestFile', _file_name) # /ManifestFile
_Same(_link, 'MapExports', _boolean) # /MAPINFO:EXPORTS
_Same(_link, 'MapFileName', _file_name)
_Same(_link, 'MergedIDLBaseFileName', _file_name) # /IDLOUT
_Same(_link, 'MergeSections', _string) # /MERGE
_Same(_link, 'MidlCommandFile', _file_name) # /MIDL
_Same(_link, 'ModuleDefinitionFile', _file_name) # /DEF
_Same(_link, 'OutputFile', _file_name) # /OUT
_Same(_link, 'PerUserRedirection', _boolean)
_Same(_link, 'Profile', _boolean) # /PROFILE
_Same(_link, 'ProfileGuidedDatabase', _file_name) # /PGD
_Same(_link, 'ProgramDatabaseFile', _file_name) # /PDB
_Same(_link, 'RegisterOutput', _boolean)
_Same(_link, 'SetChecksum', _boolean) # /RELEASE
_Same(_link, 'StackCommitSize', _string)
_Same(_link, 'StackReserveSize', _string) # /STACK
_Same(_link, 'StripPrivateSymbols', _file_name) # /PDBSTRIPPED
_Same(_link, 'SupportUnloadOfDelayLoadedDLL', _boolean) # /DELAY:UNLOAD
_Same(_link, 'SuppressStartupBanner', _boolean) # /NOLOGO
_Same(_link, 'SwapRunFromCD', _boolean) # /SWAPRUN:CD
_Same(_link, 'TurnOffAssemblyGeneration', _boolean) # /NOASSEMBLY
_Same(_link, 'TypeLibraryFile', _file_name) # /TLBOUT
_Same(_link, 'TypeLibraryResourceID', _integer) # /TLBID
_Same(_link, 'UACUIAccess', _boolean) # /uiAccess='true'
_Same(_link, 'Version', _string) # /VERSION
_Same(_link, 'EnableCOMDATFolding', _newly_boolean) # /OPT:ICF
_Same(_link, 'FixedBaseAddress', _newly_boolean) # /FIXED
_Same(_link, 'LargeAddressAware', _newly_boolean) # /LARGEADDRESSAWARE
_Same(_link, 'OptimizeReferences', _newly_boolean) # /OPT:REF
_Same(_link, 'RandomizedBaseAddress', _newly_boolean) # /DYNAMICBASE
_Same(_link, 'TerminalServerAware', _newly_boolean) # /TSAWARE
_subsystem_enumeration = _Enumeration(
['NotSet',
'Console', # /SUBSYSTEM:CONSOLE
'Windows', # /SUBSYSTEM:WINDOWS
'Native', # /SUBSYSTEM:NATIVE
'EFI Application', # /SUBSYSTEM:EFI_APPLICATION
'EFI Boot Service Driver', # /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER
'EFI ROM', # /SUBSYSTEM:EFI_ROM
'EFI Runtime', # /SUBSYSTEM:EFI_RUNTIME_DRIVER
'WindowsCE'], # /SUBSYSTEM:WINDOWSCE
new=['POSIX']) # /SUBSYSTEM:POSIX
_target_machine_enumeration = _Enumeration(
['NotSet',
'MachineX86', # /MACHINE:X86
None,
'MachineARM', # /MACHINE:ARM
'MachineEBC', # /MACHINE:EBC
'MachineIA64', # /MACHINE:IA64
None,
'MachineMIPS', # /MACHINE:MIPS
'MachineMIPS16', # /MACHINE:MIPS16
'MachineMIPSFPU', # /MACHINE:MIPSFPU
'MachineMIPSFPU16', # /MACHINE:MIPSFPU16
None,
None,
None,
'MachineSH4', # /MACHINE:SH4
None,
'MachineTHUMB', # /MACHINE:THUMB
'MachineX64']) # /MACHINE:X64
_Same(_link, 'AssemblyDebug',
_Enumeration(['',
'true', # /ASSEMBLYDEBUG
'false'])) # /ASSEMBLYDEBUG:DISABLE
_Same(_link, 'CLRImageType',
_Enumeration(['Default',
'ForceIJWImage', # /CLRIMAGETYPE:IJW
'ForcePureILImage', # /Switch="CLRIMAGETYPE:PURE
'ForceSafeILImage'])) # /Switch="CLRIMAGETYPE:SAFE
_Same(_link, 'CLRThreadAttribute',
_Enumeration(['DefaultThreadingAttribute', # /CLRTHREADATTRIBUTE:NONE
'MTAThreadingAttribute', # /CLRTHREADATTRIBUTE:MTA
'STAThreadingAttribute'])) # /CLRTHREADATTRIBUTE:STA
_Same(_link, 'DataExecutionPrevention',
_Enumeration(['',
'false', # /NXCOMPAT:NO
'true'])) # /NXCOMPAT
_Same(_link, 'Driver',
_Enumeration(['NotSet',
'Driver', # /Driver
'UpOnly', # /DRIVER:UPONLY
'WDM'])) # /DRIVER:WDM
_Same(_link, 'LinkTimeCodeGeneration',
_Enumeration(['Default',
'UseLinkTimeCodeGeneration', # /LTCG
'PGInstrument', # /LTCG:PGInstrument
'PGOptimization', # /LTCG:PGOptimize
'PGUpdate'])) # /LTCG:PGUpdate
_Same(_link, 'ShowProgress',
_Enumeration(['NotSet',
'LinkVerbose', # /VERBOSE
'LinkVerboseLib'], # /VERBOSE:Lib
new=['LinkVerboseICF', # /VERBOSE:ICF
'LinkVerboseREF', # /VERBOSE:REF
'LinkVerboseSAFESEH', # /VERBOSE:SAFESEH
'LinkVerboseCLR'])) # /VERBOSE:CLR
_Same(_link, 'SubSystem', _subsystem_enumeration)
_Same(_link, 'TargetMachine', _target_machine_enumeration)
_Same(_link, 'UACExecutionLevel',
_Enumeration(['AsInvoker', # /level='asInvoker'
'HighestAvailable', # /level='highestAvailable'
'RequireAdministrator'])) # /level='requireAdministrator'
_Same(_link, 'MinimumRequiredVersion', _string)
_Same(_link, 'TreatLinkerWarningAsErrors', _boolean) # /WX
# Options found in MSVS that have been renamed in MSBuild.
_Renamed(_link, 'ErrorReporting', 'LinkErrorReporting',
_Enumeration(['NoErrorReport', # /ERRORREPORT:NONE
'PromptImmediately', # /ERRORREPORT:PROMPT
'QueueForNextLogin'], # /ERRORREPORT:QUEUE
new=['SendErrorReport'])) # /ERRORREPORT:SEND
_Renamed(_link, 'IgnoreDefaultLibraryNames', 'IgnoreSpecificDefaultLibraries',
_file_list) # /NODEFAULTLIB
_Renamed(_link, 'ResourceOnlyDLL', 'NoEntryPoint', _boolean) # /NOENTRY
_Renamed(_link, 'SwapRunFromNet', 'SwapRunFromNET', _boolean) # /SWAPRUN:NET
_Moved(_link, 'GenerateManifest', '', _boolean)
_Moved(_link, 'IgnoreImportLibrary', '', _boolean)
_Moved(_link, 'LinkIncremental', '', _newly_boolean)
_Moved(_link, 'LinkLibraryDependencies', 'ProjectReference', _boolean)
_Moved(_link, 'UseLibraryDependencyInputs', 'ProjectReference', _boolean)
# MSVS options not found in MSBuild.
_MSVSOnly(_link, 'OptimizeForWindows98', _newly_boolean)
_MSVSOnly(_link, 'UseUnicodeResponseFiles', _boolean)
# MSBuild options not found in MSVS.
_MSBuildOnly(_link, 'BuildingInIDE', _boolean)
_MSBuildOnly(_link, 'ImageHasSafeExceptionHandlers', _boolean) # /SAFESEH
_MSBuildOnly(_link, 'LinkDLL', _boolean) # /DLL Visible='false'
_MSBuildOnly(_link, 'LinkStatus', _boolean) # /LTCG:STATUS
_MSBuildOnly(_link, 'PreventDllBinding', _boolean) # /ALLOWBIND
_MSBuildOnly(_link, 'SupportNobindOfDelayLoadedDLL', _boolean) # /DELAY:NOBIND
_MSBuildOnly(_link, 'TrackerLogDirectory', _folder_name)
_MSBuildOnly(_link, 'MSDOSStubFileName', _file_name) # /STUB Visible='false'
_MSBuildOnly(_link, 'SectionAlignment', _integer) # /ALIGN
_MSBuildOnly(_link, 'SpecifySectionAttributes', _string) # /SECTION
_MSBuildOnly(_link, 'ForceFileOutput',
_Enumeration([], new=['Enabled', # /FORCE
# /FORCE:MULTIPLE
'MultiplyDefinedSymbolOnly',
'UndefinedSymbolOnly'])) # /FORCE:UNRESOLVED
_MSBuildOnly(_link, 'CreateHotPatchableImage',
_Enumeration([], new=['Enabled', # /FUNCTIONPADMIN
'X86Image', # /FUNCTIONPADMIN:5
'X64Image', # /FUNCTIONPADMIN:6
'ItaniumImage'])) # /FUNCTIONPADMIN:16
_MSBuildOnly(_link, 'CLRSupportLastError',
_Enumeration([], new=['Enabled', # /CLRSupportLastError
'Disabled', # /CLRSupportLastError:NO
# /CLRSupportLastError:SYSTEMDLL
'SystemDlls']))
# Directives for converting VCResourceCompilerTool to ResourceCompile.
# See "c:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\1033\rc.xml" for
# the schema of the MSBuild ResourceCompile settings.
_Same(_rc, 'AdditionalOptions', _string_list)
_Same(_rc, 'AdditionalIncludeDirectories', _folder_list) # /I
_Same(_rc, 'Culture', _Integer(msbuild_base=16))
_Same(_rc, 'IgnoreStandardIncludePath', _boolean) # /X
_Same(_rc, 'PreprocessorDefinitions', _string_list) # /D
_Same(_rc, 'ResourceOutputFileName', _string) # /fo
_Same(_rc, 'ShowProgress', _boolean) # /v
# There is no UI in VisualStudio 2008 to set the following properties.
# However they are found in CL and other tools. Include them here for
# completeness, as they are very likely to have the same usage pattern.
_Same(_rc, 'SuppressStartupBanner', _boolean) # /nologo
_Same(_rc, 'UndefinePreprocessorDefinitions', _string_list) # /u
# MSBuild options not found in MSVS.
_MSBuildOnly(_rc, 'NullTerminateStrings', _boolean) # /n
_MSBuildOnly(_rc, 'TrackerLogDirectory', _folder_name)
# Directives for converting VCMIDLTool to Midl.
# See "c:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\1033\midl.xml" for
# the schema of the MSBuild Midl settings.
_Same(_midl, 'AdditionalIncludeDirectories', _folder_list) # /I
_Same(_midl, 'AdditionalOptions', _string_list)
_Same(_midl, 'CPreprocessOptions', _string) # /cpp_opt
_Same(_midl, 'ErrorCheckAllocations', _boolean) # /error allocation
_Same(_midl, 'ErrorCheckBounds', _boolean) # /error bounds_check
_Same(_midl, 'ErrorCheckEnumRange', _boolean) # /error enum
_Same(_midl, 'ErrorCheckRefPointers', _boolean) # /error ref
_Same(_midl, 'ErrorCheckStubData', _boolean) # /error stub_data
_Same(_midl, 'GenerateStublessProxies', _boolean) # /Oicf
_Same(_midl, 'GenerateTypeLibrary', _boolean)
_Same(_midl, 'HeaderFileName', _file_name) # /h
_Same(_midl, 'IgnoreStandardIncludePath', _boolean) # /no_def_idir
_Same(_midl, 'InterfaceIdentifierFileName', _file_name) # /iid
_Same(_midl, 'MkTypLibCompatible', _boolean) # /mktyplib203
_Same(_midl, 'OutputDirectory', _string) # /out
_Same(_midl, 'PreprocessorDefinitions', _string_list) # /D
_Same(_midl, 'ProxyFileName', _file_name) # /proxy
_Same(_midl, 'RedirectOutputAndErrors', _file_name) # /o
_Same(_midl, 'SuppressStartupBanner', _boolean) # /nologo
_Same(_midl, 'TypeLibraryName', _file_name) # /tlb
_Same(_midl, 'UndefinePreprocessorDefinitions', _string_list) # /U
_Same(_midl, 'WarnAsError', _boolean) # /WX
_Same(_midl, 'DefaultCharType',
_Enumeration(['Unsigned', # /char unsigned
'Signed', # /char signed
'Ascii'])) # /char ascii7
_Same(_midl, 'TargetEnvironment',
_Enumeration(['NotSet',
'Win32', # /env win32
'Itanium', # /env ia64
'X64'])) # /env x64
_Same(_midl, 'EnableErrorChecks',
_Enumeration(['EnableCustom',
'None', # /error none
'All'])) # /error all
_Same(_midl, 'StructMemberAlignment',
_Enumeration(['NotSet',
'1', # Zp1
'2', # Zp2
'4', # Zp4
'8'])) # Zp8
_Same(_midl, 'WarningLevel',
_Enumeration(['0', # /W0
'1', # /W1
'2', # /W2
'3', # /W3
'4'])) # /W4
_Renamed(_midl, 'DLLDataFileName', 'DllDataFileName', _file_name) # /dlldata
_Renamed(_midl, 'ValidateParameters', 'ValidateAllParameters',
_boolean) # /robust
# MSBuild options not found in MSVS.
_MSBuildOnly(_midl, 'ApplicationConfigurationMode', _boolean) # /app_config
_MSBuildOnly(_midl, 'ClientStubFile', _file_name) # /cstub
_MSBuildOnly(_midl, 'GenerateClientFiles',
_Enumeration([], new=['Stub', # /client stub
'None'])) # /client none
_MSBuildOnly(_midl, 'GenerateServerFiles',
_Enumeration([], new=['Stub', # /client stub
'None'])) # /client none
_MSBuildOnly(_midl, 'LocaleID', _integer) # /lcid DECIMAL
_MSBuildOnly(_midl, 'ServerStubFile', _file_name) # /sstub
_MSBuildOnly(_midl, 'SuppressCompilerWarnings', _boolean) # /no_warn
_MSBuildOnly(_midl, 'TrackerLogDirectory', _folder_name)
_MSBuildOnly(_midl, 'TypeLibFormat',
_Enumeration([], new=['NewFormat', # /newtlb
'OldFormat'])) # /oldtlb
# Directives for converting VCLibrarianTool to Lib.
# See "c:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\1033\lib.xml" for
# the schema of the MSBuild Lib settings.
_Same(_lib, 'AdditionalDependencies', _file_list)
_Same(_lib, 'AdditionalLibraryDirectories', _folder_list) # /LIBPATH
_Same(_lib, 'AdditionalOptions', _string_list)
_Same(_lib, 'ExportNamedFunctions', _string_list) # /EXPORT
_Same(_lib, 'ForceSymbolReferences', _string) # /INCLUDE
_Same(_lib, 'IgnoreAllDefaultLibraries', _boolean) # /NODEFAULTLIB
_Same(_lib, 'IgnoreSpecificDefaultLibraries', _file_list) # /NODEFAULTLIB
_Same(_lib, 'ModuleDefinitionFile', _file_name) # /DEF
_Same(_lib, 'OutputFile', _file_name) # /OUT
_Same(_lib, 'SuppressStartupBanner', _boolean) # /NOLOGO
_Same(_lib, 'UseUnicodeResponseFiles', _boolean)
_Same(_lib, 'LinkTimeCodeGeneration', _boolean) # /LTCG
_Same(_lib, 'TargetMachine', _target_machine_enumeration)
# TODO(jeanluc) _link defines the same value that gets moved to
# ProjectReference. We may want to validate that they are consistent.
_Moved(_lib, 'LinkLibraryDependencies', 'ProjectReference', _boolean)
_MSBuildOnly(_lib, 'DisplayLibrary', _string) # /LIST Visible='false'
_MSBuildOnly(_lib, 'ErrorReporting',
_Enumeration([], new=['PromptImmediately', # /ERRORREPORT:PROMPT
'QueueForNextLogin', # /ERRORREPORT:QUEUE
'SendErrorReport', # /ERRORREPORT:SEND
'NoErrorReport'])) # /ERRORREPORT:NONE
_MSBuildOnly(_lib, 'MinimumRequiredVersion', _string)
_MSBuildOnly(_lib, 'Name', _file_name) # /NAME
_MSBuildOnly(_lib, 'RemoveObjects', _file_list) # /REMOVE
_MSBuildOnly(_lib, 'SubSystem', _subsystem_enumeration)
_MSBuildOnly(_lib, 'TrackerLogDirectory', _folder_name)
_MSBuildOnly(_lib, 'TreatLibWarningAsErrors', _boolean) # /WX
_MSBuildOnly(_lib, 'Verbose', _boolean)
# Directives for converting VCManifestTool to Mt.
# See "c:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\1033\mt.xml" for
# the schema of the MSBuild Lib settings.
# Options that have the same name in MSVS and MSBuild
_Same(_manifest, 'AdditionalManifestFiles', _file_list) # /manifest
_Same(_manifest, 'AdditionalOptions', _string_list)
_Same(_manifest, 'AssemblyIdentity', _string) # /identity:
_Same(_manifest, 'ComponentFileName', _file_name) # /dll
_Same(_manifest, 'GenerateCatalogFiles', _boolean) # /makecdfs
_Same(_manifest, 'InputResourceManifests', _string) # /inputresource
_Same(_manifest, 'OutputManifestFile', _file_name) # /out
_Same(_manifest, 'RegistrarScriptFile', _file_name) # /rgs
_Same(_manifest, 'ReplacementsFile', _file_name) # /replacements
_Same(_manifest, 'SuppressStartupBanner', _boolean) # /nologo
_Same(_manifest, 'TypeLibraryFile', _file_name) # /tlb:
_Same(_manifest, 'UpdateFileHashes', _boolean) # /hashupdate
_Same(_manifest, 'UpdateFileHashesSearchPath', _file_name)
_Same(_manifest, 'VerboseOutput', _boolean) # /verbose
# Options that have moved location.
_MovedAndRenamed(_manifest, 'ManifestResourceFile',
'ManifestResourceCompile',
'ResourceOutputFileName',
_file_name)
_Moved(_manifest, 'EmbedManifest', '', _boolean)
# MSVS options not found in MSBuild.
_MSVSOnly(_manifest, 'DependencyInformationFile', _file_name)
_MSVSOnly(_manifest, 'UseFAT32Workaround', _boolean)
_MSVSOnly(_manifest, 'UseUnicodeResponseFiles', _boolean)
# MSBuild options not found in MSVS.
_MSBuildOnly(_manifest, 'EnableDPIAwareness', _boolean)
_MSBuildOnly(_manifest, 'GenerateCategoryTags', _boolean) # /category
_MSBuildOnly(_manifest, 'ManifestFromManagedAssembly',
_file_name) # /managedassemblyname
_MSBuildOnly(_manifest, 'OutputResourceManifests', _string) # /outputresource
_MSBuildOnly(_manifest, 'SuppressDependencyElement', _boolean) # /nodependency
_MSBuildOnly(_manifest, 'TrackerLogDirectory', _folder_name)
# Directives for MASM.
# See "$(VCTargetsPath)\BuildCustomizations\masm.xml" for the schema of the
# MSBuild MASM settings.
# Options that have the same name in MSVS and MSBuild.
_Same(_masm, 'UseSafeExceptionHandlers', _boolean) # /safeseh
| mit |
vinegret/youtube-dl | youtube_dl/extractor/vyborymos.py | 73 | 2031 | # coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_str
class VyboryMosIE(InfoExtractor):
_VALID_URL = r'https?://vybory\.mos\.ru/(?:#precinct/|account/channels\?.*?\bstation_id=)(?P<id>\d+)'
_TESTS = [{
'url': 'http://vybory.mos.ru/#precinct/13636',
'info_dict': {
'id': '13636',
'ext': 'mp4',
'title': 're:^Участковая избирательная комиссия №2231 [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
'description': 'Россия, Москва, улица Введенского, 32А',
'is_live': True,
},
'params': {
'skip_download': True,
}
}, {
'url': 'http://vybory.mos.ru/account/channels?station_id=13636',
'only_matching': True,
}]
def _real_extract(self, url):
station_id = self._match_id(url)
channels = self._download_json(
'http://vybory.mos.ru/account/channels?station_id=%s' % station_id,
station_id, 'Downloading channels JSON')
formats = []
for cam_num, (sid, hosts, name, _) in enumerate(channels, 1):
for num, host in enumerate(hosts, 1):
formats.append({
'url': 'http://%s/master.m3u8?sid=%s' % (host, sid),
'ext': 'mp4',
'format_id': 'camera%d-host%d' % (cam_num, num),
'format_note': '%s, %s' % (name, host),
})
info = self._download_json(
'http://vybory.mos.ru/json/voting_stations/%s/%s.json'
% (compat_str(station_id)[:3], station_id),
station_id, 'Downloading station JSON', fatal=False)
return {
'id': station_id,
'title': self._live_title(info['name'] if info else station_id),
'description': info.get('address'),
'is_live': True,
'formats': formats,
}
| unlicense |
jelugbo/ddi | common/djangoapps/course_groups/tests/test_cohorts.py | 12 | 19917 | import django.test
from django.contrib.auth.models import User
from django.conf import settings
from django.http import Http404
from django.test.utils import override_settings
from mock import call, patch
from student.models import CourseEnrollment
from student.tests.factories import UserFactory
from course_groups.models import CourseUserGroup
from course_groups import cohorts
from course_groups.tests.helpers import topic_name_to_id, config_course_cohorts, CohortFactory
from xmodule.modulestore.django import modulestore, clear_existing_modulestores
from opaque_keys.edx.locations import SlashSeparatedCourseKey
from xmodule.modulestore.tests.django_utils import mixed_store_config
# NOTE: running this with the lms.envs.test config works without
# manually overriding the modulestore. However, running with
# cms.envs.test doesn't.
TEST_DATA_DIR = settings.COMMON_TEST_DATA_ROOT
TEST_MAPPING = {'edX/toy/2012_Fall': 'xml'}
TEST_DATA_MIXED_MODULESTORE = mixed_store_config(TEST_DATA_DIR, TEST_MAPPING)
@patch("course_groups.cohorts.tracker")
class TestCohortSignals(django.test.TestCase):
def setUp(self):
self.course_key = SlashSeparatedCourseKey("dummy", "dummy", "dummy")
def test_cohort_added(self, mock_tracker):
# Add cohort
cohort = CourseUserGroup.objects.create(
name="TestCohort",
course_id=self.course_key,
group_type=CourseUserGroup.COHORT
)
mock_tracker.emit.assert_called_with(
"edx.cohort.created",
{"cohort_id": cohort.id, "cohort_name": cohort.name}
)
mock_tracker.reset_mock()
# Modify existing cohort
cohort.name = "NewName"
cohort.save()
self.assertFalse(mock_tracker.called)
# Add non-cohort group
CourseUserGroup.objects.create(
name="TestOtherGroupType",
course_id=self.course_key,
group_type="dummy"
)
self.assertFalse(mock_tracker.called)
def test_cohort_membership_changed(self, mock_tracker):
cohort_list = [CohortFactory() for _ in range(2)]
non_cohort = CourseUserGroup.objects.create(
name="dummy",
course_id=self.course_key,
group_type="dummy"
)
user_list = [UserFactory() for _ in range(2)]
mock_tracker.reset_mock()
def assert_events(event_name_suffix, user_list, cohort_list):
mock_tracker.emit.assert_has_calls([
call(
"edx.cohort.user_" + event_name_suffix,
{
"user_id": user.id,
"cohort_id": cohort.id,
"cohort_name": cohort.name,
}
)
for user in user_list for cohort in cohort_list
])
# Add users to cohort
cohort_list[0].users.add(*user_list)
assert_events("added", user_list, cohort_list[:1])
mock_tracker.reset_mock()
# Remove users from cohort
cohort_list[0].users.remove(*user_list)
assert_events("removed", user_list, cohort_list[:1])
mock_tracker.reset_mock()
# Clear users from cohort
cohort_list[0].users.add(*user_list)
cohort_list[0].users.clear()
assert_events("removed", user_list, cohort_list[:1])
mock_tracker.reset_mock()
# Clear users from non-cohort group
non_cohort.users.add(*user_list)
non_cohort.users.clear()
self.assertFalse(mock_tracker.emit.called)
# Add cohorts to user
user_list[0].course_groups.add(*cohort_list)
assert_events("added", user_list[:1], cohort_list)
mock_tracker.reset_mock()
# Remove cohorts from user
user_list[0].course_groups.remove(*cohort_list)
assert_events("removed", user_list[:1], cohort_list)
mock_tracker.reset_mock()
# Clear cohorts from user
user_list[0].course_groups.add(*cohort_list)
user_list[0].course_groups.clear()
assert_events("removed", user_list[:1], cohort_list)
mock_tracker.reset_mock()
# Clear non-cohort groups from user
user_list[0].course_groups.add(non_cohort)
user_list[0].course_groups.clear()
self.assertFalse(mock_tracker.emit.called)
@override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE)
class TestCohorts(django.test.TestCase):
def setUp(self):
"""
Make sure that course is reloaded every time--clear out the modulestore.
"""
clear_existing_modulestores()
self.toy_course_key = SlashSeparatedCourseKey("edX", "toy", "2012_Fall")
def test_is_course_cohorted(self):
"""
Make sure cohorts.is_course_cohorted() correctly reports if a course is cohorted or not.
"""
course = modulestore().get_course(self.toy_course_key)
self.assertFalse(course.is_cohorted)
self.assertFalse(cohorts.is_course_cohorted(course.id))
config_course_cohorts(course, [], cohorted=True)
self.assertTrue(course.is_cohorted)
self.assertTrue(cohorts.is_course_cohorted(course.id))
# Make sure we get a Http404 if there's no course
fake_key = SlashSeparatedCourseKey('a', 'b', 'c')
self.assertRaises(Http404, lambda: cohorts.is_course_cohorted(fake_key))
def test_get_cohort_id(self):
"""
Make sure that cohorts.get_cohort_id() correctly returns the cohort id, or raises a ValueError when given an
invalid course key.
"""
course = modulestore().get_course(self.toy_course_key)
self.assertFalse(course.is_cohorted)
user = UserFactory(username="test", email="[email protected]")
self.assertIsNone(cohorts.get_cohort_id(user, course.id))
config_course_cohorts(course, discussions=[], cohorted=True)
cohort = CohortFactory(course_id=course.id, name="TestCohort")
cohort.users.add(user)
self.assertEqual(cohorts.get_cohort_id(user, course.id), cohort.id)
self.assertRaises(
ValueError,
lambda: cohorts.get_cohort_id(user, SlashSeparatedCourseKey("course", "does_not", "exist"))
)
def test_get_cohort(self):
"""
Make sure cohorts.get_cohort() does the right thing when the course is cohorted
"""
course = modulestore().get_course(self.toy_course_key)
self.assertEqual(course.id, self.toy_course_key)
self.assertFalse(course.is_cohorted)
user = UserFactory(username="test", email="[email protected]")
other_user = UserFactory(username="test2", email="[email protected]")
self.assertIsNone(cohorts.get_cohort(user, course.id), "No cohort created yet")
cohort = CohortFactory(course_id=course.id, name="TestCohort")
cohort.users.add(user)
self.assertIsNone(
cohorts.get_cohort(user, course.id),
"Course isn't cohorted, so shouldn't have a cohort"
)
# Make the course cohorted...
config_course_cohorts(course, discussions=[], cohorted=True)
self.assertEquals(
cohorts.get_cohort(user, course.id).id,
cohort.id,
"user should be assigned to the correct cohort"
)
self.assertEquals(
cohorts.get_cohort(other_user, course.id).id,
cohorts.get_cohort_by_name(course.id, cohorts.DEFAULT_COHORT_NAME).id,
"other_user should be assigned to the default cohort"
)
def test_auto_cohorting(self):
"""
Make sure cohorts.get_cohort() does the right thing with auto_cohort_groups
"""
course = modulestore().get_course(self.toy_course_key)
self.assertFalse(course.is_cohorted)
user1 = UserFactory(username="test", email="[email protected]")
user2 = UserFactory(username="test2", email="[email protected]")
user3 = UserFactory(username="test3", email="[email protected]")
user4 = UserFactory(username="test4", email="[email protected]")
cohort = CohortFactory(course_id=course.id, name="TestCohort")
# user1 manually added to a cohort
cohort.users.add(user1)
# Add an auto_cohort_group to the course...
config_course_cohorts(
course,
discussions=[],
cohorted=True,
auto_cohort_groups=["AutoGroup"]
)
self.assertEquals(cohorts.get_cohort(user1, course.id).id, cohort.id, "user1 should stay put")
self.assertEquals(cohorts.get_cohort(user2, course.id).name, "AutoGroup", "user2 should be auto-cohorted")
# Now make the auto_cohort_group list empty
config_course_cohorts(
course,
discussions=[],
cohorted=True,
auto_cohort_groups=[]
)
self.assertEquals(
cohorts.get_cohort(user3, course.id).id,
cohorts.get_cohort_by_name(course.id, cohorts.DEFAULT_COHORT_NAME).id,
"No groups->default cohort"
)
# Now set the auto_cohort_group to something different
config_course_cohorts(
course,
discussions=[],
cohorted=True,
auto_cohort_groups=["OtherGroup"]
)
self.assertEquals(
cohorts.get_cohort(user4, course.id).name, "OtherGroup", "New list->new group"
)
self.assertEquals(
cohorts.get_cohort(user1, course.id).name, "TestCohort", "user1 should still be in originally placed cohort"
)
self.assertEquals(
cohorts.get_cohort(user2, course.id).name, "AutoGroup", "user2 should still be in originally placed cohort"
)
self.assertEquals(
cohorts.get_cohort(user3, course.id).name,
cohorts.get_cohort_by_name(course.id, cohorts.DEFAULT_COHORT_NAME).name,
"user3 should still be in the default cohort"
)
def test_auto_cohorting_randomization(self):
"""
Make sure cohorts.get_cohort() randomizes properly.
"""
course = modulestore().get_course(self.toy_course_key)
self.assertFalse(course.is_cohorted)
groups = ["group_{0}".format(n) for n in range(5)]
config_course_cohorts(
course, discussions=[], cohorted=True, auto_cohort_groups=groups
)
# Assign 100 users to cohorts
for i in range(100):
user = UserFactory(
username="test_{0}".format(i),
email="a@b{0}.com".format(i)
)
cohorts.get_cohort(user, course.id)
# Now make sure that the assignment was at least vaguely random:
# each cohort should have at least 1, and fewer than 50 students.
# (with 5 groups, probability of 0 users in any group is about
# .8**100= 2.0e-10)
for cohort_name in groups:
cohort = cohorts.get_cohort_by_name(course.id, cohort_name)
num_users = cohort.users.count()
self.assertGreater(num_users, 1)
self.assertLess(num_users, 50)
def test_get_course_cohorts_noop(self):
"""
Tests get_course_cohorts returns an empty list when no cohorts exist.
"""
course = modulestore().get_course(self.toy_course_key)
config_course_cohorts(course, [], cohorted=True)
self.assertEqual([], cohorts.get_course_cohorts(course))
def test_get_course_cohorts(self):
"""
Tests that get_course_cohorts returns all cohorts, including auto cohorts.
"""
course = modulestore().get_course(self.toy_course_key)
config_course_cohorts(
course, [], cohorted=True,
auto_cohort_groups=["AutoGroup1", "AutoGroup2"]
)
# add manual cohorts to course 1
CohortFactory(course_id=course.id, name="ManualCohort")
CohortFactory(course_id=course.id, name="ManualCohort2")
cohort_set = {c.name for c in cohorts.get_course_cohorts(course)}
self.assertEqual(cohort_set, {"AutoGroup1", "AutoGroup2", "ManualCohort", "ManualCohort2"})
def test_is_commentable_cohorted(self):
course = modulestore().get_course(self.toy_course_key)
self.assertFalse(course.is_cohorted)
def to_id(name):
return topic_name_to_id(course, name)
# no topics
self.assertFalse(
cohorts.is_commentable_cohorted(course.id, to_id("General")),
"Course doesn't even have a 'General' topic"
)
# not cohorted
config_course_cohorts(course, ["General", "Feedback"], cohorted=False)
self.assertFalse(
cohorts.is_commentable_cohorted(course.id, to_id("General")),
"Course isn't cohorted"
)
# cohorted, but top level topics aren't
config_course_cohorts(course, ["General", "Feedback"], cohorted=True)
self.assertTrue(course.is_cohorted)
self.assertFalse(
cohorts.is_commentable_cohorted(course.id, to_id("General")),
"Course is cohorted, but 'General' isn't."
)
self.assertTrue(
cohorts.is_commentable_cohorted(course.id, to_id("random")),
"Non-top-level discussion is always cohorted in cohorted courses."
)
# cohorted, including "Feedback" top-level topics aren't
config_course_cohorts(
course, ["General", "Feedback"],
cohorted=True,
cohorted_discussions=["Feedback"]
)
self.assertTrue(course.is_cohorted)
self.assertFalse(
cohorts.is_commentable_cohorted(course.id, to_id("General")),
"Course is cohorted, but 'General' isn't."
)
self.assertTrue(
cohorts.is_commentable_cohorted(course.id, to_id("Feedback")),
"Feedback was listed as cohorted. Should be."
)
def test_get_cohorted_commentables(self):
"""
Make sure cohorts.get_cohorted_commentables() correctly returns a list of strings representing cohorted
commentables. Also verify that we can't get the cohorted commentables from a course which does not exist.
"""
course = modulestore().get_course(self.toy_course_key)
self.assertEqual(cohorts.get_cohorted_commentables(course.id), set())
config_course_cohorts(course, [], cohorted=True)
self.assertEqual(cohorts.get_cohorted_commentables(course.id), set())
config_course_cohorts(
course, ["General", "Feedback"],
cohorted=True,
cohorted_discussions=["Feedback"]
)
self.assertItemsEqual(
cohorts.get_cohorted_commentables(course.id),
set([topic_name_to_id(course, "Feedback")])
)
config_course_cohorts(
course, ["General", "Feedback"],
cohorted=True,
cohorted_discussions=["General", "Feedback"]
)
self.assertItemsEqual(
cohorts.get_cohorted_commentables(course.id),
set([topic_name_to_id(course, "General"), topic_name_to_id(course, "Feedback")])
)
self.assertRaises(
Http404,
lambda: cohorts.get_cohorted_commentables(SlashSeparatedCourseKey("course", "does_not", "exist"))
)
def test_get_cohort_by_name(self):
"""
Make sure cohorts.get_cohort_by_name() properly finds a cohort by name for a given course. Also verify that it
raises an error when the cohort is not found.
"""
course = modulestore().get_course(self.toy_course_key)
self.assertRaises(
CourseUserGroup.DoesNotExist,
lambda: cohorts.get_cohort_by_name(course.id, "CohortDoesNotExist")
)
cohort = CohortFactory(course_id=course.id, name="MyCohort")
self.assertEqual(cohorts.get_cohort_by_name(course.id, "MyCohort"), cohort)
self.assertRaises(
CourseUserGroup.DoesNotExist,
lambda: cohorts.get_cohort_by_name(SlashSeparatedCourseKey("course", "does_not", "exist"), cohort)
)
def test_get_cohort_by_id(self):
"""
Make sure cohorts.get_cohort_by_id() properly finds a cohort by id for a given
course.
"""
course = modulestore().get_course(self.toy_course_key)
cohort = CohortFactory(course_id=course.id, name="MyCohort")
self.assertEqual(cohorts.get_cohort_by_id(course.id, cohort.id), cohort)
cohort.delete()
self.assertRaises(
CourseUserGroup.DoesNotExist,
lambda: cohorts.get_cohort_by_id(course.id, cohort.id)
)
@patch("course_groups.cohorts.tracker")
def test_add_cohort(self, mock_tracker):
"""
Make sure cohorts.add_cohort() properly adds a cohort to a course and handles
errors.
"""
course = modulestore().get_course(self.toy_course_key)
added_cohort = cohorts.add_cohort(course.id, "My Cohort")
mock_tracker.emit.assert_any_call(
"edx.cohort.creation_requested",
{"cohort_name": added_cohort.name, "cohort_id": added_cohort.id}
)
self.assertEqual(added_cohort.name, "My Cohort")
self.assertRaises(
ValueError,
lambda: cohorts.add_cohort(course.id, "My Cohort")
)
self.assertRaises(
ValueError,
lambda: cohorts.add_cohort(SlashSeparatedCourseKey("course", "does_not", "exist"), "My Cohort")
)
@patch("course_groups.cohorts.tracker")
def test_add_user_to_cohort(self, mock_tracker):
"""
Make sure cohorts.add_user_to_cohort() properly adds a user to a cohort and
handles errors.
"""
course_user = UserFactory(username="Username", email="[email protected]")
UserFactory(username="RandomUsername", email="[email protected]")
course = modulestore().get_course(self.toy_course_key)
CourseEnrollment.enroll(course_user, self.toy_course_key)
first_cohort = CohortFactory(course_id=course.id, name="FirstCohort")
second_cohort = CohortFactory(course_id=course.id, name="SecondCohort")
# Success cases
# We shouldn't get back a previous cohort, since the user wasn't in one
self.assertEqual(
cohorts.add_user_to_cohort(first_cohort, "Username"),
(course_user, None)
)
mock_tracker.emit.assert_any_call(
"edx.cohort.user_add_requested",
{
"user_id": course_user.id,
"cohort_id": first_cohort.id,
"cohort_name": first_cohort.name,
"previous_cohort_id": None,
"previous_cohort_name": None,
}
)
# Should get (user, previous_cohort_name) when moved from one cohort to
# another
self.assertEqual(
cohorts.add_user_to_cohort(second_cohort, "Username"),
(course_user, "FirstCohort")
)
mock_tracker.emit.assert_any_call(
"edx.cohort.user_add_requested",
{
"user_id": course_user.id,
"cohort_id": second_cohort.id,
"cohort_name": second_cohort.name,
"previous_cohort_id": first_cohort.id,
"previous_cohort_name": first_cohort.name,
}
)
# Error cases
# Should get ValueError if user already in cohort
self.assertRaises(
ValueError,
lambda: cohorts.add_user_to_cohort(second_cohort, "Username")
)
# UserDoesNotExist if user truly does not exist
self.assertRaises(
User.DoesNotExist,
lambda: cohorts.add_user_to_cohort(first_cohort, "non_existent_username")
)
| agpl-3.0 |
widdowquinn/KGML | KGML_parser.py | 1 | 7550 | # (c) The James Hutton Institute 2013
# Author: Leighton Pritchard
#
# Contact:
# [email protected]
#
# Leighton Pritchard,
# Information and Computing Sciences,
# James Hutton Institute,
# Errol Road,
# Invergowrie,
# Dundee,
# DD6 9LH,
# Scotland,
# UK
#
# The MIT License
#
# Copyright (c) 2010-2014 The James Hutton Institute
#
# 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.
""" This module provides classes and functions to parse a KGML pathway map
The KGML pathway map is parsed into the object structure defined in
KGML_Pathway.py in this module.
Classes
KGMLParser Parses KGML file
Functions
read Returns a single Pathway object, using KGMLParser
internally
"""
from KGML_pathway import *
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
try:
import xml.etree.cElementTree as ElementTree
except ImportError:
import xml.etree.ElementTree as ElementTree
def read(handle, debug=0):
""" Returns a single Pathway object. There should be one and only
one pathway in each file, but there may well be pathological
examples out there.
"""
iterator = parse(handle, debug)
try:
first = iterator.next()
except StopIteration:
first = None
if first is None:
raise ValueError("No pathways found in handle")
try:
second = iterator.next()
except StopIteration:
second = None
if second is not None:
raise ValueError("More than one pathway found in handle")
return first
def parse(handle, debug=0):
""" Returns an iterator over Pathway elements
handle file handle to a KGML file for parsing
debug integer for amount of debug information
to print
This is a generator for the return of multiple Pathway objects.
"""
# Check handle
if not hasattr(handle, 'read'):
if isinstance(handle, str):
handle = StringIO(handle)
else:
exc_txt = "An XML-containing handle or an XML string " +\
"must be provided"
raise Exception(exc_txt)
# Parse XML and return each Pathway
for event, elem in \
ElementTree.iterparse(handle, events=('start', 'end')):
if event == "end" and elem.tag == "pathway":
yield KGMLParser(elem).parse()
elem.clear()
class KGMLParser(object):
""" Parse a KGML XML Pathway entry into a Pathway object
"""
def __init__(self, elem):
self.entry = elem
def parse(self):
""" Parse the input elements
"""
def _parse_pathway(attrib):
for k, v in attrib.items():
self.pathway.__setattr__(k, v)
def _parse_entry(element):
new_entry = Entry()
for k, v in element.attrib.items():
new_entry.__setattr__(k, v)
for subelement in element.getchildren():
if subelement.tag == 'graphics':
_parse_graphics(subelement, new_entry)
elif subelement.tag == 'component':
_parse_component(subelement, new_entry)
self.pathway.add_entry(new_entry)
def _parse_graphics(element, entry):
new_graphics = Graphics(entry)
for k, v in element.attrib.items():
new_graphics.__setattr__(k, v)
entry.add_graphics(new_graphics)
def _parse_component(element, entry):
new_component = Component(entry)
for k, v in element.attrib.items():
new_component.__setattr__(k, v)
entry.add_component(new_component)
def _parse_reaction(element):
new_reaction = Reaction()
for k, v in element.attrib.items():
new_reaction.__setattr__(k, v)
for subelement in element.getchildren():
if subelement.tag == 'substrate':
new_reaction.add_substrate(int(subelement.attrib['id']))
elif subelement.tag == 'product':
new_reaction.add_product(int(subelement.attrib['id']))
self.pathway.add_reaction(new_reaction)
def _parse_relation(element):
new_relation = Relation()
new_relation.entry1 = int(element.attrib['entry1'])
new_relation.entry2 = int(element.attrib['entry2'])
new_relation.type = element.attrib['type']
for subtype in element.getchildren():
name, value = subtype.attrib['name'], subtype.attrib['value']
if name in ('compound', 'hidden compound'):
new_relation.subtypes.append((name, int(value)))
else:
new_relation.subtypes.append((name, value))
self.pathway.add_relation(new_relation)
#==========#
# Initialise Pathway
self.pathway = Pathway()
# Get information about the pathway itself
_parse_pathway(self.entry.attrib)
for element in self.entry.getchildren():
if element.tag == 'entry':
_parse_entry(element)
elif element.tag == 'reaction':
_parse_reaction(element)
elif element.tag == 'relation':
_parse_relation(element)
# Parsing of some elements not implemented - no examples yet
else:
# This should warn us of any unimplemented tags
print "Warning: tag %s not implemented in parser" % element.tag
return self.pathway
if __name__ == '__main__':
# Check large metabolism
pathway = read(open('ko01100.xml', 'rU'))
print pathway
for k, v in pathway.entries.items()[:20]:
print v
for r in pathway.reactions[:20]:
print r
print len(pathway.maps)
# Check relations
pathway = read(open('ko_metabolic/ko00010.xml', 'rU'))
print pathway
for k, v in pathway.entries.items()[:20]:
print v
for r in pathway.reactions[:20]:
print r
for r in pathway.relations[:20]:
print r
print len(pathway.maps)
# Check components
pathway = read(open('ko_metabolic/ko00253.xml', 'rU'))
print pathway
for k, v in pathway.entries.items():
print v
print len(pathway.maps)
# Test XML representation
print pathway.get_KGML()
# Test bounds of pathway
print pathway.bounds
| mit |
eegroopm/pyLATTICE | gui/pyLATTICE.py | 1 | 74321 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
pyLATTICE is...
"""
from __future__ import division #necessary for python2
from __future__ import unicode_literals
# define authorship information
__authors__ = ['Evan Groopman', 'Thomas Bernatowicz']
__author__ = ','.join(__authors__)
__credits__ = []
__copyright__ = 'Copyright (c) 2011-2014'
__license__ = 'GPL'
# maintanence information
__maintainer__ = 'Evan Groopman'
__email__ = '[email protected]'
"""
Created on Wed Apr 11 14:46:56 2012
@author: Evan Groopman
"""
#Main imports
from PyQt4 import QtCore, QtGui, uic
import os, sys
import numpy as np
import pandas as pd
import re
#Matplotlib imports
import matplotlib as mpl
mpl.use('Qt4Agg')
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
# Local files in the resource directory
import gui
from resources.TableWidget import TableWidget
from resources.Diffraction import Diffraction
#from resources.pyqtresizer import logit,slResizer,Resizer
from resources.IPythonConsole import IPythonConsole
from resources.common import common
from resources.matplotlibwidget import matplotlibWidget
from resources.Dialogs import (MineralListDialog, NewMineralDialog,
ManualConditionsDialog, SettingsDialog)
try:
from resources.dspace import DSpace
print('Importing compiled "DSpace"')
except ImportError as error:
# Attempt autocompilation.
import pyximport
pyximport.install()
from resources._dspace import DSpace
print('Building "DSpace"')
try:
from resources.diffspot import CalcSpots, CalcSpotsHCP
print('Importing compiled "DiffSpot"')
except ImportError as error:
# Attempt autocompilation.
import pyximport
pyximport.install()
from resources._diffspot import CalcSpots, CalcSpotsHCP
print('Building "DiffSpot"')
#need different compiled versions of Cython modules depending on python version
#if sys.version_info[0] == 3:
# #from resources.dspace import DSpace#Cython function for calculating d-spaces
# #from resources.diffspot import CalcSpots, CalcSpotsHCP#Cython function for calculating diffraction spot coordinates
# from resources.pyqtresizer import logit,slResizer,Resizer
#elif sys.version_info[0] == 2:
# #from resources.dspace_py2 import DSpace#Cython function for calculating d-spaces
# #from resources.diffspot_py2 import CalcSpots, CalcSpotsHCP#Cython function for calculating diffraction spot coordinates
# from resources.pyqtresizer_py2 import logit,slResizer,Resizer
#from Wulff_net import WULFF
#dealing with unicode characters in windows, which breaks compiled linux rendering
if sys.platform == 'win32':
mpl.rc('font', **{'sans-serif' : 'Arial Unicode MS','family' : 'sans-serif'})
#elif sys.platform == 'linux':# and os.path.isfile('pyLATTICE'): #on linux AND executable file exists. Does nothing if running from source
# print('Adjusting font')
# mpl.rc('font',**{'sans-serif' : 'Bitstream Vera Sans','family' : 'sans-serif'})
#use LaTeX to render symbols
#plt.rc('text', usetex=True)
mpl.rcParams['mathtext.default'] = 'regular'
#mpl.rcParams['text.latex.preamble'] = [r'\usepackage{textcomp}']
#mpl.rcParams['text.latex.unicode'] = True
#Other
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
################################################################################
## Gui file ##
# Set up window
class pyLATTICE_GUI(QtGui.QMainWindow):
def __init__(self, parent=None):
super(pyLATTICE_GUI, self).__init__(parent)
# load the ui
gui.loadUi(__file__,self)
self.version = gui.__version__
self._grabCommon()
self.Diffraction = Diffraction()
self.DiffWidget = matplotlibWidget(self.common,self.Diffraction) #mplwidget can access common data
#self.DiffWidget.setStyleSheet("font-family: 'Arial Unicode MS', Arial, sans-serif; font-size: 15px;")
self.verticalLayout.addWidget(self.DiffWidget)
self.DiffWidget.distances.connect(self.on_distances_sent)
#self.DiffWidget = self.MplWidget
self.Plot = self.DiffWidget.canvas.ax
self.Plot.axis('equal') #locks aspect ratio 1:1, even when zooming
#matplotlibWidget.setupToolbar(self.DiffWidget.canvas, self.DiffTab)
# Create the navigation toolbar, tied to the canvas
self.mpl_toolbar = NavigationToolbar(self.DiffWidget.canvas, self.DiffTab)
#add widgets to toolbar
self.comboBox_rotate = QtGui.QComboBox()
self.checkBox_labels = QtGui.QCheckBox("Labels")
self.checkBox_labels.setChecked(True)
self.mpl_toolbar.addWidget(self.comboBox_rotate)
self.mpl_toolbar.addWidget(self.checkBox_labels)
#add toolbar to tabs
self.verticalLayout.addWidget(self.mpl_toolbar)
#Plot initial zero spot
self.Plot.plot(0,0, linestyle = '', marker='o', markersize = 10, color = 'black')
self.Plot.set_xlim([-5,5])
self.Plot.set_ylim([-5,5])
#self.Plot.annotate('0 0 0', xy = (0,0), xytext=(0,10),textcoords = 'offset points', ha = 'center', va = 'bottom',
#bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.01))
#Initialize Metric tensor Tables
self.Gtable_size = (200,200)
self.Gtable = TableWidget()
self.G_inv_table = TableWidget()
self.tensorlayout.addWidget(self.Gtable,2,0) #third row, first column
self.tensorlayout.addWidget(self.G_inv_table,2,1)
self.Gtable.resize(self.Gtable_size[0],self.Gtable_size[1])
self.G_inv_table.resize(self.Gtable_size[0],self.Gtable_size[1])
self.Gtable.setData(np.eye(3))
self.G_inv_table.setData(np.eye(3))
for i in range(3):
self.Gtable.setColumnWidth(i,self.Gtable_size[0]/4)
self.Gtable.setRowHeight(i,self.Gtable_size[1]/3.5)
self.G_inv_table.setColumnWidth(i,self.Gtable_size[0]/3.35)
self.G_inv_table.setRowHeight(i,self.Gtable_size[1]/3.5)
self.a = 1; self.b=1; self.c=1
#Initialize parameter tables
self.param_table_size = (200,200)
self.Gparam_table = TableWidget()
self.Gparam_inv_table = TableWidget()
self.Gparam_table.resize(self.param_table_size[0],self.param_table_size[1])
self.Gparam_inv_table.resize(self.param_table_size[0],self.param_table_size[1])
initdat = np.transpose(np.array([[1,1,1,90,90,90]]))
self.Gparam_table.setData(initdat)
self.Gparam_inv_table.setData(initdat)
self.Gparam_table.setHorizontalHeaderLabels(['Parameters'])
self.Gparam_inv_table.setHorizontalHeaderLabels(['Parameters'])
self.Gparam_table.setVerticalHeaderLabels([u'a',u'b',u'c',u'\u03B1',u'\u03B2',u'\u03B3'])
self.Gparam_inv_table.setVerticalHeaderLabels([u'a*',u'b*',u'c*',u'\u03B1*',u'\u03B2*',u'\u03B3*'])
self.tensorlayout.addWidget(self.Gparam_table,3,0)
self.tensorlayout.addWidget(self.Gparam_inv_table,3,1)
for i in range(0,6):
self.Gparam_table.setColumnWidth(i,self.param_table_size[0])
self.Gparam_table.setRowHeight(i,self.param_table_size[0]/6.7)
self.Gparam_inv_table.setColumnWidth(i,self.param_table_size[0])
self.Gparam_inv_table.setRowHeight(i,self.param_table_size[0]/6.7)
#D-spacing table
self.dspace_table_size = (400,630)
self.dspace_table = TableWidget()
self.dspace_table.resize(self.dspace_table_size[0],self.dspace_table_size[1])
self.dspace_table.setData(np.array([[0,0,0,0]]))
self.dspace_table.setHorizontalHeaderLabels(['d-space','h','k','l'])
self.dspacelayout.addWidget(self.dspace_table)
self.dspace_table.setColumnWidth(0,80)
for i in range(1,4):
self.dspace_table.setColumnWidth(i,50)
# Set miller indices
self.miller_indices = [str(x) for x in range(-6,7)]
self.comboBox_hmin.addItems(self.miller_indices)
self.comboBox_kmin.addItems(self.miller_indices)
self.comboBox_lmin.addItems(self.miller_indices)
self.comboBox_hmin.setCurrentIndex(4)
self.comboBox_kmin.setCurrentIndex(4)
self.comboBox_lmin.setCurrentIndex(4)
# Miller max indices set to be 1 greater than selected min index
self.comboBox_hmax.addItems(self.miller_indices)
self.comboBox_kmax.addItems(self.miller_indices)
self.comboBox_lmax.addItems(self.miller_indices)
#self.setMillerMax_h()
#self.setMillerMax_k()
#self.setMillerMax_l()
self.comboBox_hmax.setCurrentIndex(8)
self.comboBox_kmax.setCurrentIndex(8)
self.comboBox_lmax.setCurrentIndex(8)
#Set zone axis parameters
#by default set as [0 0 1]
zone_indices = [str(x) for x in range(-5,6)]
self.comboBox_u.addItems(zone_indices)
self.comboBox_v.addItems(zone_indices)
self.comboBox_w.addItems(zone_indices)
self.comboBox_u.setCurrentIndex(5)
self.comboBox_v.setCurrentIndex(5)
self.comboBox_w.setCurrentIndex(6)
#set calculator comboboxes
self.comboBox_h1.addItems(self.miller_indices)
self.comboBox_h2.addItems(self.miller_indices)
self.comboBox_k1.addItems(self.miller_indices)
self.comboBox_k2.addItems(self.miller_indices)
self.comboBox_l1.addItems(self.miller_indices)
self.comboBox_l2.addItems(self.miller_indices)
self.comboBox_h1.setCurrentIndex(7)
self.comboBox_h2.setCurrentIndex(8)
self.comboBox_k1.setCurrentIndex(6)
self.comboBox_k2.setCurrentIndex(6)
self.comboBox_l1.setCurrentIndex(6)
self.comboBox_l2.setCurrentIndex(6)
#Initialize mineral database combobox
self.setMineralList()
#Initialize rotation of diffraction pattern.
#Will only offer 0,90,180,270 degrees
rotate_items = ['-180','-150','-120','-90','-60','-30','0','30','60','90','120','150','180']
self.comboBox_rotate.addItems(rotate_items)
self.comboBox_rotate.setCurrentIndex(6) #zero by default
#get values in energy, cam legnth, cam const. combo boxes
self.spinBox_beamenergy.setValue(int(self.common.beamenergy))
self.spinBox_camlength.setValue(int(self.common.camlength))
self.doubleSpinBox_camconst.setValue(self.common.camconst)
#Initialize signals and slots
#This needs to go here after setting Miller indices
#When initializing, it runs Recalculate to do metric tensor and d-spacings
#must go before setting crystal types, but after setting all of the combo boxes
#combo boxes recalculate each time their index changes once the signals/slots set up
#if signals/slots placed before, will recalc d-spacings every time you initialize a combobox value
self.signals_slots()
# Set crystal type combo box items:
self.crystaltypes = ['Cubic','Tetragonal','Orthorhombic','Trigonal', 'Hexagonal','Monoclinic','Triclinic']
self.comboBox_crystaltype.addItems(self.crystaltypes)
#Redo some labels in unicode/greek characters
self.label_alpha.setText(u'\u03B1')
self.label_beta.setText(u'\u03B2')
self.label_gamma.setText(u'\u03B3')
self.label_dist_recip.setText(u'Reciprocal Distance (\u212B\u207B\u00B9 )')
self.label_dist_real.setText(u'Real Distance (\u212B)')
self.label_dist_film.setText(u'Film Distance (cm)')
self.label_angle.setText(u'Angle (\u00B0)')
v = self.version.split('.')
pv = v[0] + '.' + v[1] #only major/minor versions. not bugfixes
self.label_pyLATTICE.setText(u'pyLATTICE %s' % pv)
#initialize popup IPython console
#can interact with specific data
self._initIPython(self.common)
def _grabCommon(self):
"""Get all common variables."""
self.common = common()
self._overline_strings = self.common._overline_strings
self.DSpaces = self.common.DSpaces
self.ZoneAxis = self.common.ZoneAxis
self.u = self.common.u
self.v = self.common.v
self.w = self.common.w
#lattice parameters and angles
self.a = self.common.a
self.b = self.common.b
self.c = self.common.c
self.astar = self.common.astar
self.bstar = self.common.bstar
self.cstar = self.common.cstar
self.alpha = self.common.alpha
self.beta = self.common.beta
self.gamma = self.common.gamma
self.alphastar = self.common.alphastar
self.betastar = self.common.betastar
self.gammastar = self.common.gammastar
#TEM params
self.beamenergy = self.common.beamenergy
self.camlength = self.common.camlength
self.camconst = self.common.camconst
self.wavelength = self.common.wavelength
#SpaceGroup data
self.sg = self.common.sg
self.sghex = self.common.sghex
self.mineraldb = self.common.mineraldb
self.manualConds = self.common.manualConds #manual space group conditions
def updateCommon(self):
"""Update all of the common variables and push these to the IPython console"""
self.common.DSpaces = self.DSpaces
self.common.ZoneAxis = self.ZoneAxis
self.common.u = self.u
self.common.v = self.v
self.common.w = self.w
self.common.a = self.a
self.common.b = self.b
self.common.c = self.c
self.common.astar = self.astar
self.common.bstar = self.bstar
self.common.cstar = self.cstar
self.common.alpha = self.alpha
self.common.beta = self.beta
self.common.gamma = self.gamma
self.common.alphastar = self.alphastar
self.common.betastar = self.betastar
self.common.gammastar = self.gammastar
#mineral database and manual conditions
#self.mineraldb = self.common.mineraldb
self.common.manualConds = self.manualConds #manual space group conditions
self.common.beamenergy = self.beamenergy = self.spinBox_beamenergy.value()
self.common.camlength = self.camlength = self.spinBox_camlength.value()
self.common.camconst = self.camconst = self.doubleSpinBox_camconst.value()
self.common.wavelength = self.wavelength = self.common.Wavelength(self.beamenergy)
self.updateIPY(self.common)
@QtCore.pyqtSlot(str,str,str,str)
def on_distances_sent(self,recip_d, real_d, film_d, angle):
self.lineEdit_recip_2.setText(recip_d)
self.lineEdit_real_2.setText(real_d)
self.lineEdit_film_2.setText(film_d)
self.lineEdit_angle_3.setText(angle)
def Recalculate(self):
"""Run MetricTensor() and D_Spacigns(). For use when slider hasn't changed"""
self.MetricTensor()
self.D_Spacings()
def ReplotDiffraction(self):
self.Recalculate()
try:
self.PlotDiffraction()
except UnboundLocalError:
pass
# def Print(self):
# """test print fn"""
# print(self.comboBox_spacegroup.currentIndex())
def signals_slots(self):
"""All of the signals and slots not in .ui file"""
#Testing
#QtCore.QObject.connect(self.command_Wulff, QtCore.SIGNAL(_fromUtf8("clicked()")),WULFF)
### Menu actions
QtCore.QObject.connect(self.actionClose, QtCore.SIGNAL(_fromUtf8("triggered()")), self.close)
QtCore.QObject.connect(self.actionAbout, QtCore.SIGNAL(_fromUtf8("triggered()")), self.About)
QtCore.QObject.connect(self.actionHow_to, QtCore.SIGNAL(_fromUtf8("triggered()")), self.HowTo)
QtCore.QObject.connect(self.actionSave_D_spacings, QtCore.SIGNAL(_fromUtf8("triggered()")), self.SaveDSpace)
QtCore.QObject.connect(self.actionRemove_DB_Minerals, QtCore.SIGNAL(_fromUtf8("triggered()")), self.removeMinerals)
QtCore.QObject.connect(self.actionSave_Mineral_Database, QtCore.SIGNAL(_fromUtf8("triggered()")), self.SaveMineralDB)
QtCore.QObject.connect(self.actionLoad_Mineral_Database, QtCore.SIGNAL(_fromUtf8("triggered()")), self.LoadMineralDB)
QtCore.QObject.connect(self.actionAppendMineral, QtCore.SIGNAL(_fromUtf8("triggered()")), self.AppendMineral)
QtCore.QObject.connect(self.actionIPython_Console, QtCore.SIGNAL(_fromUtf8("triggered()")), self.IPY)
QtCore.QObject.connect(self.actionManualCond, QtCore.SIGNAL(_fromUtf8("triggered()")), self.ManualConditions)
QtCore.QObject.connect(self.actionSettings, QtCore.SIGNAL(_fromUtf8("triggered()")), self.setSettings)
### Command buttons
QtCore.QObject.connect(self.command_Plot, QtCore.SIGNAL(_fromUtf8("clicked()")),self.PlotDiffraction)
QtCore.QObject.connect(self.command_recalculate, QtCore.SIGNAL(_fromUtf8("clicked()")),self.Recalculate)
#QtCore.QObject.connect(self.command_Wulff, QtCore.SIGNAL(_fromUtf8("clicked()")),self.updateIPY)
### crystal and cell type actions
QtCore.QObject.connect(self.comboBox_crystaltype, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(QString)")), self.setCellType)
QtCore.QObject.connect(self.comboBox_celltype, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(QString)")), self.setConditions)
QtCore.QObject.connect(self.spinBox_spacegroup, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.SpaceGroupLookup)
QtCore.QObject.connect(self.checkBox_obverse, QtCore.SIGNAL(_fromUtf8("toggled(bool)")), self.D_Spacings)
QtCore.QObject.connect(self.comboBox_mineraldb, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(QString)")), self.setMineral)
#QtCore.QObject.connect(self.comboBox_spacegroup, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(QString)")), self.D_Spacings)
### Navigation Toolbar buttons
QtCore.QObject.connect(self.comboBox_rotate, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.PlotDiffraction)
QtCore.QObject.connect(self.checkBox_labels, QtCore.SIGNAL(_fromUtf8("toggled(bool)")), self.PlotDiffraction) #labels checkbox
### Checkboxes and Miller indices
QtCore.QObject.connect(self.checkBox_samemin, QtCore.SIGNAL(_fromUtf8("toggled(bool)")), self.sameMin)
QtCore.QObject.connect(self.checkBox_samemax, QtCore.SIGNAL(_fromUtf8("toggled(bool)")), self.sameMax)
QtCore.QObject.connect(self.comboBox_hmin, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.comboBox_kmin,QtCore.SLOT(_fromUtf8("setCurrentIndex(int)")))
QtCore.QObject.connect(self.comboBox_kmin, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.comboBox_lmin,QtCore.SLOT(_fromUtf8("setCurrentIndex(int)")))
QtCore.QObject.connect(self.comboBox_lmin, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.comboBox_hmin,QtCore.SLOT(_fromUtf8("setCurrentIndex(int)")))
QtCore.QObject.connect(self.comboBox_hmax, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.comboBox_kmax,QtCore.SLOT(_fromUtf8("setCurrentIndex(int)")))
QtCore.QObject.connect(self.comboBox_kmax, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.comboBox_lmax,QtCore.SLOT(_fromUtf8("setCurrentIndex(int)")))
QtCore.QObject.connect(self.comboBox_lmax, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.comboBox_hmax,QtCore.SLOT(_fromUtf8("setCurrentIndex(int)")))
QtCore.QObject.connect(self.checkBox_showforbidden, QtCore.SIGNAL(_fromUtf8("toggled(bool)")), self.PlotDiffraction)
### Sliders/spin boxes: lattice parameters
QtCore.QObject.connect(self.hSlider_a, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.slider_to_spindouble)
QtCore.QObject.connect(self.hSlider_b, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.slider_to_spindouble)
QtCore.QObject.connect(self.hSlider_c, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.slider_to_spindouble)
QtCore.QObject.connect(self.hSlider_a, QtCore.SIGNAL(_fromUtf8("sliderReleased()")), self.D_Spacings)
QtCore.QObject.connect(self.hSlider_b, QtCore.SIGNAL(_fromUtf8("sliderReleased()")), self.D_Spacings)
QtCore.QObject.connect(self.hSlider_c, QtCore.SIGNAL(_fromUtf8("sliderReleased()")), self.D_Spacings)
QtCore.QObject.connect(self.doubleSpinBox_a, QtCore.SIGNAL(_fromUtf8("valueChanged(double)")), self.spindouble_to_slider)
QtCore.QObject.connect(self.doubleSpinBox_b, QtCore.SIGNAL(_fromUtf8("valueChanged(double)")), self.spindouble_to_slider)
QtCore.QObject.connect(self.doubleSpinBox_c, QtCore.SIGNAL(_fromUtf8("valueChanged(double)")), self.spindouble_to_slider)
QtCore.QObject.connect(self.doubleSpinBox_a, QtCore.SIGNAL(_fromUtf8("valueChanged(double)")), self.MetricTensor)
QtCore.QObject.connect(self.doubleSpinBox_b, QtCore.SIGNAL(_fromUtf8("valueChanged(double)")), self.MetricTensor)
QtCore.QObject.connect(self.doubleSpinBox_c, QtCore.SIGNAL(_fromUtf8("valueChanged(double)")), self.MetricTensor)
#QtCore.QObject.connect(self.doubleSpinBox_a, QtCore.SIGNAL(_fromUtf8("valueChanged(double)")), self.D_Spacings)
#QtCore.QObject.connect(self.doubleSpinBox_b, QtCore.SIGNAL(_fromUtf8("valueChanged(double)")), self.D_Spacings)
#QtCore.QObject.connect(self.doubleSpinBox_c, QtCore.SIGNAL(_fromUtf8("valueChanged(double)")), self.D_Spacings)
QtCore.QObject.connect(self.hSlider_alpha, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.MetricTensor)
QtCore.QObject.connect(self.hSlider_beta, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.MetricTensor)
QtCore.QObject.connect(self.hSlider_gamma, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.MetricTensor)
QtCore.QObject.connect(self.hSlider_alpha, QtCore.SIGNAL(_fromUtf8("sliderReleased()")), self.D_Spacings)
QtCore.QObject.connect(self.hSlider_beta, QtCore.SIGNAL(_fromUtf8("sliderReleased()")), self.D_Spacings)
QtCore.QObject.connect(self.hSlider_gamma, QtCore.SIGNAL(_fromUtf8("sliderReleased()")), self.D_Spacings)
#Spinboxes beam energy, cam length, camconst
QtCore.QObject.connect(self.spinBox_beamenergy,QtCore.SIGNAL(_fromUtf8("valueChanged(int)")),self.updateCommon)
QtCore.QObject.connect(self.spinBox_camlength,QtCore.SIGNAL(_fromUtf8("valueChanged(int)")),self.updateCommon)
QtCore.QObject.connect(self.doubleSpinBox_camconst,QtCore.SIGNAL(_fromUtf8("valueChanged(double)")),self.updateCommon)
#Instances to recalculate metric tensor and d-spacings
#only enable these once you get miller maxes sorted out so they don't change
QtCore.QObject.connect(self.checkBox_zoneaxis, QtCore.SIGNAL(_fromUtf8("toggled(bool)")),self.DiffWidget, QtCore.SLOT(_fromUtf8("setEnabled(bool)")))
QtCore.QObject.connect(self.comboBox_u, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.ReplotDiffraction)
QtCore.QObject.connect(self.comboBox_v, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.ReplotDiffraction)
QtCore.QObject.connect(self.comboBox_w, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.ReplotDiffraction)
QtCore.QObject.connect(self.comboBox_hmax, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.D_Spacings)
QtCore.QObject.connect(self.comboBox_hmin, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.D_Spacings)
#QtCore.QObject.connect(self.checkBox_labels, QtCore.SIGNAL(_fromUtf8("toggled(bool)")),self.UpdatePlot)
#QtCore.QObject.connect(self.comboBox_hmax, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.TempMax)
#QtCore.QObject.connect(self.comboBox_kmax, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.TempMax)
#QtCore.QObject.connect(self.comboBox_lmax, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.TempMax)
#QtCore.QObject.connect(self.comboBox_hmin, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.Recalculate)
#QtCore.QObject.connect(self.comboBox_kmin, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.Recalculate)
#QtCore.QObject.connect(self.comboBox_lmin, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.Recalculate)
#QtCore.QObject.connect(self.comboBox_w, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.ReplotDiffraction)
#Calculator Tab
QtCore.QObject.connect(self.checkBox_normals, QtCore.SIGNAL(_fromUtf8("toggled(bool)")),self.CalcLabels)
QtCore.QObject.connect(self.command_angle, QtCore.SIGNAL(_fromUtf8("clicked()")),self.Calculator)
def _initIPython(self,common):
"""Initialize IPython console from which the user can interact with data/files"""
banner = """Welcome to the pyLATTICE IPython Qt4 Console.
You are here to interact with data and parameters - Python command line knowledge required.
Use the 'whos' command for a list of available variables. Sometimes this does not work the first time.
Imported packages include: pylab (including numpy modules) as 'pl'; pandas as 'pd'
\n"""
self.ipywidget = IPythonConsole(common,banner=banner)
def IPY(self):
self.ipywidget.SHOW()
def updateIPY(self,common):
self.ipyvars = common.__dict__
self.ipywidget.pushVariables(self.ipyvars)
def slider_to_spindouble(self,slider):
"""Sliders only send/receive int data. Converts int to double by dividing by 100."""
if self.hSlider_a.isSliderDown():
self.a = self.hSlider_a.value() / 100
self.doubleSpinBox_a.setValue(self.a)
elif self.hSlider_b.isSliderDown():
self.b = self.hSlider_b.value() / 100
self.doubleSpinBox_b.setValue(self.b)
elif self.hSlider_c.isSliderDown():
self.c = self.hSlider_c.value() / 100
self.doubleSpinBox_c.setValue(self.c)
def spindouble_to_slider(self,spinbox):
"""Converts spindouble entry into int for slider (multiply by 100)"""
#There may be some redundancy in the connections setting values.
#hopefully this does not slow the program down.
#without these, some aspect often lags and gives the wrong value
if self.comboBox_crystaltype.currentText() == 'Cubic':
self.a = self.doubleSpinBox_a.value()
self.hSlider_a.setValue(self.a * 100)
self.hSlider_b.setValue(self.a * 100);self.doubleSpinBox_b.setValue(self.a)
self.hSlider_c.setValue(self.a * 100);self.doubleSpinBox_c.setValue(self.a)
elif self.comboBox_crystaltype.currentText() == 'Tetragonal':
self.a = self.doubleSpinBox_a.value()
self.hSlider_a.setValue(self.a * 100)
self.hSlider_b.setValue(self.a * 100); self.doubleSpinBox_b.setValue(self.a)
elif self.comboBox_crystaltype.currentText() == 'Trigonal':
self.a = self.doubleSpinBox_a.value()
self.hSlider_a.setValue(self.a * 100)
self.hSlider_b.setValue(self.a * 100); self.doubleSpinBox_b.setValue(self.a)
elif self.comboBox_crystaltype.currentText() == 'Hexagonal':
self.a = self.doubleSpinBox_a.value()
self.hSlider_a.setValue(self.a * 100)
self.hSlider_b.setValue(self.a * 100); self.doubleSpinBox_b.setValue(self.a)
else:
self.a = self.doubleSpinBox_a.value()
self.hSlider_a.setValue(self.a * 100)
self.b = self.doubleSpinBox_b.value()
self.hSlider_b.setValue(self.b * 100)
self.c = self.doubleSpinBox_c.value()
self.hSlider_c.setValue(self.c * 100)
def setMillerMax_h(self):
"""Sets the items available for the max miller indices to include everything greater than the selected min index"""
self.miller_max_h = [str(x) for x in range(int(self.comboBox_hmin.currentText()) + 1,7)]
self.comboBox_hmax.clear()
self.comboBox_hmax.addItems(self.miller_max_h)
def setMillerMax_k(self):
"""Sets the items available for the max miller indices to include everything greater than the selected min index"""
self.miller_max_k = [str(x) for x in range(int(self.comboBox_kmin.currentText()) + 1,7)]
self.comboBox_kmax.clear()
self.comboBox_kmax.addItems(self.miller_max_k)
def setMillerMax_l(self):
"""Sets the items available for the max miller indices to include everything greater than the selected min index"""
self.miller_max_l = [str(x) for x in range(int(self.comboBox_lmin.currentText()) + 1,7)]
self.comboBox_lmax.clear()
self.comboBox_lmax.addItems(self.miller_max_l)
def sameMin(self):
if not self.checkBox_samemin.isChecked():
#change to value_changed, not index changed. lengths may be different if checkboxes aren't clicked
QtCore.QObject.disconnect(self.comboBox_hmin, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.comboBox_kmin,QtCore.SLOT(_fromUtf8("setCurrentIndex(int)")))
QtCore.QObject.disconnect(self.comboBox_kmin, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.comboBox_lmin,QtCore.SLOT(_fromUtf8("setCurrentIndex(int)")))
QtCore.QObject.disconnect(self.comboBox_lmin, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.comboBox_hmin,QtCore.SLOT(_fromUtf8("setCurrentIndex(int)")))
elif self.checkBox_samemin.isChecked():
QtCore.QObject.connect(self.comboBox_hmin, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.comboBox_kmin,QtCore.SLOT(_fromUtf8("setCurrentIndex(int)")))
QtCore.QObject.connect(self.comboBox_kmin, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.comboBox_lmin,QtCore.SLOT(_fromUtf8("setCurrentIndex(int)")))
QtCore.QObject.connect(self.comboBox_lmin, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.comboBox_hmin,QtCore.SLOT(_fromUtf8("setCurrentIndex(int)")))
def sameMax(self):
if not self.checkBox_samemax.isChecked():
QtCore.QObject.disconnect(self.comboBox_hmax, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.comboBox_kmax,QtCore.SLOT(_fromUtf8("setCurrentIndex(int)")))
QtCore.QObject.disconnect(self.comboBox_kmax, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.comboBox_lmax,QtCore.SLOT(_fromUtf8("setCurrentIndex(int)")))
QtCore.QObject.disconnect(self.comboBox_lmax, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.comboBox_hmax,QtCore.SLOT(_fromUtf8("setCurrentIndex(int)")))
elif self.checkBox_samemax.isChecked():
QtCore.QObject.connect(self.comboBox_hmax, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.comboBox_kmax,QtCore.SLOT(_fromUtf8("setCurrentIndex(int)")))
QtCore.QObject.connect(self.comboBox_kmax, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.comboBox_lmax,QtCore.SLOT(_fromUtf8("setCurrentIndex(int)")))
QtCore.QObject.connect(self.comboBox_lmax, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.comboBox_hmax,QtCore.SLOT(_fromUtf8("setCurrentIndex(int)")))
def setMineral(self):
i = self.comboBox_mineraldb.currentIndex()
if i == 0:
pass
else:
#disconnect d-space calculations till the end
QtCore.QObject.disconnect(self.comboBox_crystaltype, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(QString)")), self.setCellType)
QtCore.QObject.disconnect(self.comboBox_celltype, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(QString)")), self.setConditions)
QtCore.QObject.disconnect(self.spinBox_spacegroup, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.SpaceGroupLookup)
m = self.mineraldb.loc[i]
ind = ['Cubic','Tetragonal','Orthorhombic','Trigonal','Hexagonal','Monoclinic','Triclinic'].index(m.Crystal)
self.comboBox_crystaltype.setCurrentIndex(ind)
self.setCellType()
ind = self.celltypes.index(m.UnitCell)
self.comboBox_celltype.setCurrentIndex(ind)
self.setConditions()
ind = self.sgnumbers.index(m.SpaceGroup)
self.comboBox_spacegroup.setCurrentIndex(ind)
#now a,b,c paramters
#print(self.sgnumbers)
self.doubleSpinBox_a.setValue(m.a)
self.a = m.a
if not np.isnan(m.b):
self.doubleSpinBox_b.setValue(m.b)
self.b = m.b
if not np.isnan(m.c):
self.doubleSpinBox_c.setValue(m.c)
self.c = m.c
try:
self.manualConds = m.SpecialConditions.split(';')
except AttributeError: #ignore floats or nans
self.manualConds = ''
self.MetricTensor()
#reconnect and calculate
QtCore.QObject.connect(self.comboBox_crystaltype, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(QString)")), self.setCellType)
QtCore.QObject.connect(self.comboBox_celltype, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(QString)")), self.setConditions)
QtCore.QObject.connect(self.spinBox_spacegroup, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.SpaceGroupLookup)
self.D_Spacings()
def setCellType(self):
"""Sets the unit cell possibilities based upon the crystal type selected"""
self.comboBox_celltype.clear()
self.comboBox_spacegroup.clear()
self.celltypes = []
if self.comboBox_crystaltype.currentText() == 'Cubic':
self.celltypes = ['Primitive','Face Centered','Body Centered']
self.length_label = u' a = b = c'
self.label_lattice_equality.setText(self.length_label)
self.hSlider_b.setDisabled(True); self.hSlider_c.setDisabled(True)
self.doubleSpinBox_b.setDisabled(True); self.doubleSpinBox_c.setDisabled(True)
self.angles_label = u' \u03B1 = \u03B2 = \u03B3 = 90°'
self.label_angle_equality.setText(self.angles_label)
self.alpha = 90; self.beta = 90; self.gamma = 90
self.hSlider_alpha.setValue(self.alpha); self.hSlider_beta.setValue(self.beta); self.hSlider_gamma.setValue(self.gamma)
#disable editing sliders and spinboxes
self.hSlider_alpha.setDisabled(True); self.hSlider_beta.setDisabled(True); self.hSlider_gamma.setDisabled(True)
self.spinBox_alpha.setDisabled(True); self.spinBox_beta.setDisabled(True); self.spinBox_gamma.setDisabled(True)
elif self.comboBox_crystaltype.currentText() == 'Tetragonal':
self.celltypes = ['Primitive','Body Centered']
self.length_label = u' a = b ≠ c'
self.label_lattice_equality.setText(self.length_label)
self.hSlider_b.setDisabled(True); self.hSlider_c.setDisabled(False)
self.doubleSpinBox_b.setDisabled(True); self.doubleSpinBox_c.setDisabled(False)
self.angles_label = u' \u03B1 = \u03B2 = \u03B3 = 90°'
self.label_angle_equality.setText(self.angles_label)
self.alpha = 90; self.beta = 90; self.gamma = 90
self.hSlider_alpha.setValue(self.alpha); self.hSlider_beta.setValue(self.beta); self.hSlider_gamma.setValue(self.gamma)
#disable editing sliders and spinboxes
self.hSlider_alpha.setDisabled(True); self.hSlider_beta.setDisabled(True); self.hSlider_gamma.setDisabled(True)
self.spinBox_alpha.setDisabled(True); self.spinBox_beta.setDisabled(True); self.spinBox_gamma.setDisabled(True)
elif self.comboBox_crystaltype.currentText() == 'Orthorhombic':
self.celltypes = ['Primitive','Face Centered','Body Centered','(001) Base Centered','(100) Base Centered']
self.length_label = u' a ≠ b ≠ c'
self.label_lattice_equality.setText(self.length_label)
self.hSlider_b.setDisabled(False); self.hSlider_c.setDisabled(False)
self.doubleSpinBox_b.setDisabled(False); self.doubleSpinBox_c.setDisabled(False)
self.angles_label = u' \u03B1 = \u03B2 = \u03B3 = 90°'
self.label_angle_equality.setText(self.angles_label)
self.alpha = 90; self.beta = 90; self.gamma = 90
self.hSlider_alpha.setValue(self.alpha); self.hSlider_beta.setValue(self.beta); self.hSlider_gamma.setValue(self.gamma)
#disable editing sliders and spinboxes
self.hSlider_alpha.setDisabled(True); self.hSlider_beta.setDisabled(True); self.hSlider_gamma.setDisabled(True)
self.spinBox_alpha.setDisabled(True); self.spinBox_beta.setDisabled(True); self.spinBox_gamma.setDisabled(True)
elif self.comboBox_crystaltype.currentText() == 'Trigonal':
self.celltypes = ['Primitive','Rhombohedral','Rhombohedral, Hexagonal Axes','Hexagonal']
self.length_label = u' a = b ≠ c'
self.label_lattice_equality.setText(self.length_label)
self.hSlider_b.setDisabled(True); self.hSlider_c.setDisabled(False)
self.doubleSpinBox_b.setDisabled(True); self.doubleSpinBox_c.setDisabled(False)
self.angles_label = u' \u03B1 = \u03B2 = 90°, \u03B3 = 120°'
self.label_angle_equality.setText(self.angles_label)
self.alpha = 90; self.beta = 90; self.gamma = 120
self.hSlider_alpha.setValue(self.alpha); self.hSlider_beta.setValue(self.beta); self.hSlider_gamma.setValue(self.gamma)
#disable editing sliders and spinboxes
self.hSlider_alpha.setDisabled(True); self.hSlider_beta.setDisabled(True); self.hSlider_gamma.setDisabled(True)
self.spinBox_alpha.setDisabled(True); self.spinBox_beta.setDisabled(True); self.spinBox_gamma.setDisabled(True)
elif self.comboBox_crystaltype.currentText() == 'Hexagonal':
self.celltypes = ['Primitive']
self.length_label = u' a = b ≠ c'
self.label_lattice_equality.setText(self.length_label)
self.hSlider_b.setDisabled(True); self.hSlider_c.setDisabled(False)
self.doubleSpinBox_b.setDisabled(True); self.doubleSpinBox_c.setDisabled(False)
self.angles_label = u' \u03B1 = \u03B2 = 90°, \u03B3 = 120°'
self.label_angle_equality.setText(self.angles_label)
self.alpha = 90; self.beta = 90; self.gamma = 120
self.hSlider_alpha.setValue(self.alpha); self.hSlider_beta.setValue(self.beta); self.hSlider_gamma.setValue(self.gamma)
#disable editing sliders and spinboxes
self.hSlider_alpha.setDisabled(True); self.hSlider_beta.setDisabled(True); self.hSlider_gamma.setDisabled(True)
self.spinBox_alpha.setDisabled(True); self.spinBox_beta.setDisabled(True); self.spinBox_gamma.setDisabled(True)
elif self.comboBox_crystaltype.currentText() == 'Monoclinic':
self.celltypes = ['Primitive','(001) Base Centered']
self.length_label = u' a ≠ b ≠ c'
self.label_lattice_equality.setText(self.length_label)
self.hSlider_b.setDisabled(False); self.hSlider_c.setDisabled(False)
self.doubleSpinBox_b.setDisabled(False); self.doubleSpinBox_c.setDisabled(False)
self.angles_label = u' \u03B1 = \u03B3 = 90°'
self.label_angle_equality.setText(self.angles_label)
self.alpha = 90; self.beta = 90; self.gamma = 90
self.hSlider_alpha.setValue(self.alpha); self.hSlider_beta.setValue(self.beta); self.hSlider_gamma.setValue(self.gamma)
#disable editing sliders and spinboxes
self.hSlider_alpha.setDisabled(True); self.hSlider_beta.setDisabled(True); self.hSlider_gamma.setDisabled(True)
self.spinBox_alpha.setDisabled(True); self.spinBox_beta.setDisabled(True); self.spinBox_gamma.setDisabled(True)
elif self.comboBox_crystaltype.currentText() == 'Triclinic':
self.celltypes = ['Primitive']
self.length_label = u' a ≠ b ≠ c'
self.label_lattice_equality.setText(self.length_label)
self.hSlider_b.setDisabled(False); self.hSlider_c.setDisabled(False)
self.doubleSpinBox_b.setDisabled(False); self.doubleSpinBox_c.setDisabled(False)
self.angles_label = u''
self.label_angle_equality.setText(self.angles_label)
#Enable editing sliders and spinboxes
self.hSlider_alpha.setDisabled(False); self.hSlider_beta.setDisabled(False); self.hSlider_gamma.setDisabled(False)
self.spinBox_alpha.setDisabled(False); self.spinBox_beta.setDisabled(False); self.spinBox_gamma.setDisabled(False)
self.comboBox_celltype.addItems(self.celltypes)
#self.Recalculate()
def setConditions(self):
"""Sets conditions based upon which unit cell type is chosen.
Store equations in strings and then evaluate and solve with eval()"""
geom = self.comboBox_crystaltype.currentText()
unit = self.comboBox_celltype.currentText()
if unit in ['Rhombohedral','Rhombohedral, Hexagonal Axes']:
self.checkBox_obverse.setDisabled(False)
else:
self.checkBox_obverse.setDisabled(True)
try: #there is a loop I cant find where this tries to calculate conditions before unit cell type is set resulting in index error.
#this simply supresses the error, as another pass is always fine.
if unit in ['Rhombohedral, Hexagonal Axes','Hexagonal']:
rhomhex=True
self.conditions = np.unique(self.sghex[self.sghex['Unit Cell'] == unit]['Conditions'])[0]
else:
rhomhex=False
self.conditions = np.unique(self.sg[self.sg['Unit Cell'] == unit]['Conditions'])[0] #grab individual condition b/c of repetition
self.setSpaceGroups(geom,unit,rhomhex)
#QtCore.QObject.disconnect(self.comboBox_spacegroup, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(QString)")), self.D_Spacings)
self.comboBox_spacegroup.clear()
self.comboBox_spacegroup.addItems(self.sgnumlist)
#QtCore.QObject.connect(self.comboBox_spacegroup, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(QString)")), self.D_Spacings)
self.Recalculate()
except IndexError:
pass
def setSpaceGroups(self,geom,unit,rhomhex=False):
"""Sets the space group options based upon crystal geometry and unit cell type"""
if rhomhex:
sg = self.sghex
elif not rhomhex:
sg = self.sg
self.sgnumbers = list(sg[(sg['Geometry'] == geom) & (sg['Unit Cell'] == unit)].index)
self.sglist = list(sg.loc[self.sgnumbers,'Patterson'])
self.sgnumlist = [str(x) + ': ' + y for x,y in zip(self.sgnumbers,self.sglist)]
def SpaceGroupConditions(self,number):
"""Looks up the space-group-specific allowed diffraction spots.
number is the specific space group number to look up."""
if not self.checkBox_spacegroup.isChecked():
sg_conditions = 'True'
elif self.checkBox_spacegroup.isChecked():
#make sure number is an integer
#something is wrong with some FCC crystals
number = int(number)
unit = self.comboBox_celltype.currentText()
if unit in ['Rhombohedral, Hexagonal Axes','Hexagonal']:
sg = self.sghex
else:
sg = self.sg
sg_conditions = sg.loc[number,'SG Conditions']
return sg_conditions
def SpaceGroupLookup(self):
"""Takes input from slider/spinbox and outputs sapcegroup info into text line"""
index = self.spinBox_spacegroup.value()
c = self.sg.loc[index,'Geometry']
#u = self.sg.loc[index,'Unit Cell']
sg = self.sg.loc[index,'Patterson']
text = ': '.join([c,sg])
self.label_spacegrouplookup.setText(text)
def MetricTensor(self):
"""Calculate and show G, the metric tensor, and G*, the inverse metric tensor.
Also call function that outputs parameters into tables."""
self.G = np.zeros([3,3])
#self.G_inv
#remember, indices start at 0
#metric tensor is axially symmetric
self.a = self.doubleSpinBox_a.value()
self.b = self.doubleSpinBox_b.value()
self.c = self.doubleSpinBox_c.value()
self.G[0,0] = self.a**2
self.G[0,1] = round(self.a * self.b * np.cos(np.radians(self.spinBox_gamma.value())),6)
self.G[1,0] = self.G[0,1]
self.G[1,1] = self.b**2
self.G[0,2] = round(self.a * self.c * np.cos(np.radians(self.spinBox_beta.value())),6)
self.G[2,0] = self.G[0,2]
self.G[2,2] = self.doubleSpinBox_c.value()**2
self.G[1,2] = round(self.c * self.b * np.cos(np.radians(self.spinBox_alpha.value())),6)
self.G[2,1] = self.G[1,2]
# calc G inverse, G*
self.G_inv = np.linalg.inv(self.G)
self.Gtable.setData(self.G)
#self.Gtable.resizeColumnsToContents()
self.G_inv_table.setData(self.G_inv)
#self.G_inv_table.resizeColumnsToContents()
for i in range(0,3):
self.Gtable.setColumnWidth(i,self.Gtable_size[0]/3.35)
self.Gtable.setRowHeight(i,self.Gtable_size[1]/3.5)
self.G_inv_table.setColumnWidth(i,self.Gtable_size[0]/3.35)
self.G_inv_table.setRowHeight(i,self.Gtable_size[1]/3.5)
self.Parameters()
def Parameters(self):
"""Grabs current parameters and outputs them in tables.
Calculates reciprocal lattice parameters as well.
Must make it deal with complex numbers, but really only necessary for Triclinic..."""
self.parameters_direct = np.transpose(np.array([[self.doubleSpinBox_a.value(),self.doubleSpinBox_b.value(),self.doubleSpinBox_c.value(),self.spinBox_alpha.value(),self.spinBox_beta.value(),self.spinBox_gamma.value()]]))
self.astar = np.sqrt(self.G_inv[0,0]); self.bstar = np.sqrt(self.G_inv[1,1]); self.cstar = np.sqrt(self.G_inv[2,2])
self.gammastar = np.arccos(self.G_inv[0,1] / (self.astar * self.bstar))*180 / np.pi
self.betastar = np.arccos(self.G_inv[0,2] / (self.astar * self.cstar))*180 / np.pi
self.alphastar = np.arccos(self.G_inv[1,2] / (self.cstar * self.bstar))*180 / np.pi
self.parameters_reciprocal = np.transpose(np.array([[self.astar,self.bstar,self.cstar,self.alphastar,self.betastar,self.gammastar]]))
self.Gparam_table.setData(self.parameters_direct)
self.Gparam_inv_table.setData(self.parameters_reciprocal)
self.Gparam_table.setHorizontalHeaderLabels(['Parameters'])
self.Gparam_inv_table.setHorizontalHeaderLabels(['Parameters'])
self.Gparam_table.setVerticalHeaderLabels([u'a',u'b',u'c',u'\u03B1',u'\u03B2',u'\u03B3'])
self.Gparam_inv_table.setVerticalHeaderLabels([u'a*',u'b*',u'c*',u'\u03B1*',u'\u03B2*',u'\u03B3*'])
for i in range(0,6):
self.Gparam_table.setColumnWidth(i,self.param_table_size[0])
self.Gparam_table.setRowHeight(i,self.param_table_size[0]/6.7)
self.Gparam_inv_table.setColumnWidth(i,self.param_table_size[0])
self.Gparam_inv_table.setRowHeight(i,self.param_table_size[0]/6.7)
def D_Spacings(self):
"""Calculates D-spacings using the metric tensor and places them in a table (sorted?)"""
#grab spacegroup conditions
#multiple different spacegroup conditions. e.g. eval('h==1 or k==1') returns a True if on is satisfied
#add all conditions together into one string
#full_conditions = self.conditions + ' and ' + sg_conditions
if self.checkBox_zoneaxis.isChecked():
try:
self.u = int(self.comboBox_u.currentText())
except ValueError:
self.u = 0
try:
self.v = int(self.comboBox_v.currentText())
except ValueError:
self.v = 0
try:
self.w = int(self.comboBox_w.currentText())
except ValueError:
self.w = 0
#set "q" for rhombohedral obserse/reverse
if self.checkBox_obverse.isChecked():
q = 1
elif not self.checkBox_obverse.isChecked():
q = -1
else:
q = 0
#make pandas dataframe with multiindex h,k,l
#reinitialize dataframe
self.DSpaces = pd.DataFrame(columns = ['d-space','h','k','l'])
self.Forbidden = pd.DataFrame(columns = ['d-space','h','k','l'])
#maybe implement masking instead of loops
hmin = int(self.comboBox_hmin.currentText())
hmax = int(self.comboBox_hmax.currentText())
kmin = int(self.comboBox_kmin.currentText())
kmax = int(self.comboBox_kmax.currentText())
lmin = int(self.comboBox_lmin.currentText())
lmax = int(self.comboBox_lmax.currentText())
gen_conditions = str(self.conditions)
#needs to deal with possibility of conditional special statements, will update dspace.pyx
#first calculate all general conditions
self.DSpaces = DSpace(self.G_inv,self.u,self.v,self.w,hmin,hmax,kmin,kmax,lmin,lmax,gen_conditions,q)
#now deal with special spacegroup conditions by removing invalid spots
sg_conditions = self.SpaceGroupConditions(self.sgnumbers[self.comboBox_spacegroup.currentIndex()])
if self.manualConds != []:
if sg_conditions == 'True':
sg_conditions = ''
for c in self.manualConds:
sg_conditions += ';%s' % c
sg_conditions = sg_conditions.lstrip(';')
self.DSpaces = self.RemoveForbidden(self.DSpaces,sg_conditions)
#sort in descending Dspace order, then by h values, then k, then l...
self.DSpaces.sort(columns=['d-space','h','k','l'],ascending=False,inplace=True)
#reset indices for convenience later
self.DSpaces.index = [x for x in range(len(self.DSpaces))]
self.common.DSpaces = self.DSpaces #update DSpaces
self.dspace_table.setData(self.DSpaces)
self.dspace_table.setColumnWidth(0,80) #make d-space column a bit wider
for i in range(1,4):
self.dspace_table.setColumnWidth(i,45)
elif not self.checkBox_zoneaxis.isChecked():
pass
try:
self.updateCommon()
except AttributeError: #first go round ipython console hasn't been initialized yet
pass
def RemoveForbidden(self,d,sgconditions):
#h = d['h']; k = d['k']; l = d['l']
f = pd.DataFrame(columns = ['d-space','h','k','l'])
try:
if eval(sgconditions):
return(d)
except (KeyError,SyntaxError): #if sgconditions not 'True'
#d[(h==k) & ~(l%2==0)]
#d = d.drop(r.index)
#split multiple conditions up
conds = sgconditions.split(';')
for c in conds: #these should be if:then statements, so remove the if:~thens
c = c.strip()
if not c.startswith('if'):
r = d[eval(c)]
d = d.drop(r.index)
else:
c = c.lstrip('if').strip()
iff, then = c.split(':') #eval doesnt care about spaces
#needed for eval
h = d.h; k = d.k; l = d.l
r = d[eval('(' + iff + ')& ~(' + then + ')')]
d = d.drop(r.index)
f = pd.concat([f,r])
f.sort(columns=['d-space','h','k','l'],ascending=False,inplace=True)
f.index = [x for x in range(len(f))]
self.common.Forbidden = f
self.Forbidden = self.common.Forbidden
return(d)
def setMineralList(self):
self.comboBox_mineraldb.clear()
self.minlist = list(self.mineraldb['Chemical'] + ': ' + self.mineraldb['Name'])
self.comboBox_mineraldb.addItems(self.minlist)
def removeMinerals(self):
QtCore.QObject.disconnect(self.comboBox_mineraldb, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(QString)")), self.setMineral)
mindiag = MineralListDialog()
model = QtGui.QStandardItemModel(mindiag.listView)
#mindiag.buttonBox.accepted.connect(mindiag.accept)
#mindiag.buttonBox.rejected.connect(mindiag.reject)
for mineral in self.minlist[1:]:
item = QtGui.QStandardItem(mineral)
item.setCheckable(True)
item.setEditable(False)
model.appendRow(item)
mindiag.listView.setModel(model)
if mindiag.exec_():
i=1
l=[]
while model.item(i):
if model.item(i).checkState():
l.append(i)
i += 1
self.mineraldb = self.mineraldb.drop(self.mineraldb.index[l])
self.mineraldb.index = list(range(len(self.mineraldb)))
self.setMineralList()
QtCore.QObject.connect(self.comboBox_mineraldb, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(QString)")), self.setMineral)
def AppendMineral(self):
QtCore.QObject.disconnect(self.comboBox_mineraldb, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(QString)")), self.setMineral)
dial = NewMineralDialog()
if dial.exec_():
name = dial.lineEdit_name.text()
sym = dial.lineEdit_sym.text()
if name == '':
name = 'Mineral'
if sym == '':
sym = 'XX'
#set special conditions to a bunch of strings or as a NaN
if self.manualConds == []:
SCs = np.nan
else:
SCs = ';'.join(self.manualConds)
params = {'Name':name, 'Chemical':sym,
'Crystal':self.comboBox_crystaltype.currentText(),
'UnitCell':self.comboBox_celltype.currentText(),
'SpaceGroup':int(self.comboBox_spacegroup.currentText().split(':')[0]),
'a':self.doubleSpinBox_a.value(),
'b':self.doubleSpinBox_b.value(),
'c':self.doubleSpinBox_c.value(),
'SpecialConditions':SCs}
self.mineraldb = self.mineraldb.append(params,ignore_index=True)
self.setMineralList()
QtCore.QObject.connect(self.comboBox_mineraldb, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(QString)")), self.setMineral)
def setSettings(self):
"""Raise SettingsDialog and pass values to pyLATTICE parameters.
Grab current settings first."""
current = {'a max':self.doubleSpinBox_a.maximum(),
'b max':self.doubleSpinBox_b.maximum(),
'c max':self.doubleSpinBox_c.maximum()}
dial = SettingsDialog(current)
if dial.exec_():
amax = dial.maxa.value()
bmax = dial.maxb.value()
cmax = dial.maxc.value()
#set slider and spinbox maxima
self.doubleSpinBox_a.setMaximum(amax)
self.doubleSpinBox_b.setMaximum(bmax)
self.doubleSpinBox_c.setMaximum(cmax)
self.hSlider_a.setMaximum(int(10*amax))
self.hSlider_b.setMaximum(int(10*bmax))
self.hSlider_c.setMaximum(int(10*cmax))
def ManualConditions(self):
"""Raise the manual space group conditions dialog"""
dial = ManualConditionsDialog(conditions= self.manualConds)
if dial.exec_():
num = dial.manualCondList.count()
self.manualConds = [dial.manualCondList.item(i).text() for i in range(num)]
def SaveDSpace(self):
self.Save(self.DSpaces)
def SaveMineralDB(self):
self.Save(self.mineraldb)
def LoadMineralDB(self):
QtCore.QObject.disconnect(self.comboBox_mineraldb, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(QString)")), self.setMineral)
ftypes = 'HDF (*.h5);;CSV (*.csv);;Excel (*.xlsx)'
fname,ffilter = QtGui.QFileDialog.getOpenFileNameAndFilter(self,caption='Load Mineral Database',directory=self.common.path,filter=ftypes)
fname = str(fname)
ffilter=str(ffilter)
#print(fname,ffilter)
name, ext = os.path.splitext(fname)
self.common.path = os.path.dirname(fname)
if ffilter.startswith('HDF'):
item = pd.read_hdf(name + '.h5','table')
elif ffilter.startswith('CSV'):
item = pd.read_csv(name + '.csv',sep=',')
elif ffilter.startswith('Excel'): #allow for different excel formats
sheetname,ok = QtGui.QInputDialog.getText(self,'Input Sheetname','Sheetname')
if ok and sheetname != '':
if ext == '.xlsx' or ext == '':
item = pd.read_excel(name + '.xlsx',str(sheetname))
elif ext == '.xls':
item = pd.read_excel(name + '.xls',str(sheetname))
self.mineraldb = item
else:
QtGui.QMessageBox.information(self, "Warning!", 'You must specify a sheet name!')
self.setMineralList()
QtCore.QObject.connect(self.comboBox_mineraldb, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(QString)")), self.setMineral)
def Save(self,item):
#item should be pandas dataframe object
ftypes = 'HDF (*.h5);;CSV (*.csv);;Excel (*.xlsx)'
fname,ffilter = QtGui.QFileDialog.getSaveFileNameAndFilter(self,caption='Save D-Spacings',directory=self.common.path,filter=ftypes)
fname = str(fname)
ffilter=str(ffilter)
#print(fname,ffilter)
name, ext = os.path.splitext(fname)
self.common.path = os.path.dirname(fname)
print(name + ext)
if ffilter.startswith('HDF'):
item.to_hdf(name + '.h5','table')
elif ffilter.startswith('CSV'):
item.to_csv(name + '.csv',sep=',')
elif ffilter.startswith('Excel'): #allow for different excel formats
if ext == '.xlsx' or ext == '':
item.to_excel(name + '.xlsx')
elif ext == '.xls':
item.to_excel(name + '.xls')
################################################################################
############################### Plotting #######################################
################################################################################
def PlotDiffraction(self):
"""Plots the current list of spots and d-spacings.
For each point in self.DSpaces [d-space,h,k,l], determines anlges for plotting."""
#initialize plot with center spot only
self.Plot.clear()
self.common._x2 = False
self.Plot.set_xlabel(u'Distance (\u212B\u207B\u00B9)')#angstrom^-1
self.Plot.set_ylabel(u'Distance (\u212B\u207B\u00B9)')
#get values in energy, cam legnth, cam const. combo boxes
self.energy = self.spinBox_beamenergy.value()
self.camlength = self.spinBox_camlength.value()
self.camconst = self.doubleSpinBox_camconst.value()
#self.Plot.plot(0,0, linestyle = '', marker='o', markersize = 10, color = 'black',picker=5, label = u'0 0 0')
#add some labels
if self.checkBox_labels.isChecked() == True:
#center spot
#self.Plot.annotate(u'0 0 0', xy = (0,0), xytext=(0,10),textcoords = 'offset points', ha = 'center', va = 'bottom',
# bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.01))
#add crystal structure information in an annotation
#grab current values
self.a = self.doubleSpinBox_a.value(); self.b = self.doubleSpinBox_b.value(); self.c = self.doubleSpinBox_c.value()
alph = self.spinBox_alpha.value(); beta = self.spinBox_beta.value(); gam = self.spinBox_gamma.value()
plot_label = r'''%s: %s; a = %.2f, b = %.2f, c = %.2f; $\alpha$ = %d$^o$, $\beta$ = %d$^o$, $\gamma$ = %d$^o$''' % (self.comboBox_crystaltype.currentText(),self.comboBox_celltype.currentText(),self.a,self.b,self.c,alph,beta,gam)
ann = self.Plot.annotate(plot_label, xy=(0.02, 1.02), xycoords='axes fraction',bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.01))
ann.draggable() #make annotation draggable
#need to choose a reference point with smallest sum of absolute miller indices
#since self.DSpaces is sorted with largest d-space first, this will be the smallest sum of abs miller indices
#first point
rotation = np.radians(float(self.comboBox_rotate.currentText()))
d = np.array(self.DSpaces['d-space'],dtype=np.float)
ref = np.array(self.DSpaces.loc[0,['h','k','l']],dtype=np.int)
Q2 = np.array(self.DSpaces[['h','k','l']],dtype=np.int)
recip_vec = np.array([self.astar,self.bstar,self.cstar],dtype=np.float)
dir_vec = np.array([self.u,self.v,self.w],dtype=np.int)
#add extra factor if hcp unit cell
t = self.comboBox_crystaltype.currentText()
#must check that Forbidden dataframe isn't empty for a spcific zone axis
showf = self.checkBox_showforbidden.isChecked() and not self.Forbidden.empty
if t in ['Hexagonal','Trigonal']:
#print('Hexagonal')
#change dtypes
ref = np.array(ref,dtype=np.float)
Q2 = np.array(Q2,dtype=np.float)
lam = np.sqrt(2/3)*(self.c/self.a)
ref[2] = ref[2]/lam
ref = np.hstack([ref,-(ref[0]+ref[1])]) #add i direction, but to the end b/c it doesnt matter
Q2[:,2] = Q2[:,2]/lam
Q2 = np.append(Q2,np.array([-Q2[:,0]-Q2[:,1]]).T,axis=1)
theta,x,y = CalcSpotsHCP(d,Q2,ref,recip_vec,dir_vec,rotation)
if showf:
df = np.array(self.Forbidden['d-space'],dtype=np.float)
Q2f = np.array(self.Forbidden[['h','k','l']],dtype=np.int)
Q2f = np.array(Q2f,dtype=np.float)
Q2f[:,2] = Q2f[:,2]/lam
Q2f = np.append(Q2f,np.array([-Q2f[:,0]-Q2f[:,1]]).T,axis=1)
thetaf,xf,yf = CalcSpotsHCP(df,Q2f,ref,recip_vec,dir_vec,rotation)
else:
theta,x,y = CalcSpots(d,Q2,ref,recip_vec,self.G_inv,dir_vec,rotation)
if showf:
df = np.array(self.Forbidden['d-space'],dtype=np.float)
Q2f = np.array(self.Forbidden[['h','k','l']],dtype=np.int)
thetaf,xf,yf = CalcSpots(df,Q2f,ref,recip_vec,self.G_inv,dir_vec,rotation)
self.DSpaces['theta'] = np.degrees(theta).round(2); self.DSpaces['x'] = x; self.DSpaces['y'] = y
if showf:
self.Forbidden['theta'] = np.degrees(thetaf).round(2); self.Forbidden['x'] = xf; self.Forbidden['y'] = yf
for i in range(len(self.Forbidden)):
label = ' '.join([str(int(x)) for x in self.Forbidden.loc[i,['h','k','l']]]) #this is a bit dense, but makes a list of str() hkl values, then concatenates
#convert negative numbers to overline numbers for visual effect
for j,num in enumerate(self._overline_strings):
match = re.search(u'-%d' % (j+1),label)
if match:
label = re.sub(match.group(),num,label)
#add each label and coordinate to DSpace dataframe
# self.DSpaces.loc[i,'x'] = coords[0]
# self.DSpaces.loc[i,'y'] = coords[1]
self.Forbidden.loc[i,'label'] = label
#print(self.DSpaces)
#make label for each spot
for i in range(len(self.DSpaces)):
label = r' '.join([str(int(x)) for x in self.DSpaces.loc[i,['h','k','l']]]) #this is a bit dense, but makes a list of str() hkl values, then concatenates
#convert negative numbers to overline numbers for visual effect
for j,num in enumerate(self._overline_strings):
match = re.search(u'-%d' % (j+1),label)
if match:
label = re.sub(match.group(),num,label)
#add each label and coordinate to DSpace dataframe
# self.DSpaces.loc[i,'x'] = coords[0]
# self.DSpaces.loc[i,'y'] = coords[1]
label = r'$%s$' % label.replace(' ','\ ') #convert to mathtex string and add spaces
self.DSpaces.loc[i,'label'] = label
#add 000 spot
self.DSpaces.loc[len(self.DSpaces),['d-space','h','k','l','x','y','label']] = [0,0,0,0,0,0,r'$0\ 0\ 0$']
#print(self.DSpaces)
#scatterplots make it difficult to get data back in matplotlibwidget
# for i in range(len(self.DSpaces)):
self.Plot.plot(self.DSpaces['x'],self.DSpaces['y'],ls='',marker='o',markersize=10,color='k',picker=5)#,label='%i %i %i' % (self.DSpaces.loc[i,['h']],self.DSpaces.loc[i,['k']],self.DSpaces.loc[i,['l']]))
if showf:
self.Plot.plot(self.Forbidden['x'],self.Forbidden['y'],ls='',marker='o',markersize=7,color='gray', alpha=.7)
#xmax = max(self.DSpaces['x']); xmin = min(self.DSpaces['x'])
#ymax = max(self.DSpaces['y']); ymin = min(self.DSpaces['y'])
#self.Plot.set_xlim([1.5*xmin,1.5*xmax])
#self.Plot.set_ylim([1.5*ymin,1.5*ymax])
if self.checkBox_labels.isChecked() == True:
for i in range(len(self.DSpaces)):
#label = self.MathLabels(i)
label = self.DSpaces.loc[i,'label']
self.Plot.annotate(label, xy = (self.DSpaces.loc[i,'x'],self.DSpaces.loc[i,'y']), xytext=(0,10),textcoords = 'offset points', ha = 'center', va = 'bottom',
bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.01))
if showf:
for i in range(len(self.Forbidden)):
#label = self.MathLabels(i)
label = self.Forbidden.loc[i,'label']
self.Plot.annotate(label, xy = (self.Forbidden.loc[i,'x'],self.Forbidden.loc[i,'y']), xytext=(0,10),textcoords = 'offset points', ha = 'center', va = 'bottom',color='gray',
bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.01))
if showf:
self.common.Forbidden = self.Forbidden
self.common.DSpaces = self.DSpaces
self.common.a = self.doubleSpinBox_a.value()#for determining arrow size in plot
self.DiffWidget.canvas.draw()
def MathLabels(self,i):
'''Make labels with overlines instead of minus signs for plotting with matplotlib.
i is the index for DSpaces'''
label = r''
if self.DSpaces.loc[i,'h'] < 0:
label+=r'$\bar %i$ ' % abs(self.DSpaces.loc[i,'h'])
else:
label+=r'%i ' % self.DSpaces.loc[i,'h']
if self.DSpaces.loc[i,'k'] < 0:
label+=r'$\bar %i$ ' % abs(self.DSpaces.loc[i,'k'])
else:
label+=r'%i ' % self.DSpaces.loc[i,'k']
if self.DSpaces.loc[i,'l'] < 0:
label+=r'$\bar %i$' % abs(self.DSpaces.loc[i,'l'])
else:
label+=r'%i' % self.DSpaces.loc[i,'l']
return(label)
################################################################################
############################### Calculator #####################################
################################################################################
def Calculator(self):
"""Grabs current miller indices or zone directions and calls AngleCalc"""
h1 = int(self.comboBox_h1.currentText())
h2 = int(self.comboBox_h2.currentText())
k1 = int(self.comboBox_k1.currentText())
k2 = int(self.comboBox_k2.currentText())
l1 = int(self.comboBox_l1.currentText())
l2 = int(self.comboBox_l2.currentText())
i1 = -(h1+k1)
i2 = -(h2+k2)
hex = self.checkBox_hexagonal.isChecked()
angle = round(np.degrees(self.Diffraction.PlaneAngle(p1=np.array([h1,k1,l1]),p2=np.array([h2,k2,l2]),hex=hex)),2)
if np.isnan(angle):
QtGui.QMessageBox.information(self, "Uh, Oh!", 'There is no [0 0 0] direction/plane!')
else:
if self.checkBox_normals.isChecked():
self.lineEdit_angle.setText(u'φ = %.2f°' % angle)
bra = u'('
ket = u')'
elif not self.checkBox_normals.isChecked():
self.lineEdit_angle.setText(u'ρ = %.2f°' % angle)
bra = u'['
ket = u']'
if hex == False:
hkls = [bra,h1,k1,l1,ket,bra,h2,k2,l2,ket]
for j,it in enumerate(hkls):
if type(it) == int and it < 0:
hkls[j] = self._overline_strings[abs(it)-1]
self.lineEdit_dirs.setText(u'%s%s%s%s%s \u2220 %s%s%s%s%s' % tuple(hkls))
else:
hkls = [bra,h1,k1,i1,l1,ket,bra,h2,k2,i2,l2,ket]
for j,it in enumerate(hkls):
if type(it) == int and it < 0:
hkls[j] = self._overline_strings[abs(it)-1]
self.lineEdit_dirs.setText(u'%s%s%s%s%s%s \u2220 %s%s%s%s%s%s' % tuple(hkls))
def CalcLabels(self):
"""Rewrite labels for aesthetics"""
if self.checkBox_normals.isChecked():
self.label_h2.setText(u'h')
self.label_k2.setText(u'k')
self.label_l2.setText(u'l')
#self.label_h2.setAlignment(0x0004)
#self.label_k2.setAlignment(0x0004)
#self.label_l2.setAlignment(0x0004)
elif not self.checkBox_normals.isChecked():
self.label_h2.setText(u'u')
self.label_k2.setText(u'v')
self.label_l2.setText(u'w')
#self.label_h2.setAlignment(0x0004)
#self.label_k2.setAlignment(0x0004)
#self.label_l2.setAlignment(0x0004)
################################################################################
############################### Other ##########################################
################################################################################
def About(self):
"""Displays the About message"""
QtGui.QMessageBox.information(self, "About",
"""pyLATTICE %s:
Written by Evan Groopman
Based upon LATTICE (DOS) by Thomas Bernatowicz
c. 2011-2014
For help contact: [email protected]""" % self.version)
def HowTo(self):
"""How-to dialog box"""
howtomessage = (
"""
- Select crystal type, unit cell type, and lattice parameters to calculate the metric tensor.
- OR select a mineral from the database.
- D-spacings will be calculated between the selected Miller indices.
- Select zone axis and press "Plot" to show diffraction pattern.
- Select two diffraction spots to measure distance and angle.
Note: pyLATTICE only includes general reflection conditions for each space group. It does not includes special conditions based upon multiplcity, site symmetry, etc. EXCEPT for FCC diamond #227.
""")
QtGui.QMessageBox.information(self, "How to use",
howtomessage)
| gpl-2.0 |
rsjohnco/rez | src/rez/packages_.py | 1 | 19212 | from rez.package_repository import package_repository_manager
from rez.package_resources_ import PackageFamilyResource, PackageResource, \
VariantResource, package_family_schema, package_schema, variant_schema, \
package_release_keys
from rez.package_serialise import dump_package_data
from rez.utils.data_utils import cached_property
from rez.utils.formatting import StringFormatMixin, StringFormatType
from rez.utils.filesystem import is_subdirectory
from rez.utils.schema import schema_keys
from rez.utils.resources import ResourceHandle, ResourceWrapper
from rez.exceptions import PackageMetadataError, PackageFamilyNotFoundError
from rez.vendor.version.version import VersionRange
from rez.vendor.version.requirement import VersionedObject
from rez.serialise import load_from_file, FileFormat
from rez.config import config
from rez.system import system
import os.path
import sys
#------------------------------------------------------------------------------
# package-related classes
#------------------------------------------------------------------------------
class PackageRepositoryResourceWrapper(ResourceWrapper, StringFormatMixin):
format_expand = StringFormatType.unchanged
def validated_data(self):
data = ResourceWrapper.validated_data(self)
data = dict((k, v) for k, v in data.iteritems() if v is not None)
return data
class PackageFamily(PackageRepositoryResourceWrapper):
"""A package family.
Note:
Do not instantiate this class directly, instead use the function
`iter_package_families`.
"""
keys = schema_keys(package_family_schema)
def __init__(self, resource):
assert isinstance(resource, PackageFamilyResource)
super(PackageFamily, self).__init__(resource)
def iter_packages(self):
"""Iterate over the packages within this family, in no particular order.
Returns:
`Package` iterator.
"""
repo = self.resource._repository
for package in repo.iter_packages(self.resource):
yield Package(package)
class PackageBaseResourceWrapper(PackageRepositoryResourceWrapper):
"""Abstract base class for `Package` and `Variant`.
"""
@property
def uri(self):
return self.resource.uri
@property
def config(self):
"""Returns the config for this package.
Defaults to global config if this package did not provide a 'config'
section.
"""
return self.resource.config or config
@cached_property
def is_local(self):
"""Returns True if the package is in the local package repository"""
local_repo = package_repository_manager.get_repository(
self.config.local_packages_path)
return (self.resource._repository.uid == local_repo.uid)
def print_info(self, buf=None, format_=FileFormat.yaml,
skip_attributes=None, include_release=False):
"""Print the contents of the package.
Args:
buf (file-like object): Stream to write to.
format_ (`FileFormat`): Format to write in.
skip_attributes (list of str): List of attributes to not print.
include_release (bool): If True, include release-related attributes,
such as 'timestamp' and 'changelog'
"""
data = self.validated_data().copy()
# config is a special case. We only really want to show any config settings
# that were in the package.py, not the entire Config contents that get
# grafted onto the Package/Variant instance. However Variant has an empy
# 'data' dict property, since it forwards data from its parent package.
data.pop("config", None)
if self.config:
if isinstance(self, Package):
config_dict = self.data.get("config")
else:
config_dict = self.parent.data.get("config")
data["config"] = config_dict
if not include_release:
skip_attributes = list(skip_attributes or []) + list(package_release_keys)
buf = buf or sys.stdout
dump_package_data(data, buf=buf, format_=format_,
skip_attributes=skip_attributes)
class Package(PackageBaseResourceWrapper):
"""A package.
Note:
Do not instantiate this class directly, instead use the function
`iter_packages` or `PackageFamily.iter_packages`.
"""
keys = schema_keys(package_schema)
def __init__(self, resource):
assert isinstance(resource, PackageResource)
super(Package, self).__init__(resource)
@cached_property
def qualified_name(self):
"""Get the qualified name of the package.
Returns:
str: Name of the package with version, eg "maya-2016.1".
"""
o = VersionedObject.construct(self.name, self.version)
return str(o)
@cached_property
def parent(self):
"""Get the parent package family.
Returns:
`PackageFamily`.
"""
repo = self.resource._repository
family = repo.get_parent_package_family(self.resource)
return PackageFamily(family) if family else None
@cached_property
def num_variants(self):
return len(self.data.get("variants", []))
def iter_variants(self):
"""Iterate over the variants within this package, in index order.
Returns:
`Variant` iterator.
"""
repo = self.resource._repository
for variant in repo.iter_variants(self.resource):
yield Variant(variant)
def get_variant(self, index=None):
"""Get the variant with the associated index.
Returns:
`Variant` object, or None if no variant with the given index exists.
"""
for variant in self.iter_variants():
if variant.index == index:
return variant
class Variant(PackageBaseResourceWrapper):
"""A package variant.
Note:
Do not instantiate this class directly, instead use the function
`Package.iter_variants`.
"""
keys = schema_keys(variant_schema)
keys.update(["index", "root", "subpath"])
def __init__(self, resource):
assert isinstance(resource, VariantResource)
super(Variant, self).__init__(resource)
@cached_property
def qualified_package_name(self):
o = VersionedObject.construct(self.name, self.version)
return str(o)
@cached_property
def qualified_name(self):
"""Get the qualified name of the variant.
Returns:
str: Name of the variant with version and index, eg "maya-2016.1[1]".
"""
idxstr = '' if self.index is None else str(self.index)
return "%s[%s]" % (self.qualified_package_name, idxstr)
@cached_property
def parent(self):
"""Get the parent package.
Returns:
`Package`.
"""
repo = self.resource._repository
package = repo.get_parent_package(self.resource)
return Package(package)
def get_requires(self, build_requires=False, private_build_requires=False):
"""Get the requirements of the variant.
Args:
build_requires (bool): If True, include build requirements.
private_build_requires (bool): If True, include private build
requirements.
Returns:
List of `Requirement` objects.
"""
requires = self.requires or []
if build_requires:
requires = requires + (self.build_requires or [])
if private_build_requires:
requires = requires + (self.private_build_requires or [])
return requires
def install(self, path, dry_run=False, overrides=None):
"""Install this variant into another package repository.
If the package already exists, this variant will be correctly merged
into the package. If the variant already exists in this package, the
existing variant is returned.
Args:
path (str): Path to destination package repository.
dry_run (bool): If True, do not actually install the variant. In this
mode, a `Variant` instance is only returned if the equivalent
variant already exists in this repository; otherwise, None is
returned.
overrides (dict): Use this to change or add attributes to the
installed variant.
Returns:
`Variant` object - the (existing or newly created) variant in the
specified repository. If `dry_run` is True, None may be returned.
"""
repo = package_repository_manager.get_repository(path)
resource = repo.install_variant(self.resource,
dry_run=dry_run,
overrides=overrides)
if resource is None:
return None
elif resource is self.resource:
return self
else:
return Variant(resource)
class PackageSearchPath(object):
"""A list of package repositories.
For example, $REZ_PACKAGES_PATH refers to a list of repositories.
"""
def __init__(self, packages_path):
"""Create a package repository list.
Args:
packages_path (list of str): List of package repositories.
"""
self.paths = packages_path
def iter_packages(self, name, range_=None):
"""See `iter_packages`.
Returns:
`Package` iterator.
"""
for package in iter_packages(name=name, range_=range_, paths=self.paths):
yield package
def __contains__(self, package):
"""See if a package is in this list of repositories.
Note:
This does not verify the existance of the resource, only that the
resource's repository is in this list.
Args:
package (`Package` or `Variant`): Package to search for.
Returns:
bool: True if the resource is in the list of repositories, False
otherwise.
"""
return (package.resource._repository.uid in self._repository_uids)
@cached_property
def _repository_uids(self):
uids = set()
for path in self.paths:
repo = package_repository_manager.get_repository(path)
uids.add(repo.uid)
return uids
#------------------------------------------------------------------------------
# resource acquisition functions
#------------------------------------------------------------------------------
def iter_package_families(paths=None):
"""Iterate over package families, in no particular order.
Note that multiple package families with the same name can be returned.
Unlike packages, families later in the searchpath are not hidden by earlier
families.
Args:
paths (list of str, optional): paths to search for package families,
defaults to `config.packages_path`.
Returns:
`PackageFamily` iterator.
"""
for path in (paths or config.packages_path):
repo = package_repository_manager.get_repository(path)
for resource in repo.iter_package_families():
yield PackageFamily(resource)
def iter_packages(name, range_=None, paths=None):
"""Iterate over `Package` instances, in no particular order.
Packages of the same name and version earlier in the search path take
precedence - equivalent packages later in the paths are ignored. Packages
are not returned in any specific order.
Args:
name (str): Name of the package, eg 'maya'.
range_ (VersionRange or str): If provided, limits the versions returned
to those in `range_`.
paths (list of str, optional): paths to search for packages, defaults
to `config.packages_path`.
Returns:
`Package` iterator.
"""
entries = _get_families(name, paths)
seen = set()
for repo, family_resource in entries:
for package_resource in repo.iter_packages(family_resource):
key = (package_resource.name, package_resource.version)
if key in seen:
continue
seen.add(key)
if range_:
if isinstance(range_, basestring):
range_ = VersionRange(range_)
if package_resource.version not in range_:
continue
yield Package(package_resource)
def get_package(name, version, paths=None):
"""Get an exact version of a package.
Args:
name (str): Name of the package, eg 'maya'.
version (Version or str): Version of the package, eg '1.0.0'
paths (list of str, optional): paths to search for package, defaults
to `config.packages_path`.
Returns:
`Package` object, or None if the package was not found.
"""
if isinstance(version, basestring):
range_ = VersionRange("==%s" % version)
else:
range_ = VersionRange.from_version(version, "==")
it = iter_packages(name, range_, paths)
try:
return it.next()
except StopIteration:
return None
def get_package_from_string(txt, paths=None):
"""Get a package given a string.
Args:
txt (str): String such as 'foo', 'bah-1.3'.
paths (list of str, optional): paths to search for package, defaults
to `config.packages_path`.
Returns:
`Package` instance, or None if no package was found.
"""
o = VersionedObject(txt)
return get_package(o.name, o.version, paths=paths)
def get_developer_package(path):
"""Load a developer package.
A developer package may for example be a package.yaml or package.py in a
user's source directory.
Note:
The resulting package has a 'filepath' attribute added to it, that does
not normally appear on a `Package` object. A developer package is the
only case where we know we can directly associate a 'package.*' file
with a package - other packages can come from any kind of package repo,
which may or may not associate a single file with a single package (or
any file for that matter - it may come from a database).
Args:
path: Directory containing the package definition file.
Returns:
`Package` object.
"""
data = None
for format_ in (FileFormat.py, FileFormat.yaml):
filepath = os.path.join(path, "package.%s" % format_.extension)
if os.path.isfile(filepath):
data = load_from_file(filepath, format_)
break
if data is None:
raise PackageMetadataError("No package definition file found at %s" % path)
name = data.get("name")
if name is None or not isinstance(name, basestring):
raise PackageMetadataError(
"Error in %r - missing or non-string field 'name'" % filepath)
package = create_package(name, data)
setattr(package, "filepath", filepath)
return package
def create_package(name, data):
"""Create a package given package data.
Args:
name (str): Package name.
data (dict): Package data. Must conform to `package_maker.package_schema`.
Returns:
`Package` object.
"""
from rez.package_maker__ import PackageMaker
maker = PackageMaker(name, data)
return maker.get_package()
def get_variant(variant_handle):
"""Create a variant given its handle.
Args:
variant_handle (`ResourceHandle` or dict): Resource handle, or
equivalent dict.
Returns:
`Variant`.
"""
if isinstance(variant_handle, dict):
variant_handle = ResourceHandle.from_dict(variant_handle)
variant_resource = package_repository_manager.get_resource(variant_handle)
variant = Variant(variant_resource)
return variant
def get_last_release_time(name, paths=None):
"""Returns the most recent time this package was released.
Note that releasing a variant into an already-released package is also
considered a package release.
Returns:
int: Epoch time of last package release, or zero if this cannot be
determined.
"""
entries = _get_families(name, paths)
max_time = 0
for repo, family_resource in entries:
time_ = repo.get_last_release_time(family_resource)
if time_ == 0:
return 0
max_time = max(max_time, time_)
return max_time
def get_completions(prefix, paths=None, family_only=False):
"""Get autocompletion options given a prefix string.
Example:
>>> get_completions("may")
set(["maya", "maya_utils"])
>>> get_completions("maya-")
set(["maya-2013.1", "maya-2015.0.sp1"])
Args:
prefix (str): Prefix to match.
paths (list of str): paths to search for packages, defaults to
`config.packages_path`.
family_only (bool): If True, only match package names, do not include
version component.
Returns:
Set of strings, may be empty.
"""
op = None
if prefix:
if prefix[0] in ('!', '~'):
if family_only:
return set()
op = prefix[0]
prefix = prefix[1:]
fam = None
for ch in ('-', '@', '#'):
if ch in prefix:
if family_only:
return set()
fam = prefix.split(ch)[0]
break
words = set()
if not fam:
words = set(x.name for x in iter_package_families(paths=paths)
if x.name.startswith(prefix))
if len(words) == 1:
fam = iter(words).next()
if family_only:
return words
if fam:
it = iter_packages(fam, paths=paths)
words.update(x.qualified_name for x in it
if x.qualified_name.startswith(prefix))
if op:
words = set(op + x for x in words)
return words
def get_latest_package(name, range_=None, paths=None, error=False):
"""Get the latest package for a given package name.
Args:
name (str): Package name.
range_ (`VersionRange`): Version range to search within.
paths (list of str, optional): paths to search for package families,
defaults to `config.packages_path`.
error (bool): If True, raise an error if no package is found.
Returns:
`Package` object, or None if no package is found.
"""
it = iter_packages(name, range_=range_, paths=paths)
try:
return max(it, key=lambda x: x.version)
except ValueError: # empty sequence
if error:
raise PackageFamilyNotFoundError("No such package family %r" % name)
return None
def _get_families(name, paths=None):
entries = []
for path in (paths or config.packages_path):
repo = package_repository_manager.get_repository(path)
family_resource = repo.get_package_family(name)
if family_resource:
entries.append((repo, family_resource))
return entries
| gpl-3.0 |
Shaswat27/scipy | scipy/optimize/tests/test__differential_evolution.py | 1 | 17376 | """
Unit tests for the differential global minimization algorithm.
"""
from scipy.optimize import _differentialevolution
from scipy.optimize._differentialevolution import DifferentialEvolutionSolver
from scipy.optimize import differential_evolution
import numpy as np
from scipy.optimize import rosen
from numpy.testing import (assert_equal, TestCase, assert_allclose,
run_module_suite, assert_almost_equal,
assert_string_equal, assert_raises, assert_)
class TestDifferentialEvolutionSolver(TestCase):
def setUp(self):
self.old_seterr = np.seterr(invalid='raise')
self.limits = np.array([[0., 0.],
[2., 2.]])
self.bounds = [(0., 2.), (0., 2.)]
self.dummy_solver = DifferentialEvolutionSolver(self.quadratic,
[(0, 100)])
# dummy_solver2 will be used to test mutation strategies
self.dummy_solver2 = DifferentialEvolutionSolver(self.quadratic,
[(0, 1)],
popsize=7,
mutation=0.5)
# create a population that's only 7 members long
# [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]
population = np.atleast_2d(np.arange(0.1, 0.8, 0.1)).T
self.dummy_solver2.population = population
def tearDown(self):
np.seterr(**self.old_seterr)
def quadratic(self, x):
return x[0]**2
def test__strategy_resolves(self):
# test that the correct mutation function is resolved by
# different requested strategy arguments
solver = DifferentialEvolutionSolver(rosen,
self.bounds,
strategy='best1exp')
assert_equal(solver.strategy, 'best1exp')
assert_equal(solver.mutation_func.__name__, '_best1')
solver = DifferentialEvolutionSolver(rosen,
self.bounds,
strategy='best1bin')
assert_equal(solver.strategy, 'best1bin')
assert_equal(solver.mutation_func.__name__, '_best1')
solver = DifferentialEvolutionSolver(rosen,
self.bounds,
strategy='rand1bin')
assert_equal(solver.strategy, 'rand1bin')
assert_equal(solver.mutation_func.__name__, '_rand1')
solver = DifferentialEvolutionSolver(rosen,
self.bounds,
strategy='rand1exp')
assert_equal(solver.strategy, 'rand1exp')
assert_equal(solver.mutation_func.__name__, '_rand1')
solver = DifferentialEvolutionSolver(rosen,
self.bounds,
strategy='rand2exp')
assert_equal(solver.strategy, 'rand2exp')
assert_equal(solver.mutation_func.__name__, '_rand2')
solver = DifferentialEvolutionSolver(rosen,
self.bounds,
strategy='best2bin')
assert_equal(solver.strategy, 'best2bin')
assert_equal(solver.mutation_func.__name__, '_best2')
solver = DifferentialEvolutionSolver(rosen,
self.bounds,
strategy='rand2bin')
assert_equal(solver.strategy, 'rand2bin')
assert_equal(solver.mutation_func.__name__, '_rand2')
solver = DifferentialEvolutionSolver(rosen,
self.bounds,
strategy='rand2exp')
assert_equal(solver.strategy, 'rand2exp')
assert_equal(solver.mutation_func.__name__, '_rand2')
solver = DifferentialEvolutionSolver(rosen,
self.bounds,
strategy='randtobest1bin')
assert_equal(solver.strategy, 'randtobest1bin')
assert_equal(solver.mutation_func.__name__, '_randtobest1')
solver = DifferentialEvolutionSolver(rosen,
self.bounds,
strategy='randtobest1exp')
assert_equal(solver.strategy, 'randtobest1exp')
assert_equal(solver.mutation_func.__name__, '_randtobest1')
def test__mutate1(self):
# strategies */1/*, i.e. rand/1/bin, best/1/exp, etc.
result = np.array([0.05])
trial = self.dummy_solver2._best1((2, 3, 4, 5, 6))
assert_allclose(trial, result)
result = np.array([0.25])
trial = self.dummy_solver2._rand1((2, 3, 4, 5, 6))
assert_allclose(trial, result)
def test__mutate2(self):
# strategies */2/*, i.e. rand/2/bin, best/2/exp, etc.
# [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]
result = np.array([-0.1])
trial = self.dummy_solver2._best2((2, 3, 4, 5, 6))
assert_allclose(trial, result)
result = np.array([0.1])
trial = self.dummy_solver2._rand2((2, 3, 4, 5, 6))
assert_allclose(trial, result)
def test__randtobest1(self):
# strategies randtobest/1/*
result = np.array([0.1])
trial = self.dummy_solver2._randtobest1(1, (2, 3, 4, 5, 6))
assert_allclose(trial, result)
def test_can_init_with_dithering(self):
mutation = (0.5, 1)
solver = DifferentialEvolutionSolver(self.quadratic,
self.bounds,
mutation=mutation)
self.assertEqual(solver.dither, list(mutation))
def test_invalid_mutation_values_arent_accepted(self):
func = rosen
mutation = (0.5, 3)
self.assertRaises(ValueError,
DifferentialEvolutionSolver,
func,
self.bounds,
mutation=mutation)
mutation = (-1, 1)
self.assertRaises(ValueError,
DifferentialEvolutionSolver,
func,
self.bounds,
mutation=mutation)
mutation = (0.1, np.nan)
self.assertRaises(ValueError,
DifferentialEvolutionSolver,
func,
self.bounds,
mutation=mutation)
mutation = 0.5
solver = DifferentialEvolutionSolver(func,
self.bounds,
mutation=mutation)
assert_equal(0.5, solver.scale)
assert_equal(None, solver.dither)
def test__scale_parameters(self):
trial = np.array([0.3])
assert_equal(30, self.dummy_solver._scale_parameters(trial))
# it should also work with the limits reversed
self.dummy_solver.limits = np.array([[100], [0.]])
assert_equal(30, self.dummy_solver._scale_parameters(trial))
def test__unscale_parameters(self):
trial = np.array([30])
assert_equal(0.3, self.dummy_solver._unscale_parameters(trial))
# it should also work with the limits reversed
self.dummy_solver.limits = np.array([[100], [0.]])
assert_equal(0.3, self.dummy_solver._unscale_parameters(trial))
def test__ensure_constraint(self):
trial = np.array([1.1, -100, 2., 300., -0.00001])
self.dummy_solver._ensure_constraint(trial)
assert_equal(np.all(trial <= 1), True)
def test_differential_evolution(self):
# test that the Jmin of DifferentialEvolutionSolver
# is the same as the function evaluation
solver = DifferentialEvolutionSolver(self.quadratic, [(-2, 2)])
result = solver.solve()
assert_almost_equal(result.fun, self.quadratic(result.x))
def test_best_solution_retrieval(self):
# test that the getter property method for the best solution works.
solver = DifferentialEvolutionSolver(self.quadratic, [(-2, 2)])
result = solver.solve()
assert_equal(result.x, solver.x)
def test_callback_terminates(self):
# test that if the callback returns true, then the minimization halts
bounds = [(0, 2), (0, 2)]
def callback(param, convergence=0.):
return True
result = differential_evolution(rosen, bounds, callback=callback)
assert_string_equal(result.message,
'callback function requested stop early '
'by returning True')
def test_args_tuple_is_passed(self):
# test that the args tuple is passed to the cost function properly.
bounds = [(-10, 10)]
args = (1., 2., 3.)
def quadratic(x, *args):
if type(args) != tuple:
raise ValueError('args should be a tuple')
return args[0] + args[1] * x + args[2] * x**2.
result = differential_evolution(quadratic,
bounds,
args=args,
polish=True)
assert_almost_equal(result.fun, 2 / 3.)
def test_init_with_invalid_strategy(self):
# test that passing an invalid strategy raises ValueError
func = rosen
bounds = [(-3, 3)]
self.assertRaises(ValueError,
differential_evolution,
func,
bounds,
strategy='abc')
def test_bounds_checking(self):
# test that the bounds checking works
func = rosen
bounds = [(-3, None)]
self.assertRaises(ValueError,
differential_evolution,
func,
bounds)
bounds = [(-3)]
self.assertRaises(ValueError,
differential_evolution,
func,
bounds)
bounds = [(-3, 3), (3, 4, 5)]
self.assertRaises(ValueError,
differential_evolution,
func,
bounds)
def test_select_samples(self):
# select_samples should return 5 separate random numbers.
limits = np.arange(12., dtype='float64').reshape(2, 6)
bounds = list(zip(limits[0, :], limits[1, :]))
solver = DifferentialEvolutionSolver(None, bounds, popsize=1)
candidate = 0
r1, r2, r3, r4, r5 = solver._select_samples(candidate, 5)
assert_equal(
len(np.unique(np.array([candidate, r1, r2, r3, r4, r5]))), 6)
def test_maxiter_stops_solve(self):
# test that if the maximum number of iterations is exceeded
# the solver stops.
solver = DifferentialEvolutionSolver(rosen, self.bounds, maxiter=1)
result = solver.solve()
assert_equal(result.success, False)
assert_equal(result.message,
'Maximum number of iterations has been exceeded.')
def test_maxfun_stops_solve(self):
# test that if the maximum number of function evaluations is exceeded
# during initialisation the solver stops
solver = DifferentialEvolutionSolver(rosen, self.bounds, maxfun=1,
polish=False)
result = solver.solve()
assert_equal(result.nfev, 2)
assert_equal(result.success, False)
assert_equal(result.message,
'Maximum number of function evaluations has '
'been exceeded.')
# test that if the maximum number of function evaluations is exceeded
# during the actual minimisation, then the solver stops.
# Have to turn polishing off, as this will still occur even if maxfun
# is reached. For popsize=5 and len(bounds)=2, then there are only 10
# function evaluations during initialisation.
solver = DifferentialEvolutionSolver(rosen,
self.bounds,
popsize=5,
polish=False,
maxfun=40)
result = solver.solve()
assert_equal(result.nfev, 41)
assert_equal(result.success, False)
assert_equal(result.message,
'Maximum number of function evaluations has '
'been exceeded.')
def test_quadratic(self):
# test the quadratic function from object
solver = DifferentialEvolutionSolver(self.quadratic,
[(-100, 100)],
tol=0.02)
solver.solve()
assert_equal(np.argmin(solver.population_energies), 0)
def test_quadratic_from_diff_ev(self):
# test the quadratic function from differential_evolution function
differential_evolution(self.quadratic,
[(-100, 100)],
tol=0.02)
def test_seed_gives_repeatability(self):
result = differential_evolution(self.quadratic,
[(-100, 100)],
polish=False,
seed=1,
tol=0.5)
result2 = differential_evolution(self.quadratic,
[(-100, 100)],
polish=False,
seed=1,
tol=0.5)
assert_equal(result.x, result2.x)
def test_exp_runs(self):
# test whether exponential mutation loop runs
solver = DifferentialEvolutionSolver(rosen,
self.bounds,
strategy='best1exp',
maxiter=1)
solver.solve()
def test__make_random_gen(self):
# If seed is None, return the RandomState singleton used by np.random.
# If seed is an int, return a new RandomState instance seeded with seed.
# If seed is already a RandomState instance, return it.
# Otherwise raise ValueError.
rsi = _differentialevolution._make_random_gen(1)
assert_equal(type(rsi), np.random.RandomState)
rsi = _differentialevolution._make_random_gen(rsi)
assert_equal(type(rsi), np.random.RandomState)
rsi = _differentialevolution._make_random_gen(None)
assert_equal(type(rsi), np.random.RandomState)
self.assertRaises(
ValueError, _differentialevolution._make_random_gen, 'a')
def test_gh_4511_regression(self):
# This modification of the differential evolution docstring example
# uses a custom popsize that had triggered an off-by-one error.
# Because we do not care about solving the optimization problem in
# this test, we use maxiter=1 to reduce the testing time.
bounds = [(-5, 5), (-5, 5)]
result = differential_evolution(rosen, bounds, popsize=1815, maxiter=1)
def test_calculate_population_energies(self):
# if popsize is 2 then the overall generation has size (4,)
solver = DifferentialEvolutionSolver(rosen, self.bounds, popsize=2)
solver._calculate_population_energies()
assert_equal(np.argmin(solver.population_energies), 0)
# initial calculation of the energies should require 4 nfev.
assert_equal(solver._nfev, 4)
def test_iteration(self):
# test that DifferentialEvolutionSolver is iterable
# if popsize is 2 then the overall generation has size (4,)
solver = DifferentialEvolutionSolver(rosen, self.bounds, popsize=2,
maxfun=8)
x, fun = next(solver)
assert_equal(np.size(x, 0), 2)
# 4 nfev are required for initial calculation of energies, 4 nfev are
# required for the evolution of the 4 population members.
assert_equal(solver._nfev, 8)
# the next generation should halt because it exceeds maxfun
assert_raises(StopIteration, next, solver)
# check a proper minimisation can be done by an iterable solver
solver = DifferentialEvolutionSolver(rosen, self.bounds)
for i, soln in enumerate(solver):
x_current, fun_current = soln
# need to have this otherwise the solver would never stop.
if i == 1000:
break
assert_almost_equal(fun_current, 0)
def test_convergence(self):
solver = DifferentialEvolutionSolver(rosen, self.bounds, tol=0.2,
polish=False)
solver.solve()
assert_(solver.convergence < 0.2)
if __name__ == '__main__':
run_module_suite()
| bsd-3-clause |
GheRivero/ansible | lib/ansible/parsing/splitter.py | 49 | 10682 | # (c) 2014 James Cammarata, <[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/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import codecs
import re
from ansible.errors import AnsibleParserError
from ansible.module_utils._text import to_text
from ansible.parsing.quoting import unquote
# Decode escapes adapted from rspeer's answer here:
# http://stackoverflow.com/questions/4020539/process-escape-sequences-in-a-string-in-python
_HEXCHAR = '[a-fA-F0-9]'
_ESCAPE_SEQUENCE_RE = re.compile(r'''
( \\U{0} # 8-digit hex escapes
| \\u{1} # 4-digit hex escapes
| \\x{2} # 2-digit hex escapes
| \\N\{{[^}}]+\}} # Unicode characters by name
| \\[\\'"abfnrtv] # Single-character escapes
)'''.format(_HEXCHAR * 8, _HEXCHAR * 4, _HEXCHAR * 2), re.UNICODE | re.VERBOSE)
def _decode_escapes(s):
def decode_match(match):
return codecs.decode(match.group(0), 'unicode-escape')
return _ESCAPE_SEQUENCE_RE.sub(decode_match, s)
def parse_kv(args, check_raw=False):
'''
Convert a string of key/value items to a dict. If any free-form params
are found and the check_raw option is set to True, they will be added
to a new parameter called '_raw_params'. If check_raw is not enabled,
they will simply be ignored.
'''
args = to_text(args, nonstring='passthru')
options = {}
if args is not None:
try:
vargs = split_args(args)
except ValueError as ve:
if 'no closing quotation' in str(ve).lower():
raise AnsibleParserError("error parsing argument string, try quoting the entire line.", orig_exc=ve)
else:
raise
raw_params = []
for orig_x in vargs:
x = _decode_escapes(orig_x)
if "=" in x:
pos = 0
try:
while True:
pos = x.index('=', pos + 1)
if pos > 0 and x[pos - 1] != '\\':
break
except ValueError:
# ran out of string, but we must have some escaped equals,
# so replace those and append this to the list of raw params
raw_params.append(x.replace('\\=', '='))
continue
k = x[:pos]
v = x[pos + 1:]
# FIXME: make the retrieval of this list of shell/command
# options a function, so the list is centralized
if check_raw and k not in ('creates', 'removes', 'chdir', 'executable', 'warn'):
raw_params.append(orig_x)
else:
options[k.strip()] = unquote(v.strip())
else:
raw_params.append(orig_x)
# recombine the free-form params, if any were found, and assign
# them to a special option for use later by the shell/command module
if len(raw_params) > 0:
options[u'_raw_params'] = ' '.join(raw_params)
return options
def _get_quote_state(token, quote_char):
'''
the goal of this block is to determine if the quoted string
is unterminated in which case it needs to be put back together
'''
# the char before the current one, used to see if
# the current character is escaped
prev_char = None
for idx, cur_char in enumerate(token):
if idx > 0:
prev_char = token[idx - 1]
if cur_char in '"\'' and prev_char != '\\':
if quote_char:
if cur_char == quote_char:
quote_char = None
else:
quote_char = cur_char
return quote_char
def _count_jinja2_blocks(token, cur_depth, open_token, close_token):
'''
this function counts the number of opening/closing blocks for a
given opening/closing type and adjusts the current depth for that
block based on the difference
'''
num_open = token.count(open_token)
num_close = token.count(close_token)
if num_open != num_close:
cur_depth += (num_open - num_close)
if cur_depth < 0:
cur_depth = 0
return cur_depth
def split_args(args):
'''
Splits args on whitespace, but intelligently reassembles
those that may have been split over a jinja2 block or quotes.
When used in a remote module, we won't ever have to be concerned about
jinja2 blocks, however this function is/will be used in the
core portions as well before the args are templated.
example input: a=b c="foo bar"
example output: ['a=b', 'c="foo bar"']
Basically this is a variation shlex that has some more intelligence for
how Ansible needs to use it.
'''
# the list of params parsed out of the arg string
# this is going to be the result value when we are done
params = []
# Initial split on white space
args = args.strip()
items = args.strip().split('\n')
# iterate over the tokens, and reassemble any that may have been
# split on a space inside a jinja2 block.
# ex if tokens are "{{", "foo", "}}" these go together
# These variables are used
# to keep track of the state of the parsing, since blocks and quotes
# may be nested within each other.
quote_char = None
inside_quotes = False
print_depth = 0 # used to count nested jinja2 {{ }} blocks
block_depth = 0 # used to count nested jinja2 {% %} blocks
comment_depth = 0 # used to count nested jinja2 {# #} blocks
# now we loop over each split chunk, coalescing tokens if the white space
# split occurred within quotes or a jinja2 block of some kind
for (itemidx, item) in enumerate(items):
# we split on spaces and newlines separately, so that we
# can tell which character we split on for reassembly
# inside quotation characters
tokens = item.strip().split(' ')
line_continuation = False
for (idx, token) in enumerate(tokens):
# if we hit a line continuation character, but
# we're not inside quotes, ignore it and continue
# on to the next token while setting a flag
if token == '\\' and not inside_quotes:
line_continuation = True
continue
# store the previous quoting state for checking later
was_inside_quotes = inside_quotes
quote_char = _get_quote_state(token, quote_char)
inside_quotes = quote_char is not None
# multiple conditions may append a token to the list of params,
# so we keep track with this flag to make sure it only happens once
# append means add to the end of the list, don't append means concatenate
# it to the end of the last token
appended = False
# if we're inside quotes now, but weren't before, append the token
# to the end of the list, since we'll tack on more to it later
# otherwise, if we're inside any jinja2 block, inside quotes, or we were
# inside quotes (but aren't now) concat this token to the last param
if inside_quotes and not was_inside_quotes and not(print_depth or block_depth or comment_depth):
params.append(token)
appended = True
elif print_depth or block_depth or comment_depth or inside_quotes or was_inside_quotes:
if idx == 0 and was_inside_quotes:
params[-1] = "%s%s" % (params[-1], token)
elif len(tokens) > 1:
spacer = ''
if idx > 0:
spacer = ' '
params[-1] = "%s%s%s" % (params[-1], spacer, token)
else:
params[-1] = "%s\n%s" % (params[-1], token)
appended = True
# if the number of paired block tags is not the same, the depth has changed, so we calculate that here
# and may append the current token to the params (if we haven't previously done so)
prev_print_depth = print_depth
print_depth = _count_jinja2_blocks(token, print_depth, "{{", "}}")
if print_depth != prev_print_depth and not appended:
params.append(token)
appended = True
prev_block_depth = block_depth
block_depth = _count_jinja2_blocks(token, block_depth, "{%", "%}")
if block_depth != prev_block_depth and not appended:
params.append(token)
appended = True
prev_comment_depth = comment_depth
comment_depth = _count_jinja2_blocks(token, comment_depth, "{#", "#}")
if comment_depth != prev_comment_depth and not appended:
params.append(token)
appended = True
# finally, if we're at zero depth for all blocks and not inside quotes, and have not
# yet appended anything to the list of params, we do so now
if not (print_depth or block_depth or comment_depth) and not inside_quotes and not appended and token != '':
params.append(token)
# if this was the last token in the list, and we have more than
# one item (meaning we split on newlines), add a newline back here
# to preserve the original structure
if len(items) > 1 and itemidx != len(items) - 1 and not line_continuation:
params[-1] += '\n'
# always clear the line continuation flag
line_continuation = False
# If we're done and things are not at zero depth or we're still inside quotes,
# raise an error to indicate that the args were unbalanced
if print_depth or block_depth or comment_depth or inside_quotes:
raise AnsibleParserError(u"failed at splitting arguments, either an unbalanced jinja2 block or quotes: {0}".format(args))
return params
| gpl-3.0 |
seeminglee/pyglet64 | experimental/console.py | 29 | 3991 | #!/usr/bin/env python
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import code
import sys
import traceback
import pyglet.event
import pyglet.text
from pyglet.window import key
from pyglet.gl import *
class Console(object):
def __init__(self, width, height, globals=None, locals=None):
self.font = pyglet.text.default_font_factory.get_font('bitstream vera sans mono', 12)
self.lines = []
self.buffer = ''
self.pre_buffer = ''
self.prompt = '>>> '
self.prompt2 = '... '
self.globals = globals
self.locals = locals
self.write_pending = ''
self.width, self.height = (width, height)
self.max_lines = self.height / self.font.glyph_height - 1
self.write('pyglet command console\n')
self.write('Version %s\n' % __version__)
def on_key_press(self, symbol, modifiers):
# TODO cursor control / line editing
if modifiers & key.key.MOD_CTRL and symbol == key.key.C:
self.buffer = ''
self.pre_buffer = ''
return
if symbol == key.key.ENTER:
self.write('%s%s\n' % (self.get_prompt(), self.buffer))
self.execute(self.pre_buffer + self.buffer)
self.buffer = ''
return
if symbol == key.key.BACKSPACE:
self.buffer = self.buffer[:-1]
return
return EVENT_UNHANDLED
def on_text(self, text):
if ' ' <= text <= '~':
self.buffer += text
if 0xae <= ord(text) <= 0xff:
self.buffer += text
def write(self, text):
if self.write_pending:
text = self.write_pending + text
self.write_pending = ''
if type(text) in (str, unicode):
text = text.split('\n')
if text[-1] != '':
self.write_pending = text[-1]
del text[-1]
self.lines = [pyglet.text.layout_text(line.strip(), font=self.font)
for line in text] + self.lines
if len(self.lines) > self.max_lines:
del self.lines[-1]
def execute(self, input):
old_stderr, old_stdout = sys.stderr, sys.stdout
sys.stderr = sys.stdout = self
try:
c = code.compile_command(input, '<pyglet console>')
if c is None:
self.pre_buffer = '%s\n' % input
else:
self.pre_buffer = ''
result = eval(c, self.globals, self.locals)
if result is not None:
self.write('%r\n' % result)
except:
traceback.print_exc()
self.pre_buffer = ''
sys.stderr = old_stderr
sys.stdout = old_stdout
def get_prompt(self):
if self.pre_buffer:
return self.prompt2
return self.prompt
__last = None
def draw(self):
pyglet.text.begin()
glPushMatrix()
glTranslatef(0, self.height, 0)
for line in self.lines[::-1]:
line.draw()
glTranslatef(0, -self.font.glyph_height, 0)
line = self.get_prompt() + self.buffer
if self.__last is None or line != self.__last[0]:
self.__last = (line, pyglet.text.layout_text(line.strip(),
font=self.font))
self.__last[1].draw()
glPopMatrix()
pyglet.text.end()
if __name__ == '__main__':
from pyglet.window import *
from pyglet.window.event import *
from pyglet import clock
w1 = Window(width=600, height=400)
console = Console(w1.width, w1.height)
w1.push_handlers(console)
c = clock.Clock()
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0, w1.width, 0, w1.height, -1, 1)
glEnable(GL_COLOR_MATERIAL)
glMatrixMode(GL_MODELVIEW)
glClearColor(1, 1, 1, 1)
while not w1.has_exit:
c.set_fps(60)
w1.dispatch_events()
glClear(GL_COLOR_BUFFER_BIT)
console.draw()
w1.flip()
| bsd-3-clause |
javier-ruiz-b/docker-rasppi-images | raspberry-google-home/env/lib/python3.7/site-packages/rsa/__init__.py | 1 | 1542 | # Copyright 2011 Sybren A. Stüvel <[email protected]>
#
# 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
#
# https://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.
"""RSA module
Module for calculating large primes, and RSA encryption, decryption, signing
and verification. Includes generating public and private keys.
WARNING: this implementation does not use compression of the cleartext input to
prevent repetitions, or other common security improvements. Use with care.
"""
from rsa.key import newkeys, PrivateKey, PublicKey
from rsa.pkcs1 import encrypt, decrypt, sign, verify, DecryptionError, \
VerificationError, find_signature_hash, sign_hash, compute_hash
__author__ = "Sybren Stuvel, Barry Mead and Yesudeep Mangalapilly"
__date__ = '2020-06-12'
__version__ = '4.6'
# Do doctest if we're run directly
if __name__ == "__main__":
import doctest
doctest.testmod()
__all__ = ["newkeys", "encrypt", "decrypt", "sign", "verify", 'PublicKey',
'PrivateKey', 'DecryptionError', 'VerificationError',
'find_signature_hash', 'compute_hash', 'sign_hash']
| apache-2.0 |
BitWriters/Zenith_project | zango/lib/python3.5/site-packages/django/core/mail/__init__.py | 230 | 4701 | """
Tools for sending email.
"""
from __future__ import unicode_literals
from django.conf import settings
from django.utils.module_loading import import_string
# Imported for backwards compatibility, and for the sake
# of a cleaner namespace. These symbols used to be in
# django/core/mail.py before the introduction of email
# backends and the subsequent reorganization (See #10355)
from django.core.mail.utils import CachedDnsName, DNS_NAME
from django.core.mail.message import (
EmailMessage, EmailMultiAlternatives,
SafeMIMEText, SafeMIMEMultipart,
DEFAULT_ATTACHMENT_MIME_TYPE, make_msgid,
BadHeaderError, forbid_multi_line_headers)
__all__ = [
'CachedDnsName', 'DNS_NAME', 'EmailMessage', 'EmailMultiAlternatives',
'SafeMIMEText', 'SafeMIMEMultipart', 'DEFAULT_ATTACHMENT_MIME_TYPE',
'make_msgid', 'BadHeaderError', 'forbid_multi_line_headers',
'get_connection', 'send_mail', 'send_mass_mail', 'mail_admins',
'mail_managers',
]
def get_connection(backend=None, fail_silently=False, **kwds):
"""Load an email backend and return an instance of it.
If backend is None (default) settings.EMAIL_BACKEND is used.
Both fail_silently and other keyword arguments are used in the
constructor of the backend.
"""
klass = import_string(backend or settings.EMAIL_BACKEND)
return klass(fail_silently=fail_silently, **kwds)
def send_mail(subject, message, from_email, recipient_list,
fail_silently=False, auth_user=None, auth_password=None,
connection=None, html_message=None):
"""
Easy wrapper for sending a single message to a recipient list. All members
of the recipient list will see the other recipients in the 'To' field.
If auth_user is None, the EMAIL_HOST_USER setting is used.
If auth_password is None, the EMAIL_HOST_PASSWORD setting is used.
Note: The API for this method is frozen. New code wanting to extend the
functionality should use the EmailMessage class directly.
"""
connection = connection or get_connection(username=auth_user,
password=auth_password,
fail_silently=fail_silently)
mail = EmailMultiAlternatives(subject, message, from_email, recipient_list,
connection=connection)
if html_message:
mail.attach_alternative(html_message, 'text/html')
return mail.send()
def send_mass_mail(datatuple, fail_silently=False, auth_user=None,
auth_password=None, connection=None):
"""
Given a datatuple of (subject, message, from_email, recipient_list), sends
each message to each recipient list. Returns the number of emails sent.
If from_email is None, the DEFAULT_FROM_EMAIL setting is used.
If auth_user and auth_password are set, they're used to log in.
If auth_user is None, the EMAIL_HOST_USER setting is used.
If auth_password is None, the EMAIL_HOST_PASSWORD setting is used.
Note: The API for this method is frozen. New code wanting to extend the
functionality should use the EmailMessage class directly.
"""
connection = connection or get_connection(username=auth_user,
password=auth_password,
fail_silently=fail_silently)
messages = [EmailMessage(subject, message, sender, recipient,
connection=connection)
for subject, message, sender, recipient in datatuple]
return connection.send_messages(messages)
def mail_admins(subject, message, fail_silently=False, connection=None,
html_message=None):
"""Sends a message to the admins, as defined by the ADMINS setting."""
if not settings.ADMINS:
return
mail = EmailMultiAlternatives('%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject),
message, settings.SERVER_EMAIL, [a[1] for a in settings.ADMINS],
connection=connection)
if html_message:
mail.attach_alternative(html_message, 'text/html')
mail.send(fail_silently=fail_silently)
def mail_managers(subject, message, fail_silently=False, connection=None,
html_message=None):
"""Sends a message to the managers, as defined by the MANAGERS setting."""
if not settings.MANAGERS:
return
mail = EmailMultiAlternatives('%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject),
message, settings.SERVER_EMAIL, [a[1] for a in settings.MANAGERS],
connection=connection)
if html_message:
mail.attach_alternative(html_message, 'text/html')
mail.send(fail_silently=fail_silently)
| mit |
infoxchange/lettuce | tests/integration/lib/Django-1.3/django/template/__init__.py | 561 | 3247 | """
This is the Django template system.
How it works:
The Lexer.tokenize() function converts a template string (i.e., a string containing
markup with custom template tags) to tokens, which can be either plain text
(TOKEN_TEXT), variables (TOKEN_VAR) or block statements (TOKEN_BLOCK).
The Parser() class takes a list of tokens in its constructor, and its parse()
method returns a compiled template -- which is, under the hood, a list of
Node objects.
Each Node is responsible for creating some sort of output -- e.g. simple text
(TextNode), variable values in a given context (VariableNode), results of basic
logic (IfNode), results of looping (ForNode), or anything else. The core Node
types are TextNode, VariableNode, IfNode and ForNode, but plugin modules can
define their own custom node types.
Each Node has a render() method, which takes a Context and returns a string of
the rendered node. For example, the render() method of a Variable Node returns
the variable's value as a string. The render() method of an IfNode returns the
rendered output of whatever was inside the loop, recursively.
The Template class is a convenient wrapper that takes care of template
compilation and rendering.
Usage:
The only thing you should ever use directly in this file is the Template class.
Create a compiled template object with a template_string, then call render()
with a context. In the compilation stage, the TemplateSyntaxError exception
will be raised if the template doesn't have proper syntax.
Sample code:
>>> from django import template
>>> s = u'<html>{% if test %}<h1>{{ varvalue }}</h1>{% endif %}</html>'
>>> t = template.Template(s)
(t is now a compiled template, and its render() method can be called multiple
times with multiple contexts)
>>> c = template.Context({'test':True, 'varvalue': 'Hello'})
>>> t.render(c)
u'<html><h1>Hello</h1></html>'
>>> c = template.Context({'test':False, 'varvalue': 'Hello'})
>>> t.render(c)
u'<html></html>'
"""
# Template lexing symbols
from django.template.base import (ALLOWED_VARIABLE_CHARS, BLOCK_TAG_END,
BLOCK_TAG_START, COMMENT_TAG_END, COMMENT_TAG_START,
FILTER_ARGUMENT_SEPARATOR, FILTER_SEPARATOR, SINGLE_BRACE_END,
SINGLE_BRACE_START, TOKEN_BLOCK, TOKEN_COMMENT, TOKEN_TEXT, TOKEN_VAR,
TRANSLATOR_COMMENT_MARK, UNKNOWN_SOURCE, VARIABLE_ATTRIBUTE_SEPARATOR,
VARIABLE_TAG_END, VARIABLE_TAG_START, filter_re, tag_re)
# Exceptions
from django.template.base import (ContextPopException, InvalidTemplateLibrary,
TemplateDoesNotExist, TemplateEncodingError, TemplateSyntaxError,
VariableDoesNotExist)
# Template parts
from django.template.base import (Context, FilterExpression, Lexer, Node,
NodeList, Parser, RequestContext, Origin, StringOrigin, Template,
TextNode, Token, TokenParser, Variable, VariableNode, constant_string,
filter_raw_string)
# Compiling templates
from django.template.base import (compile_string, resolve_variable,
unescape_string_literal, generic_tag_compiler)
# Library management
from django.template.base import (Library, add_to_builtins, builtins,
get_library, get_templatetags_modules, get_text_list, import_library,
libraries)
__all__ = ('Template', 'Context', 'RequestContext', 'compile_string')
| gpl-3.0 |
sdphome/UHF_Reader | rfs/rootfs/usr/lib/python2.7/encodings/mac_iceland.py | 593 | 13754 | """ Python Character Mapping Codec mac_iceland generated from 'MAPPINGS/VENDORS/APPLE/ICELAND.TXT' with gencodec.py.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_table)
def decode(self,input,errors='strict'):
return codecs.charmap_decode(input,errors,decoding_table)
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input, final=False):
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
### encodings module API
def getregentry():
return codecs.CodecInfo(
name='mac-iceland',
encode=Codec().encode,
decode=Codec().decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamreader=StreamReader,
streamwriter=StreamWriter,
)
### Decoding Table
decoding_table = (
u'\x00' # 0x00 -> CONTROL CHARACTER
u'\x01' # 0x01 -> CONTROL CHARACTER
u'\x02' # 0x02 -> CONTROL CHARACTER
u'\x03' # 0x03 -> CONTROL CHARACTER
u'\x04' # 0x04 -> CONTROL CHARACTER
u'\x05' # 0x05 -> CONTROL CHARACTER
u'\x06' # 0x06 -> CONTROL CHARACTER
u'\x07' # 0x07 -> CONTROL CHARACTER
u'\x08' # 0x08 -> CONTROL CHARACTER
u'\t' # 0x09 -> CONTROL CHARACTER
u'\n' # 0x0A -> CONTROL CHARACTER
u'\x0b' # 0x0B -> CONTROL CHARACTER
u'\x0c' # 0x0C -> CONTROL CHARACTER
u'\r' # 0x0D -> CONTROL CHARACTER
u'\x0e' # 0x0E -> CONTROL CHARACTER
u'\x0f' # 0x0F -> CONTROL CHARACTER
u'\x10' # 0x10 -> CONTROL CHARACTER
u'\x11' # 0x11 -> CONTROL CHARACTER
u'\x12' # 0x12 -> CONTROL CHARACTER
u'\x13' # 0x13 -> CONTROL CHARACTER
u'\x14' # 0x14 -> CONTROL CHARACTER
u'\x15' # 0x15 -> CONTROL CHARACTER
u'\x16' # 0x16 -> CONTROL CHARACTER
u'\x17' # 0x17 -> CONTROL CHARACTER
u'\x18' # 0x18 -> CONTROL CHARACTER
u'\x19' # 0x19 -> CONTROL CHARACTER
u'\x1a' # 0x1A -> CONTROL CHARACTER
u'\x1b' # 0x1B -> CONTROL CHARACTER
u'\x1c' # 0x1C -> CONTROL CHARACTER
u'\x1d' # 0x1D -> CONTROL CHARACTER
u'\x1e' # 0x1E -> CONTROL CHARACTER
u'\x1f' # 0x1F -> CONTROL CHARACTER
u' ' # 0x20 -> SPACE
u'!' # 0x21 -> EXCLAMATION MARK
u'"' # 0x22 -> QUOTATION MARK
u'#' # 0x23 -> NUMBER SIGN
u'$' # 0x24 -> DOLLAR SIGN
u'%' # 0x25 -> PERCENT SIGN
u'&' # 0x26 -> AMPERSAND
u"'" # 0x27 -> APOSTROPHE
u'(' # 0x28 -> LEFT PARENTHESIS
u')' # 0x29 -> RIGHT PARENTHESIS
u'*' # 0x2A -> ASTERISK
u'+' # 0x2B -> PLUS SIGN
u',' # 0x2C -> COMMA
u'-' # 0x2D -> HYPHEN-MINUS
u'.' # 0x2E -> FULL STOP
u'/' # 0x2F -> SOLIDUS
u'0' # 0x30 -> DIGIT ZERO
u'1' # 0x31 -> DIGIT ONE
u'2' # 0x32 -> DIGIT TWO
u'3' # 0x33 -> DIGIT THREE
u'4' # 0x34 -> DIGIT FOUR
u'5' # 0x35 -> DIGIT FIVE
u'6' # 0x36 -> DIGIT SIX
u'7' # 0x37 -> DIGIT SEVEN
u'8' # 0x38 -> DIGIT EIGHT
u'9' # 0x39 -> DIGIT NINE
u':' # 0x3A -> COLON
u';' # 0x3B -> SEMICOLON
u'<' # 0x3C -> LESS-THAN SIGN
u'=' # 0x3D -> EQUALS SIGN
u'>' # 0x3E -> GREATER-THAN SIGN
u'?' # 0x3F -> QUESTION MARK
u'@' # 0x40 -> COMMERCIAL AT
u'A' # 0x41 -> LATIN CAPITAL LETTER A
u'B' # 0x42 -> LATIN CAPITAL LETTER B
u'C' # 0x43 -> LATIN CAPITAL LETTER C
u'D' # 0x44 -> LATIN CAPITAL LETTER D
u'E' # 0x45 -> LATIN CAPITAL LETTER E
u'F' # 0x46 -> LATIN CAPITAL LETTER F
u'G' # 0x47 -> LATIN CAPITAL LETTER G
u'H' # 0x48 -> LATIN CAPITAL LETTER H
u'I' # 0x49 -> LATIN CAPITAL LETTER I
u'J' # 0x4A -> LATIN CAPITAL LETTER J
u'K' # 0x4B -> LATIN CAPITAL LETTER K
u'L' # 0x4C -> LATIN CAPITAL LETTER L
u'M' # 0x4D -> LATIN CAPITAL LETTER M
u'N' # 0x4E -> LATIN CAPITAL LETTER N
u'O' # 0x4F -> LATIN CAPITAL LETTER O
u'P' # 0x50 -> LATIN CAPITAL LETTER P
u'Q' # 0x51 -> LATIN CAPITAL LETTER Q
u'R' # 0x52 -> LATIN CAPITAL LETTER R
u'S' # 0x53 -> LATIN CAPITAL LETTER S
u'T' # 0x54 -> LATIN CAPITAL LETTER T
u'U' # 0x55 -> LATIN CAPITAL LETTER U
u'V' # 0x56 -> LATIN CAPITAL LETTER V
u'W' # 0x57 -> LATIN CAPITAL LETTER W
u'X' # 0x58 -> LATIN CAPITAL LETTER X
u'Y' # 0x59 -> LATIN CAPITAL LETTER Y
u'Z' # 0x5A -> LATIN CAPITAL LETTER Z
u'[' # 0x5B -> LEFT SQUARE BRACKET
u'\\' # 0x5C -> REVERSE SOLIDUS
u']' # 0x5D -> RIGHT SQUARE BRACKET
u'^' # 0x5E -> CIRCUMFLEX ACCENT
u'_' # 0x5F -> LOW LINE
u'`' # 0x60 -> GRAVE ACCENT
u'a' # 0x61 -> LATIN SMALL LETTER A
u'b' # 0x62 -> LATIN SMALL LETTER B
u'c' # 0x63 -> LATIN SMALL LETTER C
u'd' # 0x64 -> LATIN SMALL LETTER D
u'e' # 0x65 -> LATIN SMALL LETTER E
u'f' # 0x66 -> LATIN SMALL LETTER F
u'g' # 0x67 -> LATIN SMALL LETTER G
u'h' # 0x68 -> LATIN SMALL LETTER H
u'i' # 0x69 -> LATIN SMALL LETTER I
u'j' # 0x6A -> LATIN SMALL LETTER J
u'k' # 0x6B -> LATIN SMALL LETTER K
u'l' # 0x6C -> LATIN SMALL LETTER L
u'm' # 0x6D -> LATIN SMALL LETTER M
u'n' # 0x6E -> LATIN SMALL LETTER N
u'o' # 0x6F -> LATIN SMALL LETTER O
u'p' # 0x70 -> LATIN SMALL LETTER P
u'q' # 0x71 -> LATIN SMALL LETTER Q
u'r' # 0x72 -> LATIN SMALL LETTER R
u's' # 0x73 -> LATIN SMALL LETTER S
u't' # 0x74 -> LATIN SMALL LETTER T
u'u' # 0x75 -> LATIN SMALL LETTER U
u'v' # 0x76 -> LATIN SMALL LETTER V
u'w' # 0x77 -> LATIN SMALL LETTER W
u'x' # 0x78 -> LATIN SMALL LETTER X
u'y' # 0x79 -> LATIN SMALL LETTER Y
u'z' # 0x7A -> LATIN SMALL LETTER Z
u'{' # 0x7B -> LEFT CURLY BRACKET
u'|' # 0x7C -> VERTICAL LINE
u'}' # 0x7D -> RIGHT CURLY BRACKET
u'~' # 0x7E -> TILDE
u'\x7f' # 0x7F -> CONTROL CHARACTER
u'\xc4' # 0x80 -> LATIN CAPITAL LETTER A WITH DIAERESIS
u'\xc5' # 0x81 -> LATIN CAPITAL LETTER A WITH RING ABOVE
u'\xc7' # 0x82 -> LATIN CAPITAL LETTER C WITH CEDILLA
u'\xc9' # 0x83 -> LATIN CAPITAL LETTER E WITH ACUTE
u'\xd1' # 0x84 -> LATIN CAPITAL LETTER N WITH TILDE
u'\xd6' # 0x85 -> LATIN CAPITAL LETTER O WITH DIAERESIS
u'\xdc' # 0x86 -> LATIN CAPITAL LETTER U WITH DIAERESIS
u'\xe1' # 0x87 -> LATIN SMALL LETTER A WITH ACUTE
u'\xe0' # 0x88 -> LATIN SMALL LETTER A WITH GRAVE
u'\xe2' # 0x89 -> LATIN SMALL LETTER A WITH CIRCUMFLEX
u'\xe4' # 0x8A -> LATIN SMALL LETTER A WITH DIAERESIS
u'\xe3' # 0x8B -> LATIN SMALL LETTER A WITH TILDE
u'\xe5' # 0x8C -> LATIN SMALL LETTER A WITH RING ABOVE
u'\xe7' # 0x8D -> LATIN SMALL LETTER C WITH CEDILLA
u'\xe9' # 0x8E -> LATIN SMALL LETTER E WITH ACUTE
u'\xe8' # 0x8F -> LATIN SMALL LETTER E WITH GRAVE
u'\xea' # 0x90 -> LATIN SMALL LETTER E WITH CIRCUMFLEX
u'\xeb' # 0x91 -> LATIN SMALL LETTER E WITH DIAERESIS
u'\xed' # 0x92 -> LATIN SMALL LETTER I WITH ACUTE
u'\xec' # 0x93 -> LATIN SMALL LETTER I WITH GRAVE
u'\xee' # 0x94 -> LATIN SMALL LETTER I WITH CIRCUMFLEX
u'\xef' # 0x95 -> LATIN SMALL LETTER I WITH DIAERESIS
u'\xf1' # 0x96 -> LATIN SMALL LETTER N WITH TILDE
u'\xf3' # 0x97 -> LATIN SMALL LETTER O WITH ACUTE
u'\xf2' # 0x98 -> LATIN SMALL LETTER O WITH GRAVE
u'\xf4' # 0x99 -> LATIN SMALL LETTER O WITH CIRCUMFLEX
u'\xf6' # 0x9A -> LATIN SMALL LETTER O WITH DIAERESIS
u'\xf5' # 0x9B -> LATIN SMALL LETTER O WITH TILDE
u'\xfa' # 0x9C -> LATIN SMALL LETTER U WITH ACUTE
u'\xf9' # 0x9D -> LATIN SMALL LETTER U WITH GRAVE
u'\xfb' # 0x9E -> LATIN SMALL LETTER U WITH CIRCUMFLEX
u'\xfc' # 0x9F -> LATIN SMALL LETTER U WITH DIAERESIS
u'\xdd' # 0xA0 -> LATIN CAPITAL LETTER Y WITH ACUTE
u'\xb0' # 0xA1 -> DEGREE SIGN
u'\xa2' # 0xA2 -> CENT SIGN
u'\xa3' # 0xA3 -> POUND SIGN
u'\xa7' # 0xA4 -> SECTION SIGN
u'\u2022' # 0xA5 -> BULLET
u'\xb6' # 0xA6 -> PILCROW SIGN
u'\xdf' # 0xA7 -> LATIN SMALL LETTER SHARP S
u'\xae' # 0xA8 -> REGISTERED SIGN
u'\xa9' # 0xA9 -> COPYRIGHT SIGN
u'\u2122' # 0xAA -> TRADE MARK SIGN
u'\xb4' # 0xAB -> ACUTE ACCENT
u'\xa8' # 0xAC -> DIAERESIS
u'\u2260' # 0xAD -> NOT EQUAL TO
u'\xc6' # 0xAE -> LATIN CAPITAL LETTER AE
u'\xd8' # 0xAF -> LATIN CAPITAL LETTER O WITH STROKE
u'\u221e' # 0xB0 -> INFINITY
u'\xb1' # 0xB1 -> PLUS-MINUS SIGN
u'\u2264' # 0xB2 -> LESS-THAN OR EQUAL TO
u'\u2265' # 0xB3 -> GREATER-THAN OR EQUAL TO
u'\xa5' # 0xB4 -> YEN SIGN
u'\xb5' # 0xB5 -> MICRO SIGN
u'\u2202' # 0xB6 -> PARTIAL DIFFERENTIAL
u'\u2211' # 0xB7 -> N-ARY SUMMATION
u'\u220f' # 0xB8 -> N-ARY PRODUCT
u'\u03c0' # 0xB9 -> GREEK SMALL LETTER PI
u'\u222b' # 0xBA -> INTEGRAL
u'\xaa' # 0xBB -> FEMININE ORDINAL INDICATOR
u'\xba' # 0xBC -> MASCULINE ORDINAL INDICATOR
u'\u03a9' # 0xBD -> GREEK CAPITAL LETTER OMEGA
u'\xe6' # 0xBE -> LATIN SMALL LETTER AE
u'\xf8' # 0xBF -> LATIN SMALL LETTER O WITH STROKE
u'\xbf' # 0xC0 -> INVERTED QUESTION MARK
u'\xa1' # 0xC1 -> INVERTED EXCLAMATION MARK
u'\xac' # 0xC2 -> NOT SIGN
u'\u221a' # 0xC3 -> SQUARE ROOT
u'\u0192' # 0xC4 -> LATIN SMALL LETTER F WITH HOOK
u'\u2248' # 0xC5 -> ALMOST EQUAL TO
u'\u2206' # 0xC6 -> INCREMENT
u'\xab' # 0xC7 -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
u'\xbb' # 0xC8 -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
u'\u2026' # 0xC9 -> HORIZONTAL ELLIPSIS
u'\xa0' # 0xCA -> NO-BREAK SPACE
u'\xc0' # 0xCB -> LATIN CAPITAL LETTER A WITH GRAVE
u'\xc3' # 0xCC -> LATIN CAPITAL LETTER A WITH TILDE
u'\xd5' # 0xCD -> LATIN CAPITAL LETTER O WITH TILDE
u'\u0152' # 0xCE -> LATIN CAPITAL LIGATURE OE
u'\u0153' # 0xCF -> LATIN SMALL LIGATURE OE
u'\u2013' # 0xD0 -> EN DASH
u'\u2014' # 0xD1 -> EM DASH
u'\u201c' # 0xD2 -> LEFT DOUBLE QUOTATION MARK
u'\u201d' # 0xD3 -> RIGHT DOUBLE QUOTATION MARK
u'\u2018' # 0xD4 -> LEFT SINGLE QUOTATION MARK
u'\u2019' # 0xD5 -> RIGHT SINGLE QUOTATION MARK
u'\xf7' # 0xD6 -> DIVISION SIGN
u'\u25ca' # 0xD7 -> LOZENGE
u'\xff' # 0xD8 -> LATIN SMALL LETTER Y WITH DIAERESIS
u'\u0178' # 0xD9 -> LATIN CAPITAL LETTER Y WITH DIAERESIS
u'\u2044' # 0xDA -> FRACTION SLASH
u'\u20ac' # 0xDB -> EURO SIGN
u'\xd0' # 0xDC -> LATIN CAPITAL LETTER ETH
u'\xf0' # 0xDD -> LATIN SMALL LETTER ETH
u'\xde' # 0xDE -> LATIN CAPITAL LETTER THORN
u'\xfe' # 0xDF -> LATIN SMALL LETTER THORN
u'\xfd' # 0xE0 -> LATIN SMALL LETTER Y WITH ACUTE
u'\xb7' # 0xE1 -> MIDDLE DOT
u'\u201a' # 0xE2 -> SINGLE LOW-9 QUOTATION MARK
u'\u201e' # 0xE3 -> DOUBLE LOW-9 QUOTATION MARK
u'\u2030' # 0xE4 -> PER MILLE SIGN
u'\xc2' # 0xE5 -> LATIN CAPITAL LETTER A WITH CIRCUMFLEX
u'\xca' # 0xE6 -> LATIN CAPITAL LETTER E WITH CIRCUMFLEX
u'\xc1' # 0xE7 -> LATIN CAPITAL LETTER A WITH ACUTE
u'\xcb' # 0xE8 -> LATIN CAPITAL LETTER E WITH DIAERESIS
u'\xc8' # 0xE9 -> LATIN CAPITAL LETTER E WITH GRAVE
u'\xcd' # 0xEA -> LATIN CAPITAL LETTER I WITH ACUTE
u'\xce' # 0xEB -> LATIN CAPITAL LETTER I WITH CIRCUMFLEX
u'\xcf' # 0xEC -> LATIN CAPITAL LETTER I WITH DIAERESIS
u'\xcc' # 0xED -> LATIN CAPITAL LETTER I WITH GRAVE
u'\xd3' # 0xEE -> LATIN CAPITAL LETTER O WITH ACUTE
u'\xd4' # 0xEF -> LATIN CAPITAL LETTER O WITH CIRCUMFLEX
u'\uf8ff' # 0xF0 -> Apple logo
u'\xd2' # 0xF1 -> LATIN CAPITAL LETTER O WITH GRAVE
u'\xda' # 0xF2 -> LATIN CAPITAL LETTER U WITH ACUTE
u'\xdb' # 0xF3 -> LATIN CAPITAL LETTER U WITH CIRCUMFLEX
u'\xd9' # 0xF4 -> LATIN CAPITAL LETTER U WITH GRAVE
u'\u0131' # 0xF5 -> LATIN SMALL LETTER DOTLESS I
u'\u02c6' # 0xF6 -> MODIFIER LETTER CIRCUMFLEX ACCENT
u'\u02dc' # 0xF7 -> SMALL TILDE
u'\xaf' # 0xF8 -> MACRON
u'\u02d8' # 0xF9 -> BREVE
u'\u02d9' # 0xFA -> DOT ABOVE
u'\u02da' # 0xFB -> RING ABOVE
u'\xb8' # 0xFC -> CEDILLA
u'\u02dd' # 0xFD -> DOUBLE ACUTE ACCENT
u'\u02db' # 0xFE -> OGONEK
u'\u02c7' # 0xFF -> CARON
)
### Encoding table
encoding_table=codecs.charmap_build(decoding_table)
| gpl-3.0 |
ZhangXinNan/tensorflow | tensorflow/contrib/signal/python/ops/spectral_ops.py | 27 | 12618 | # 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.
# ==============================================================================
"""Spectral operations (e.g. Short-time Fourier Transform)."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import numpy as np
from tensorflow.contrib.signal.python.ops import reconstruction_ops
from tensorflow.contrib.signal.python.ops import shape_ops
from tensorflow.contrib.signal.python.ops import window_ops
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import spectral_ops
def stft(signals, frame_length, frame_step, fft_length=None,
window_fn=functools.partial(window_ops.hann_window, periodic=True),
pad_end=False, name=None):
"""Computes the [Short-time Fourier Transform][stft] of `signals`.
Implemented with GPU-compatible ops and supports gradients.
Args:
signals: A `[..., samples]` `float32` `Tensor` of real-valued signals.
frame_length: An integer scalar `Tensor`. The window length in samples.
frame_step: An integer scalar `Tensor`. The number of samples to step.
fft_length: An integer scalar `Tensor`. The size of the FFT to apply.
If not provided, uses the smallest power of 2 enclosing `frame_length`.
window_fn: A callable that takes a window length and a `dtype` keyword
argument and returns a `[window_length]` `Tensor` of samples in the
provided datatype. If set to `None`, no windowing is used.
pad_end: Whether to pad the end of `signals` with zeros when the provided
frame length and step produces a frame that lies partially past its end.
name: An optional name for the operation.
Returns:
A `[..., frames, fft_unique_bins]` `Tensor` of `complex64` STFT values where
`fft_unique_bins` is `fft_length // 2 + 1` (the unique components of the
FFT).
Raises:
ValueError: If `signals` is not at least rank 1, `frame_length` is
not scalar, or `frame_step` is not scalar.
[stft]: https://en.wikipedia.org/wiki/Short-time_Fourier_transform
"""
with ops.name_scope(name, 'stft', [signals, frame_length,
frame_step]):
signals = ops.convert_to_tensor(signals, name='signals')
signals.shape.with_rank_at_least(1)
frame_length = ops.convert_to_tensor(frame_length, name='frame_length')
frame_length.shape.assert_has_rank(0)
frame_step = ops.convert_to_tensor(frame_step, name='frame_step')
frame_step.shape.assert_has_rank(0)
if fft_length is None:
fft_length = _enclosing_power_of_two(frame_length)
else:
fft_length = ops.convert_to_tensor(fft_length, name='fft_length')
framed_signals = shape_ops.frame(
signals, frame_length, frame_step, pad_end=pad_end)
# Optionally window the framed signals.
if window_fn is not None:
window = window_fn(frame_length, dtype=framed_signals.dtype)
framed_signals *= window
# spectral_ops.rfft produces the (fft_length/2 + 1) unique components of the
# FFT of the real windowed signals in framed_signals.
return spectral_ops.rfft(framed_signals, [fft_length])
def inverse_stft_window_fn(frame_step,
forward_window_fn=functools.partial(
window_ops.hann_window, periodic=True),
name=None):
"""Generates a window function that can be used in `inverse_stft`.
Constructs a window that is equal to the forward window with a further
pointwise amplitude correction. `inverse_stft_window_fn` is equivalent to
`forward_window_fn` in the case where it would produce an exact inverse.
See examples in `inverse_stft` documentation for usage.
Args:
frame_step: An integer scalar `Tensor`. The number of samples to step.
forward_window_fn: window_fn used in the forward transform, `stft`.
name: An optional name for the operation.
Returns:
A callable that takes a window length and a `dtype` keyword argument and
returns a `[window_length]` `Tensor` of samples in the provided datatype.
The returned window is suitable for reconstructing original waveform in
inverse_stft.
"""
with ops.name_scope(name, 'inverse_stft_window_fn', [forward_window_fn]):
frame_step = ops.convert_to_tensor(frame_step, name='frame_step')
frame_step.shape.assert_has_rank(0)
def inverse_stft_window_fn_inner(frame_length, dtype):
"""Computes a window that can be used in `inverse_stft`.
Args:
frame_length: An integer scalar `Tensor`. The window length in samples.
dtype: Data type of waveform passed to `stft`.
Returns:
A window suitable for reconstructing original waveform in `inverse_stft`.
Raises:
ValueError: If `frame_length` is not scalar, `forward_window_fn` is not a
callable that takes a window length and a `dtype` keyword argument and
returns a `[window_length]` `Tensor` of samples in the provided datatype
`frame_step` is not scalar, or `frame_step` is not scalar.
"""
with ops.name_scope(name, 'inverse_stft_window_fn', [forward_window_fn]):
frame_length = ops.convert_to_tensor(frame_length, name='frame_length')
frame_length.shape.assert_has_rank(0)
# Use equation 7 from Griffin + Lim.
forward_window = forward_window_fn(frame_length, dtype=dtype)
denom = math_ops.square(forward_window)
overlaps = -(-frame_length // frame_step) # Ceiling division.
denom = array_ops.pad(denom, [(0, overlaps * frame_step - frame_length)])
denom = array_ops.reshape(denom, [overlaps, frame_step])
denom = math_ops.reduce_sum(denom, 0, keepdims=True)
denom = array_ops.tile(denom, [overlaps, 1])
denom = array_ops.reshape(denom, [overlaps * frame_step])
return forward_window / denom[:frame_length]
return inverse_stft_window_fn_inner
def inverse_stft(stfts,
frame_length,
frame_step,
fft_length=None,
window_fn=functools.partial(window_ops.hann_window,
periodic=True),
name=None):
"""Computes the inverse [Short-time Fourier Transform][stft] of `stfts`.
To reconstruct an original waveform, a complimentary window function should
be used in inverse_stft. Such a window function can be constructed with
tf.contrib.signal.inverse_stft_window_fn.
Example:
```python
frame_length = 400
frame_step = 160
waveform = tf.placeholder(dtype=tf.float32, shape=[1000])
stft = tf.contrib.signal.stft(waveform, frame_length, frame_step)
inverse_stft = tf.contrib.signal.inverse_stft(
stft, frame_length, frame_step,
window_fn=tf.contrib.signal.inverse_stft_window_fn(frame_step))
```
if a custom window_fn is used in stft, it must be passed to
inverse_stft_window_fn:
```python
frame_length = 400
frame_step = 160
window_fn = functools.partial(window_ops.hamming_window, periodic=True),
waveform = tf.placeholder(dtype=tf.float32, shape=[1000])
stft = tf.contrib.signal.stft(
waveform, frame_length, frame_step, window_fn=window_fn)
inverse_stft = tf.contrib.signal.inverse_stft(
stft, frame_length, frame_step,
window_fn=tf.contrib.signal.inverse_stft_window_fn(
frame_step, forward_window_fn=window_fn))
```
Implemented with GPU-compatible ops and supports gradients.
Args:
stfts: A `complex64` `[..., frames, fft_unique_bins]` `Tensor` of STFT bins
representing a batch of `fft_length`-point STFTs where `fft_unique_bins`
is `fft_length // 2 + 1`
frame_length: An integer scalar `Tensor`. The window length in samples.
frame_step: An integer scalar `Tensor`. The number of samples to step.
fft_length: An integer scalar `Tensor`. The size of the FFT that produced
`stfts`. If not provided, uses the smallest power of 2 enclosing
`frame_length`.
window_fn: A callable that takes a window length and a `dtype` keyword
argument and returns a `[window_length]` `Tensor` of samples in the
provided datatype. If set to `None`, no windowing is used.
name: An optional name for the operation.
Returns:
A `[..., samples]` `Tensor` of `float32` signals representing the inverse
STFT for each input STFT in `stfts`.
Raises:
ValueError: If `stfts` is not at least rank 2, `frame_length` is not scalar,
`frame_step` is not scalar, or `fft_length` is not scalar.
[stft]: https://en.wikipedia.org/wiki/Short-time_Fourier_transform
"""
with ops.name_scope(name, 'inverse_stft', [stfts]):
stfts = ops.convert_to_tensor(stfts, name='stfts')
stfts.shape.with_rank_at_least(2)
frame_length = ops.convert_to_tensor(frame_length, name='frame_length')
frame_length.shape.assert_has_rank(0)
frame_step = ops.convert_to_tensor(frame_step, name='frame_step')
frame_step.shape.assert_has_rank(0)
if fft_length is None:
fft_length = _enclosing_power_of_two(frame_length)
else:
fft_length = ops.convert_to_tensor(fft_length, name='fft_length')
fft_length.shape.assert_has_rank(0)
real_frames = spectral_ops.irfft(stfts, [fft_length])
# frame_length may be larger or smaller than fft_length, so we pad or
# truncate real_frames to frame_length.
frame_length_static = tensor_util.constant_value(frame_length)
# If we don't know the shape of real_frames's inner dimension, pad and
# truncate to frame_length.
if (frame_length_static is None or
real_frames.shape.ndims is None or
real_frames.shape[-1].value is None):
real_frames = real_frames[..., :frame_length]
real_frames_rank = array_ops.rank(real_frames)
real_frames_shape = array_ops.shape(real_frames)
paddings = array_ops.concat(
[array_ops.zeros([real_frames_rank - 1, 2],
dtype=frame_length.dtype),
[[0, math_ops.maximum(0, frame_length - real_frames_shape[-1])]]], 0)
real_frames = array_ops.pad(real_frames, paddings)
# We know real_frames's last dimension and frame_length statically. If they
# are different, then pad or truncate real_frames to frame_length.
elif real_frames.shape[-1].value > frame_length_static:
real_frames = real_frames[..., :frame_length_static]
elif real_frames.shape[-1].value < frame_length_static:
pad_amount = frame_length_static - real_frames.shape[-1].value
real_frames = array_ops.pad(real_frames,
[[0, 0]] * (real_frames.shape.ndims - 1) +
[[0, pad_amount]])
# The above code pads the inner dimension of real_frames to frame_length,
# but it does so in a way that may not be shape-inference friendly.
# Restore shape information if we are able to.
if frame_length_static is not None and real_frames.shape.ndims is not None:
real_frames.set_shape([None] * (real_frames.shape.ndims - 1) +
[frame_length_static])
# Optionally window and overlap-add the inner 2 dimensions of real_frames
# into a single [samples] dimension.
if window_fn is not None:
window = window_fn(frame_length, dtype=stfts.dtype.real_dtype)
real_frames *= window
return reconstruction_ops.overlap_and_add(real_frames, frame_step)
def _enclosing_power_of_two(value):
"""Return 2**N for integer N such that 2**N >= value."""
value_static = tensor_util.constant_value(value)
if value_static is not None:
return constant_op.constant(
int(2**np.ceil(np.log(value_static) / np.log(2.0))), value.dtype)
return math_ops.cast(
math_ops.pow(2.0, math_ops.ceil(
math_ops.log(math_ops.to_float(value)) / math_ops.log(2.0))),
value.dtype)
| apache-2.0 |
najmacherrad/master_thesis | Waltz/plotcomparaisons_waltz.py | 1 | 7577 | # Waltz
# Compare results between wild type and mutant
# coding=utf-8
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import csv
from scipy import stats
from pylab import plot, show, savefig, xlim, figure, \
hold, ylim, legend, boxplot, setp, axes
import pylab
from numpy import *
def getColumn(filename, column,deli):
results = csv.reader(open(filename), delimiter=deli)
return [result[column] for result in results]
#import files
file_wt = 'waltzresults_wt.csv'
file_mut = 'waltzresults_mut.csv'
#------------------------------------
# AGGREGATION
#------------------------------------
#--------------------------------------
# SCATTER PLOT
pred_wt = getColumn(file_wt,3,'\t')
pred_mut = getColumn(file_mut,3,'\t')
pred_wt.pop(0)
pred_mut.pop(0)
x,y=[],[]
for i in range(0,len(pred_wt)): #max=98.662207
if pred_wt[i]=='NA':
x.append(np.nan)
else:
x.append(float(pred_wt[i]))
for i in range(0,len(pred_mut)): #max=99.665552
if pred_mut[i]=='NA':
y.append(np.nan)
else:
y.append(float(pred_mut[i]))
fig = plt.figure()
a=b=[0,100]
plt.scatter(x, y,edgecolor = 'none', c= 'k')
plt.plot(a,b,'r-')
plt.grid('on')
plt.xlim(-1,101)
plt.ylim(-1,101)
plt.xlabel('Wild types')
plt.ylabel('Deleterious DIDA mutants')
fig.savefig('waltz_wtVSmut.jpg')
#----------------
# PROBABILITY DENSITY CURVE
fig = figure()
mu1, std1 = stats.norm.fit(x)
mu2, std2 = stats.norm.fit(y)
xmin1, xmax1 = plt.xlim()
xmin2, xmax2 = plt.xlim()
x1 = np.linspace(xmin1, 100, 100)
x2 = np.linspace(xmin2, 100, 100)
p1 = stats.norm.pdf(x1, mu1, std1)
p2 = stats.norm.pdf(x2, mu2, std2)
plt.plot(x1, p1, 'k',label='Wild types (fit results: mu=%.2f,std=%.2f)'%(mu1, std1))
plt.plot(x2, p2, 'r',label='Deleterious DIDA mutants \n(fit results: mu=%.2f,std=%.2f)'%(mu2, std2))
plt.xlabel('Aggregation conformation predicted values (amylogenic regions)')
plt.ylabel('Frequency')
plt.xlim(0,100)
#plt.ylim(0,0.0)
plt.legend(loc='upper right')
fig.savefig('histwaltz_missense.png')
#missense_wt - missense_mut
miss=[]
[miss.append(a_i - b_i) for a_i, b_i in zip(x, y)]
#KOLMOGOROV-SMINORV:
stats.kstest(miss,'norm') # (D,pvalue) = (0.3552063996073398, 0.0)
#So we reject H0 -> not normal distribution
#WILCOXON TEST:
stats.wilcoxon(miss) # (T, pvalue) = (4898.0, 0.29548245005836105)
#So we do not reject H0 -> There is no significant difference between wt and mut
#--------------------------------------
# AGGREGATION ENVIRONMENT
#--------------------------------------
#--------------------------------------
# SCATTER PLOT
pred_wt = getColumn(file_wt,4,'\t')
pred_mut = getColumn(file_mut,4,'\t')
pred_wt.pop(0)
pred_mut.pop(0)
x,y=[],[]
for i in range(0,len(pred_wt)): #max=98.662207
if pred_wt[i]=='NA':
x.append(np.nan)
else:
x.append(float(pred_wt[i]))
for i in range(0,len(pred_mut)): #max=98.996656
if pred_mut[i]=='NA':
y.append(np.nan)
else:
y.append(float(pred_mut[i]))
fig = plt.figure()
a=b=[0,100]
plt.scatter(x, y,edgecolor = 'none', c= 'k')
plt.plot(a,b,'r-')
plt.grid('on')
plt.xlim(-1,101)
plt.ylim(-1,101)
plt.xlabel('Wild types')
plt.ylabel('Deleterious DIDA mutants')
fig.savefig('waltz_envt_wtVSmut.jpg')
#--------------------------------------
# HISTOGRAM
fig = figure()
mu1, std1 = stats.norm.fit(x)
mu2, std2 = stats.norm.fit(y)
xmin1, xmax1 = plt.xlim()
xmin2, xmax2 = plt.xlim()
x1 = np.linspace(xmin1, 100, 100)
x2 = np.linspace(xmin2, 100, 100)
p1 = stats.norm.pdf(x1, mu1, std1)
p2 = stats.norm.pdf(x2, mu2, std2)
plt.plot(x1, p1, 'k',label='Wild types (fit results: mu=%.2f,std=%.2f)'%(mu1, std1))
plt.plot(x2, p2, 'r',label='Deleterious DIDA mutants \n(fit results: mu=%.2f,std=%.2f)'%(mu2, std2))
plt.xlabel('Aggregation conformation predicted values (amylogenic regions)')
plt.ylabel('Frequency')
plt.xlim(0,100)
plt.ylim(0,0.06)
plt.legend(loc='upper right')
fig.savefig('histwaltzenvt_missense.png')
#missense_wt - missense_mut
miss=[]
[miss.append(a_i - b_i) for a_i, b_i in zip(x, y)]
#KOLMOGOROV-SMINORV:
stats.kstest(miss,'norm') # (D,pvalue) = (0.34964202670995748, 0.0)
#So we reject H0 -> not normal distribution
#WILCOXON TEST:
stats.wilcoxon(miss) #-> (T, pvalue) = (8711.0, 0.55024961096028457)
#So we do not reject H0 -> There is no significant difference between wt and mut
#-----------------------------------------------------------------------------
# OUTLIERS FOR AGGREGATION ()
#-----------------------------------------------------------------------------
pred_wt = getColumn(file_wt,3,'\t')
pred_mut = getColumn(file_mut,3,'\t')
pred_wt.pop(0)
pred_mut.pop(0)
pred_envt_wt = getColumn(file_wt,4,'\t')
pred_envt_mut = getColumn(file_mut,4,'\t')
pred_envt_wt.pop(0)
pred_envt_mut.pop(0)
variant_liste = getColumn(file_wt,0,'\t')
output = open('waltz_outliers.csv','w')
output.write('ID,agg_wt,agg_mut,difference,agg_envt_wt,agg_envt_mut,difference_envt\n')
for i in range(0,len(pred_wt)):
for j in range(0,len(pred_mut)):
if i==j:
if pred_wt[i]!='NA'and pred_mut[j]!='NA':
if (abs(float(pred_wt[i])-float(pred_mut[j]))) > 20:
output.write(variant_liste[i+1] + ',' + pred_wt[i] + ',' + pred_mut[j] + ',' + str(abs(float(pred_wt[i])-float(pred_mut[j]))) + ',' + pred_envt_wt[i] + ',' + pred_envt_mut[i] + ',' + str(abs(float(pred_envt_wt[i])-float(pred_envt_mut[j]))) + '\n')
output.close()
#-------------------------------------------------------------------------------
#COMPARISON WITH NETSURFP RSA
#-------------------------------------------------------------------------------
W_wt = pd.read_csv(file_wt,'\t')
W_mut = pd.read_csv(file_mut,'\t')
W_wt['DWaltz'] = ''
W_wt['DWaltz'] = W_wt.aggregation - W_mut.aggregation
W_wt['DWaltz_envt'] = ''
W_wt['DWaltz_envt'] = W_wt.aggregation_envt - W_mut.aggregation_envt
W_wt = W_wt.drop(['aggregation','aggregation_envt'], 1)
W_wt.to_csv('waltzresults_compare.csv', index=False)
#RESIDUE
waltz = getColumn('waltzresults_compare.csv',3,',')
waltz.pop(0)
netsurfp = getColumn('netsurfpresults_compare.csv',3,',')
netsurfp.pop(0)
x,y=[],[]
for i in range(0,len(netsurfp)): #min=-0.183 and max=0.302
if netsurfp[i]=='':
x.append(np.nan)
else:
x.append(float(netsurfp[i]))
for i in range(0,len(waltz)): #min=-98.862207 and max=98.327759
if waltz[i]=='':
y.append(np.nan)
else:
y.append(float(waltz[i]))
fig = plt.figure()
plt.scatter(x, y,edgecolor = 'none', c= 'k')
plt.grid('on')
plt.xlim(-0.4,0.4)
plt.ylim(-100,100)
plt.xlabel('delta(Solvent accessibility prediction) by NetSurfP')
plt.ylabel('delta(Aggregation conformation prediction) by Waltz')
fig.savefig('WaltzVSnetsurfp.jpg')
#ENVIRONMENT
waltz_envt = getColumn('waltzresults_compare.csv',4,',')
waltz_envt.pop(0)
netsurfp_envt = getColumn('netsurfpresults_compare.csv',4,',')
netsurfp_envt.pop(0)
x,y=[],[]
for i in range(0,len(netsurfp_envt)): #min=-0.183 and max=0.302
if netsurfp_envt[i]=='':
x.append(np.nan)
else:
x.append(float(netsurfp_envt[i]))
for i in range(0,len(waltz_envt)): #min=-98.862207 and max=98.327759
if waltz_envt[i]=='':
y.append(np.nan)
else:
y.append(float(waltz_envt[i]))
fig = plt.figure()
plt.scatter(x, y,edgecolor = 'none', c= 'k')
plt.grid('on')
plt.xlim(-0.4,0.4)
plt.ylim(-100,100)
plt.xlabel('delta(Solvent accessibility prediction) by NetSurfP')
plt.ylabel('delta(Aggregation conformation prediction) by Waltz')
fig.savefig('WaltzVSnetsurfp_envt.jpg')
| mit |
kurtrwall/wagtail | wagtail/utils/deprecation.py | 2 | 1995 | from __future__ import absolute_import, unicode_literals
import warnings
class RemovedInWagtail17Warning(DeprecationWarning):
pass
removed_in_next_version_warning = RemovedInWagtail17Warning
class RemovedInWagtail18Warning(PendingDeprecationWarning):
pass
class ThisShouldBeAList(list):
"""
Some properties - such as Indexed.search_fields - used to be tuples. This
is incorrect, and they should have been lists. Changing these to be a list
now would be backwards incompatible, as people do
.. code-block:: python
search_fields = Page.search_fields + (
SearchField('body')
)
Adding a tuple to the end of a list causes an error.
This class will allow tuples to be added to it, as in the above behaviour,
but will raise a deprecation warning if someone does this.
"""
message = 'Using a {type} for {name} is deprecated, use a list instead'
def __init__(self, items, name, category):
super(ThisShouldBeAList, self).__init__(items)
self.name = name
self.category = category
def _format_message(self, rhs):
return self.message.format(name=self.name, type=type(rhs).__name__)
def __add__(self, rhs):
cls = type(self)
if isinstance(rhs, tuple):
# Seems that a tuple was passed in. Raise a deprecation
# warning, but then keep going anyway.
message = self._format_message(rhs)
warnings.warn(message, category=self.category, stacklevel=2)
rhs = list(rhs)
return cls(super(ThisShouldBeAList, self).__add__(list(rhs)),
name=self.name, category=self.category)
class SearchFieldsShouldBeAList(ThisShouldBeAList):
"""
Indexed.search_fields was a tuple, but it should have been a list
"""
def __init__(self, items, name='search_fields', category=RemovedInWagtail17Warning):
super(SearchFieldsShouldBeAList, self).__init__(items, name, category)
| bsd-3-clause |
paulballesty/zxcvbn | data-scripts/count_wiktionary.py | 16 | 2670 | #!/usr/bin/python
import os
import sys
import codecs
import operator
from unidecode import unidecode
def usage():
return '''
This script extracts words and counts from a 2006 wiktionary word frequency study over American
television and movies. To use, first visit the study and download, as .html files, all 26 of the
frequency lists:
https://en.wiktionary.org/wiki/Wiktionary:Frequency_lists#TV_and_movie_scripts
Put those into a single directory and point it to this script:
%s wiktionary_html_dir ../data/us_tv_and_film.txt
output.txt will include one line per word in the study, ordered by rank, of the form:
word1 count1
word2 count2
...
''' % sys.argv[0]
def parse_wiki_tokens(html_doc_str):
'''fragile hax, but checks the result at the end'''
results = []
last3 = ['', '', '']
header = True
skipped = 0
for line in html_doc_str.split('\n'):
last3.pop(0)
last3.append(line.strip())
if all(s.startswith('<td>') and not s == '<td></td>' for s in last3):
if header:
header = False
continue
last3 = [s.replace('<td>', '').replace('</td>', '').strip() for s in last3]
rank, token, count = last3
rank = int(rank.split()[0])
token = token.replace('</a>', '')
token = token[token.index('>')+1:]
token = normalize(token)
# wikitonary has thousands of words that end in 's
# keep the common ones (rank under 1000), discard the rest
#
# otherwise end up with a bunch of duplicates eg victor / victor's
if token.endswith("'s") and rank > 1000:
skipped += 1
continue
count = int(count)
results.append((rank, token, count))
# early docs have 1k entries, later 2k, last 1284
assert len(results) + skipped in [1000, 2000, 1284]
return results
def normalize(token):
return unidecode(token).lower()
def main(wiktionary_html_root, output_filename):
rank_token_count = [] # list of 3-tuples
for filename in os.listdir(wiktionary_html_root):
path = os.path.join(wiktionary_html_root, filename)
with codecs.open(path, 'r', 'utf8') as f:
rank_token_count.extend(parse_wiki_tokens(f.read()))
rank_token_count.sort(key=operator.itemgetter(0))
with codecs.open(output_filename, 'w', 'utf8') as f:
for rank, token, count in rank_token_count:
f.write('%-18s %d\n' % (token, count))
if __name__ == '__main__':
if len(sys.argv) != 3:
print usage()
else:
main(*sys.argv[1:])
sys.exit(0)
| mit |
LighthouseHPC/lighthouse | src/Dlighthouse/lighthouse/views/lapack_sylvester.py | 2 | 8761 | import string, types, sys, os, StringIO, re, shlex, json, zipfile
from collections import OrderedDict
from itertools import chain
from django.contrib.auth.decorators import login_required
from django.core.servers.basehttp import FileWrapper
from django.http import HttpResponse, HttpResponseNotFound
from django.shortcuts import render_to_response, redirect, render
from django.template import RequestContext
from django.template.loader import render_to_string
from django.views.decorators.csrf import csrf_exempt
from lighthouse.forms.lapack_sylvester import *
from lighthouse.models.lapack_sylvester import lapack_sylvester
from lighthouse.models.lapack_choiceDict import *
from lighthouse.views.lapack_eigen import question_and_answer
import datetime
##############################################
######--------- Guided Search --------- ######
##############################################
form_order_standard = ('standardGeneralizedForm', 'complexNumberForm', 'standardConditionForm', 'singleDoubleForm') ## form order for standard Sylvester equation
form_order_generalized = ('standardGeneralizedForm', 'complexNumberForm', 'generalizedConditionForm', 'singleDoubleForm') ## form order for generalized Sylvester equation
form_HTML = ['standardGeneralizedForm', 'standardConditionForm', 'generalizedConditionForm'] ## forms with HTML format
### help functions
def find_nextForm(currentForm_name, request):
print request.session['form_order']
current_index = request.session['form_order'].index(currentForm_name)
nextForm_name = ""
nextForm = ""
try:
## search for 'none' and return the first column that has zero to be the next question/form
next_index = next(i for i in range(current_index+1, len(request.session['form_order'])))
nextForm_name = request.session['form_order'][next_index]
print nextForm_name
nextForm = getattr(sys.modules[__name__], nextForm_name)()
## the end of the guided search or other errors
except Exception as e:
print type(e)
print "e.message: ", e.message
print "e.args: ", e.args
return {'nextForm_name': nextForm_name, 'nextForm': nextForm}
### set up initial sessions
def sessionSetup(request):
for item in ['standardGeneralizedForm', 'standardConditionForm', 'generalizedConditionForm', 'complexNumberForm', 'singleDoubleForm']:
key = 'sylvester_'+item[:-4]
request.session[key] = ''
request.session['currentForm_name'] = 'standardGeneralizedForm'
request.session['Results'] = lapack_sylvester.objects.all()
request.session['sylvester_guided_answered'] = OrderedDict()
request.session['form_order'] = []
### start guided search views
def index(request):
# set up session keys and values
sessionSetup(request)
## get ready for the template
context = {
'formHTML': "standardGeneralizedForm",
'form': "invalid",
'sylvester_guided_answered' : '',
'results' : 'start',
}
return render_to_response('lighthouse/lapack_sylvester/index.html', context_instance=RequestContext(request, context))
def guidedSearch(request):
form = getattr(sys.modules[__name__], request.session['currentForm_name'])(request.GET or None)
if form.is_valid():
## get current question and user's answer
current_question = request.session['currentForm_name'][:-4]
formField_name = 'sylvester_'+current_question
value = form.cleaned_data[formField_name]
choices = form.fields[formField_name].choices
request.session['sylvester_guided_answered'].update(question_and_answer(form, value, choices))
## generate a session for current question/answer -->request.session[sylvester_currentQuestion] = answer
request.session[formField_name] = value
## decide which form order to use
if request.session['currentForm_name'] == 'standardGeneralizedForm' and request.session['sylvester_standardGeneralized'] == 'standard':
request.session['form_order'] = form_order_standard
elif request.session['currentForm_name'] == 'standardGeneralizedForm' and request.session['sylvester_standardGeneralized'] == 'generalized':
request.session['form_order'] = form_order_generalized
if request.session['sylvester_standardCondition'] == 'no' or request.session['sylvester_generalizedCondition'] == 'no': ## stop search
return index(request)
else:
## do search based on user's response (no search needed for 'standardConditionForm', 'generalizedConditionForm')
if request.session['currentForm_name'] not in ['standardConditionForm', 'generalizedConditionForm']:
lookup = "%s__contains" % current_question
query = {lookup : value}
request.session['Results'] = request.session['Results'].filter(**query)
## call function find_nextForm to set up next form for next question
dict_nextQuestion = find_nextForm(request.session['currentForm_name'], request)
nextForm_name = dict_nextQuestion['nextForm_name']
nextForm = dict_nextQuestion['nextForm']
## make next form current for request.session['currentForm_name']
request.session['currentForm_name'] = nextForm_name
## decide whether or not to use form HTML files (if help buttons are needed, use HTML file instead of form)
if nextForm_name in form_HTML:
formHTML = nextForm_name
else:
formHTML = "invalid"
## get ready for the template
context = {
'formHTML': formHTML,
'form': nextForm,
'sylvester_guided_answered' : request.session['sylvester_guided_answered'],
'results' : request.session['Results']
}
return render_to_response('lighthouse/lapack_sylvester/index.html', context_instance=RequestContext(request, context))
else:
return index(request)
##############################################
######-------- Advanced Search -------- ######
##############################################
def advancedSearch(request):
standardDict = {'complexNumber':[], 'singleDouble':[]}
generalizedDict = {'complexNumber':[], 'singleDouble':[]}
request.session['advancedResults'] = []
form = advancedForm(request.POST or None)
### search for standard routines
if form['standard_search'].value() == 'yes':
## get standard data
standardDict['complexNumber'] = form['standard_complexNumber'].value()
standardDict['singleDouble'] = form['standard_singleDouble'].value()
## search for standard routines
for item1 in standardDict['complexNumber']:
for item2 in standardDict['singleDouble']:
kwargs = {
'standardGeneralized': 'standard',
'complexNumber': item1,
'singleDouble': item2,
}
request.session['advancedResults'].extend(lapack_sylvester.objects.filter(**kwargs))
### search for generalized routines
if form['generalized_search'].value() == 'yes':
## get generalized data
generalizedDict['complexNumber'] = form['generalized_complexNumber'].value()
generalizedDict['singleDouble'] = form['generalized_singleDouble'].value()
## search for generalized routines
for item1 in generalizedDict['complexNumber']:
for item2 in generalizedDict['singleDouble']:
print item1, item2
kwargs = {
'standardGeneralized': 'generalized',
'complexNumber': item1,
'singleDouble': item2,
}
request.session['advancedResults'].extend(lapack_sylvester.objects.filter(**kwargs))
## be ready for switching to guided search
sessionSetup(request)
## context includes guided search form
context = {
'form_submitted': form,
'results': request.session['advancedResults'],
'AdvancedTab': True,
'formHTML': "standardGeneralizedForm",
'form': "invalid",
'sylvester_guided_answered' : '',
}
return render_to_response('lighthouse/lapack_sylvester/index.html', context_instance=RequestContext(request, context))
| mit |
deadlyraptor/reels | spreadchimp.py | 1 | 2493 | import os
import csv
import xlrd
# Assumes the directory with the workbook is relative to the script's location.
directory = 'workbooks/'
file = os.listdir(directory)[0]
workbook = (f'{directory}/{file}')
# Preps the workbook that contains the information desired.
wb = xlrd.open_workbook(workbook)
sh = wb.sheet_by_index(0)
total_rows = sh.nrows
first_row = 6 # skips the first six rows as they are irrelevant.
# Collects the names of all the films for which individual workbooks need to be
# created.
films = []
for row in range(first_row, total_rows):
row_values = sh.row_values(row)
film_title = row_values[20]
if film_title in films:
pass
else:
films.append(film_title)
def prep_contacts(film):
'''Collects all contacts that match the given film into a list that will be
used to write to the actual spreadsheet.
Arguments:
film = The film that contacts purchased tickets for.
Returns:
contacts = The list of all contacts for a given film.
'''
contacts = []
for row in range(first_row, total_rows):
contact = []
row_values = sh.row_values(row)
opt_in = row_values[5]
film_title = row_values[20]
if not opt_in:
continue
elif opt_in and film_title == film:
address = '{0} {1} {2} {3} {4}'.format(
row_values[11], # address 1
row_values[12], # address 2
row_values[13].title(), # city
row_values[14], # state
row_values[15]) # zip
contact = [row_values[3], # email
row_values[2].title(), # first name
row_values[1].title(), # last name
row_values[16].replace('No Primary Phone', ''), # phone
address] # full address
contacts.append(contact)
return contacts
headers = ['Email', 'First Name', 'Last Name', 'Phone', 'Full Address']
for film in films:
contacts = prep_contacts(film)
with open(f'{film}.csv', mode='w') as outfile:
writer = csv.writer(outfile, delimiter=',', quotechar='"',
quoting=csv.QUOTE_MINIMAL)
writer.writerow(headers)
for contact in contacts:
writer.writerow(contact)
| mit |
satishgoda/bokeh | examples/plotting/file/unemployment.py | 46 | 1846 | from collections import OrderedDict
import numpy as np
from bokeh.plotting import ColumnDataSource, figure, show, output_file
from bokeh.models import HoverTool
from bokeh.sampledata.unemployment1948 import data
# Read in the data with pandas. Convert the year column to string
data['Year'] = [str(x) for x in data['Year']]
years = list(data['Year'])
months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
data = data.set_index('Year')
# this is the colormap from the original plot
colors = [
"#75968f", "#a5bab7", "#c9d9d3", "#e2e2e2", "#dfccce",
"#ddb7b1", "#cc7878", "#933b41", "#550b1d"
]
# Set up the data for plotting. We will need to have values for every
# pair of year/month names. Map the rate to a color.
month = []
year = []
color = []
rate = []
for y in years:
for m in months:
month.append(m)
year.append(y)
monthly_rate = data[m][y]
rate.append(monthly_rate)
color.append(colors[min(int(monthly_rate)-2, 8)])
source = ColumnDataSource(
data=dict(month=month, year=year, color=color, rate=rate)
)
output_file('unemployment.html')
TOOLS = "resize,hover,save,pan,box_zoom,wheel_zoom"
p = figure(title="US Unemployment (1948 - 2013)",
x_range=years, y_range=list(reversed(months)),
x_axis_location="above", plot_width=900, plot_height=400,
toolbar_location="left", tools=TOOLS)
p.rect("year", "month", 1, 1, source=source,
color="color", line_color=None)
p.grid.grid_line_color = None
p.axis.axis_line_color = None
p.axis.major_tick_line_color = None
p.axis.major_label_text_font_size = "5pt"
p.axis.major_label_standoff = 0
p.xaxis.major_label_orientation = np.pi/3
hover = p.select(dict(type=HoverTool))
hover.tooltips = OrderedDict([
('date', '@month @year'),
('rate', '@rate'),
])
show(p) # show the plot
| bsd-3-clause |
birryree/servo | components/script/dom/bindings/codegen/parser/tests/test_conditional_dictionary_member.py | 120 | 3162 | def WebIDLTest(parser, harness):
parser.parse("""
dictionary Dict {
any foo;
[ChromeOnly] any bar;
};
""")
results = parser.finish()
harness.check(len(results), 1, "Should have a dictionary")
members = results[0].members;
harness.check(len(members), 2, "Should have two members")
# Note that members are ordered lexicographically, so "bar" comes
# before "foo".
harness.ok(members[0].getExtendedAttribute("ChromeOnly"),
"First member is not ChromeOnly")
harness.ok(not members[1].getExtendedAttribute("ChromeOnly"),
"Second member is ChromeOnly")
parser = parser.reset()
parser.parse("""
dictionary Dict {
any foo;
any bar;
};
interface Iface {
[Constant, Cached] readonly attribute Dict dict;
};
""")
results = parser.finish()
harness.check(len(results), 2, "Should have a dictionary and an interface")
parser = parser.reset()
exception = None
try:
parser.parse("""
dictionary Dict {
any foo;
[ChromeOnly] any bar;
};
interface Iface {
[Constant, Cached] readonly attribute Dict dict;
};
""")
results = parser.finish()
except Exception, exception:
pass
harness.ok(exception, "Should have thrown.")
harness.check(exception.message,
"[Cached] and [StoreInSlot] must not be used on an attribute "
"whose type contains a [ChromeOnly] dictionary member",
"Should have thrown the right exception")
parser = parser.reset()
exception = None
try:
parser.parse("""
dictionary ParentDict {
[ChromeOnly] any bar;
};
dictionary Dict : ParentDict {
any foo;
};
interface Iface {
[Constant, Cached] readonly attribute Dict dict;
};
""")
results = parser.finish()
except Exception, exception:
pass
harness.ok(exception, "Should have thrown (2).")
harness.check(exception.message,
"[Cached] and [StoreInSlot] must not be used on an attribute "
"whose type contains a [ChromeOnly] dictionary member",
"Should have thrown the right exception (2)")
parser = parser.reset()
exception = None
try:
parser.parse("""
dictionary GrandParentDict {
[ChromeOnly] any baz;
};
dictionary ParentDict : GrandParentDict {
any bar;
};
dictionary Dict : ParentDict {
any foo;
};
interface Iface {
[Constant, Cached] readonly attribute Dict dict;
};
""")
results = parser.finish()
except Exception, exception:
pass
harness.ok(exception, "Should have thrown (3).")
harness.check(exception.message,
"[Cached] and [StoreInSlot] must not be used on an attribute "
"whose type contains a [ChromeOnly] dictionary member",
"Should have thrown the right exception (3)")
| mpl-2.0 |
firebitsbr/raspberry_pwn | src/pentest/voiper/fuzzer/fuzzers.py | 8 | 10273 | '''
This file is part of VoIPER.
VoIPER 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.
VoIPER 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 VoIPER. If not, see <http://www.gnu.org/licenses/>.
Copyright 2008, http://www.unprotectedhex.com
Contact: [email protected]
'''
import sys
import os
import string
import time
# modify import path instead of adding a __init__.py as I want to keep
# a the Sulley install as unmodified as possible to facilitate easy updating
# if there are changes to it.
# Props to Pedram Amini and Aaron Portnoy for creating such a great framework
sys.path.append(''.join([os.getcwd(), '/sulley']))
from random import Random
from protocol_logic.sip_agent import T_COMPLETE_OK
from protocol_logic.sip_utilities import SIPCrashDetector
from protocol_logic.sip_utilities import SIPInviteCanceler
from protocol_logic import sip_parser
from misc.utilities import Logger
from fuzzer_parents import AbstractFuzzer
from fuzzer_parents import AbstractSIPFuzzer
from fuzzer_parents import AbstractSIPInviteFuzzer
from socket import *
from sulley import *
################################################################################
class Callable:
def __init__(self, anycallable):
'''
Wrapper class so I can have unbound class methods. Apparently python doesn't
allow these by default. This code/idiom came from some standard example on the
Interwebs
'''
self.__call__ = anycallable
class SIPInviteStructureFuzzer(AbstractSIPInviteFuzzer):
'''
Fuzz the structure of an INVITE request e.g repeats, line folding etc
'''
def fuzz(self):
self.sess.add_target(self.target)
self.sess.connect(s_get("INVITE_STRUCTURE"), callback=self.generate_unique_attributes)
self.sess.fuzz()
def info(self=None):
h = ["Name: SIPInviteStructureFuzzer\n",
"Protocol: SIP\n",
"Success Factor: Low\n",
"Fuzzes the structure of a SIP request by repeating blocks, fuzzing delimiters and ",
"generally altering how a SIP request is structured",
]
return ''.join(h)
info = Callable(info)
class SIPInviteRequestLineFuzzer(AbstractSIPInviteFuzzer):
def fuzz(self):
self.sess.add_target(self.target)
self.sess.connect(s_get("INVITE_REQUEST_LINE"), callback=self.generate_unique_attributes)
self.sess.fuzz()
def info(self=None):
h = ["Name: SIPInviteRequestLineFuzzer\n",
"Protocol: SIP\n",
"Success Factor: Low\n",
"Extensively tests the first line of an INVITE request by including all valid parts ",
"specified in SIP RFC 3375"
]
return ''.join(h)
info = Callable(info)
class SIPInviteCommonFuzzer(AbstractSIPInviteFuzzer):
def fuzz(self):
self.sess.add_target(self.target)
self.sess.connect(s_get("INVITE_COMMON"), callback=self.generate_unique_attributes)
self.sess.fuzz()
def info(self=None):
h = ["Name: SIPInviteCommonFuzzer\n",
"Protocol: SIP\n",
"Success Factor: High\n",
"Fuzzes the headers commonly found and most likely to be processed in a SIP INVITE request\n"
]
return ''.join(h)
info = Callable(info)
class SIPInviteOtherFuzzer(AbstractSIPInviteFuzzer):
def fuzz(self):
self.sess.add_target(self.target)
self.sess.connect(s_get("INVITE_OTHER"), callback=self.generate_unique_attributes)
self.sess.fuzz()
def info(self=None):
h = ["Name: SIPInviteOtherFuzzer\n",
"Protocol: SIP\n",
"Success Factor: Low\n",
"Tests all other headers specified as part of an INVITE besides those found in the ",
"SIPInviteCommonFuzzer. Many of these are seemingly unparsed and ignored by a lot of devices.\n"
]
return ''.join(h)
info = Callable(info)
class SDPFuzzer(AbstractSIPInviteFuzzer):
'''
Extends the Abstract INVITE fuzzer because it requires the INVITE
cancelling functionality. Fuzzes the SDP content of an INVITE.
'''
def fuzz(self):
self.sess.add_target(self.target)
self.sess.connect(s_get("SDP"), callback=self.generate_unique_attributes)
self.sess.fuzz()
def info(self=None):
h = ["Name: SDPFuzzer\n",
"Protocol: SDP\n",
"Success Factor: High\n",
"Fuzzes the SDP protocol as part of a SIP INVITE\n"
]
return ''.join(h)
info = Callable(info)
class SIPDumbACKFuzzer(AbstractSIPFuzzer):
'''
A dumb ACK fuzzer that doesn't wait for any kind of responses or what not.
'''
def fuzz(self):
self.sess.add_target(self.target)
self.sess.connect(s_get("ACK"), callback=self.generate_unique_attributes)
self.sess.fuzz()
def info(self=None):
h = ["Name: SIPDumbACKFuzzer\n",
"Protocol: SIP\n",
"Success Factor: Unknown\n",
"A dumb ACK fuzzer with no transaction state awareness. \n",
]
return ''.join(h)
info = Callable(info)
class SIPDumbCANCELFuzzer(AbstractSIPFuzzer):
'''
A dumb CANCEL fuzzer that doesn't wait for any kind of responses or what not.
'''
def fuzz(self):
self.sess.add_target(self.target)
self.sess.connect(s_get("CANCEL"), callback=self.generate_unique_attributes)
self.sess.fuzz()
def info(self=None):
h = ["Name: SIPDumbCANCELFuzzer\n",
"Protocol: SIP\n",
"Success Factor: Unknown\n",
"A dumb CANCEL request fuzzer with no transaction state awareness\n",
]
return ''.join(h)
info = Callable(info)
class SIPDumbREGISTERFuzzer(AbstractSIPFuzzer):
def fuzz(self):
self.sess.add_target(self.target)
self.sess.connect(s_get("REGISTER"), callback=self.generate_unique_attributes)
self.sess.fuzz()
def info(self=None):
h = ["Name: SIPDumbREGISTERFuzzer\n",
"Protocol: SIP\n",
"Success Factor: Unknown\n",
"A dumb REGISTER request fuzzer with no transaction state awareness\n",
]
return ''.join(h)
info = Callable(info)
class SIPSUBSCRIBEFuzzer(AbstractSIPFuzzer):
def fuzz(self):
self.sess.add_target(self.target)
self.sess.connect(s_get("SUBSCRIBE"), callback=self.generate_unique_attributes)
self.sess.fuzz()
def info(self=None):
h = ["Name: SIPSUBSCRIBEFuzzer\n",
"Protocol: SIP\n",
"Success Factor: Unknown\n",
"A fuzzer for the SUBSCRIBE SIP verb\n",
]
return ''.join(h)
info = Callable(info)
class SIPNOTIFYFuzzer(AbstractSIPFuzzer):
def fuzz(self):
self.sess.add_target(self.target)
self.sess.connect(s_get("NOTIFY"), callback=self.generate_unique_attributes)
self.sess.fuzz()
def info(self=None):
h = ["Name: SIPNOTIFYFuzzer\n",
"Protocol: SIP\n",
"Success Factor: Unknown\n",
"A fuzzer for the NOTIFY SIP verb\n",
]
return ''.join(h)
info = Callable(info)
class SIPACKFuzzer(AbstractSIPFuzzer):
def fuzz(self):
self.invite_cancel_dict = {
sip_parser.r_SEND : (self.invite.process,
{sip_parser.r_1XX : (self.cancel.process,
{sip_parser.r_4XX : (None, None),
sip_parser.r_5XX : (None, None),
sip_parser.r_6XX : (None, None),
sip_parser.r_2XX : (None, None),
}
)
}
)
}
self.pre_send_functions.append(self.invite_cancel)
self.sess.add_target(self.target)
self.sess.connect(s_get("ACK"), callback=self.generate_unique_attributes)
self.sess.fuzz()
def info(self=None):
h = ["Name: SIPACKFuzzer\n",
"Protocol: SIP\n",
"Success Factor: Unknown\n",
"A fuzzer for the ACK SIP verb that first attempts to manipulate the target device into a state where it would expect an ACK\n",
]
return ''.join(h)
info = Callable(info)
def invite_cancel(self, sock):
result = None
while result != T_COMPLETE_OK:
result, self.curr_invite_branch = self.sip_agent.process_transaction(
self.invite_cancel_dict,
self.response_q,
self.request_q,
{'user' : self.user,
'target_user' : self.target_user,
'host' : self.host,
'port' : self.port}
)
if result != T_COMPLETE_OK:
print >>sys.stderr, 'Invite cancel for ACK fuzz didnt complete. Trying again'
time.sleep(.2)
'''
class SDPEncodedFuzzer(AbstractSIPInviteFuzzer):
def fuzz(self):
self.sess.add_target(self.target)
self.sess.connect(s_get("SDP_ENCODED"), callback=self.generate_unique_attributes)
self.sess.fuzz()
class OptionsFuzzer(AbstractSIPFuzzer):
def fuzz(self):
self.sess.add_target(self.target)
self.sess.connect(s_get("OPTIONS"), callback=self.generate_unique_attributes)
self.sess.fuzz()
'''
################################################################################
| gpl-3.0 |
bakkou-badri/dataminingproject | env/lib/python2.7/site-packages/numpy/polynomial/polynomial.py | 14 | 47103 | """
Objects for dealing with polynomials.
This module provides a number of objects (mostly functions) useful for
dealing with polynomials, including a `Polynomial` class that
encapsulates the usual arithmetic operations. (General information
on how this module represents and works with polynomial objects is in
the docstring for its "parent" sub-package, `numpy.polynomial`).
Constants
---------
- `polydomain` -- Polynomial default domain, [-1,1].
- `polyzero` -- (Coefficients of the) "zero polynomial."
- `polyone` -- (Coefficients of the) constant polynomial 1.
- `polyx` -- (Coefficients of the) identity map polynomial, ``f(x) = x``.
Arithmetic
----------
- `polyadd` -- add two polynomials.
- `polysub` -- subtract one polynomial from another.
- `polymul` -- multiply two polynomials.
- `polydiv` -- divide one polynomial by another.
- `polypow` -- raise a polynomial to an positive integer power
- `polyval` -- evaluate a polynomial at given points.
- `polyval2d` -- evaluate a 2D polynomial at given points.
- `polyval3d` -- evaluate a 3D polynomial at given points.
- `polygrid2d` -- evaluate a 2D polynomial on a Cartesian product.
- `polygrid3d` -- evaluate a 3D polynomial on a Cartesian product.
Calculus
--------
- `polyder` -- differentiate a polynomial.
- `polyint` -- integrate a polynomial.
Misc Functions
--------------
- `polyfromroots` -- create a polynomial with specified roots.
- `polyroots` -- find the roots of a polynomial.
- `polyvander` -- Vandermonde-like matrix for powers.
- `polyvander2d` -- Vandermonde-like matrix for 2D power series.
- `polyvander3d` -- Vandermonde-like matrix for 3D power series.
- `polycompanion` -- companion matrix in power series form.
- `polyfit` -- least-squares fit returning a polynomial.
- `polytrim` -- trim leading coefficients from a polynomial.
- `polyline` -- polynomial representing given straight line.
Classes
-------
- `Polynomial` -- polynomial class.
See also
--------
`numpy.polynomial`
"""
from __future__ import division, absolute_import, print_function
__all__ = ['polyzero', 'polyone', 'polyx', 'polydomain', 'polyline',
'polyadd', 'polysub', 'polymulx', 'polymul', 'polydiv', 'polypow',
'polyval', 'polyder', 'polyint', 'polyfromroots', 'polyvander',
'polyfit', 'polytrim', 'polyroots', 'Polynomial', 'polyval2d',
'polyval3d', 'polygrid2d', 'polygrid3d', 'polyvander2d', 'polyvander3d']
import numpy as np
import numpy.linalg as la
from . import polyutils as pu
import warnings
from .polytemplate import polytemplate
polytrim = pu.trimcoef
#
# These are constant arrays are of integer type so as to be compatible
# with the widest range of other types, such as Decimal.
#
# Polynomial default domain.
polydomain = np.array([-1, 1])
# Polynomial coefficients representing zero.
polyzero = np.array([0])
# Polynomial coefficients representing one.
polyone = np.array([1])
# Polynomial coefficients representing the identity x.
polyx = np.array([0, 1])
#
# Polynomial series functions
#
def polyline(off, scl) :
"""
Returns an array representing a linear polynomial.
Parameters
----------
off, scl : scalars
The "y-intercept" and "slope" of the line, respectively.
Returns
-------
y : ndarray
This module's representation of the linear polynomial ``off +
scl*x``.
See Also
--------
chebline
Examples
--------
>>> from numpy import polynomial as P
>>> P.polyline(1,-1)
array([ 1, -1])
>>> P.polyval(1, P.polyline(1,-1)) # should be 0
0.0
"""
if scl != 0 :
return np.array([off, scl])
else :
return np.array([off])
def polyfromroots(roots) :
"""
Generate a monic polynomial with given roots.
Return the coefficients of the polynomial
.. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n),
where the `r_n` are the roots specified in `roots`. If a zero has
multiplicity n, then it must appear in `roots` n times. For instance,
if 2 is a root of multiplicity three and 3 is a root of multiplicity 2,
then `roots` looks something like [2, 2, 2, 3, 3]. The roots can appear
in any order.
If the returned coefficients are `c`, then
.. math:: p(x) = c_0 + c_1 * x + ... + x^n
The coefficient of the last term is 1 for monic polynomials in this
form.
Parameters
----------
roots : array_like
Sequence containing the roots.
Returns
-------
out : ndarray
1-D array of the polynomial's coefficients If all the roots are
real, then `out` is also real, otherwise it is complex. (see
Examples below).
See Also
--------
chebfromroots, legfromroots, lagfromroots, hermfromroots
hermefromroots
Notes
-----
The coefficients are determined by multiplying together linear factors
of the form `(x - r_i)`, i.e.
.. math:: p(x) = (x - r_0) (x - r_1) ... (x - r_n)
where ``n == len(roots) - 1``; note that this implies that `1` is always
returned for :math:`a_n`.
Examples
--------
>>> import numpy.polynomial as P
>>> P.polyfromroots((-1,0,1)) # x(x - 1)(x + 1) = x^3 - x
array([ 0., -1., 0., 1.])
>>> j = complex(0,1)
>>> P.polyfromroots((-j,j)) # complex returned, though values are real
array([ 1.+0.j, 0.+0.j, 1.+0.j])
"""
if len(roots) == 0 :
return np.ones(1)
else :
[roots] = pu.as_series([roots], trim=False)
roots.sort()
p = [polyline(-r, 1) for r in roots]
n = len(p)
while n > 1:
m, r = divmod(n, 2)
tmp = [polymul(p[i], p[i+m]) for i in range(m)]
if r:
tmp[0] = polymul(tmp[0], p[-1])
p = tmp
n = m
return p[0]
def polyadd(c1, c2):
"""
Add one polynomial to another.
Returns the sum of two polynomials `c1` + `c2`. The arguments are
sequences of coefficients from lowest order term to highest, i.e.,
[1,2,3] represents the polynomial ``1 + 2*x + 3*x**2``.
Parameters
----------
c1, c2 : array_like
1-D arrays of polynomial coefficients ordered from low to high.
Returns
-------
out : ndarray
The coefficient array representing their sum.
See Also
--------
polysub, polymul, polydiv, polypow
Examples
--------
>>> from numpy import polynomial as P
>>> c1 = (1,2,3)
>>> c2 = (3,2,1)
>>> sum = P.polyadd(c1,c2); sum
array([ 4., 4., 4.])
>>> P.polyval(2, sum) # 4 + 4(2) + 4(2**2)
28.0
"""
# c1, c2 are trimmed copies
[c1, c2] = pu.as_series([c1, c2])
if len(c1) > len(c2) :
c1[:c2.size] += c2
ret = c1
else :
c2[:c1.size] += c1
ret = c2
return pu.trimseq(ret)
def polysub(c1, c2):
"""
Subtract one polynomial from another.
Returns the difference of two polynomials `c1` - `c2`. The arguments
are sequences of coefficients from lowest order term to highest, i.e.,
[1,2,3] represents the polynomial ``1 + 2*x + 3*x**2``.
Parameters
----------
c1, c2 : array_like
1-D arrays of polynomial coefficients ordered from low to
high.
Returns
-------
out : ndarray
Of coefficients representing their difference.
See Also
--------
polyadd, polymul, polydiv, polypow
Examples
--------
>>> from numpy import polynomial as P
>>> c1 = (1,2,3)
>>> c2 = (3,2,1)
>>> P.polysub(c1,c2)
array([-2., 0., 2.])
>>> P.polysub(c2,c1) # -P.polysub(c1,c2)
array([ 2., 0., -2.])
"""
# c1, c2 are trimmed copies
[c1, c2] = pu.as_series([c1, c2])
if len(c1) > len(c2) :
c1[:c2.size] -= c2
ret = c1
else :
c2 = -c2
c2[:c1.size] += c1
ret = c2
return pu.trimseq(ret)
def polymulx(c):
"""Multiply a polynomial by x.
Multiply the polynomial `c` by x, where x is the independent
variable.
Parameters
----------
c : array_like
1-D array of polynomial coefficients ordered from low to
high.
Returns
-------
out : ndarray
Array representing the result of the multiplication.
Notes
-----
.. versionadded:: 1.5.0
"""
# c is a trimmed copy
[c] = pu.as_series([c])
# The zero series needs special treatment
if len(c) == 1 and c[0] == 0:
return c
prd = np.empty(len(c) + 1, dtype=c.dtype)
prd[0] = c[0]*0
prd[1:] = c
return prd
def polymul(c1, c2):
"""
Multiply one polynomial by another.
Returns the product of two polynomials `c1` * `c2`. The arguments are
sequences of coefficients, from lowest order term to highest, e.g.,
[1,2,3] represents the polynomial ``1 + 2*x + 3*x**2.``
Parameters
----------
c1, c2 : array_like
1-D arrays of coefficients representing a polynomial, relative to the
"standard" basis, and ordered from lowest order term to highest.
Returns
-------
out : ndarray
Of the coefficients of their product.
See Also
--------
polyadd, polysub, polydiv, polypow
Examples
--------
>>> import numpy.polynomial as P
>>> c1 = (1,2,3)
>>> c2 = (3,2,1)
>>> P.polymul(c1,c2)
array([ 3., 8., 14., 8., 3.])
"""
# c1, c2 are trimmed copies
[c1, c2] = pu.as_series([c1, c2])
ret = np.convolve(c1, c2)
return pu.trimseq(ret)
def polydiv(c1, c2):
"""
Divide one polynomial by another.
Returns the quotient-with-remainder of two polynomials `c1` / `c2`.
The arguments are sequences of coefficients, from lowest order term
to highest, e.g., [1,2,3] represents ``1 + 2*x + 3*x**2``.
Parameters
----------
c1, c2 : array_like
1-D arrays of polynomial coefficients ordered from low to high.
Returns
-------
[quo, rem] : ndarrays
Of coefficient series representing the quotient and remainder.
See Also
--------
polyadd, polysub, polymul, polypow
Examples
--------
>>> import numpy.polynomial as P
>>> c1 = (1,2,3)
>>> c2 = (3,2,1)
>>> P.polydiv(c1,c2)
(array([ 3.]), array([-8., -4.]))
>>> P.polydiv(c2,c1)
(array([ 0.33333333]), array([ 2.66666667, 1.33333333]))
"""
# c1, c2 are trimmed copies
[c1, c2] = pu.as_series([c1, c2])
if c2[-1] == 0 :
raise ZeroDivisionError()
len1 = len(c1)
len2 = len(c2)
if len2 == 1 :
return c1/c2[-1], c1[:1]*0
elif len1 < len2 :
return c1[:1]*0, c1
else :
dlen = len1 - len2
scl = c2[-1]
c2 = c2[:-1]/scl
i = dlen
j = len1 - 1
while i >= 0 :
c1[i:j] -= c2*c1[j]
i -= 1
j -= 1
return c1[j+1:]/scl, pu.trimseq(c1[:j+1])
def polypow(c, pow, maxpower=None) :
"""Raise a polynomial to a power.
Returns the polynomial `c` raised to the power `pow`. The argument
`c` is a sequence of coefficients ordered from low to high. i.e.,
[1,2,3] is the series ``1 + 2*x + 3*x**2.``
Parameters
----------
c : array_like
1-D array of array of series coefficients ordered from low to
high degree.
pow : integer
Power to which the series will be raised
maxpower : integer, optional
Maximum power allowed. This is mainly to limit growth of the series
to unmanageable size. Default is 16
Returns
-------
coef : ndarray
Power series of power.
See Also
--------
polyadd, polysub, polymul, polydiv
Examples
--------
"""
# c is a trimmed copy
[c] = pu.as_series([c])
power = int(pow)
if power != pow or power < 0 :
raise ValueError("Power must be a non-negative integer.")
elif maxpower is not None and power > maxpower :
raise ValueError("Power is too large")
elif power == 0 :
return np.array([1], dtype=c.dtype)
elif power == 1 :
return c
else :
# This can be made more efficient by using powers of two
# in the usual way.
prd = c
for i in range(2, power + 1) :
prd = np.convolve(prd, c)
return prd
def polyder(c, m=1, scl=1, axis=0):
"""
Differentiate a polynomial.
Returns the polynomial coefficients `c` differentiated `m` times along
`axis`. At each iteration the result is multiplied by `scl` (the
scaling factor is for use in a linear change of variable). The
argument `c` is an array of coefficients from low to high degree along
each axis, e.g., [1,2,3] represents the polynomial ``1 + 2*x + 3*x**2``
while [[1,2],[1,2]] represents ``1 + 1*x + 2*y + 2*x*y`` if axis=0 is
``x`` and axis=1 is ``y``.
Parameters
----------
c : array_like
Array of polynomial coefficients. If c is multidimensional the
different axis correspond to different variables with the degree
in each axis given by the corresponding index.
m : int, optional
Number of derivatives taken, must be non-negative. (Default: 1)
scl : scalar, optional
Each differentiation is multiplied by `scl`. The end result is
multiplication by ``scl**m``. This is for use in a linear change
of variable. (Default: 1)
axis : int, optional
Axis over which the derivative is taken. (Default: 0).
.. versionadded:: 1.7.0
Returns
-------
der : ndarray
Polynomial coefficients of the derivative.
See Also
--------
polyint
Examples
--------
>>> from numpy import polynomial as P
>>> c = (1,2,3,4) # 1 + 2x + 3x**2 + 4x**3
>>> P.polyder(c) # (d/dx)(c) = 2 + 6x + 12x**2
array([ 2., 6., 12.])
>>> P.polyder(c,3) # (d**3/dx**3)(c) = 24
array([ 24.])
>>> P.polyder(c,scl=-1) # (d/d(-x))(c) = -2 - 6x - 12x**2
array([ -2., -6., -12.])
>>> P.polyder(c,2,-1) # (d**2/d(-x)**2)(c) = 6 + 24x
array([ 6., 24.])
"""
c = np.array(c, ndmin=1, copy=1)
if c.dtype.char in '?bBhHiIlLqQpP':
# astype fails with NA
c = c + 0.0
cdt = c.dtype
cnt, iaxis = [int(t) for t in [m, axis]]
if cnt != m:
raise ValueError("The order of derivation must be integer")
if cnt < 0:
raise ValueError("The order of derivation must be non-negative")
if iaxis != axis:
raise ValueError("The axis must be integer")
if not -c.ndim <= iaxis < c.ndim:
raise ValueError("The axis is out of range")
if iaxis < 0:
iaxis += c.ndim
if cnt == 0:
return c
c = np.rollaxis(c, iaxis)
n = len(c)
if cnt >= n:
c = c[:1]*0
else :
for i in range(cnt):
n = n - 1
c *= scl
der = np.empty((n,) + c.shape[1:], dtype=cdt)
for j in range(n, 0, -1):
der[j - 1] = j*c[j]
c = der
c = np.rollaxis(c, 0, iaxis + 1)
return c
def polyint(c, m=1, k=[], lbnd=0, scl=1, axis=0):
"""
Integrate a polynomial.
Returns the polynomial coefficients `c` integrated `m` times from
`lbnd` along `axis`. At each iteration the resulting series is
**multiplied** by `scl` and an integration constant, `k`, is added.
The scaling factor is for use in a linear change of variable. ("Buyer
beware": note that, depending on what one is doing, one may want `scl`
to be the reciprocal of what one might expect; for more information,
see the Notes section below.) The argument `c` is an array of
coefficients, from low to high degree along each axis, e.g., [1,2,3]
represents the polynomial ``1 + 2*x + 3*x**2`` while [[1,2],[1,2]]
represents ``1 + 1*x + 2*y + 2*x*y`` if axis=0 is ``x`` and axis=1 is
``y``.
Parameters
----------
c : array_like
1-D array of polynomial coefficients, ordered from low to high.
m : int, optional
Order of integration, must be positive. (Default: 1)
k : {[], list, scalar}, optional
Integration constant(s). The value of the first integral at zero
is the first value in the list, the value of the second integral
at zero is the second value, etc. If ``k == []`` (the default),
all constants are set to zero. If ``m == 1``, a single scalar can
be given instead of a list.
lbnd : scalar, optional
The lower bound of the integral. (Default: 0)
scl : scalar, optional
Following each integration the result is *multiplied* by `scl`
before the integration constant is added. (Default: 1)
axis : int, optional
Axis over which the integral is taken. (Default: 0).
.. versionadded:: 1.7.0
Returns
-------
S : ndarray
Coefficient array of the integral.
Raises
------
ValueError
If ``m < 1``, ``len(k) > m``.
See Also
--------
polyder
Notes
-----
Note that the result of each integration is *multiplied* by `scl`. Why
is this important to note? Say one is making a linear change of
variable :math:`u = ax + b` in an integral relative to `x`. Then
.. math::`dx = du/a`, so one will need to set `scl` equal to
:math:`1/a` - perhaps not what one would have first thought.
Examples
--------
>>> from numpy import polynomial as P
>>> c = (1,2,3)
>>> P.polyint(c) # should return array([0, 1, 1, 1])
array([ 0., 1., 1., 1.])
>>> P.polyint(c,3) # should return array([0, 0, 0, 1/6, 1/12, 1/20])
array([ 0. , 0. , 0. , 0.16666667, 0.08333333,
0.05 ])
>>> P.polyint(c,k=3) # should return array([3, 1, 1, 1])
array([ 3., 1., 1., 1.])
>>> P.polyint(c,lbnd=-2) # should return array([6, 1, 1, 1])
array([ 6., 1., 1., 1.])
>>> P.polyint(c,scl=-2) # should return array([0, -2, -2, -2])
array([ 0., -2., -2., -2.])
"""
c = np.array(c, ndmin=1, copy=1)
if c.dtype.char in '?bBhHiIlLqQpP':
# astype doesn't preserve mask attribute.
c = c + 0.0
cdt = c.dtype
if not np.iterable(k):
k = [k]
cnt, iaxis = [int(t) for t in [m, axis]]
if cnt != m:
raise ValueError("The order of integration must be integer")
if cnt < 0 :
raise ValueError("The order of integration must be non-negative")
if len(k) > cnt :
raise ValueError("Too many integration constants")
if iaxis != axis:
raise ValueError("The axis must be integer")
if not -c.ndim <= iaxis < c.ndim:
raise ValueError("The axis is out of range")
if iaxis < 0:
iaxis += c.ndim
if cnt == 0:
return c
k = list(k) + [0]*(cnt - len(k))
c = np.rollaxis(c, iaxis)
for i in range(cnt):
n = len(c)
c *= scl
if n == 1 and np.all(c[0] == 0):
c[0] += k[i]
else:
tmp = np.empty((n + 1,) + c.shape[1:], dtype=cdt)
tmp[0] = c[0]*0
tmp[1] = c[0]
for j in range(1, n):
tmp[j + 1] = c[j]/(j + 1)
tmp[0] += k[i] - polyval(lbnd, tmp)
c = tmp
c = np.rollaxis(c, 0, iaxis + 1)
return c
def polyval(x, c, tensor=True):
"""
Evaluate a polynomial at points x.
If `c` is of length `n + 1`, this function returns the value
.. math:: p(x) = c_0 + c_1 * x + ... + c_n * x^n
The parameter `x` is converted to an array only if it is a tuple or a
list, otherwise it is treated as a scalar. In either case, either `x`
or its elements must support multiplication and addition both with
themselves and with the elements of `c`.
If `c` is a 1-D array, then `p(x)` will have the same shape as `x`. If
`c` is multidimensional, then the shape of the result depends on the
value of `tensor`. If `tensor` is true the shape will be c.shape[1:] +
x.shape. If `tensor` is false the shape will be c.shape[1:]. Note that
scalars have shape (,).
Trailing zeros in the coefficients will be used in the evaluation, so
they should be avoided if efficiency is a concern.
Parameters
----------
x : array_like, compatible object
If `x` is a list or tuple, it is converted to an ndarray, otherwise
it is left unchanged and treated as a scalar. In either case, `x`
or its elements must support addition and multiplication with
with themselves and with the elements of `c`.
c : array_like
Array of coefficients ordered so that the coefficients for terms of
degree n are contained in c[n]. If `c` is multidimensional the
remaining indices enumerate multiple polynomials. In the two
dimensional case the coefficients may be thought of as stored in
the columns of `c`.
tensor : boolean, optional
If True, the shape of the coefficient array is extended with ones
on the right, one for each dimension of `x`. Scalars have dimension 0
for this action. The result is that every column of coefficients in
`c` is evaluated for every element of `x`. If False, `x` is broadcast
over the columns of `c` for the evaluation. This keyword is useful
when `c` is multidimensional. The default value is True.
.. versionadded:: 1.7.0
Returns
-------
values : ndarray, compatible object
The shape of the returned array is described above.
See Also
--------
polyval2d, polygrid2d, polyval3d, polygrid3d
Notes
-----
The evaluation uses Horner's method.
Examples
--------
>>> from numpy.polynomial.polynomial import polyval
>>> polyval(1, [1,2,3])
6.0
>>> a = np.arange(4).reshape(2,2)
>>> a
array([[0, 1],
[2, 3]])
>>> polyval(a, [1,2,3])
array([[ 1., 6.],
[ 17., 34.]])
>>> coef = np.arange(4).reshape(2,2) # multidimensional coefficients
>>> coef
array([[0, 1],
[2, 3]])
>>> polyval([1,2], coef, tensor=True)
array([[ 2., 4.],
[ 4., 7.]])
>>> polyval([1,2], coef, tensor=False)
array([ 2., 7.])
"""
c = np.array(c, ndmin=1, copy=0)
if c.dtype.char in '?bBhHiIlLqQpP':
# astype fails with NA
c = c + 0.0
if isinstance(x, (tuple, list)):
x = np.asarray(x)
if isinstance(x, np.ndarray) and tensor:
c = c.reshape(c.shape + (1,)*x.ndim)
c0 = c[-1] + x*0
for i in range(2, len(c) + 1) :
c0 = c[-i] + c0*x
return c0
def polyval2d(x, y, c):
"""
Evaluate a 2-D polynomial at points (x, y).
This function returns the value
.. math:: p(x,y) = \\sum_{i,j} c_{i,j} * x^i * y^j
The parameters `x` and `y` are converted to arrays only if they are
tuples or a lists, otherwise they are treated as a scalars and they
must have the same shape after conversion. In either case, either `x`
and `y` or their elements must support multiplication and addition both
with themselves and with the elements of `c`.
If `c` has fewer than two dimensions, ones are implicitly appended to
its shape to make it 2-D. The shape of the result will be c.shape[2:] +
x.shape.
Parameters
----------
x, y : array_like, compatible objects
The two dimensional series is evaluated at the points `(x, y)`,
where `x` and `y` must have the same shape. If `x` or `y` is a list
or tuple, it is first converted to an ndarray, otherwise it is left
unchanged and, if it isn't an ndarray, it is treated as a scalar.
c : array_like
Array of coefficients ordered so that the coefficient of the term
of multi-degree i,j is contained in `c[i,j]`. If `c` has
dimension greater than two the remaining indices enumerate multiple
sets of coefficients.
Returns
-------
values : ndarray, compatible object
The values of the two dimensional polynomial at points formed with
pairs of corresponding values from `x` and `y`.
See Also
--------
polyval, polygrid2d, polyval3d, polygrid3d
Notes
-----
.. versionadded::1.7.0
"""
try:
x, y = np.array((x, y), copy=0)
except:
raise ValueError('x, y are incompatible')
c = polyval(x, c)
c = polyval(y, c, tensor=False)
return c
def polygrid2d(x, y, c):
"""
Evaluate a 2-D polynomial on the Cartesian product of x and y.
This function returns the values:
.. math:: p(a,b) = \\sum_{i,j} c_{i,j} * a^i * b^j
where the points `(a, b)` consist of all pairs formed by taking
`a` from `x` and `b` from `y`. The resulting points form a grid with
`x` in the first dimension and `y` in the second.
The parameters `x` and `y` are converted to arrays only if they are
tuples or a lists, otherwise they are treated as a scalars. In either
case, either `x` and `y` or their elements must support multiplication
and addition both with themselves and with the elements of `c`.
If `c` has fewer than two dimensions, ones are implicitly appended to
its shape to make it 2-D. The shape of the result will be c.shape[2:] +
x.shape + y.shape.
Parameters
----------
x, y : array_like, compatible objects
The two dimensional series is evaluated at the points in the
Cartesian product of `x` and `y`. If `x` or `y` is a list or
tuple, it is first converted to an ndarray, otherwise it is left
unchanged and, if it isn't an ndarray, it is treated as a scalar.
c : array_like
Array of coefficients ordered so that the coefficients for terms of
degree i,j are contained in ``c[i,j]``. If `c` has dimension
greater than two the remaining indices enumerate multiple sets of
coefficients.
Returns
-------
values : ndarray, compatible object
The values of the two dimensional polynomial at points in the Cartesian
product of `x` and `y`.
See Also
--------
polyval, polyval2d, polyval3d, polygrid3d
Notes
-----
.. versionadded::1.7.0
"""
c = polyval(x, c)
c = polyval(y, c)
return c
def polyval3d(x, y, z, c):
"""
Evaluate a 3-D polynomial at points (x, y, z).
This function returns the values:
.. math:: p(x,y,z) = \\sum_{i,j,k} c_{i,j,k} * x^i * y^j * z^k
The parameters `x`, `y`, and `z` are converted to arrays only if
they are tuples or a lists, otherwise they are treated as a scalars and
they must have the same shape after conversion. In either case, either
`x`, `y`, and `z` or their elements must support multiplication and
addition both with themselves and with the elements of `c`.
If `c` has fewer than 3 dimensions, ones are implicitly appended to its
shape to make it 3-D. The shape of the result will be c.shape[3:] +
x.shape.
Parameters
----------
x, y, z : array_like, compatible object
The three dimensional series is evaluated at the points
`(x, y, z)`, where `x`, `y`, and `z` must have the same shape. If
any of `x`, `y`, or `z` is a list or tuple, it is first converted
to an ndarray, otherwise it is left unchanged and if it isn't an
ndarray it is treated as a scalar.
c : array_like
Array of coefficients ordered so that the coefficient of the term of
multi-degree i,j,k is contained in ``c[i,j,k]``. If `c` has dimension
greater than 3 the remaining indices enumerate multiple sets of
coefficients.
Returns
-------
values : ndarray, compatible object
The values of the multidimensional polynomial on points formed with
triples of corresponding values from `x`, `y`, and `z`.
See Also
--------
polyval, polyval2d, polygrid2d, polygrid3d
Notes
-----
.. versionadded::1.7.0
"""
try:
x, y, z = np.array((x, y, z), copy=0)
except:
raise ValueError('x, y, z are incompatible')
c = polyval(x, c)
c = polyval(y, c, tensor=False)
c = polyval(z, c, tensor=False)
return c
def polygrid3d(x, y, z, c):
"""
Evaluate a 3-D polynomial on the Cartesian product of x, y and z.
This function returns the values:
.. math:: p(a,b,c) = \\sum_{i,j,k} c_{i,j,k} * a^i * b^j * c^k
where the points `(a, b, c)` consist of all triples formed by taking
`a` from `x`, `b` from `y`, and `c` from `z`. The resulting points form
a grid with `x` in the first dimension, `y` in the second, and `z` in
the third.
The parameters `x`, `y`, and `z` are converted to arrays only if they
are tuples or a lists, otherwise they are treated as a scalars. In
either case, either `x`, `y`, and `z` or their elements must support
multiplication and addition both with themselves and with the elements
of `c`.
If `c` has fewer than three dimensions, ones are implicitly appended to
its shape to make it 3-D. The shape of the result will be c.shape[3:] +
x.shape + y.shape + z.shape.
Parameters
----------
x, y, z : array_like, compatible objects
The three dimensional series is evaluated at the points in the
Cartesian product of `x`, `y`, and `z`. If `x`,`y`, or `z` is a
list or tuple, it is first converted to an ndarray, otherwise it is
left unchanged and, if it isn't an ndarray, it is treated as a
scalar.
c : array_like
Array of coefficients ordered so that the coefficients for terms of
degree i,j are contained in ``c[i,j]``. If `c` has dimension
greater than two the remaining indices enumerate multiple sets of
coefficients.
Returns
-------
values : ndarray, compatible object
The values of the two dimensional polynomial at points in the Cartesian
product of `x` and `y`.
See Also
--------
polyval, polyval2d, polygrid2d, polyval3d
Notes
-----
.. versionadded::1.7.0
"""
c = polyval(x, c)
c = polyval(y, c)
c = polyval(z, c)
return c
def polyvander(x, deg) :
"""Vandermonde matrix of given degree.
Returns the Vandermonde matrix of degree `deg` and sample points
`x`. The Vandermonde matrix is defined by
.. math:: V[..., i] = x^i,
where `0 <= i <= deg`. The leading indices of `V` index the elements of
`x` and the last index is the power of `x`.
If `c` is a 1-D array of coefficients of length `n + 1` and `V` is the
matrix ``V = polyvander(x, n)``, then ``np.dot(V, c)`` and
``polyval(x, c)`` are the same up to roundoff. This equivalence is
useful both for least squares fitting and for the evaluation of a large
number of polynomials of the same degree and sample points.
Parameters
----------
x : array_like
Array of points. The dtype is converted to float64 or complex128
depending on whether any of the elements are complex. If `x` is
scalar it is converted to a 1-D array.
deg : int
Degree of the resulting matrix.
Returns
-------
vander : ndarray.
The Vandermonde matrix. The shape of the returned matrix is
``x.shape + (deg + 1,)``, where the last index is the power of `x`.
The dtype will be the same as the converted `x`.
See Also
--------
polyvander2d, polyvander3d
"""
ideg = int(deg)
if ideg != deg:
raise ValueError("deg must be integer")
if ideg < 0:
raise ValueError("deg must be non-negative")
x = np.array(x, copy=0, ndmin=1) + 0.0
dims = (ideg + 1,) + x.shape
dtyp = x.dtype
v = np.empty(dims, dtype=dtyp)
v[0] = x*0 + 1
if ideg > 0 :
v[1] = x
for i in range(2, ideg + 1) :
v[i] = v[i-1]*x
return np.rollaxis(v, 0, v.ndim)
def polyvander2d(x, y, deg) :
"""Pseudo-Vandermonde matrix of given degrees.
Returns the pseudo-Vandermonde matrix of degrees `deg` and sample
points `(x, y)`. The pseudo-Vandermonde matrix is defined by
.. math:: V[..., deg[1]*i + j] = x^i * y^j,
where `0 <= i <= deg[0]` and `0 <= j <= deg[1]`. The leading indices of
`V` index the points `(x, y)` and the last index encodes the powers of
`x` and `y`.
If ``V = polyvander2d(x, y, [xdeg, ydeg])``, then the columns of `V`
correspond to the elements of a 2-D coefficient array `c` of shape
(xdeg + 1, ydeg + 1) in the order
.. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ...
and ``np.dot(V, c.flat)`` and ``polyval2d(x, y, c)`` will be the same
up to roundoff. This equivalence is useful both for least squares
fitting and for the evaluation of a large number of 2-D polynomials
of the same degrees and sample points.
Parameters
----------
x, y : array_like
Arrays of point coordinates, all of the same shape. The dtypes
will be converted to either float64 or complex128 depending on
whether any of the elements are complex. Scalars are converted to
1-D arrays.
deg : list of ints
List of maximum degrees of the form [x_deg, y_deg].
Returns
-------
vander2d : ndarray
The shape of the returned matrix is ``x.shape + (order,)``, where
:math:`order = (deg[0]+1)*(deg([1]+1)`. The dtype will be the same
as the converted `x` and `y`.
See Also
--------
polyvander, polyvander3d. polyval2d, polyval3d
"""
ideg = [int(d) for d in deg]
is_valid = [id == d and id >= 0 for id, d in zip(ideg, deg)]
if is_valid != [1, 1]:
raise ValueError("degrees must be non-negative integers")
degx, degy = ideg
x, y = np.array((x, y), copy=0) + 0.0
vx = polyvander(x, degx)
vy = polyvander(y, degy)
v = vx[..., None]*vy[..., None,:]
# einsum bug
#v = np.einsum("...i,...j->...ij", vx, vy)
return v.reshape(v.shape[:-2] + (-1,))
def polyvander3d(x, y, z, deg) :
"""Pseudo-Vandermonde matrix of given degrees.
Returns the pseudo-Vandermonde matrix of degrees `deg` and sample
points `(x, y, z)`. If `l, m, n` are the given degrees in `x, y, z`,
then The pseudo-Vandermonde matrix is defined by
.. math:: V[..., (m+1)(n+1)i + (n+1)j + k] = x^i * y^j * z^k,
where `0 <= i <= l`, `0 <= j <= m`, and `0 <= j <= n`. The leading
indices of `V` index the points `(x, y, z)` and the last index encodes
the powers of `x`, `y`, and `z`.
If ``V = polyvander3d(x, y, z, [xdeg, ydeg, zdeg])``, then the columns
of `V` correspond to the elements of a 3-D coefficient array `c` of
shape (xdeg + 1, ydeg + 1, zdeg + 1) in the order
.. math:: c_{000}, c_{001}, c_{002},... , c_{010}, c_{011}, c_{012},...
and ``np.dot(V, c.flat)`` and ``polyval3d(x, y, z, c)`` will be the
same up to roundoff. This equivalence is useful both for least squares
fitting and for the evaluation of a large number of 3-D polynomials
of the same degrees and sample points.
Parameters
----------
x, y, z : array_like
Arrays of point coordinates, all of the same shape. The dtypes will
be converted to either float64 or complex128 depending on whether
any of the elements are complex. Scalars are converted to 1-D
arrays.
deg : list of ints
List of maximum degrees of the form [x_deg, y_deg, z_deg].
Returns
-------
vander3d : ndarray
The shape of the returned matrix is ``x.shape + (order,)``, where
:math:`order = (deg[0]+1)*(deg([1]+1)*(deg[2]+1)`. The dtype will
be the same as the converted `x`, `y`, and `z`.
See Also
--------
polyvander, polyvander3d. polyval2d, polyval3d
Notes
-----
.. versionadded::1.7.0
"""
ideg = [int(d) for d in deg]
is_valid = [id == d and id >= 0 for id, d in zip(ideg, deg)]
if is_valid != [1, 1, 1]:
raise ValueError("degrees must be non-negative integers")
degx, degy, degz = ideg
x, y, z = np.array((x, y, z), copy=0) + 0.0
vx = polyvander(x, degx)
vy = polyvander(y, degy)
vz = polyvander(z, degz)
v = vx[..., None, None]*vy[..., None,:, None]*vz[..., None, None,:]
# einsum bug
#v = np.einsum("...i, ...j, ...k->...ijk", vx, vy, vz)
return v.reshape(v.shape[:-3] + (-1,))
def polyfit(x, y, deg, rcond=None, full=False, w=None):
"""
Least-squares fit of a polynomial to data.
Return the coefficients of a polynomial of degree `deg` that is the
least squares fit to the data values `y` given at points `x`. If `y` is
1-D the returned coefficients will also be 1-D. If `y` is 2-D multiple
fits are done, one for each column of `y`, and the resulting
coefficients are stored in the corresponding columns of a 2-D return.
The fitted polynomial(s) are in the form
.. math:: p(x) = c_0 + c_1 * x + ... + c_n * x^n,
where `n` is `deg`.
Since numpy version 1.7.0, polyfit also supports NA. If any of the
elements of `x`, `y`, or `w` are NA, then the corresponding rows of the
linear least squares problem (see Notes) are set to 0. If `y` is 2-D,
then an NA in any row of `y` invalidates that whole row.
Parameters
----------
x : array_like, shape (`M`,)
x-coordinates of the `M` sample (data) points ``(x[i], y[i])``.
y : array_like, shape (`M`,) or (`M`, `K`)
y-coordinates of the sample points. Several sets of sample points
sharing the same x-coordinates can be (independently) fit with one
call to `polyfit` by passing in for `y` a 2-D array that contains
one data set per column.
deg : int
Degree of the polynomial(s) to be fit.
rcond : float, optional
Relative condition number of the fit. Singular values smaller
than `rcond`, relative to the largest singular value, will be
ignored. The default value is ``len(x)*eps``, where `eps` is the
relative precision of the platform's float type, about 2e-16 in
most cases.
full : bool, optional
Switch determining the nature of the return value. When ``False``
(the default) just the coefficients are returned; when ``True``,
diagnostic information from the singular value decomposition (used
to solve the fit's matrix equation) is also returned.
w : array_like, shape (`M`,), optional
Weights. If not None, the contribution of each point
``(x[i],y[i])`` to the fit is weighted by `w[i]`. Ideally the
weights are chosen so that the errors of the products ``w[i]*y[i]``
all have the same variance. The default value is None.
.. versionadded:: 1.5.0
Returns
-------
coef : ndarray, shape (`deg` + 1,) or (`deg` + 1, `K`)
Polynomial coefficients ordered from low to high. If `y` was 2-D,
the coefficients in column `k` of `coef` represent the polynomial
fit to the data in `y`'s `k`-th column.
[residuals, rank, singular_values, rcond] : present when `full` == True
Sum of the squared residuals (SSR) of the least-squares fit; the
effective rank of the scaled Vandermonde matrix; its singular
values; and the specified value of `rcond`. For more information,
see `linalg.lstsq`.
Raises
------
RankWarning
Raised if the matrix in the least-squares fit is rank deficient.
The warning is only raised if `full` == False. The warnings can
be turned off by:
>>> import warnings
>>> warnings.simplefilter('ignore', RankWarning)
See Also
--------
chebfit, legfit, lagfit, hermfit, hermefit
polyval : Evaluates a polynomial.
polyvander : Vandermonde matrix for powers.
linalg.lstsq : Computes a least-squares fit from the matrix.
scipy.interpolate.UnivariateSpline : Computes spline fits.
Notes
-----
The solution is the coefficients of the polynomial `p` that minimizes
the sum of the weighted squared errors
.. math :: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2,
where the :math:`w_j` are the weights. This problem is solved by
setting up the (typically) over-determined matrix equation:
.. math :: V(x) * c = w * y,
where `V` is the weighted pseudo Vandermonde matrix of `x`, `c` are the
coefficients to be solved for, `w` are the weights, and `y` are the
observed values. This equation is then solved using the singular value
decomposition of `V`.
If some of the singular values of `V` are so small that they are
neglected (and `full` == ``False``), a `RankWarning` will be raised.
This means that the coefficient values may be poorly determined.
Fitting to a lower order polynomial will usually get rid of the warning
(but may not be what you want, of course; if you have independent
reason(s) for choosing the degree which isn't working, you may have to:
a) reconsider those reasons, and/or b) reconsider the quality of your
data). The `rcond` parameter can also be set to a value smaller than
its default, but the resulting fit may be spurious and have large
contributions from roundoff error.
Polynomial fits using double precision tend to "fail" at about
(polynomial) degree 20. Fits using Chebyshev or Legendre series are
generally better conditioned, but much can still depend on the
distribution of the sample points and the smoothness of the data. If
the quality of the fit is inadequate, splines may be a good
alternative.
Examples
--------
>>> from numpy import polynomial as P
>>> x = np.linspace(-1,1,51) # x "data": [-1, -0.96, ..., 0.96, 1]
>>> y = x**3 - x + np.random.randn(len(x)) # x^3 - x + N(0,1) "noise"
>>> c, stats = P.polyfit(x,y,3,full=True)
>>> c # c[0], c[2] should be approx. 0, c[1] approx. -1, c[3] approx. 1
array([ 0.01909725, -1.30598256, -0.00577963, 1.02644286])
>>> stats # note the large SSR, explaining the rather poor results
[array([ 38.06116253]), 4, array([ 1.38446749, 1.32119158, 0.50443316,
0.28853036]), 1.1324274851176597e-014]
Same thing without the added noise
>>> y = x**3 - x
>>> c, stats = P.polyfit(x,y,3,full=True)
>>> c # c[0], c[2] should be "very close to 0", c[1] ~= -1, c[3] ~= 1
array([ -1.73362882e-17, -1.00000000e+00, -2.67471909e-16,
1.00000000e+00])
>>> stats # note the minuscule SSR
[array([ 7.46346754e-31]), 4, array([ 1.38446749, 1.32119158,
0.50443316, 0.28853036]), 1.1324274851176597e-014]
"""
order = int(deg) + 1
x = np.asarray(x) + 0.0
y = np.asarray(y) + 0.0
# check arguments.
if deg < 0 :
raise ValueError("expected deg >= 0")
if x.ndim != 1:
raise TypeError("expected 1D vector for x")
if x.size == 0:
raise TypeError("expected non-empty vector for x")
if y.ndim < 1 or y.ndim > 2 :
raise TypeError("expected 1D or 2D array for y")
if len(x) != len(y):
raise TypeError("expected x and y to have same length")
# set up the least squares matrices in transposed form
lhs = polyvander(x, deg).T
rhs = y.T
if w is not None:
w = np.asarray(w) + 0.0
if w.ndim != 1:
raise TypeError("expected 1D vector for w")
if len(x) != len(w):
raise TypeError("expected x and w to have same length")
# apply weights. Don't use inplace operations as they
# can cause problems with NA.
lhs = lhs * w
rhs = rhs * w
# set rcond
if rcond is None :
rcond = len(x)*np.finfo(x.dtype).eps
# Determine the norms of the design matrix columns.
if issubclass(lhs.dtype.type, np.complexfloating):
scl = np.sqrt((np.square(lhs.real) + np.square(lhs.imag)).sum(1))
else:
scl = np.sqrt(np.square(lhs).sum(1))
scl[scl == 0] = 1
# Solve the least squares problem.
c, resids, rank, s = la.lstsq(lhs.T/scl, rhs.T, rcond)
c = (c.T/scl).T
# warn on rank reduction
if rank != order and not full:
msg = "The fit may be poorly conditioned"
warnings.warn(msg, pu.RankWarning)
if full :
return c, [resids, rank, s, rcond]
else :
return c
def polycompanion(c):
"""
Return the companion matrix of c.
The companion matrix for power series cannot be made symmetric by
scaling the basis, so this function differs from those for the
orthogonal polynomials.
Parameters
----------
c : array_like
1-D array of polynomial coefficients ordered from low to high
degree.
Returns
-------
mat : ndarray
Companion matrix of dimensions (deg, deg).
Notes
-----
.. versionadded:: 1.7.0
"""
# c is a trimmed copy
[c] = pu.as_series([c])
if len(c) < 2 :
raise ValueError('Series must have maximum degree of at least 1.')
if len(c) == 2:
return np.array([[-c[0]/c[1]]])
n = len(c) - 1
mat = np.zeros((n, n), dtype=c.dtype)
bot = mat.reshape(-1)[n::n+1]
bot[...] = 1
mat[:, -1] -= c[:-1]/c[-1]
return mat
def polyroots(c):
"""
Compute the roots of a polynomial.
Return the roots (a.k.a. "zeros") of the polynomial
.. math:: p(x) = \\sum_i c[i] * x^i.
Parameters
----------
c : 1-D array_like
1-D array of polynomial coefficients.
Returns
-------
out : ndarray
Array of the roots of the polynomial. If all the roots are real,
then `out` is also real, otherwise it is complex.
See Also
--------
chebroots
Notes
-----
The root estimates are obtained as the eigenvalues of the companion
matrix, Roots far from the origin of the complex plane may have large
errors due to the numerical instability of the power series for such
values. Roots with multiplicity greater than 1 will also show larger
errors as the value of the series near such points is relatively
insensitive to errors in the roots. Isolated roots near the origin can
be improved by a few iterations of Newton's method.
Examples
--------
>>> import numpy.polynomial.polynomial as poly
>>> poly.polyroots(poly.polyfromroots((-1,0,1)))
array([-1., 0., 1.])
>>> poly.polyroots(poly.polyfromroots((-1,0,1))).dtype
dtype('float64')
>>> j = complex(0,1)
>>> poly.polyroots(poly.polyfromroots((-j,0,j)))
array([ 0.00000000e+00+0.j, 0.00000000e+00+1.j, 2.77555756e-17-1.j])
"""
# c is a trimmed copy
[c] = pu.as_series([c])
if len(c) < 2:
return np.array([], dtype=c.dtype)
if len(c) == 2:
return np.array([-c[0]/c[1]])
m = polycompanion(c)
r = la.eigvals(m)
r.sort()
return r
#
# polynomial class
#
exec(polytemplate.substitute(name='Polynomial', nick='poly', domain='[-1,1]'))
| gpl-2.0 |
ville-k/tensorflow | tensorflow/contrib/stateless/python/kernel_tests/stateless_random_ops_test.py | 54 | 3287 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for stateless random ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.contrib import stateless
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import random_seed
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.platform import test
CASES = [(stateless.stateless_random_uniform, random_ops.random_uniform),
(stateless.stateless_random_normal, random_ops.random_normal),
(stateless.stateless_truncated_normal, random_ops.truncated_normal)]
def invert_philox(key, value):
"""Invert the Philox bijection."""
key = np.array(key, dtype=np.uint32)
value = np.array(value, dtype=np.uint32)
step = np.array([0x9E3779B9, 0xBB67AE85], dtype=np.uint32)
for n in range(10)[::-1]:
key0, key1 = key + n * step
v0 = value[3] * 0x991a7cdb & 0xffffffff
v2 = value[1] * 0x6d7cae67 & 0xffffffff
hi0 = v0 * 0xD2511F53 >> 32
hi1 = v2 * 0xCD9E8D57 >> 32
v1 = hi1 ^ value[0] ^ key0
v3 = hi0 ^ value[2] ^ key1
value = v0, v1, v2, v3
return np.array(value)
class StatelessOpsTest(test.TestCase):
def testMatchStateful(self):
# Stateless ops should be the same as stateful ops on the first call
# after seed scrambling.
key = 0x3ec8f720, 0x02461e29
for seed in (7, 17), (11, 5), (2, 3):
preseed = invert_philox(key, (seed[0], 0, seed[1], 0)).astype(np.uint64)
preseed = preseed[::2] | preseed[1::2] << 32
random_seed.set_random_seed(seed[0])
with self.test_session(use_gpu=True):
for stateless_op, stateful_op in CASES:
for shape in (), (3,), (2, 5):
stateful = stateful_op(shape, seed=seed[1])
pure = stateless_op(shape, seed=preseed)
self.assertAllEqual(stateful.eval(), pure.eval())
def testDeterminism(self):
# Stateless values should be equal iff the seeds are equal (roughly)
with self.test_session(use_gpu=True):
seed_t = array_ops.placeholder(dtypes.int64, shape=[2])
seeds = [(x, y) for x in range(5) for y in range(5)] * 3
for stateless_op, _ in CASES:
for shape in (), (3,), (2, 5):
pure = stateless_op(shape, seed=seed_t)
values = [(seed, pure.eval(feed_dict={seed_t: seed}))
for seed in seeds]
for s0, v0 in values:
for s1, v1 in values:
self.assertEqual(s0 == s1, np.all(v0 == v1))
if __name__ == '__main__':
test.main()
| apache-2.0 |
tony810430/flink | flink-end-to-end-tests/flink-python-test/python/python_job.py | 2 | 3480 | ################################################################################
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
################################################################################
import logging
import os
import shutil
import sys
import tempfile
from pyflink.table import EnvironmentSettings, TableEnvironment
def word_count():
content = "line Licensed to the Apache Software Foundation ASF under one " \
"line or more contributor license agreements See the NOTICE file " \
"line distributed with this work for additional information " \
"line regarding copyright ownership The ASF licenses this file " \
"to you under the Apache License Version the " \
"License you may not use this file except in compliance " \
"with the License"
env_settings = EnvironmentSettings.new_instance().in_batch_mode().use_blink_planner().build()
t_env = TableEnvironment.create(environment_settings=env_settings)
# used to test pipeline.jars and pipleline.classpaths
config_key = sys.argv[1]
config_value = sys.argv[2]
t_env.get_config().get_configuration().set_string(config_key, config_value)
# register Results table in table environment
tmp_dir = tempfile.gettempdir()
result_path = tmp_dir + '/result'
if os.path.exists(result_path):
try:
if os.path.isfile(result_path):
os.remove(result_path)
else:
shutil.rmtree(result_path)
except OSError as e:
logging.error("Error removing directory: %s - %s.", e.filename, e.strerror)
logging.info("Results directory: %s", result_path)
sink_ddl = """
create table Results(
word VARCHAR,
`count` BIGINT,
`count_java` BIGINT
) with (
'connector.type' = 'filesystem',
'format.type' = 'csv',
'connector.path' = '{}'
)
""".format(result_path)
t_env.execute_sql(sink_ddl)
t_env.execute_sql("create temporary system function add_one as 'add_one.add_one' language python")
t_env.register_java_function("add_one_java", "org.apache.flink.python.tests.util.AddOne")
elements = [(word, 0) for word in content.split(" ")]
t_env.from_elements(elements, ["word", "count"]) \
.select("word, add_one(count) as count, add_one_java(count) as count_java") \
.group_by("word") \
.select("word, count(count) as count, count(count_java) as count_java") \
.execute_insert("Results")
if __name__ == '__main__':
logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(message)s")
word_count()
| apache-2.0 |
lu18887/perhapsgeekblog | perhapsgeek/zinnia/xmlrpc/__init__.py | 14 | 1235 | """XML-RPC methods for Zinnia"""
ZINNIA_XMLRPC_PINGBACK = [
('zinnia.xmlrpc.pingback.pingback_ping',
'pingback.ping'),
('zinnia.xmlrpc.pingback.pingback_extensions_get_pingbacks',
'pingback.extensions.getPingbacks')]
ZINNIA_XMLRPC_METAWEBLOG = [
('zinnia.xmlrpc.metaweblog.get_users_blogs',
'blogger.getUsersBlogs'),
('zinnia.xmlrpc.metaweblog.get_user_info',
'blogger.getUserInfo'),
('zinnia.xmlrpc.metaweblog.delete_post',
'blogger.deletePost'),
('zinnia.xmlrpc.metaweblog.get_authors',
'wp.getAuthors'),
('zinnia.xmlrpc.metaweblog.get_tags',
'wp.getTags'),
('zinnia.xmlrpc.metaweblog.get_categories',
'metaWeblog.getCategories'),
('zinnia.xmlrpc.metaweblog.new_category',
'wp.newCategory'),
('zinnia.xmlrpc.metaweblog.get_recent_posts',
'metaWeblog.getRecentPosts'),
('zinnia.xmlrpc.metaweblog.get_post',
'metaWeblog.getPost'),
('zinnia.xmlrpc.metaweblog.new_post',
'metaWeblog.newPost'),
('zinnia.xmlrpc.metaweblog.edit_post',
'metaWeblog.editPost'),
('zinnia.xmlrpc.metaweblog.new_media_object',
'metaWeblog.newMediaObject')]
ZINNIA_XMLRPC_METHODS = ZINNIA_XMLRPC_PINGBACK + ZINNIA_XMLRPC_METAWEBLOG
| mit |
zhiyanfoo/crunch-shake | crunch-shake/utils.py | 2 | 1649 | import json
import re
from collections import namedtuple
import string
# INPUT OUTPUT
def file_to_list(path):
with open(path, 'r') as inputFile:
return inputFile.readlines()
def json_file_to_dict(path):
with open(path, 'r') as jsonFile:
return json.load(jsonFile)
def to_json(x, path):
with open(path, 'w') as jsonFile:
json.dump(x, jsonFile)
def list_to_file(li, path):
with open(path, 'w') as outputFile:
outputFile.writelines(li)
def str_to_file(x, path):
with open(path, 'w') as outputFile:
outputFile.write(x)
# MATCHERS
def get_title(raw_play_lines):
pattern = re.compile("<title>(.*): Entire Play.*")
for line in raw_play_lines:
match = pattern.search(line)
if match:
return match.group(1)
raise ValueError
def get_matcher(words, identifier):
joined_words = "|".join(words)
pattern = "(?P<{0}>".format(identifier) + joined_words + ")"
matcher = re.compile(
pattern,
re.IGNORECASE)
return matcher
Matcher = namedtuple('Matcher', ['dialogue', 'character', 'stage_direction',
'instruction', 'act', 'scene'])
# HELPERS
def invert_dict(front_dict):
""" Take a dict of key->values and return values->[keys] """
back_dict = { value : [] for value in front_dict.values() }
for key, value in front_dict.items():
back_dict[value].append(key)
return back_dict
def create_remove_punctuation():
remove_punct_map = dict.fromkeys(map(ord, string.punctuation))
def remove_punctuation(line):
return line.translate(remove_punct_map)
return remove_punctuation
| mit |
huijunwu/heron | heron/instance/src/python/instance/st_heron_instance.py | 5 | 17184 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
'''module for single-thread Heron Instance in python'''
import argparse
import collections
import logging
import os
import resource
import traceback
import signal
import yaml
import heronpy.api.api_constants as api_constants
from heronpy.api.state.state import HashMapState
from heron.common.src.python.utils import log
from heron.proto import physical_plan_pb2, tuple_pb2, ckptmgr_pb2, common_pb2
from heron.instance.src.python.utils.misc import HeronCommunicator
from heron.instance.src.python.utils.misc import SerializerHelper
from heron.instance.src.python.utils.misc import PhysicalPlanHelper
from heron.instance.src.python.utils.metrics import GatewayMetrics, PyMetrics, MetricsCollector
from heron.instance.src.python.network import MetricsManagerClient, SingleThreadStmgrClient
from heron.instance.src.python.network import create_socket_options
from heron.instance.src.python.network import GatewayLooper
from heron.instance.src.python.basics import SpoutInstance, BoltInstance
import heron.instance.src.python.utils.system_constants as constants
from heron.instance.src.python.utils import system_config
Log = log.Log
AssignedInstance = collections.namedtuple('AssignedInstance', 'is_spout, protobuf, py_class')
def set_resource_limit(max_ram):
resource.setrlimit(resource.RLIMIT_RSS, (max_ram, max_ram))
# pylint: disable=too-many-instance-attributes
class SingleThreadHeronInstance(object):
"""SingleThreadHeronInstance is an implementation of Heron Instance in python"""
STREAM_MGR_HOST = "127.0.0.1"
METRICS_MGR_HOST = "127.0.0.1"
def __init__(self, topology_name, topology_id, instance,
stream_port, metrics_port, topo_pex_file_path):
# Basic information about this heron instance
self.topology_name = topology_name
self.topology_id = topology_id
self.instance = instance
self.stream_port = stream_port
self.metrics_port = metrics_port
self.topo_pex_file_abs_path = os.path.abspath(topo_pex_file_path)
self.sys_config = system_config.get_sys_config()
self.in_stream = HeronCommunicator(producer_cb=None, consumer_cb=None)
self.out_stream = HeronCommunicator(producer_cb=None, consumer_cb=None)
self.socket_map = dict()
self.looper = GatewayLooper(self.socket_map)
# Initialize metrics related
self.out_metrics = HeronCommunicator()
self.out_metrics.\
register_capacity(self.sys_config[constants.INSTANCE_INTERNAL_METRICS_WRITE_QUEUE_CAPACITY])
self.metrics_collector = MetricsCollector(self.looper, self.out_metrics)
self.gateway_metrics = GatewayMetrics(self.metrics_collector)
self.py_metrics = PyMetrics(self.metrics_collector)
# Create socket options and socket clients
socket_options = create_socket_options()
self._stmgr_client = \
SingleThreadStmgrClient(self.looper, self, self.STREAM_MGR_HOST, stream_port,
topology_name, topology_id, instance, self.socket_map,
self.gateway_metrics, socket_options)
self._metrics_client = \
MetricsManagerClient(self.looper, self.METRICS_MGR_HOST, metrics_port, instance,
self.out_metrics, self.in_stream, self.out_stream,
self.socket_map, socket_options, self.gateway_metrics, self.py_metrics)
self.my_pplan_helper = None
self.serializer = None
# my_instance is a AssignedInstance tuple
self.my_instance = None
self.is_instance_started = False
self.is_stateful_started = False
self.stateful_state = None
# Debugging purposes
def go_trace(_, stack):
with open("/tmp/trace.log", "w") as f:
traceback.print_stack(stack, file=f)
self.looper.register_timer_task_in_sec(self.looper.exit_loop, 0.0)
signal.signal(signal.SIGUSR1, go_trace)
def start(self):
self._stmgr_client.start_connect()
self._metrics_client.start_connect()
# call send_buffered_messages every time it is waken up
self.looper.add_wakeup_task(self.send_buffered_messages)
self.looper.loop()
def handle_new_tuple_set_2(self, hts2):
"""Called when new HeronTupleSet2 arrives
Convert(Assemble) HeronTupleSet2(raw byte array) to HeronTupleSet
See more at GitHub PR #1421
:param tuple_msg_set: HeronTupleSet2 type
"""
if self.my_pplan_helper is None or self.my_instance is None:
Log.error("Got tuple set when no instance assigned yet")
else:
hts = tuple_pb2.HeronTupleSet()
if hts2.HasField('control'):
hts.control.CopyFrom(hts2.control)
else:
hdts = tuple_pb2.HeronDataTupleSet()
hdts.stream.CopyFrom(hts2.data.stream)
try:
for trunk in hts2.data.tuples:
added_tuple = hdts.tuples.add()
added_tuple.ParseFromString(trunk)
except Exception:
Log.exception('Fail to deserialize HeronDataTuple')
hts.data.CopyFrom(hdts)
self.in_stream.offer(hts)
if self.my_pplan_helper.is_topology_running():
self.my_instance.py_class.process_incoming_tuples()
def handle_initiate_stateful_checkpoint(self, ckptmsg):
"""Called when we get InitiateStatefulCheckpoint message
:param ckptmsg: InitiateStatefulCheckpoint type
"""
self.in_stream.offer(ckptmsg)
if self.my_pplan_helper.is_topology_running():
self.my_instance.py_class.process_incoming_tuples()
def handle_start_stateful_processing(self, start_msg):
"""Called when we receive StartInstanceStatefulProcessing message
:param start_msg: StartInstanceStatefulProcessing type
"""
Log.info("Received start stateful processing for %s" % start_msg.checkpoint_id)
self.is_stateful_started = True
self.start_instance_if_possible()
def handle_restore_instance_state(self, restore_msg):
"""Called when we receive RestoreInstanceStateRequest message
:param restore_msg: RestoreInstanceStateRequest type
"""
Log.info("Restoring instance state to checkpoint %s" % restore_msg.state.checkpoint_id)
# Stop the instance
if self.is_stateful_started:
self.my_instance.py_class.stop()
self.my_instance.py_class.clear_collector()
self.is_stateful_started = False
# Clear all buffers
self.in_stream.clear()
self.out_stream.clear()
# Deser the state
if self.stateful_state is not None:
self.stateful_state.clear()
if restore_msg.state.state is not None and restore_msg.state.state:
try:
self.stateful_state = self.serializer.deserialize(restore_msg.state.state)
except Exception as e:
raise RuntimeError("Could not serialize state during restore " + str(e))
else:
Log.info("The restore request does not have an actual state")
if self.stateful_state is None:
self.stateful_state = HashMapState()
Log.info("Instance restore state deserialized")
# Send the response back
resp = ckptmgr_pb2.RestoreInstanceStateResponse()
resp.status.status = common_pb2.StatusCode.Value("OK")
resp.checkpoint_id = restore_msg.state.checkpoint_id
self._stmgr_client.send_message(resp)
def send_buffered_messages(self):
"""Send messages in out_stream to the Stream Manager"""
while not self.out_stream.is_empty() and self._stmgr_client.is_registered:
tuple_set = self.out_stream.poll()
if isinstance(tuple_set, tuple_pb2.HeronTupleSet):
tuple_set.src_task_id = self.my_pplan_helper.my_task_id
self.gateway_metrics.update_sent_packet(tuple_set.ByteSize())
self._stmgr_client.send_message(tuple_set)
def _handle_state_change_msg(self, new_helper):
"""Called when state change is commanded by stream manager"""
assert self.my_pplan_helper is not None
assert self.my_instance is not None and self.my_instance.py_class is not None
if self.my_pplan_helper.get_topology_state() != new_helper.get_topology_state():
# handle state change
# update the pplan_helper
self.my_pplan_helper = new_helper
if new_helper.is_topology_running():
if not self.is_instance_started:
self.start_instance_if_possible()
self.my_instance.py_class.invoke_activate()
elif new_helper.is_topology_paused():
self.my_instance.py_class.invoke_deactivate()
else:
raise RuntimeError("Unexpected TopologyState update: %s" % new_helper.get_topology_state())
else:
Log.info("Topology state remains the same.")
def handle_assignment_msg(self, pplan):
"""Called when new NewInstanceAssignmentMessage arrives
Tells this instance to become either spout/bolt.
:param pplan: PhysicalPlan proto
"""
new_helper = PhysicalPlanHelper(pplan, self.instance.instance_id,
self.topo_pex_file_abs_path)
if self.my_pplan_helper is not None and \
(self.my_pplan_helper.my_component_name != new_helper.my_component_name or
self.my_pplan_helper.my_task_id != new_helper.my_task_id):
raise RuntimeError("Our Assignment has changed. We will die to pick it.")
new_helper.set_topology_context(self.metrics_collector)
if self.my_pplan_helper is None:
Log.info("Received a new Physical Plan")
Log.info("Push the new pplan_helper to Heron Instance")
self._handle_assignment_msg(new_helper)
else:
Log.info("Received a new Physical Plan with the same assignment -- State Change")
Log.info("Old state: %s, new state: %s.",
self.my_pplan_helper.get_topology_state(), new_helper.get_topology_state())
self._handle_state_change_msg(new_helper)
def _handle_assignment_msg(self, pplan_helper):
self.my_pplan_helper = pplan_helper
self.serializer = SerializerHelper.get_serializer(self.my_pplan_helper.context)
if self.my_pplan_helper.is_spout:
# Starting a spout
my_spout = self.my_pplan_helper.get_my_spout()
Log.info("Incarnating ourselves as spout: %s with task id %s",
self.my_pplan_helper.my_component_name, str(self.my_pplan_helper.my_task_id))
self.in_stream. \
register_capacity(self.sys_config[constants.INSTANCE_INTERNAL_SPOUT_READ_QUEUE_CAPACITY])
self.out_stream. \
register_capacity(self.sys_config[constants.INSTANCE_INTERNAL_SPOUT_WRITE_QUEUE_CAPACITY])
py_spout_instance = SpoutInstance(self.my_pplan_helper, self.in_stream, self.out_stream,
self.looper)
self.my_instance = AssignedInstance(is_spout=True,
protobuf=my_spout,
py_class=py_spout_instance)
else:
# Starting a bolt
my_bolt = self.my_pplan_helper.get_my_bolt()
Log.info("Incarnating ourselves as bolt: %s with task id %s",
self.my_pplan_helper.my_component_name, str(self.my_pplan_helper.my_task_id))
self.in_stream. \
register_capacity(self.sys_config[constants.INSTANCE_INTERNAL_BOLT_READ_QUEUE_CAPACITY])
self.out_stream. \
register_capacity(self.sys_config[constants.INSTANCE_INTERNAL_BOLT_WRITE_QUEUE_CAPACITY])
py_bolt_instance = BoltInstance(self.my_pplan_helper, self.in_stream, self.out_stream,
self.looper)
self.my_instance = AssignedInstance(is_spout=False,
protobuf=my_bolt,
py_class=py_bolt_instance)
if self.my_pplan_helper.is_topology_running():
try:
self.start_instance_if_possible()
except Exception as e:
Log.error("Error with starting bolt/spout instance: " + str(e))
Log.error(traceback.format_exc())
else:
Log.info("The instance is deployed in deactivated state")
def start_instance_if_possible(self):
if self.my_pplan_helper is None:
return
if not self.my_pplan_helper.is_topology_running():
return
context = self.my_pplan_helper.context
mode = context.get_cluster_config().get(api_constants.TOPOLOGY_RELIABILITY_MODE,
api_constants.TopologyReliabilityMode.ATMOST_ONCE)
is_stateful = bool(mode == api_constants.TopologyReliabilityMode.EFFECTIVELY_ONCE)
if is_stateful and not self.is_stateful_started:
return
try:
Log.info("Starting bolt/spout instance now...")
self.my_instance.py_class.start(self.stateful_state)
self.is_instance_started = True
Log.info("Started instance successfully.")
except Exception as e:
Log.error(traceback.format_exc())
Log.error("Error when starting bolt/spout, bailing out...: %s", str(e))
self.looper.exit_loop()
def yaml_config_reader(config_path):
"""Reads yaml config file and returns auto-typed config_dict"""
if not config_path.endswith(".yaml"):
raise ValueError("Config file not yaml")
with open(config_path, 'r') as f:
config = yaml.load(f)
return config
# pylint: disable=missing-docstring
def main():
parser = argparse.ArgumentParser(description='Heron Python Instance')
parser.add_argument('--topology_name', required=True, help='Topology Name')
parser.add_argument('--topology_id', required=True, help='Topology Id')
parser.add_argument('--instance_id', required=True, help='Instance Id')
parser.add_argument('--component_name', required=True, help='Component Name')
parser.add_argument('--task_id', required=True, help='Task Id', type=int)
parser.add_argument('--component_index', required=True, help='Component Index', type=int)
parser.add_argument('--stmgr_id', required=True, help='StMgr Id')
parser.add_argument('--stmgr_port', required=True, help='StMgr Port', type=int)
parser.add_argument('--metricsmgr_port', required=True, help='MetricsMgr Port', type=int)
parser.add_argument('--sys_config', required=True, help='System Config File')
parser.add_argument('--override_config', required=True, help='Override Config File')
parser.add_argument('--topology_pex', required=True, help='Topology Pex File')
parser.add_argument('--max_ram', required=True, help='Maximum RAM to limit', type=int)
args = parser.parse_args()
sys_config = yaml_config_reader(args.sys_config)
override_config = yaml_config_reader(args.override_config)
system_config.set_sys_config(sys_config, override_config)
# get combined configuration
sys_config = system_config.get_sys_config()
# set resource limits
set_resource_limit(args.max_ram)
# create the protobuf instance
instance_info = physical_plan_pb2.InstanceInfo()
instance_info.task_id = args.task_id
instance_info.component_index = args.component_index
instance_info.component_name = args.component_name
instance = physical_plan_pb2.Instance()
instance.instance_id = args.instance_id
instance.stmgr_id = args.stmgr_id
instance.info.MergeFrom(instance_info)
# Logging init
log_dir = os.path.abspath(sys_config[constants.HERON_LOGGING_DIRECTORY])
max_log_files = sys_config[constants.HERON_LOGGING_MAXIMUM_FILES]
max_log_bytes = sys_config[constants.HERON_LOGGING_MAXIMUM_SIZE_MB] * constants.MB
log_file = os.path.join(log_dir, args.instance_id + ".log.0")
log.init_rotating_logger(level=logging.INFO, logfile=log_file,
max_files=max_log_files, max_bytes=max_log_bytes)
Log.info("\nStarting instance: " + args.instance_id + " for topology: " + args.topology_name +
" and topologyId: " + args.topology_id + " for component: " + args.component_name +
" with taskId: " + str(args.task_id) + " and componentIndex: " +
str(args.component_index) +
" and stmgrId: " + args.stmgr_id + " and stmgrPort: " + str(args.stmgr_port) +
" and metricsManagerPort: " + str(args.metricsmgr_port) +
"\n **Topology Pex file located at: " + args.topology_pex)
Log.debug("System config: " + str(sys_config))
Log.debug("Override config: " + str(override_config))
Log.debug("Maximum RAM: " + str(args.max_ram))
heron_instance = SingleThreadHeronInstance(args.topology_name, args.topology_id, instance,
args.stmgr_port, args.metricsmgr_port,
args.topology_pex)
heron_instance.start()
if __name__ == '__main__':
main()
| apache-2.0 |
skulbrane/googletest | test/gtest_env_var_test.py | 2408 | 3487 | #!/usr/bin/env python
#
# Copyright 2008, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Verifies that Google Test correctly parses environment variables."""
__author__ = '[email protected] (Zhanyong Wan)'
import os
import gtest_test_utils
IS_WINDOWS = os.name == 'nt'
IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux'
COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_env_var_test_')
environ = os.environ.copy()
def AssertEq(expected, actual):
if expected != actual:
print 'Expected: %s' % (expected,)
print ' Actual: %s' % (actual,)
raise AssertionError
def SetEnvVar(env_var, value):
"""Sets the env variable to 'value'; unsets it when 'value' is None."""
if value is not None:
environ[env_var] = value
elif env_var in environ:
del environ[env_var]
def GetFlag(flag):
"""Runs gtest_env_var_test_ and returns its output."""
args = [COMMAND]
if flag is not None:
args += [flag]
return gtest_test_utils.Subprocess(args, env=environ).output
def TestFlag(flag, test_val, default_val):
"""Verifies that the given flag is affected by the corresponding env var."""
env_var = 'GTEST_' + flag.upper()
SetEnvVar(env_var, test_val)
AssertEq(test_val, GetFlag(flag))
SetEnvVar(env_var, None)
AssertEq(default_val, GetFlag(flag))
class GTestEnvVarTest(gtest_test_utils.TestCase):
def testEnvVarAffectsFlag(self):
"""Tests that environment variable should affect the corresponding flag."""
TestFlag('break_on_failure', '1', '0')
TestFlag('color', 'yes', 'auto')
TestFlag('filter', 'FooTest.Bar', '*')
TestFlag('output', 'xml:tmp/foo.xml', '')
TestFlag('print_time', '0', '1')
TestFlag('repeat', '999', '1')
TestFlag('throw_on_failure', '1', '0')
TestFlag('death_test_style', 'threadsafe', 'fast')
TestFlag('catch_exceptions', '0', '1')
if IS_LINUX:
TestFlag('death_test_use_fork', '1', '0')
TestFlag('stack_trace_depth', '0', '100')
if __name__ == '__main__':
gtest_test_utils.Main()
| bsd-3-clause |
mancoast/CPythonPyc_test | cpython/253_test_dummy_thread.py | 70 | 7192 | """Generic thread tests.
Meant to be used by dummy_thread and thread. To allow for different modules
to be used, test_main() can be called with the module to use as the thread
implementation as its sole argument.
"""
import dummy_thread as _thread
import time
import Queue
import random
import unittest
from test import test_support
DELAY = 0 # Set > 0 when testing a module other than dummy_thread, such as
# the 'thread' module.
class LockTests(unittest.TestCase):
"""Test lock objects."""
def setUp(self):
# Create a lock
self.lock = _thread.allocate_lock()
def test_initlock(self):
#Make sure locks start locked
self.failUnless(not self.lock.locked(),
"Lock object is not initialized unlocked.")
def test_release(self):
# Test self.lock.release()
self.lock.acquire()
self.lock.release()
self.failUnless(not self.lock.locked(),
"Lock object did not release properly.")
def test_improper_release(self):
#Make sure release of an unlocked thread raises _thread.error
self.failUnlessRaises(_thread.error, self.lock.release)
def test_cond_acquire_success(self):
#Make sure the conditional acquiring of the lock works.
self.failUnless(self.lock.acquire(0),
"Conditional acquiring of the lock failed.")
def test_cond_acquire_fail(self):
#Test acquiring locked lock returns False
self.lock.acquire(0)
self.failUnless(not self.lock.acquire(0),
"Conditional acquiring of a locked lock incorrectly "
"succeeded.")
def test_uncond_acquire_success(self):
#Make sure unconditional acquiring of a lock works.
self.lock.acquire()
self.failUnless(self.lock.locked(),
"Uncondional locking failed.")
def test_uncond_acquire_return_val(self):
#Make sure that an unconditional locking returns True.
self.failUnless(self.lock.acquire(1) is True,
"Unconditional locking did not return True.")
self.failUnless(self.lock.acquire() is True)
def test_uncond_acquire_blocking(self):
#Make sure that unconditional acquiring of a locked lock blocks.
def delay_unlock(to_unlock, delay):
"""Hold on to lock for a set amount of time before unlocking."""
time.sleep(delay)
to_unlock.release()
self.lock.acquire()
start_time = int(time.time())
_thread.start_new_thread(delay_unlock,(self.lock, DELAY))
if test_support.verbose:
print
print "*** Waiting for thread to release the lock "\
"(approx. %s sec.) ***" % DELAY
self.lock.acquire()
end_time = int(time.time())
if test_support.verbose:
print "done"
self.failUnless((end_time - start_time) >= DELAY,
"Blocking by unconditional acquiring failed.")
class MiscTests(unittest.TestCase):
"""Miscellaneous tests."""
def test_exit(self):
#Make sure _thread.exit() raises SystemExit
self.failUnlessRaises(SystemExit, _thread.exit)
def test_ident(self):
#Test sanity of _thread.get_ident()
self.failUnless(isinstance(_thread.get_ident(), int),
"_thread.get_ident() returned a non-integer")
self.failUnless(_thread.get_ident() != 0,
"_thread.get_ident() returned 0")
def test_LockType(self):
#Make sure _thread.LockType is the same type as _thread.allocate_locke()
self.failUnless(isinstance(_thread.allocate_lock(), _thread.LockType),
"_thread.LockType is not an instance of what is "
"returned by _thread.allocate_lock()")
def test_interrupt_main(self):
#Calling start_new_thread with a function that executes interrupt_main
# should raise KeyboardInterrupt upon completion.
def call_interrupt():
_thread.interrupt_main()
self.failUnlessRaises(KeyboardInterrupt, _thread.start_new_thread,
call_interrupt, tuple())
def test_interrupt_in_main(self):
# Make sure that if interrupt_main is called in main threat that
# KeyboardInterrupt is raised instantly.
self.failUnlessRaises(KeyboardInterrupt, _thread.interrupt_main)
class ThreadTests(unittest.TestCase):
"""Test thread creation."""
def test_arg_passing(self):
#Make sure that parameter passing works.
def arg_tester(queue, arg1=False, arg2=False):
"""Use to test _thread.start_new_thread() passes args properly."""
queue.put((arg1, arg2))
testing_queue = Queue.Queue(1)
_thread.start_new_thread(arg_tester, (testing_queue, True, True))
result = testing_queue.get()
self.failUnless(result[0] and result[1],
"Argument passing for thread creation using tuple failed")
_thread.start_new_thread(arg_tester, tuple(), {'queue':testing_queue,
'arg1':True, 'arg2':True})
result = testing_queue.get()
self.failUnless(result[0] and result[1],
"Argument passing for thread creation using kwargs failed")
_thread.start_new_thread(arg_tester, (testing_queue, True), {'arg2':True})
result = testing_queue.get()
self.failUnless(result[0] and result[1],
"Argument passing for thread creation using both tuple"
" and kwargs failed")
def test_multi_creation(self):
#Make sure multiple threads can be created.
def queue_mark(queue, delay):
"""Wait for ``delay`` seconds and then put something into ``queue``"""
time.sleep(delay)
queue.put(_thread.get_ident())
thread_count = 5
testing_queue = Queue.Queue(thread_count)
if test_support.verbose:
print
print "*** Testing multiple thread creation "\
"(will take approx. %s to %s sec.) ***" % (DELAY, thread_count)
for count in xrange(thread_count):
if DELAY:
local_delay = round(random.random(), 1)
else:
local_delay = 0
_thread.start_new_thread(queue_mark,
(testing_queue, local_delay))
time.sleep(DELAY)
if test_support.verbose:
print 'done'
self.failUnless(testing_queue.qsize() == thread_count,
"Not all %s threads executed properly after %s sec." %
(thread_count, DELAY))
def test_main(imported_module=None):
global _thread, DELAY
if imported_module:
_thread = imported_module
DELAY = 2
if test_support.verbose:
print
print "*** Using %s as _thread module ***" % _thread
test_support.run_unittest(LockTests, MiscTests, ThreadTests)
if __name__ == '__main__':
test_main()
| gpl-3.0 |
liam-middlebrook/yaml-cpp.new-api | test/gmock-1.7.0/gtest/test/gtest_throw_on_failure_test.py | 2917 | 5766 | #!/usr/bin/env python
#
# Copyright 2009, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Tests Google Test's throw-on-failure mode with exceptions disabled.
This script invokes gtest_throw_on_failure_test_ (a program written with
Google Test) with different environments and command line flags.
"""
__author__ = '[email protected] (Zhanyong Wan)'
import os
import gtest_test_utils
# Constants.
# The command line flag for enabling/disabling the throw-on-failure mode.
THROW_ON_FAILURE = 'gtest_throw_on_failure'
# Path to the gtest_throw_on_failure_test_ program, compiled with
# exceptions disabled.
EXE_PATH = gtest_test_utils.GetTestExecutablePath(
'gtest_throw_on_failure_test_')
# Utilities.
def SetEnvVar(env_var, value):
"""Sets an environment variable to a given value; unsets it when the
given value is None.
"""
env_var = env_var.upper()
if value is not None:
os.environ[env_var] = value
elif env_var in os.environ:
del os.environ[env_var]
def Run(command):
"""Runs a command; returns True/False if its exit code is/isn't 0."""
print 'Running "%s". . .' % ' '.join(command)
p = gtest_test_utils.Subprocess(command)
return p.exited and p.exit_code == 0
# The tests. TODO([email protected]): refactor the class to share common
# logic with code in gtest_break_on_failure_unittest.py.
class ThrowOnFailureTest(gtest_test_utils.TestCase):
"""Tests the throw-on-failure mode."""
def RunAndVerify(self, env_var_value, flag_value, should_fail):
"""Runs gtest_throw_on_failure_test_ and verifies that it does
(or does not) exit with a non-zero code.
Args:
env_var_value: value of the GTEST_BREAK_ON_FAILURE environment
variable; None if the variable should be unset.
flag_value: value of the --gtest_break_on_failure flag;
None if the flag should not be present.
should_fail: True iff the program is expected to fail.
"""
SetEnvVar(THROW_ON_FAILURE, env_var_value)
if env_var_value is None:
env_var_value_msg = ' is not set'
else:
env_var_value_msg = '=' + env_var_value
if flag_value is None:
flag = ''
elif flag_value == '0':
flag = '--%s=0' % THROW_ON_FAILURE
else:
flag = '--%s' % THROW_ON_FAILURE
command = [EXE_PATH]
if flag:
command.append(flag)
if should_fail:
should_or_not = 'should'
else:
should_or_not = 'should not'
failed = not Run(command)
SetEnvVar(THROW_ON_FAILURE, None)
msg = ('when %s%s, an assertion failure in "%s" %s cause a non-zero '
'exit code.' %
(THROW_ON_FAILURE, env_var_value_msg, ' '.join(command),
should_or_not))
self.assert_(failed == should_fail, msg)
def testDefaultBehavior(self):
"""Tests the behavior of the default mode."""
self.RunAndVerify(env_var_value=None, flag_value=None, should_fail=False)
def testThrowOnFailureEnvVar(self):
"""Tests using the GTEST_THROW_ON_FAILURE environment variable."""
self.RunAndVerify(env_var_value='0',
flag_value=None,
should_fail=False)
self.RunAndVerify(env_var_value='1',
flag_value=None,
should_fail=True)
def testThrowOnFailureFlag(self):
"""Tests using the --gtest_throw_on_failure flag."""
self.RunAndVerify(env_var_value=None,
flag_value='0',
should_fail=False)
self.RunAndVerify(env_var_value=None,
flag_value='1',
should_fail=True)
def testThrowOnFailureFlagOverridesEnvVar(self):
"""Tests that --gtest_throw_on_failure overrides GTEST_THROW_ON_FAILURE."""
self.RunAndVerify(env_var_value='0',
flag_value='0',
should_fail=False)
self.RunAndVerify(env_var_value='0',
flag_value='1',
should_fail=True)
self.RunAndVerify(env_var_value='1',
flag_value='0',
should_fail=False)
self.RunAndVerify(env_var_value='1',
flag_value='1',
should_fail=True)
if __name__ == '__main__':
gtest_test_utils.Main()
| mit |
acuzzio/GridQuantumPropagator | src/quantumpropagator/TDPropagator.py | 1 | 30840 | ''' this is the module for the hamiltonian '''
import numpy as np
import os
import pickle
import datetime
from quantumpropagator import (printDict, printDictKeys, loadInputYAML, bring_input_to_AU,
warning, labTranformA, gaussian2, makeJustAnother2DgraphComplex,
fromHartreetoCmMin1, makeJustAnother2DgraphMULTI,derivative3d,rk4Ene3d,derivative1dPhi,
good, asyncFun, derivative1dGam, create_enumerated_folder, fromCmMin1toFs,
makeJustAnother2DgraphComplexALLS, derivative2dGamThe, retrieve_hdf5_data,
writeH5file, writeH5fileDict, heatMap2dWavefunction, abs2, fromHartoEv,
makeJustAnother2DgraphComplexSINGLE, fromLabelsToFloats, derivative2dGamTheMu,
graphic_Pulse,derivative3dMu,equilibriumIndex, readWholeH5toDict, err)
from quantumpropagator.CPropagator import (CextractEnergy3dMu, Cderivative3dMu, Cenergy_2d_GamThe,
Cderivative_2d_GamThe,Cenergy_1D_Phi, Cderivative_1D_Phi,
Cenergy_1D_Gam, Cderivative_1D_Gam, Cenergy_1D_The,
Cderivative_1D_The,Crk4Ene3d, version_Cpropagator, pulZe,
Cderivative3dMu_reverse_time)
def calculate_stuffs_on_WF(single_wf, inp, outputFile):
'''
This function is a standalone function that recreates the output file counting also the absorbing potential
'''
counter = 0
nstates = inp['nstates']
ii = 0
wf = single_wf['WF']
t_fs,t = single_wf['Time']
kind = inp['kind']
if kind != '3d':
err('This function is implemented only in 3d code')
CEnergy, Cpropagator = select_propagator(kind)
kin, pot, pul, absS = CEnergy(t,wf,inp)
kinetic = np.vdot(wf,kin)
potential = np.vdot(wf,pot)
pulse_interaction = np.vdot(wf,pul)
absorbing_potential = np.vdot(wf,absS)
absorbing_potential_thing = np.real(-2j * absorbing_potential)
total = kinetic + potential + pulse_interaction
initialTotal = inp['initialTotal']
norm_wf = np.linalg.norm(wf)
outputStringS = ' {:04d} |{:10d} |{:11.4f} | {:+e} | {:+7.5e} | {:+7.5e} | {:+7.5e} | {:+7.5e} | {:+7.5e} | {:+10.3e} | {:+10.3e} | {:+10.3e} | {:+10.3e} |'
outputString = outputStringS.format(counter, ii,t*0.02418884,1-norm_wf,fromHartoEv(kinetic.real),fromHartoEv(potential.real),fromHartoEv(total.real),fromHartoEv(initialTotal - total.real), fromHartoEv(pulse_interaction.real), pulZe(t,inp['pulseX']), pulZe(t,inp['pulseY']), pulZe(t,inp['pulseZ']), absorbing_potential_thing)
print(outputString)
kind = inp['kind']
outputStringA = "{:11.4f} {:+7.5e}".format(t,absorbing_potential_thing)
for i in range(nstates):
if kind == '3d':
singleStatewf = wf[:,:,:,i]
singleAbspote = absS[:,:,:,i]
norm_loss_this_step = np.real(-2j * np.vdot(singleStatewf,singleAbspote))
if kind == 'GamThe':
err('no 2d here')
elif kind == 'Phi' or kind == 'Gam' or kind == 'The':
err('no 1d here')
outputStringA += " {:+7.5e} ".format(norm_loss_this_step)
with open(outputFile, "a") as oof:
outputStringS2 = '{}'
outputString2 = outputStringS2.format(outputStringA)
oof.write(outputString2 + '\n')
def expandcube(inp):
return inp
def doubleAxespoins1(Y):
N = len(Y)
X = np.arange(0, 2*N, 2)
X_new = np.arange(2*N-1) # Where you want to interpolate
Y_new = np.interp(X_new, X, Y)
return(Y_new)
def doubleAxespoins(Y):
return (doubleAxespoins1(doubleAxespoins1(Y)))
def select_propagator(kind):
'''
This function will return correct function name for the propagators
kind :: String <- the kind of dynamics
'''
Propagators = {'3d' : (CextractEnergy3dMu, Cderivative3dMu),
'GamThe' : (Cenergy_2d_GamThe,Cderivative_2d_GamThe),
'Phi' : (Cenergy_1D_Phi, Cderivative_1D_Phi),
'Gam' : (Cenergy_1D_Gam, Cderivative_1D_Gam),
'The' : (Cenergy_1D_The, Cderivative_1D_The),
}
return Propagators[kind]
def propagate3D(dataDict, inputDict):
'''
Two dictionaries, one from data file and one from input file
it starts and run the 3d propagation of the wavefunction...
'''
printDict(inputDict)
printDictKeys(dataDict)
printDictKeys(inputDict)
#startState = inputDict['states']
_, _, _, nstates = dataDict['potCube'].shape
phiL, gamL, theL, natoms, _ = dataDict['geoCUBE'].shape
# INITIAL WF default values
if 'factor' in inputDict:
factor = inputDict['factor']
warning('WF widened using factor: {}'.format(factor))
else:
factor = 1
if 'displ' in inputDict:
displ = inputDict['displ']
else:
displ = (0,0,0)
if 'init_mom' in inputDict:
init_mom = inputDict['init_mom']
else:
init_mom = (0,0,0)
if 'initial_state' in inputDict:
initial_state = inputDict['initial_state']
warning('Initial gaussian wavepacket in state {}'.format(initial_state))
else:
initial_state = 0
wf = np.zeros((phiL, gamL, theL, nstates), dtype=complex)
print(initial_state)
wf[:,:,:,initial_state] = initialCondition3d(wf[:,:,:,initial_state],dataDict,factor,displ,init_mom)
# Take values array from labels (radians already)
phis,gams,thes = fromLabelsToFloats(dataDict)
# take step
dphi = phis[0] - phis[1]
dgam = gams[0] - gams[1]
dthe = thes[0] - thes[1]
inp = { 'dt' : inputDict['dt'],
'fullTime' : inputDict['fullTime'],
'phiL' : phiL,
'gamL' : gamL,
'theL' : theL,
'natoms' : natoms,
'phis' : phis,
'gams' : gams,
'thes' : thes,
'dphi' : dphi,
'dgam' : dgam,
'dthe' : dthe,
'potCube' : dataDict['potCube'],
'kinCube' : dataDict['kinCube'],
'dipCube' : dataDict['dipCUBE'],
'nacCube' : dataDict['smoCube'],
'pulseX' : inputDict['pulseX'],
'pulseY' : inputDict['pulseY'],
'pulseZ' : inputDict['pulseZ'],
'nstates' : nstates,
'kind' : inputDict['kind'],
}
#########################################
# Here the cube expansion/interpolation #
#########################################
inp = expandcube(inp)
########################################
# Potentials to Zero and normalization #
########################################
inp['potCube'] = dataDict['potCube'] - np.amin(dataDict['potCube'])
norm_wf = np.linalg.norm(wf)
good('starting NORM deviation : {}'.format(1-norm_wf))
# magnify the potcube
if 'enePot' in inputDict:
enePot = inputDict['enePot']
inp['potCube'] = inp['potCube'] * enePot
if enePot == 0:
warning('This simulation is done with zero Potential energy')
elif enePot == 1:
good('Simulation done with original Potential energy')
else:
warning('The potential energy has been magnified {} times'.format(enePot))
# constant the kinCube
kinK = False
if kinK:
kokoko = 1000
inp['kinCube'] = inp['kinCube']*kokoko
warning('kincube divided by {}'.format(kokoko))
if 'multiply_nac' in inputDict:
# this keyword can be used to multiply NACs. It works with a float or a list of triplet
# multiply_nac : 10 -> will multiply all by 10
# multiply_nac : [[1,2,10.0],[3,4,5.0]] -> will multiply 1,2 by 10 and 3,4 by 5
nac_multiplier = inputDict['multiply_nac']
if type(nac_multiplier) == int or type(nac_multiplier) == float:
warning('all Nacs are multiplied by {}'.format(nac_multiplier))
inp['nacCube'] = inp['nacCube'] * nac_multiplier
if type(nac_multiplier) == list:
warning('There is a list of nac multiplications, check input')
for state_one, state_two, multiply_factor in nac_multiplier:
inp['nacCube'][:,:,:,state_one,state_two,:] = inp['nacCube'][:,:,:,state_one,state_two,:]*multiply_factor
inp['nacCube'][:,:,:,state_two,state_one,:] = inp['nacCube'][:,:,:,state_two,state_one,:]*multiply_factor
warning('NACS corresponding of state {} and state {} are multiplied by {}'.format(state_one, state_two, multiply_factor))
inp['Nac_multiplier'] = nac_multiplier
nameRoot = create_enumerated_folder(inputDict['outFol'])
inputDict['outFol'] = nameRoot
inp['outFol'] = nameRoot
numStates = inputDict['states']
###################
# Absorbing Thing #
###################
if 'absorb' in inputDict:
good('ABSORBING POTENTIAL is taken from file')
file_absorb = inputDict['absorb']
print('{}'.format(file_absorb))
inp['absorb'] = retrieve_hdf5_data(file_absorb,'absorb')
else:
good('NO ABSORBING POTENTIAL')
inp['absorb'] = np.zeros_like(inp['potCube'])
################
# slice states #
################
kind = inp['kind']
# Take equilibrium points from directionFile
# warning('This is a bad equilibriumfinder')
# gsm_phi_ind, gsm_gam_ind, gsm_the_ind = equilibriumIndex(inputDict['directions1'],dataDict)
gsm_phi_ind, gsm_gam_ind, gsm_the_ind = (29,28,55)
warning('You inserted equilibrium points by hand: {} {} {}'.format(gsm_phi_ind, gsm_gam_ind, gsm_the_ind))
inp['nstates'] = numStates
if kind == '3d':
inp['potCube'] = inp['potCube'][:,:,:,:numStates]
inp['kinCube'] = inp['kinCube'][:,:,:]
inp['dipCube'] = inp['dipCube'][:,:,:,:,:numStates,:numStates]
wf = wf[:,:,:,:numStates]
good('Propagation in 3D.')
print('\nDimensions:\nPhi: {}\nGam: {}\nThet: {}\nNstates: {}\nNatoms: {}\n'.format(phiL, gamL, theL,numStates, natoms))
elif kind == 'GamThe':
inp['potCube'] = inp['potCube'][gsm_phi_ind,:,:,:numStates]
inp['kinCube'] = inp['kinCube'][gsm_phi_ind,:,:]
inp['dipCube'] = inp['dipCube'][gsm_phi_ind,:,:,:,:numStates,:numStates]
wf = wf[gsm_phi_ind,:,:,:numStates]
good('Propagation in GAM-THE with Phi {}'.format(gsm_phi_ind))
print('Shapes: P:{} K:{} W:{} D:{}'.format(inp['potCube'].shape, inp['kinCube'].shape, wf.shape, inp['dipCube'].shape))
print('\nDimensions:\nGam: {}\nThe: {}\nNstates: {}\nNatoms: {}\n'.format(gamL, theL, numStates, natoms))
norm_wf = np.linalg.norm(wf)
wf = wf / norm_wf
elif kind == 'Phi':
inp['potCube'] = inp['potCube'][:,gsm_gam_ind,gsm_the_ind,:numStates]
inp['kinCube'] = inp['kinCube'][:,gsm_gam_ind,gsm_the_ind]
inp['dipCube'] = inp['dipCube'][:,gsm_gam_ind,gsm_the_ind,:,:numStates,:numStates]
wf = wf[:,gsm_gam_ind,gsm_the_ind,:numStates]
good('Propagation in PHI with Gam {} and The {}'.format(gsm_gam_ind,gsm_the_ind))
print('Shapes: P:{} K:{} W:{} D:{}'.format(inp['potCube'].shape, inp['kinCube'].shape, wf.shape, inp['dipCube'].shape))
print('\nDimensions:\nPhi: {}\nNstates: {}\nNatoms: {}\n'.format(phiL, numStates, natoms))
norm_wf = np.linalg.norm(wf)
wf = wf / norm_wf
elif kind == 'Gam':
inp['potCube'] = inp['potCube'][gsm_phi_ind,:,gsm_the_ind,:numStates]
inp['kinCube'] = inp['kinCube'][gsm_phi_ind,:,gsm_the_ind]
inp['dipCube'] = inp['dipCube'][gsm_phi_ind,:,gsm_the_ind,:,:numStates,:numStates]
wf = wf[gsm_phi_ind,:,gsm_the_ind,:numStates]
good('Propagation in GAM with Phi {} and The {}'.format(gsm_phi_ind,gsm_the_ind))
print('Shapes: P:{} K:{} W:{} D:{}'.format(inp['potCube'].shape, inp['kinCube'].shape, wf.shape, inp['dipCube'].shape))
print('\nDimensions:\nGam: {}\nNstates: {}\nNatoms: {}\n'.format(gamL, numStates, natoms))
norm_wf = np.linalg.norm(wf)
wf = wf / norm_wf
elif kind == 'The':
sposta = False
if sposta:
gsm_phi_ind = 20
gsm_gam_ind = 20
warning('Phi is {}, NOT EQUILIBRIUM'.format(gsm_phi_ind))
warning('Gam is {}, NOT EQUILIBRIUM'.format(gsm_gam_ind))
inp['potCube'] = inp['potCube'][gsm_phi_ind,gsm_gam_ind,:,:numStates]
inp['absorb'] = inp['absorb'][gsm_phi_ind,gsm_gam_ind,:,:numStates]
inp['kinCube'] = inp['kinCube'][gsm_phi_ind,gsm_gam_ind,:]
inp['dipCube'] = inp['dipCube'][gsm_phi_ind,gsm_gam_ind,:,:,:numStates,:numStates]
inp['nacCube'] = inp['nacCube'][gsm_phi_ind,gsm_gam_ind,:,:numStates,:numStates,:]
wf = wf[gsm_phi_ind,gsm_gam_ind,:,:numStates]
# doubleGridPoints
doubleThis = False
if doubleThis:
warning('POINTS DOUBLED ALONG THETA')
inp['thes'] = doubleAxespoins(inp['thes'])
inp['theL'] = inp['thes'].size
inp['dthe'] = inp['thes'][0] - inp['thes'][1]
inp['potCube'] = np.array([doubleAxespoins(x) for x in inp['potCube'].T]).T
newWf = np.empty((inp['theL'],numStates), dtype=complex)
for ssssss in range(numStates):
newWf[:,ssssss] = doubleAxespoins(wf[:,ssssss])
wf = newWf
newNac = np.empty((inp['theL'],numStates,numStates,3))
for nnn in range(2):
for mmm in range(2):
for aaa in range(3):
newNac[:,nnn,mmm,aaa] = doubleAxespoins(inp['nacCube'][:,nnn,mmm,aaa])
inp['nacCube'] = newNac
newKin = np.empty((inp['theL'],9,3))
for nnn in range(9):
for mmm in range(3):
newKin[:,nnn,mmm] = doubleAxespoins(inp['kinCube'][:,nnn,mmm])
inp['kinCube'] = newKin
good('Propagation in THE with Phi {} and Gam {}'.format(gsm_phi_ind,gsm_gam_ind))
print('Shapes: P:{} K:{} W:{} D:{}'.format(inp['potCube'].shape, inp['kinCube'].shape, wf.shape, inp['dipCube'].shape))
print('\nDimensions:\nThe: {}\nNstates: {}\nNatoms: {}\n'.format(theL, numStates, natoms))
norm_wf = np.linalg.norm(wf)
wf = wf / norm_wf
else:
err('I do not recognize the kind')
initial_time_simulation = 0.0
# take a wf from file (and not from initial condition)
if 'initialFile' in inputDict:
warning('we are taking initial wf from file')
wffn = inputDict['initialFile']
print('File -> {}'.format(wffn))
wf_not_norm = retrieve_hdf5_data(wffn,'WF')
initial_time_simulation = retrieve_hdf5_data(wffn,'Time')[1] # in hartree
#wf = wf_not_norm/np.linalg.norm(wf_not_norm)
wf = wf_not_norm
#############################
# PROPAGATOR SELECTION HERE #
#############################
CEnergy, Cpropagator = select_propagator(kind)
good('Cpropagator version: {}'.format(version_Cpropagator()))
# INITIAL DYNAMICS VALUES
dt = inp['dt']
if 'reverse_time' in inputDict:
warning('Time is reversed !!')
dt = -dt
Cpropagator = Cderivative3dMu_reverse_time
t = initial_time_simulation
counter = 0
fulltime = inp['fullTime']
fulltimeSteps = int(fulltime/abs(dt))
deltasGraph = inputDict['deltasGraph']
print('I will do {} steps.\n'.format(fulltimeSteps))
outputFile = os.path.join(nameRoot, 'output')
outputFileP = os.path.join(nameRoot, 'outputPopul')
outputFileA = os.path.join(nameRoot, 'Output_Abs')
print('\ntail -f {}\n'.format(outputFileP))
if inputDict['readme']:
outputFilereadme = os.path.join(nameRoot, 'README')
with open(outputFilereadme, "w") as oofRR:
oofRR.write(inputDict['readme'])
print('file readme written')
# calculating initial total/potential/kinetic
kin, pot, pul, absS = CEnergy(t,wf,inp)
kinetic = np.vdot(wf,kin)
potential = np.vdot(wf,pot)
pulse_interaction = np.vdot(wf,pul)
initialTotal = kinetic + potential + pulse_interaction
inp['initialTotal'] = initialTotal.real
# to give the graph a nice range
inp['vmax_value'] = abs2(wf).max()
# graph the pulse
graphic_Pulse(inp)
# saving input data in h5 file
dataH5filename = os.path.join(nameRoot, 'allInput.h5')
writeH5fileDict(dataH5filename,inp)
# print top of table
header = ' Coun | step N | fs | NORM devia. | Kin. Energy | Pot. Energy | Total Energy | Tot devia. | Pulse_Inter. | Pulse X | Pulse Y | Pulse Z | Norm Loss |'
bar = ('-' * (len(header)))
print('Energies in ElectronVolt \n{}\n{}\n{}'.format(bar,header,bar))
for ii in range(fulltimeSteps):
if (ii % deltasGraph) == 0 or ii==fulltimeSteps-1:
# async is awesome. But it is not needed in 1d and maybe in 2d.
if kind == '3D':
asyncFun(doAsyncStuffs,wf,t,ii,inp,inputDict,counter,outputFile,outputFileP,outputFileA,CEnergy)
else:
doAsyncStuffs(wf,t,ii,inp,inputDict,counter,outputFile,outputFileP,outputFileA,CEnergy)
counter += 1
wf = Crk4Ene3d(Cpropagator,t,wf,inp)
t = t + dt
def restart_propagation(inp,inputDict):
'''
This function restarts a propagation that has been stopped
'''
import glob
nameRoot = inputDict['outFol']
list_wave_h5 = sorted(glob.glob(nameRoot + '/Gaussian*.h5'))
last_wave_h5 = list_wave_h5[-1]
wf = retrieve_hdf5_data(last_wave_h5,'WF')
t = retrieve_hdf5_data(last_wave_h5,'Time')[1] # [1] is atomic units
kind = inp['kind']
deltasGraph = inputDict['deltasGraph']
counter = len(list_wave_h5) - 1
dt = inputDict['dt']
fulltime = inputDict['fullTime']
fulltimeSteps = int(fulltime/dt)
outputFile = os.path.join(nameRoot, 'output')
outputFileP = os.path.join(nameRoot, 'outputPopul')
outputFileA = os.path.join(nameRoot, 'Output_Abs')
if (inputDict['fullTime'] == inp['fullTime']):
good('Safe restart with same fulltime')
#h5_data_file = os.path.join(nameRoot,'allInput.h5')
else:
h5_data_file = os.path.join(nameRoot,'allInput.h5')
dict_all_data = readWholeH5toDict(h5_data_file)
dict_all_data['fullTime'] = inputDict['fullTime']
writeH5fileDict(h5_data_file, dict_all_data)
good('different fullTime detected and allInput updated')
print('\ntail -f {}\n'.format(outputFileP))
CEnergy, Cpropagator = select_propagator(kind)
good('Cpropagator version: {}'.format(version_Cpropagator()))
ii_initial = counter * deltasGraph
print('I will do {} more steps.\n'.format(fulltimeSteps-ii_initial))
if True:
print('Calculation restart forced on me... I assume you did everything you need')
else:
warning('Did you restart this from a finished calculation?')
strout = "rm {}\nsed -i '$ d' {}\nsed -i '$ d' {}\n"
print(strout.format(last_wave_h5,outputFile,outputFileP))
input("Press Enter to continue...")
strOUT = '{} {} {}'.format(ii_initial,counter,fulltimeSteps)
good(strOUT)
for ii in range(ii_initial,fulltimeSteps):
#print('ii = {}'.format(ii))
if ((ii % deltasGraph) == 0 or ii==fulltimeSteps-1):
# async is awesome. But it is not needed in 1d and maybe in 2d.
if kind == '3D':
asyncFun(doAsyncStuffs,wf,t,ii,inp,inputDict,counter,outputFile,outputFileP,outputFileA,CEnergy)
else:
doAsyncStuffs(wf,t,ii,inp,inputDict,counter,outputFile,outputFileP,outputFileA,CEnergy)
counter += 1
wf = Crk4Ene3d(Cpropagator,t,wf,inp)
t = t + dt
def doAsyncStuffs(wf,t,ii,inp,inputDict,counter,outputFile,outputFileP,outputFileA,CEnergy):
nameRoot = inputDict['outFol']
nstates = inp['nstates']
name = os.path.join(nameRoot, 'Gaussian' + '{:04}'.format(counter))
h5name = name + ".h5"
writeH5file(h5name,[("WF", wf),("Time", [t*0.02418884,t])])
time1 = datetime.datetime.now()
kin, pot, pul, absS = CEnergy(t,wf,inp)
time2 = datetime.datetime.now()
#print(time2-time1)
kinetic = np.vdot(wf,kin)
potential = np.vdot(wf,pot)
pulse_interaction = np.vdot(wf,pul)
absorbing_potential = np.vdot(wf,absS)
#print(absorbing_potential)
# you asked and discussed with Stephan about it. This is the norm loss due to CAP complex absorbing potential. It needs to be multiplied by -2i.
absorbing_potential_thing = np.real(-2j * absorbing_potential)
#print(absorbing_potential_thing)
total = kinetic + potential + pulse_interaction
initialTotal = inp['initialTotal']
norm_wf = np.linalg.norm(wf)
## you wanted to print the header when the table goes off screen... this is why you get the rows number
#rows, _ = os.popen('stty size', 'r').read().split()
#if int(rows) // counter == 0:
# print('zero')
outputStringS = ' {:04d} |{:10d} |{:11.4f} | {:+e} | {:+7.5e} | {:+7.5e} | {:+7.5e} | {:+7.5e} | {:+7.5e} | {:+10.3e} | {:+10.3e} | {:+10.3e} | {:+10.3e} |'
outputString = outputStringS.format(counter,
ii,
t*0.02418884,
1-norm_wf,
fromHartoEv(kinetic.real),
fromHartoEv(potential.real),
fromHartoEv(total.real),
fromHartoEv(initialTotal - total.real),
fromHartoEv(pulse_interaction.real),
pulZe(t,inp['pulseX']),
pulZe(t,inp['pulseY']),
pulZe(t,inp['pulseZ']),
absorbing_potential_thing)
print(outputString)
kind = inp['kind']
outputStringSP = "{:11.4f}".format(t/41.3)
outputStringA = "{:11.4f} {:+7.5e}".format(t,absorbing_potential_thing)
for i in range(nstates):
if kind == '3d':
singleStatewf = wf[:,:,:,i]
singleAbspote = absS[:,:,:,i]
norm_loss_this_step = np.real(-2j * np.vdot(singleStatewf,singleAbspote))
if kind == 'GamThe':
singleStatewf = wf[:,:,i]
elif kind == 'Phi' or kind == 'Gam' or kind == 'The':
singleStatewf = wf[:,i]
outputStringA += " {:+7.5e} ".format(norm_loss_this_step)
outputStringSP += " {:+7.5e} ".format(np.linalg.norm(singleStatewf)**2)
with open(outputFileA, "a") as oofA:
oofA.write(outputStringA + '\n')
with open(outputFileP, "a") as oofP:
oofP.write(outputStringSP + '\n')
with open(outputFile, "a") as oof:
outputStringS2 = '{} {} {} {} {} {} {} {} {} {} {} {}'
outputString2 = outputStringS2.format(counter,ii,t/41.3,1-norm_wf,fromHartoEv(kinetic.real),fromHartoEv(potential.real),fromHartoEv(total.real),fromHartoEv(initialTotal - total.real), pulZe(t,inp['pulseX']), pulZe(t,inp['pulseY']), pulZe(t,inp['pulseZ']), absorbing_potential_thing)
oof.write(outputString2 + '\n')
#####################
# on the fly graphs #
#####################
if 'graphs' in inputDict:
vmaxV = inp['vmax_value']
# I am sure there is a better way to do this...
if kind == 'Phi':
valuesX = inp['phis']
label = 'Phi {:11.4f}'.format(t/41.3)
elif kind == 'Gam':
valuesX = inp['gams']
label = 'Gam {:11.4f}'.format(t/41.3)
pot=inp['potCube'][0]
elif kind == 'The':
valuesX = inp['thes']
label = 'The {:11.4f}'.format(t/41.3)
if kind == 'Phi' or kind == 'Gam' or kind == 'The':
graphFileName = name + ".png"
makeJustAnother2DgraphComplexSINGLE(valuesX,wf,graphFileName,label)
if kind == 'GamThe':
for i in range(nstates):
for j in range(i+1): # In python the handshakes are like this...
graphFileName = '{}_state_{}_{}.png'.format(name,i,j)
heatMap2dWavefunction(wf[:,:,i],wf[:,:,j],graphFileName,t/41.3,vmaxV)
def forcehere(vec,ind,h=None):
'''
calculates the numerical force at point at index index
vector :: np.array(double)
index :: Int
'''
if h == None:
warning('dimensionality is not clear')
h = 1
num = (-vec[ind-2]+16*vec[ind-1]-30*vec[ind]+16*vec[ind+1]-vec[ind+2])
denom = 12 * h**2
return(num/denom)
def initialCondition3d(wf, dataDict, factor=None, displ=None, init_mom=None):
'''
calculates the initial condition WV
wf :: np.array(phiL,gamL,theL) Complex
datadict :: Dictionary {}
'''
good('Initial condition printing')
# Take equilibrium points
#gsm_phi_ind = dataDict['phis'].index('P000-000')
#gsm_gam_ind = dataDict['gams'].index('P016-923')
#gsm_the_ind = dataDict['thes'].index('P114-804')
gsm_phi_ind = 29
gsm_gam_ind = 28
gsm_the_ind = 55
warning('Equilibrium points put by hand: {} {} {}'.format(gsm_phi_ind,gsm_gam_ind,gsm_the_ind))
# Take values array from labels
phis,gams,thes = fromLabelsToFloats(dataDict)
# take step
dphi = phis[0] - phis[1]
dgam = gams[0] - gams[1]
dthe = thes[0] - thes[1]
# take range
range_phi = phis[-1] - phis[0]
range_gam = gams[-1] - gams[0]
range_the = thes[-1] - thes[0]
# slice out the parabolas at equilibrium geometry
pot = dataDict['potCube']
parabola_phi = pot[:,gsm_gam_ind,gsm_the_ind,0]
parabola_gam = pot[gsm_phi_ind,:,gsm_the_ind,0]
parabola_the = pot[gsm_phi_ind,gsm_gam_ind,:,0]
# calculate force with finite difference # WATCH OUT RADIANS AND ANGLES HERE
force_phi = forcehere(parabola_phi, gsm_phi_ind, h=dphi)
force_gam = forcehere(parabola_gam, gsm_gam_ind, h=dgam)
force_the = forcehere(parabola_the, gsm_the_ind, h=dthe)
# Now, I want the coefficients of the second derivative of the kinetic energy jacobian
# for the equilibrium geometry, so that I can calculate the gaussian.
# in the diagonal approximation those are the diagonal elements, thus element 0,4,8.
coe_phi = dataDict['kinCube'][gsm_phi_ind,gsm_gam_ind,gsm_the_ind,0,2]
coe_gam = dataDict['kinCube'][gsm_phi_ind,gsm_gam_ind,gsm_the_ind,4,2]
# these three lines are here because we wanted to debug Gamma
#coe_gam = dataDict['kinCube'][gsm_phi_ind,gsm_gam_ind,gsm_the_ind,0,2]
#warning('coe_gam has been changed !!! in initialcondition function')
coe_the = dataDict['kinCube'][gsm_phi_ind,gsm_gam_ind,gsm_the_ind,8,2]
# they need to be multiplied by (-2 * hbar**2), where hbar is 1. And inverted, because the MASS
# is at denominator, and we kind of want the mass...
G_phi = 1 / ( -2 * coe_phi )
G_gam = 1 / ( -2 * coe_gam )
G_the = 1 / ( -2 * coe_the )
# factor is just to wide the gaussian a little bit leave it to one.
factor = factor or 1
if factor != 1:
warning('You have a factor of {} enabled on initial condition'.format(factor))
G_phi = G_phi/factor
G_gam = G_gam/factor
G_the = G_the/factor
Gw_phi = np.sqrt(force_phi*G_phi)
Gw_gam = np.sqrt(force_gam*G_gam)
Gw_the = np.sqrt(force_the*G_the)
w_phi = np.sqrt(force_phi/G_phi)
w_gam = np.sqrt(force_gam/G_gam)
w_the = np.sqrt(force_the/G_the)
# displacements from equilibrium geometry
displ = displ or (0,0,0)
displPhi,displGam,displThe = displ
if displPhi != 0 or displGam != 0 or displThe != 0:
warning('Some displacements activated | Phi {} | Gam {} | The {}'.format(displPhi,displGam,displThe))
phi0 = phis[displPhi]
gam0 = gams[displGam]
the0 = thes[displThe]
# initial moments?
init_mom = init_mom or (0, 0, 0)
init_momPhi, init_momGam, init_momThe = init_mom
if init_momPhi != 0 or init_momGam != 0 or init_momThe != 0:
warning('Some inititial moment is activated | Phi {} | Gam {} | The {}'.format(init_momPhi,init_momGam,init_momThe))
for p, phi in enumerate(phis):
phiV = gaussian2(phi, phi0, Gw_phi, init_momPhi)
for g, gam in enumerate(gams):
gamV = gaussian2(gam, gam0, Gw_gam, init_momGam)
for t , the in enumerate(thes):
theV = gaussian2(the, the0, Gw_the, init_momThe)
#print('I: {}\tV: {}\tZ: {}\tG: {}\t'.format(t,the,the0,theV))
wf[p,g,t] = phiV * gamV * theV
norm_wf = np.linalg.norm(wf)
print('NORM before normalization: {:e}'.format(norm_wf))
print('Steps: phi({:.3f}) gam({:.3f}) the({:.3f})'.format(dphi,dgam,dthe))
print('Range: phi({:.3f}) gam({:.3f}) the({:.3f})'.format(range_phi,range_gam,range_the))
wf = wf / norm_wf
print(wf.shape)
print('\n\nparabola force constant: {:e} {:e} {:e}'.format(force_phi,force_gam,force_the))
print('values on Jacobian 2nd derivative: {:e} {:e} {:e}'.format(coe_phi,coe_gam,coe_the))
print('G: {:e} {:e} {:e}'.format(G_phi,G_gam,G_the))
print('Gw: {:e} {:e} {:e}'.format(Gw_phi,Gw_gam,Gw_the))
print('w: {:e} {:e} {:e}'.format(w_phi,w_gam,w_the))
print('cm-1: {:e} {:e} {:e}'.format(fromHartreetoCmMin1(w_phi),
fromHartreetoCmMin1(w_gam),
fromHartreetoCmMin1(w_the)))
print('fs: {:e} {:e} {:e}'.format(fromCmMin1toFs(w_phi),
fromCmMin1toFs(w_gam),
fromCmMin1toFs(w_the)))
return(wf)
def main():
fn1 = '/home/alessio/Desktop/a-3dScanSashaSupport/n-Propagation/input.yml'
inputAU = bring_input_to_AU(loadInputYAML(fn1))
if 'dataFile' in inputAU:
name_data_file = inputAU['dataFile']
# LAUNCH THE PROPAGATION, BITCH
if name_data_file[-3:] == 'npy':
data = np.load(name_data_file)
# [()] <- because np.load returns a numpy wrapper on the dictionary
dictionary_data = data[()]
propagate3D(dictionary_data, inputAU)
elif name_data_file[-3:] == 'kle':
with open(name_data_file, "rb") as input_file:
dictionary_data = pickle.load(input_file)
propagate3D(dictionary_data, inputAU)
if __name__ == "__main__":
import cProfile
cProfile.run('main()', sort='time')
| gpl-3.0 |
yamt/neutron | quantum/plugins/cisco/tests/unit/test_database.py | 1 | 25556 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011, Cisco Systems, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
# @author: Rohit Agarwalla, Cisco Systems, Inc.
"""
test_database.py is an independent test suite
that tests the database api method calls
"""
from quantum.openstack.common import log as logging
import quantum.plugins.cisco.db.api as db
import quantum.plugins.cisco.db.l2network_db as l2network_db
import quantum.plugins.cisco.db.nexus_db_v2 as nexus_db
from quantum.tests import base
LOG = logging.getLogger(__name__)
class NexusDB(object):
"""Class consisting of methods to call nexus db methods."""
def get_all_nexusportbindings(self):
"""Get all nexus port bindings."""
bindings = []
try:
for bind in nexus_db.get_all_nexusport_bindings():
LOG.debug("Getting nexus port binding : %s" % bind.port_id)
bind_dict = {}
bind_dict["port-id"] = str(bind.port_id)
bind_dict["vlan-id"] = str(bind.vlan_id)
bindings.append(bind_dict)
except Exception as exc:
LOG.error("Failed to get all bindings: %s" % str(exc))
return bindings
def get_nexusportbinding(self, vlan_id):
"""Get nexus port binding."""
binding = []
try:
for bind in nexus_db.get_nexusport_binding(vlan_id):
LOG.debug("Getting nexus port binding : %s" % bind.port_id)
bind_dict = {}
bind_dict["port-id"] = str(bind.port_id)
bind_dict["vlan-id"] = str(bind.vlan_id)
binding.append(bind_dict)
except Exception as exc:
LOG.error("Failed to get all bindings: %s" % str(exc))
return binding
def create_nexusportbinding(self, port_id, vlan_id):
"""Create nexus port binding."""
bind_dict = {}
try:
res = nexus_db.add_nexusport_binding(port_id, vlan_id)
LOG.debug("Created nexus port binding : %s" % res.port_id)
bind_dict["port-id"] = str(res.port_id)
bind_dict["vlan-id"] = str(res.vlan_id)
return bind_dict
except Exception as exc:
LOG.error("Failed to create nexus binding: %s" % str(exc))
def delete_nexusportbinding(self, vlan_id):
"""Delete nexus port binding."""
bindings = []
try:
bind = nexus_db.remove_nexusport_binding(vlan_id)
for res in bind:
LOG.debug("Deleted nexus port binding: %s" % res.vlan_id)
bind_dict = {}
bind_dict["port-id"] = res.port_id
bindings.append(bind_dict)
return bindings
except Exception as exc:
raise Exception("Failed to delete nexus port binding: %s"
% str(exc))
def update_nexusport_binding(self, port_id, new_vlan_id):
"""Update nexus port binding."""
try:
res = nexus_db.update_nexusport_binding(port_id, new_vlan_id)
LOG.debug("Updating nexus port binding : %s" % res.port_id)
bind_dict = {}
bind_dict["port-id"] = str(res.port_id)
bind_dict["vlan-id"] = str(res.vlan_id)
return bind_dict
except Exception as exc:
raise Exception("Failed to update nexus port binding vnic: %s"
% str(exc))
class L2networkDB(object):
"""Class conisting of methods to call L2network db methods."""
def get_all_vlan_bindings(self):
"""Get all vlan binding into a list of dict."""
vlans = []
try:
for vlan_bind in l2network_db.get_all_vlan_bindings():
LOG.debug("Getting vlan bindings for vlan: %s" %
vlan_bind.vlan_id)
vlan_dict = {}
vlan_dict["vlan-id"] = str(vlan_bind.vlan_id)
vlan_dict["vlan-name"] = vlan_bind.vlan_name
vlan_dict["net-id"] = str(vlan_bind.network_id)
vlans.append(vlan_dict)
except Exception as exc:
LOG.error("Failed to get all vlan bindings: %s" % str(exc))
return vlans
def get_vlan_binding(self, network_id):
"""Get a vlan binding."""
vlan = []
try:
for vlan_bind in l2network_db.get_vlan_binding(network_id):
LOG.debug("Getting vlan binding for vlan: %s" %
vlan_bind.vlan_id)
vlan_dict = {}
vlan_dict["vlan-id"] = str(vlan_bind.vlan_id)
vlan_dict["vlan-name"] = vlan_bind.vlan_name
vlan_dict["net-id"] = str(vlan_bind.network_id)
vlan.append(vlan_dict)
except Exception as exc:
LOG.error("Failed to get vlan binding: %s" % str(exc))
return vlan
def create_vlan_binding(self, vlan_id, vlan_name, network_id):
"""Create a vlan binding."""
vlan_dict = {}
try:
res = l2network_db.add_vlan_binding(vlan_id, vlan_name, network_id)
LOG.debug("Created vlan binding for vlan: %s" % res.vlan_id)
vlan_dict["vlan-id"] = str(res.vlan_id)
vlan_dict["vlan-name"] = res.vlan_name
vlan_dict["net-id"] = str(res.network_id)
return vlan_dict
except Exception as exc:
LOG.error("Failed to create vlan binding: %s" % str(exc))
def delete_vlan_binding(self, network_id):
"""Delete a vlan binding."""
try:
res = l2network_db.remove_vlan_binding(network_id)
LOG.debug("Deleted vlan binding for vlan: %s" % res.vlan_id)
vlan_dict = {}
vlan_dict["vlan-id"] = str(res.vlan_id)
return vlan_dict
except Exception as exc:
raise Exception("Failed to delete vlan binding: %s" % str(exc))
def update_vlan_binding(self, network_id, vlan_id, vlan_name):
"""Update a vlan binding."""
try:
res = l2network_db.update_vlan_binding(network_id, vlan_id,
vlan_name)
LOG.debug("Updating vlan binding for vlan: %s" % res.vlan_id)
vlan_dict = {}
vlan_dict["vlan-id"] = str(res.vlan_id)
vlan_dict["vlan-name"] = res.vlan_name
vlan_dict["net-id"] = str(res.network_id)
return vlan_dict
except Exception as exc:
raise Exception("Failed to update vlan binding: %s" % str(exc))
class QuantumDB(object):
"""Class conisting of methods to call Quantum db methods."""
def get_all_networks(self, tenant_id):
"""Get all networks."""
nets = []
try:
for net in db.network_list(tenant_id):
LOG.debug("Getting network: %s" % net.uuid)
net_dict = {}
net_dict["tenant-id"] = net.tenant_id
net_dict["net-id"] = str(net.uuid)
net_dict["net-name"] = net.name
nets.append(net_dict)
except Exception as exc:
LOG.error("Failed to get all networks: %s" % str(exc))
return nets
def get_network(self, network_id):
"""Get a network."""
net = []
try:
for net in db.network_get(network_id):
LOG.debug("Getting network: %s" % net.uuid)
net_dict = {}
net_dict["tenant-id"] = net.tenant_id
net_dict["net-id"] = str(net.uuid)
net_dict["net-name"] = net.name
net.append(net_dict)
except Exception as exc:
LOG.error("Failed to get network: %s" % str(exc))
return net
def create_network(self, tenant_id, net_name):
"""Create a network."""
net_dict = {}
try:
res = db.network_create(tenant_id, net_name)
LOG.debug("Created network: %s" % res.uuid)
net_dict["tenant-id"] = res.tenant_id
net_dict["net-id"] = str(res.uuid)
net_dict["net-name"] = res.name
return net_dict
except Exception as exc:
LOG.error("Failed to create network: %s" % str(exc))
def delete_network(self, net_id):
"""Delete a network."""
try:
net = db.network_destroy(net_id)
LOG.debug("Deleted network: %s" % net.uuid)
net_dict = {}
net_dict["net-id"] = str(net.uuid)
return net_dict
except Exception as exc:
raise Exception("Failed to delete port: %s" % str(exc))
def update_network(self, tenant_id, net_id, **kwargs):
"""Update a network."""
try:
net = db.network_update(net_id, tenant_id, **kwargs)
LOG.debug("Updated network: %s" % net.uuid)
net_dict = {}
net_dict["net-id"] = str(net.uuid)
net_dict["net-name"] = net.name
return net_dict
except Exception as exc:
raise Exception("Failed to update network: %s" % str(exc))
def get_all_ports(self, net_id):
"""Get all ports."""
ports = []
try:
for port in db.port_list(net_id):
LOG.debug("Getting port: %s" % port.uuid)
port_dict = {}
port_dict["port-id"] = str(port.uuid)
port_dict["net-id"] = str(port.network_id)
port_dict["int-id"] = port.interface_id
port_dict["state"] = port.state
port_dict["net"] = port.network
ports.append(port_dict)
return ports
except Exception as exc:
LOG.error("Failed to get all ports: %s" % str(exc))
def get_port(self, net_id, port_id):
"""Get a port."""
port_list = []
port = db.port_get(net_id, port_id)
try:
LOG.debug("Getting port: %s" % port.uuid)
port_dict = {}
port_dict["port-id"] = str(port.uuid)
port_dict["net-id"] = str(port.network_id)
port_dict["int-id"] = port.interface_id
port_dict["state"] = port.state
port_list.append(port_dict)
return port_list
except Exception as exc:
LOG.error("Failed to get port: %s" % str(exc))
def create_port(self, net_id):
"""Add a port."""
port_dict = {}
try:
port = db.port_create(net_id)
LOG.debug("Creating port %s" % port.uuid)
port_dict["port-id"] = str(port.uuid)
port_dict["net-id"] = str(port.network_id)
port_dict["int-id"] = port.interface_id
port_dict["state"] = port.state
return port_dict
except Exception as exc:
LOG.error("Failed to create port: %s" % str(exc))
def delete_port(self, net_id, port_id):
"""Delete a port."""
try:
port = db.port_destroy(net_id, port_id)
LOG.debug("Deleted port %s" % port.uuid)
port_dict = {}
port_dict["port-id"] = str(port.uuid)
return port_dict
except Exception as exc:
raise Exception("Failed to delete port: %s" % str(exc))
def update_port(self, net_id, port_id, port_state):
"""Update a port."""
try:
port = db.port_set_state(net_id, port_id, port_state)
LOG.debug("Updated port %s" % port.uuid)
port_dict = {}
port_dict["port-id"] = str(port.uuid)
port_dict["net-id"] = str(port.network_id)
port_dict["int-id"] = port.interface_id
port_dict["state"] = port.state
return port_dict
except Exception as exc:
raise Exception("Failed to update port state: %s" % str(exc))
def plug_interface(self, net_id, port_id, int_id):
"""Plug interface to a port."""
try:
port = db.port_set_attachment(net_id, port_id, int_id)
LOG.debug("Attached interface to port %s" % port.uuid)
port_dict = {}
port_dict["port-id"] = str(port.uuid)
port_dict["net-id"] = str(port.network_id)
port_dict["int-id"] = port.interface_id
port_dict["state"] = port.state
return port_dict
except Exception as exc:
raise Exception("Failed to plug interface: %s" % str(exc))
def unplug_interface(self, net_id, port_id):
"""Unplug interface to a port."""
try:
port = db.port_unset_attachment(net_id, port_id)
LOG.debug("Detached interface from port %s" % port.uuid)
port_dict = {}
port_dict["port-id"] = str(port.uuid)
port_dict["net-id"] = str(port.network_id)
port_dict["int-id"] = port.interface_id
port_dict["state"] = port.state
return port_dict
except Exception as exc:
raise Exception("Failed to unplug interface: %s" % str(exc))
class NexusDBTest(base.BaseTestCase):
"""Class conisting of nexus DB unit tests."""
def setUp(self):
super(NexusDBTest, self).setUp()
"""Setup for nexus db tests."""
l2network_db.initialize()
self.addCleanup(db.clear_db)
self.dbtest = NexusDB()
LOG.debug("Setup")
def testa_create_nexusportbinding(self):
"""Create nexus port binding."""
binding1 = self.dbtest.create_nexusportbinding("port1", 10)
self.assertTrue(binding1["port-id"] == "port1")
self.tearDown_nexusportbinding()
def testb_getall_nexusportbindings(self):
"""Get all nexus port bindings."""
self.dbtest.create_nexusportbinding("port1", 10)
self.dbtest.create_nexusportbinding("port2", 10)
bindings = self.dbtest.get_all_nexusportbindings()
count = 0
for bind in bindings:
if "port" in bind["port-id"]:
count += 1
self.assertTrue(count == 2)
self.tearDown_nexusportbinding()
def testc_delete_nexusportbinding(self):
"""Delete nexus port binding."""
self.dbtest.create_nexusportbinding("port1", 10)
self.dbtest.delete_nexusportbinding(10)
bindings = self.dbtest.get_all_nexusportbindings()
count = 0
for bind in bindings:
if "port " in bind["port-id"]:
count += 1
self.assertTrue(count == 0)
self.tearDown_nexusportbinding()
def testd_update_nexusportbinding(self):
"""Update nexus port binding."""
binding1 = self.dbtest.create_nexusportbinding("port1", 10)
binding1 = self.dbtest.update_nexusport_binding(binding1["port-id"],
20)
bindings = self.dbtest.get_all_nexusportbindings()
count = 0
for bind in bindings:
if "20" in str(bind["vlan-id"]):
count += 1
self.assertTrue(count == 1)
self.tearDown_nexusportbinding()
def tearDown_nexusportbinding(self):
"""Tear down nexus port binding table."""
LOG.debug("Tearing Down Nexus port Bindings")
binds = self.dbtest.get_all_nexusportbindings()
for bind in binds:
vlan_id = bind["vlan-id"]
self.dbtest.delete_nexusportbinding(vlan_id)
class L2networkDBTest(base.BaseTestCase):
"""Class conisting of L2network DB unit tests."""
def setUp(self):
"""Setup for tests."""
super(L2networkDBTest, self).setUp()
l2network_db.initialize()
self.dbtest = L2networkDB()
self.quantum = QuantumDB()
self.addCleanup(db.clear_db)
LOG.debug("Setup")
def testa_create_vlanbinding(self):
"""Test add vlan binding."""
net1 = self.quantum.create_network("t1", "netid1")
vlan1 = self.dbtest.create_vlan_binding(10, "vlan1", net1["net-id"])
self.assertTrue(vlan1["vlan-id"] == "10")
self.teardown_vlanbinding()
self.teardown_network()
def testb_getall_vlanbindings(self):
"""Test get all vlan bindings."""
net1 = self.quantum.create_network("t1", "netid1")
net2 = self.quantum.create_network("t1", "netid2")
vlan1 = self.dbtest.create_vlan_binding(10, "vlan1", net1["net-id"])
self.assertTrue(vlan1["vlan-id"] == "10")
vlan2 = self.dbtest.create_vlan_binding(20, "vlan2", net2["net-id"])
self.assertTrue(vlan2["vlan-id"] == "20")
vlans = self.dbtest.get_all_vlan_bindings()
count = 0
for vlan in vlans:
if "vlan" in vlan["vlan-name"]:
count += 1
self.assertTrue(count == 2)
self.teardown_vlanbinding()
self.teardown_network()
def testc_delete_vlanbinding(self):
"""Test delete vlan binding."""
net1 = self.quantum.create_network("t1", "netid1")
vlan1 = self.dbtest.create_vlan_binding(10, "vlan1", net1["net-id"])
self.assertTrue(vlan1["vlan-id"] == "10")
self.dbtest.delete_vlan_binding(net1["net-id"])
vlans = self.dbtest.get_all_vlan_bindings()
count = 0
for vlan in vlans:
if "vlan " in vlan["vlan-name"]:
count += 1
self.assertTrue(count == 0)
self.teardown_vlanbinding()
self.teardown_network()
def testd_update_vlanbinding(self):
"""Test update vlan binding."""
net1 = self.quantum.create_network("t1", "netid1")
vlan1 = self.dbtest.create_vlan_binding(10, "vlan1", net1["net-id"])
self.assertTrue(vlan1["vlan-id"] == "10")
vlan1 = self.dbtest.update_vlan_binding(net1["net-id"], 11, "newvlan1")
vlans = self.dbtest.get_all_vlan_bindings()
count = 0
for vlan in vlans:
if "new" in vlan["vlan-name"]:
count += 1
self.assertTrue(count == 1)
self.teardown_vlanbinding()
self.teardown_network()
def testm_test_vlanids(self):
"""Test vlanid methods."""
l2network_db.create_vlanids()
vlanids = l2network_db.get_all_vlanids()
self.assertTrue(len(vlanids) > 0)
vlanid = l2network_db.reserve_vlanid()
used = l2network_db.is_vlanid_used(vlanid)
self.assertTrue(used)
used = l2network_db.release_vlanid(vlanid)
self.assertFalse(used)
#counting on default teardown here to clear db
def teardown_network(self):
"""tearDown Network table."""
LOG.debug("Tearing Down Network")
nets = self.quantum.get_all_networks("t1")
for net in nets:
netid = net["net-id"]
self.quantum.delete_network(netid)
def teardown_port(self):
"""tearDown Port table."""
LOG.debug("Tearing Down Port")
nets = self.quantum.get_all_networks("t1")
for net in nets:
netid = net["net-id"]
ports = self.quantum.get_all_ports(netid)
for port in ports:
portid = port["port-id"]
self.quantum.delete_port(netid, portid)
def teardown_vlanbinding(self):
"""tearDown VlanBinding table."""
LOG.debug("Tearing Down Vlan Binding")
vlans = self.dbtest.get_all_vlan_bindings()
for vlan in vlans:
netid = vlan["net-id"]
self.dbtest.delete_vlan_binding(netid)
class QuantumDBTest(base.BaseTestCase):
"""Class conisting of Quantum DB unit tests."""
def setUp(self):
"""Setup for tests."""
super(QuantumDBTest, self).setUp()
l2network_db.initialize()
self.addCleanup(db.clear_db)
self.dbtest = QuantumDB()
self.tenant_id = "t1"
LOG.debug("Setup")
def testa_create_network(self):
"""Test to create network."""
net1 = self.dbtest.create_network(self.tenant_id, "plugin_test1")
self.assertTrue(net1["net-name"] == "plugin_test1")
self.teardown_network_port()
def testb_get_networks(self):
"""Test to get all networks."""
net1 = self.dbtest.create_network(self.tenant_id, "plugin_test1")
self.assertTrue(net1["net-name"] == "plugin_test1")
net2 = self.dbtest.create_network(self.tenant_id, "plugin_test2")
self.assertTrue(net2["net-name"] == "plugin_test2")
nets = self.dbtest.get_all_networks(self.tenant_id)
count = 0
for net in nets:
if "plugin_test" in net["net-name"]:
count += 1
self.assertTrue(count == 2)
self.teardown_network_port()
def testc_delete_network(self):
"""Test to delete network."""
net1 = self.dbtest.create_network(self.tenant_id, "plugin_test1")
self.assertTrue(net1["net-name"] == "plugin_test1")
self.dbtest.delete_network(net1["net-id"])
nets = self.dbtest.get_all_networks(self.tenant_id)
count = 0
for net in nets:
if "plugin_test1" in net["net-name"]:
count += 1
self.assertTrue(count == 0)
self.teardown_network_port()
def testd_update_network(self):
"""Test to update (rename) network."""
net1 = self.dbtest.create_network(self.tenant_id, "plugin_test1")
self.assertTrue(net1["net-name"] == "plugin_test1")
net = self.dbtest.update_network(self.tenant_id, net1["net-id"],
name="plugin_test1_renamed")
self.assertTrue(net["net-name"] == "plugin_test1_renamed")
self.teardown_network_port()
def teste_create_port(self):
"""Test to create port."""
net1 = self.dbtest.create_network(self.tenant_id, "plugin_test1")
port = self.dbtest.create_port(net1["net-id"])
self.assertTrue(port["net-id"] == net1["net-id"])
ports = self.dbtest.get_all_ports(net1["net-id"])
count = 0
for por in ports:
count += 1
self.assertTrue(count == 1)
self.teardown_network_port()
def testf_delete_port(self):
"""Test to delete port."""
net1 = self.dbtest.create_network(self.tenant_id, "plugin_test1")
port = self.dbtest.create_port(net1["net-id"])
self.assertTrue(port["net-id"] == net1["net-id"])
ports = self.dbtest.get_all_ports(net1["net-id"])
count = 0
for por in ports:
count += 1
self.assertTrue(count == 1)
for por in ports:
self.dbtest.delete_port(net1["net-id"], por["port-id"])
ports = self.dbtest.get_all_ports(net1["net-id"])
count = 0
for por in ports:
count += 1
self.assertTrue(count == 0)
self.teardown_network_port()
def testg_plug_unplug_interface(self):
"""Test to plug/unplug interface."""
net1 = self.dbtest.create_network(self.tenant_id, "plugin_test1")
port1 = self.dbtest.create_port(net1["net-id"])
self.dbtest.plug_interface(net1["net-id"], port1["port-id"], "vif1.1")
port = self.dbtest.get_port(net1["net-id"], port1["port-id"])
self.assertTrue(port[0]["int-id"] == "vif1.1")
self.dbtest.unplug_interface(net1["net-id"], port1["port-id"])
port = self.dbtest.get_port(net1["net-id"], port1["port-id"])
self.assertTrue(port[0]["int-id"] is None)
self.teardown_network_port()
def testh_joined_test(self):
"""Test to get network and port."""
net1 = self.dbtest.create_network("t1", "net1")
port1 = self.dbtest.create_port(net1["net-id"])
self.assertTrue(port1["net-id"] == net1["net-id"])
port2 = self.dbtest.create_port(net1["net-id"])
self.assertTrue(port2["net-id"] == net1["net-id"])
ports = self.dbtest.get_all_ports(net1["net-id"])
for port in ports:
net = port["net"]
LOG.debug("Port id %s Net id %s" % (port["port-id"], net.uuid))
self.teardown_joined_test()
def teardown_network_port(self):
"""tearDown for Network and Port table."""
networks = self.dbtest.get_all_networks(self.tenant_id)
for net in networks:
netid = net["net-id"]
name = net["net-name"]
if "plugin_test" in name:
ports = self.dbtest.get_all_ports(netid)
for por in ports:
self.dbtest.delete_port(netid, por["port-id"])
self.dbtest.delete_network(netid)
def teardown_joined_test(self):
"""tearDown for joined Network and Port test."""
LOG.debug("Tearing Down Network and Ports")
nets = self.dbtest.get_all_networks("t1")
for net in nets:
netid = net["net-id"]
ports = self.dbtest.get_all_ports(netid)
for port in ports:
self.dbtest.delete_port(port["net-id"], port["port-id"])
self.dbtest.delete_network(netid)
| apache-2.0 |
clangen/projectM-musikcube | src/WinLibs/freetype-2.3.5/src/tools/glnames.py | 16 | 103307 | #!/usr/bin/env python
#
#
# FreeType 2 glyph name builder
#
# Copyright 1996-2000, 2003, 2005, 2007 by
# David Turner, Robert Wilhelm, and Werner Lemberg.
#
# This file is part of the FreeType project, and may only be used, modified,
# and distributed under the terms of the FreeType project license,
# LICENSE.TXT. By continuing to use, modify, or distribute this file you
# indicate that you have read the license and understand and accept it
# fully.
"""\
usage: %s <output-file>
This python script generates the glyph names tables defined in the
PSNames module.
Its single argument is the name of the header file to be created.
"""
import sys, string, struct, re, os.path
# This table lists the glyphs according to the Macintosh specification.
# It is used by the TrueType Postscript names table.
#
# See
#
# http://fonts.apple.com/TTRefMan/RM06/Chap6post.html
#
# for the official list.
#
mac_standard_names = \
[
# 0
".notdef", ".null", "nonmarkingreturn", "space", "exclam",
"quotedbl", "numbersign", "dollar", "percent", "ampersand",
# 10
"quotesingle", "parenleft", "parenright", "asterisk", "plus",
"comma", "hyphen", "period", "slash", "zero",
# 20
"one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "colon",
# 30
"semicolon", "less", "equal", "greater", "question",
"at", "A", "B", "C", "D",
# 40
"E", "F", "G", "H", "I",
"J", "K", "L", "M", "N",
# 50
"O", "P", "Q", "R", "S",
"T", "U", "V", "W", "X",
# 60
"Y", "Z", "bracketleft", "backslash", "bracketright",
"asciicircum", "underscore", "grave", "a", "b",
# 70
"c", "d", "e", "f", "g",
"h", "i", "j", "k", "l",
# 80
"m", "n", "o", "p", "q",
"r", "s", "t", "u", "v",
# 90
"w", "x", "y", "z", "braceleft",
"bar", "braceright", "asciitilde", "Adieresis", "Aring",
# 100
"Ccedilla", "Eacute", "Ntilde", "Odieresis", "Udieresis",
"aacute", "agrave", "acircumflex", "adieresis", "atilde",
# 110
"aring", "ccedilla", "eacute", "egrave", "ecircumflex",
"edieresis", "iacute", "igrave", "icircumflex", "idieresis",
# 120
"ntilde", "oacute", "ograve", "ocircumflex", "odieresis",
"otilde", "uacute", "ugrave", "ucircumflex", "udieresis",
# 130
"dagger", "degree", "cent", "sterling", "section",
"bullet", "paragraph", "germandbls", "registered", "copyright",
# 140
"trademark", "acute", "dieresis", "notequal", "AE",
"Oslash", "infinity", "plusminus", "lessequal", "greaterequal",
# 150
"yen", "mu", "partialdiff", "summation", "product",
"pi", "integral", "ordfeminine", "ordmasculine", "Omega",
# 160
"ae", "oslash", "questiondown", "exclamdown", "logicalnot",
"radical", "florin", "approxequal", "Delta", "guillemotleft",
# 170
"guillemotright", "ellipsis", "nonbreakingspace", "Agrave", "Atilde",
"Otilde", "OE", "oe", "endash", "emdash",
# 180
"quotedblleft", "quotedblright", "quoteleft", "quoteright", "divide",
"lozenge", "ydieresis", "Ydieresis", "fraction", "currency",
# 190
"guilsinglleft", "guilsinglright", "fi", "fl", "daggerdbl",
"periodcentered", "quotesinglbase", "quotedblbase", "perthousand",
"Acircumflex",
# 200
"Ecircumflex", "Aacute", "Edieresis", "Egrave", "Iacute",
"Icircumflex", "Idieresis", "Igrave", "Oacute", "Ocircumflex",
# 210
"apple", "Ograve", "Uacute", "Ucircumflex", "Ugrave",
"dotlessi", "circumflex", "tilde", "macron", "breve",
# 220
"dotaccent", "ring", "cedilla", "hungarumlaut", "ogonek",
"caron", "Lslash", "lslash", "Scaron", "scaron",
# 230
"Zcaron", "zcaron", "brokenbar", "Eth", "eth",
"Yacute", "yacute", "Thorn", "thorn", "minus",
# 240
"multiply", "onesuperior", "twosuperior", "threesuperior", "onehalf",
"onequarter", "threequarters", "franc", "Gbreve", "gbreve",
# 250
"Idotaccent", "Scedilla", "scedilla", "Cacute", "cacute",
"Ccaron", "ccaron", "dcroat"
]
# The list of standard `SID' glyph names. For the official list,
# see Annex A of document at
#
# http://partners.adobe.com/asn/developer/pdfs/tn/5176.CFF.pdf.
#
sid_standard_names = \
[
# 0
".notdef", "space", "exclam", "quotedbl", "numbersign",
"dollar", "percent", "ampersand", "quoteright", "parenleft",
# 10
"parenright", "asterisk", "plus", "comma", "hyphen",
"period", "slash", "zero", "one", "two",
# 20
"three", "four", "five", "six", "seven",
"eight", "nine", "colon", "semicolon", "less",
# 30
"equal", "greater", "question", "at", "A",
"B", "C", "D", "E", "F",
# 40
"G", "H", "I", "J", "K",
"L", "M", "N", "O", "P",
# 50
"Q", "R", "S", "T", "U",
"V", "W", "X", "Y", "Z",
# 60
"bracketleft", "backslash", "bracketright", "asciicircum", "underscore",
"quoteleft", "a", "b", "c", "d",
# 70
"e", "f", "g", "h", "i",
"j", "k", "l", "m", "n",
# 80
"o", "p", "q", "r", "s",
"t", "u", "v", "w", "x",
# 90
"y", "z", "braceleft", "bar", "braceright",
"asciitilde", "exclamdown", "cent", "sterling", "fraction",
# 100
"yen", "florin", "section", "currency", "quotesingle",
"quotedblleft", "guillemotleft", "guilsinglleft", "guilsinglright", "fi",
# 110
"fl", "endash", "dagger", "daggerdbl", "periodcentered",
"paragraph", "bullet", "quotesinglbase", "quotedblbase", "quotedblright",
# 120
"guillemotright", "ellipsis", "perthousand", "questiondown", "grave",
"acute", "circumflex", "tilde", "macron", "breve",
# 130
"dotaccent", "dieresis", "ring", "cedilla", "hungarumlaut",
"ogonek", "caron", "emdash", "AE", "ordfeminine",
# 140
"Lslash", "Oslash", "OE", "ordmasculine", "ae",
"dotlessi", "lslash", "oslash", "oe", "germandbls",
# 150
"onesuperior", "logicalnot", "mu", "trademark", "Eth",
"onehalf", "plusminus", "Thorn", "onequarter", "divide",
# 160
"brokenbar", "degree", "thorn", "threequarters", "twosuperior",
"registered", "minus", "eth", "multiply", "threesuperior",
# 170
"copyright", "Aacute", "Acircumflex", "Adieresis", "Agrave",
"Aring", "Atilde", "Ccedilla", "Eacute", "Ecircumflex",
# 180
"Edieresis", "Egrave", "Iacute", "Icircumflex", "Idieresis",
"Igrave", "Ntilde", "Oacute", "Ocircumflex", "Odieresis",
# 190
"Ograve", "Otilde", "Scaron", "Uacute", "Ucircumflex",
"Udieresis", "Ugrave", "Yacute", "Ydieresis", "Zcaron",
# 200
"aacute", "acircumflex", "adieresis", "agrave", "aring",
"atilde", "ccedilla", "eacute", "ecircumflex", "edieresis",
# 210
"egrave", "iacute", "icircumflex", "idieresis", "igrave",
"ntilde", "oacute", "ocircumflex", "odieresis", "ograve",
# 220
"otilde", "scaron", "uacute", "ucircumflex", "udieresis",
"ugrave", "yacute", "ydieresis", "zcaron", "exclamsmall",
# 230
"Hungarumlautsmall", "dollaroldstyle", "dollarsuperior", "ampersandsmall",
"Acutesmall",
"parenleftsuperior", "parenrightsuperior", "twodotenleader",
"onedotenleader", "zerooldstyle",
# 240
"oneoldstyle", "twooldstyle", "threeoldstyle", "fouroldstyle",
"fiveoldstyle",
"sixoldstyle", "sevenoldstyle", "eightoldstyle", "nineoldstyle",
"commasuperior",
# 250
"threequartersemdash", "periodsuperior", "questionsmall", "asuperior",
"bsuperior",
"centsuperior", "dsuperior", "esuperior", "isuperior", "lsuperior",
# 260
"msuperior", "nsuperior", "osuperior", "rsuperior", "ssuperior",
"tsuperior", "ff", "ffi", "ffl", "parenleftinferior",
# 270
"parenrightinferior", "Circumflexsmall", "hyphensuperior", "Gravesmall",
"Asmall",
"Bsmall", "Csmall", "Dsmall", "Esmall", "Fsmall",
# 280
"Gsmall", "Hsmall", "Ismall", "Jsmall", "Ksmall",
"Lsmall", "Msmall", "Nsmall", "Osmall", "Psmall",
# 290
"Qsmall", "Rsmall", "Ssmall", "Tsmall", "Usmall",
"Vsmall", "Wsmall", "Xsmall", "Ysmall", "Zsmall",
# 300
"colonmonetary", "onefitted", "rupiah", "Tildesmall", "exclamdownsmall",
"centoldstyle", "Lslashsmall", "Scaronsmall", "Zcaronsmall",
"Dieresissmall",
# 310
"Brevesmall", "Caronsmall", "Dotaccentsmall", "Macronsmall", "figuredash",
"hypheninferior", "Ogoneksmall", "Ringsmall", "Cedillasmall",
"questiondownsmall",
# 320
"oneeighth", "threeeighths", "fiveeighths", "seveneighths", "onethird",
"twothirds", "zerosuperior", "foursuperior", "fivesuperior",
"sixsuperior",
# 330
"sevensuperior", "eightsuperior", "ninesuperior", "zeroinferior",
"oneinferior",
"twoinferior", "threeinferior", "fourinferior", "fiveinferior",
"sixinferior",
# 340
"seveninferior", "eightinferior", "nineinferior", "centinferior",
"dollarinferior",
"periodinferior", "commainferior", "Agravesmall", "Aacutesmall",
"Acircumflexsmall",
# 350
"Atildesmall", "Adieresissmall", "Aringsmall", "AEsmall", "Ccedillasmall",
"Egravesmall", "Eacutesmall", "Ecircumflexsmall", "Edieresissmall",
"Igravesmall",
# 360
"Iacutesmall", "Icircumflexsmall", "Idieresissmall", "Ethsmall",
"Ntildesmall",
"Ogravesmall", "Oacutesmall", "Ocircumflexsmall", "Otildesmall",
"Odieresissmall",
# 370
"OEsmall", "Oslashsmall", "Ugravesmall", "Uacutesmall",
"Ucircumflexsmall",
"Udieresissmall", "Yacutesmall", "Thornsmall", "Ydieresissmall",
"001.000",
# 380
"001.001", "001.002", "001.003", "Black", "Bold",
"Book", "Light", "Medium", "Regular", "Roman",
# 390
"Semibold"
]
# This table maps character codes of the Adobe Standard Type 1
# encoding to glyph indices in the sid_standard_names table.
#
t1_standard_encoding = \
[
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
49, 50, 51, 52, 53, 54, 55, 56, 57, 58,
59, 60, 61, 62, 63, 64, 65, 66, 67, 68,
69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
79, 80, 81, 82, 83, 84, 85, 86, 87, 88,
89, 90, 91, 92, 93, 94, 95, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 96, 97, 98, 99, 100, 101, 102, 103, 104,
105, 106, 107, 108, 109, 110, 0, 111, 112, 113,
114, 0, 115, 116, 117, 118, 119, 120, 121, 122,
0, 123, 0, 124, 125, 126, 127, 128, 129, 130,
131, 0, 132, 133, 0, 134, 135, 136, 137, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 138, 0, 139, 0, 0,
0, 0, 140, 141, 142, 143, 0, 0, 0, 0,
0, 144, 0, 0, 0, 145, 0, 0, 146, 147,
148, 149, 0, 0, 0, 0
]
# This table maps character codes of the Adobe Expert Type 1
# encoding to glyph indices in the sid_standard_names table.
#
t1_expert_encoding = \
[
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 229, 230, 0, 231, 232, 233, 234,
235, 236, 237, 238, 13, 14, 15, 99, 239, 240,
241, 242, 243, 244, 245, 246, 247, 248, 27, 28,
249, 250, 251, 252, 0, 253, 254, 255, 256, 257,
0, 0, 0, 258, 0, 0, 259, 260, 261, 262,
0, 0, 263, 264, 265, 0, 266, 109, 110, 267,
268, 269, 0, 270, 271, 272, 273, 274, 275, 276,
277, 278, 279, 280, 281, 282, 283, 284, 285, 286,
287, 288, 289, 290, 291, 292, 293, 294, 295, 296,
297, 298, 299, 300, 301, 302, 303, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 304, 305, 306, 0, 0, 307, 308, 309, 310,
311, 0, 312, 0, 0, 313, 0, 0, 314, 315,
0, 0, 316, 317, 318, 0, 0, 0, 158, 155,
163, 319, 320, 321, 322, 323, 324, 325, 0, 0,
326, 150, 164, 169, 327, 328, 329, 330, 331, 332,
333, 334, 335, 336, 337, 338, 339, 340, 341, 342,
343, 344, 345, 346, 347, 348, 349, 350, 351, 352,
353, 354, 355, 356, 357, 358, 359, 360, 361, 362,
363, 364, 365, 366, 367, 368, 369, 370, 371, 372,
373, 374, 375, 376, 377, 378
]
# This data has been taken literally from the file `glyphlist.txt',
# version 2.0, 22 Sept 2002. It is available from
#
# http://partners.adobe.com/asn/developer/typeforum/unicodegn.html
# http://partners.adobe.com/public/developer/en/opentype/glyphlist.txt
#
adobe_glyph_list = """\
A;0041
AE;00C6
AEacute;01FC
AEmacron;01E2
AEsmall;F7E6
Aacute;00C1
Aacutesmall;F7E1
Abreve;0102
Abreveacute;1EAE
Abrevecyrillic;04D0
Abrevedotbelow;1EB6
Abrevegrave;1EB0
Abrevehookabove;1EB2
Abrevetilde;1EB4
Acaron;01CD
Acircle;24B6
Acircumflex;00C2
Acircumflexacute;1EA4
Acircumflexdotbelow;1EAC
Acircumflexgrave;1EA6
Acircumflexhookabove;1EA8
Acircumflexsmall;F7E2
Acircumflextilde;1EAA
Acute;F6C9
Acutesmall;F7B4
Acyrillic;0410
Adblgrave;0200
Adieresis;00C4
Adieresiscyrillic;04D2
Adieresismacron;01DE
Adieresissmall;F7E4
Adotbelow;1EA0
Adotmacron;01E0
Agrave;00C0
Agravesmall;F7E0
Ahookabove;1EA2
Aiecyrillic;04D4
Ainvertedbreve;0202
Alpha;0391
Alphatonos;0386
Amacron;0100
Amonospace;FF21
Aogonek;0104
Aring;00C5
Aringacute;01FA
Aringbelow;1E00
Aringsmall;F7E5
Asmall;F761
Atilde;00C3
Atildesmall;F7E3
Aybarmenian;0531
B;0042
Bcircle;24B7
Bdotaccent;1E02
Bdotbelow;1E04
Becyrillic;0411
Benarmenian;0532
Beta;0392
Bhook;0181
Blinebelow;1E06
Bmonospace;FF22
Brevesmall;F6F4
Bsmall;F762
Btopbar;0182
C;0043
Caarmenian;053E
Cacute;0106
Caron;F6CA
Caronsmall;F6F5
Ccaron;010C
Ccedilla;00C7
Ccedillaacute;1E08
Ccedillasmall;F7E7
Ccircle;24B8
Ccircumflex;0108
Cdot;010A
Cdotaccent;010A
Cedillasmall;F7B8
Chaarmenian;0549
Cheabkhasiancyrillic;04BC
Checyrillic;0427
Chedescenderabkhasiancyrillic;04BE
Chedescendercyrillic;04B6
Chedieresiscyrillic;04F4
Cheharmenian;0543
Chekhakassiancyrillic;04CB
Cheverticalstrokecyrillic;04B8
Chi;03A7
Chook;0187
Circumflexsmall;F6F6
Cmonospace;FF23
Coarmenian;0551
Csmall;F763
D;0044
DZ;01F1
DZcaron;01C4
Daarmenian;0534
Dafrican;0189
Dcaron;010E
Dcedilla;1E10
Dcircle;24B9
Dcircumflexbelow;1E12
Dcroat;0110
Ddotaccent;1E0A
Ddotbelow;1E0C
Decyrillic;0414
Deicoptic;03EE
Delta;2206
Deltagreek;0394
Dhook;018A
Dieresis;F6CB
DieresisAcute;F6CC
DieresisGrave;F6CD
Dieresissmall;F7A8
Digammagreek;03DC
Djecyrillic;0402
Dlinebelow;1E0E
Dmonospace;FF24
Dotaccentsmall;F6F7
Dslash;0110
Dsmall;F764
Dtopbar;018B
Dz;01F2
Dzcaron;01C5
Dzeabkhasiancyrillic;04E0
Dzecyrillic;0405
Dzhecyrillic;040F
E;0045
Eacute;00C9
Eacutesmall;F7E9
Ebreve;0114
Ecaron;011A
Ecedillabreve;1E1C
Echarmenian;0535
Ecircle;24BA
Ecircumflex;00CA
Ecircumflexacute;1EBE
Ecircumflexbelow;1E18
Ecircumflexdotbelow;1EC6
Ecircumflexgrave;1EC0
Ecircumflexhookabove;1EC2
Ecircumflexsmall;F7EA
Ecircumflextilde;1EC4
Ecyrillic;0404
Edblgrave;0204
Edieresis;00CB
Edieresissmall;F7EB
Edot;0116
Edotaccent;0116
Edotbelow;1EB8
Efcyrillic;0424
Egrave;00C8
Egravesmall;F7E8
Eharmenian;0537
Ehookabove;1EBA
Eightroman;2167
Einvertedbreve;0206
Eiotifiedcyrillic;0464
Elcyrillic;041B
Elevenroman;216A
Emacron;0112
Emacronacute;1E16
Emacrongrave;1E14
Emcyrillic;041C
Emonospace;FF25
Encyrillic;041D
Endescendercyrillic;04A2
Eng;014A
Enghecyrillic;04A4
Enhookcyrillic;04C7
Eogonek;0118
Eopen;0190
Epsilon;0395
Epsilontonos;0388
Ercyrillic;0420
Ereversed;018E
Ereversedcyrillic;042D
Escyrillic;0421
Esdescendercyrillic;04AA
Esh;01A9
Esmall;F765
Eta;0397
Etarmenian;0538
Etatonos;0389
Eth;00D0
Ethsmall;F7F0
Etilde;1EBC
Etildebelow;1E1A
Euro;20AC
Ezh;01B7
Ezhcaron;01EE
Ezhreversed;01B8
F;0046
Fcircle;24BB
Fdotaccent;1E1E
Feharmenian;0556
Feicoptic;03E4
Fhook;0191
Fitacyrillic;0472
Fiveroman;2164
Fmonospace;FF26
Fourroman;2163
Fsmall;F766
G;0047
GBsquare;3387
Gacute;01F4
Gamma;0393
Gammaafrican;0194
Gangiacoptic;03EA
Gbreve;011E
Gcaron;01E6
Gcedilla;0122
Gcircle;24BC
Gcircumflex;011C
Gcommaaccent;0122
Gdot;0120
Gdotaccent;0120
Gecyrillic;0413
Ghadarmenian;0542
Ghemiddlehookcyrillic;0494
Ghestrokecyrillic;0492
Gheupturncyrillic;0490
Ghook;0193
Gimarmenian;0533
Gjecyrillic;0403
Gmacron;1E20
Gmonospace;FF27
Grave;F6CE
Gravesmall;F760
Gsmall;F767
Gsmallhook;029B
Gstroke;01E4
H;0048
H18533;25CF
H18543;25AA
H18551;25AB
H22073;25A1
HPsquare;33CB
Haabkhasiancyrillic;04A8
Hadescendercyrillic;04B2
Hardsigncyrillic;042A
Hbar;0126
Hbrevebelow;1E2A
Hcedilla;1E28
Hcircle;24BD
Hcircumflex;0124
Hdieresis;1E26
Hdotaccent;1E22
Hdotbelow;1E24
Hmonospace;FF28
Hoarmenian;0540
Horicoptic;03E8
Hsmall;F768
Hungarumlaut;F6CF
Hungarumlautsmall;F6F8
Hzsquare;3390
I;0049
IAcyrillic;042F
IJ;0132
IUcyrillic;042E
Iacute;00CD
Iacutesmall;F7ED
Ibreve;012C
Icaron;01CF
Icircle;24BE
Icircumflex;00CE
Icircumflexsmall;F7EE
Icyrillic;0406
Idblgrave;0208
Idieresis;00CF
Idieresisacute;1E2E
Idieresiscyrillic;04E4
Idieresissmall;F7EF
Idot;0130
Idotaccent;0130
Idotbelow;1ECA
Iebrevecyrillic;04D6
Iecyrillic;0415
Ifraktur;2111
Igrave;00CC
Igravesmall;F7EC
Ihookabove;1EC8
Iicyrillic;0418
Iinvertedbreve;020A
Iishortcyrillic;0419
Imacron;012A
Imacroncyrillic;04E2
Imonospace;FF29
Iniarmenian;053B
Iocyrillic;0401
Iogonek;012E
Iota;0399
Iotaafrican;0196
Iotadieresis;03AA
Iotatonos;038A
Ismall;F769
Istroke;0197
Itilde;0128
Itildebelow;1E2C
Izhitsacyrillic;0474
Izhitsadblgravecyrillic;0476
J;004A
Jaarmenian;0541
Jcircle;24BF
Jcircumflex;0134
Jecyrillic;0408
Jheharmenian;054B
Jmonospace;FF2A
Jsmall;F76A
K;004B
KBsquare;3385
KKsquare;33CD
Kabashkircyrillic;04A0
Kacute;1E30
Kacyrillic;041A
Kadescendercyrillic;049A
Kahookcyrillic;04C3
Kappa;039A
Kastrokecyrillic;049E
Kaverticalstrokecyrillic;049C
Kcaron;01E8
Kcedilla;0136
Kcircle;24C0
Kcommaaccent;0136
Kdotbelow;1E32
Keharmenian;0554
Kenarmenian;053F
Khacyrillic;0425
Kheicoptic;03E6
Khook;0198
Kjecyrillic;040C
Klinebelow;1E34
Kmonospace;FF2B
Koppacyrillic;0480
Koppagreek;03DE
Ksicyrillic;046E
Ksmall;F76B
L;004C
LJ;01C7
LL;F6BF
Lacute;0139
Lambda;039B
Lcaron;013D
Lcedilla;013B
Lcircle;24C1
Lcircumflexbelow;1E3C
Lcommaaccent;013B
Ldot;013F
Ldotaccent;013F
Ldotbelow;1E36
Ldotbelowmacron;1E38
Liwnarmenian;053C
Lj;01C8
Ljecyrillic;0409
Llinebelow;1E3A
Lmonospace;FF2C
Lslash;0141
Lslashsmall;F6F9
Lsmall;F76C
M;004D
MBsquare;3386
Macron;F6D0
Macronsmall;F7AF
Macute;1E3E
Mcircle;24C2
Mdotaccent;1E40
Mdotbelow;1E42
Menarmenian;0544
Mmonospace;FF2D
Msmall;F76D
Mturned;019C
Mu;039C
N;004E
NJ;01CA
Nacute;0143
Ncaron;0147
Ncedilla;0145
Ncircle;24C3
Ncircumflexbelow;1E4A
Ncommaaccent;0145
Ndotaccent;1E44
Ndotbelow;1E46
Nhookleft;019D
Nineroman;2168
Nj;01CB
Njecyrillic;040A
Nlinebelow;1E48
Nmonospace;FF2E
Nowarmenian;0546
Nsmall;F76E
Ntilde;00D1
Ntildesmall;F7F1
Nu;039D
O;004F
OE;0152
OEsmall;F6FA
Oacute;00D3
Oacutesmall;F7F3
Obarredcyrillic;04E8
Obarreddieresiscyrillic;04EA
Obreve;014E
Ocaron;01D1
Ocenteredtilde;019F
Ocircle;24C4
Ocircumflex;00D4
Ocircumflexacute;1ED0
Ocircumflexdotbelow;1ED8
Ocircumflexgrave;1ED2
Ocircumflexhookabove;1ED4
Ocircumflexsmall;F7F4
Ocircumflextilde;1ED6
Ocyrillic;041E
Odblacute;0150
Odblgrave;020C
Odieresis;00D6
Odieresiscyrillic;04E6
Odieresissmall;F7F6
Odotbelow;1ECC
Ogoneksmall;F6FB
Ograve;00D2
Ogravesmall;F7F2
Oharmenian;0555
Ohm;2126
Ohookabove;1ECE
Ohorn;01A0
Ohornacute;1EDA
Ohorndotbelow;1EE2
Ohorngrave;1EDC
Ohornhookabove;1EDE
Ohorntilde;1EE0
Ohungarumlaut;0150
Oi;01A2
Oinvertedbreve;020E
Omacron;014C
Omacronacute;1E52
Omacrongrave;1E50
Omega;2126
Omegacyrillic;0460
Omegagreek;03A9
Omegaroundcyrillic;047A
Omegatitlocyrillic;047C
Omegatonos;038F
Omicron;039F
Omicrontonos;038C
Omonospace;FF2F
Oneroman;2160
Oogonek;01EA
Oogonekmacron;01EC
Oopen;0186
Oslash;00D8
Oslashacute;01FE
Oslashsmall;F7F8
Osmall;F76F
Ostrokeacute;01FE
Otcyrillic;047E
Otilde;00D5
Otildeacute;1E4C
Otildedieresis;1E4E
Otildesmall;F7F5
P;0050
Pacute;1E54
Pcircle;24C5
Pdotaccent;1E56
Pecyrillic;041F
Peharmenian;054A
Pemiddlehookcyrillic;04A6
Phi;03A6
Phook;01A4
Pi;03A0
Piwrarmenian;0553
Pmonospace;FF30
Psi;03A8
Psicyrillic;0470
Psmall;F770
Q;0051
Qcircle;24C6
Qmonospace;FF31
Qsmall;F771
R;0052
Raarmenian;054C
Racute;0154
Rcaron;0158
Rcedilla;0156
Rcircle;24C7
Rcommaaccent;0156
Rdblgrave;0210
Rdotaccent;1E58
Rdotbelow;1E5A
Rdotbelowmacron;1E5C
Reharmenian;0550
Rfraktur;211C
Rho;03A1
Ringsmall;F6FC
Rinvertedbreve;0212
Rlinebelow;1E5E
Rmonospace;FF32
Rsmall;F772
Rsmallinverted;0281
Rsmallinvertedsuperior;02B6
S;0053
SF010000;250C
SF020000;2514
SF030000;2510
SF040000;2518
SF050000;253C
SF060000;252C
SF070000;2534
SF080000;251C
SF090000;2524
SF100000;2500
SF110000;2502
SF190000;2561
SF200000;2562
SF210000;2556
SF220000;2555
SF230000;2563
SF240000;2551
SF250000;2557
SF260000;255D
SF270000;255C
SF280000;255B
SF360000;255E
SF370000;255F
SF380000;255A
SF390000;2554
SF400000;2569
SF410000;2566
SF420000;2560
SF430000;2550
SF440000;256C
SF450000;2567
SF460000;2568
SF470000;2564
SF480000;2565
SF490000;2559
SF500000;2558
SF510000;2552
SF520000;2553
SF530000;256B
SF540000;256A
Sacute;015A
Sacutedotaccent;1E64
Sampigreek;03E0
Scaron;0160
Scarondotaccent;1E66
Scaronsmall;F6FD
Scedilla;015E
Schwa;018F
Schwacyrillic;04D8
Schwadieresiscyrillic;04DA
Scircle;24C8
Scircumflex;015C
Scommaaccent;0218
Sdotaccent;1E60
Sdotbelow;1E62
Sdotbelowdotaccent;1E68
Seharmenian;054D
Sevenroman;2166
Shaarmenian;0547
Shacyrillic;0428
Shchacyrillic;0429
Sheicoptic;03E2
Shhacyrillic;04BA
Shimacoptic;03EC
Sigma;03A3
Sixroman;2165
Smonospace;FF33
Softsigncyrillic;042C
Ssmall;F773
Stigmagreek;03DA
T;0054
Tau;03A4
Tbar;0166
Tcaron;0164
Tcedilla;0162
Tcircle;24C9
Tcircumflexbelow;1E70
Tcommaaccent;0162
Tdotaccent;1E6A
Tdotbelow;1E6C
Tecyrillic;0422
Tedescendercyrillic;04AC
Tenroman;2169
Tetsecyrillic;04B4
Theta;0398
Thook;01AC
Thorn;00DE
Thornsmall;F7FE
Threeroman;2162
Tildesmall;F6FE
Tiwnarmenian;054F
Tlinebelow;1E6E
Tmonospace;FF34
Toarmenian;0539
Tonefive;01BC
Tonesix;0184
Tonetwo;01A7
Tretroflexhook;01AE
Tsecyrillic;0426
Tshecyrillic;040B
Tsmall;F774
Twelveroman;216B
Tworoman;2161
U;0055
Uacute;00DA
Uacutesmall;F7FA
Ubreve;016C
Ucaron;01D3
Ucircle;24CA
Ucircumflex;00DB
Ucircumflexbelow;1E76
Ucircumflexsmall;F7FB
Ucyrillic;0423
Udblacute;0170
Udblgrave;0214
Udieresis;00DC
Udieresisacute;01D7
Udieresisbelow;1E72
Udieresiscaron;01D9
Udieresiscyrillic;04F0
Udieresisgrave;01DB
Udieresismacron;01D5
Udieresissmall;F7FC
Udotbelow;1EE4
Ugrave;00D9
Ugravesmall;F7F9
Uhookabove;1EE6
Uhorn;01AF
Uhornacute;1EE8
Uhorndotbelow;1EF0
Uhorngrave;1EEA
Uhornhookabove;1EEC
Uhorntilde;1EEE
Uhungarumlaut;0170
Uhungarumlautcyrillic;04F2
Uinvertedbreve;0216
Ukcyrillic;0478
Umacron;016A
Umacroncyrillic;04EE
Umacrondieresis;1E7A
Umonospace;FF35
Uogonek;0172
Upsilon;03A5
Upsilon1;03D2
Upsilonacutehooksymbolgreek;03D3
Upsilonafrican;01B1
Upsilondieresis;03AB
Upsilondieresishooksymbolgreek;03D4
Upsilonhooksymbol;03D2
Upsilontonos;038E
Uring;016E
Ushortcyrillic;040E
Usmall;F775
Ustraightcyrillic;04AE
Ustraightstrokecyrillic;04B0
Utilde;0168
Utildeacute;1E78
Utildebelow;1E74
V;0056
Vcircle;24CB
Vdotbelow;1E7E
Vecyrillic;0412
Vewarmenian;054E
Vhook;01B2
Vmonospace;FF36
Voarmenian;0548
Vsmall;F776
Vtilde;1E7C
W;0057
Wacute;1E82
Wcircle;24CC
Wcircumflex;0174
Wdieresis;1E84
Wdotaccent;1E86
Wdotbelow;1E88
Wgrave;1E80
Wmonospace;FF37
Wsmall;F777
X;0058
Xcircle;24CD
Xdieresis;1E8C
Xdotaccent;1E8A
Xeharmenian;053D
Xi;039E
Xmonospace;FF38
Xsmall;F778
Y;0059
Yacute;00DD
Yacutesmall;F7FD
Yatcyrillic;0462
Ycircle;24CE
Ycircumflex;0176
Ydieresis;0178
Ydieresissmall;F7FF
Ydotaccent;1E8E
Ydotbelow;1EF4
Yericyrillic;042B
Yerudieresiscyrillic;04F8
Ygrave;1EF2
Yhook;01B3
Yhookabove;1EF6
Yiarmenian;0545
Yicyrillic;0407
Yiwnarmenian;0552
Ymonospace;FF39
Ysmall;F779
Ytilde;1EF8
Yusbigcyrillic;046A
Yusbigiotifiedcyrillic;046C
Yuslittlecyrillic;0466
Yuslittleiotifiedcyrillic;0468
Z;005A
Zaarmenian;0536
Zacute;0179
Zcaron;017D
Zcaronsmall;F6FF
Zcircle;24CF
Zcircumflex;1E90
Zdot;017B
Zdotaccent;017B
Zdotbelow;1E92
Zecyrillic;0417
Zedescendercyrillic;0498
Zedieresiscyrillic;04DE
Zeta;0396
Zhearmenian;053A
Zhebrevecyrillic;04C1
Zhecyrillic;0416
Zhedescendercyrillic;0496
Zhedieresiscyrillic;04DC
Zlinebelow;1E94
Zmonospace;FF3A
Zsmall;F77A
Zstroke;01B5
a;0061
aabengali;0986
aacute;00E1
aadeva;0906
aagujarati;0A86
aagurmukhi;0A06
aamatragurmukhi;0A3E
aarusquare;3303
aavowelsignbengali;09BE
aavowelsigndeva;093E
aavowelsigngujarati;0ABE
abbreviationmarkarmenian;055F
abbreviationsigndeva;0970
abengali;0985
abopomofo;311A
abreve;0103
abreveacute;1EAF
abrevecyrillic;04D1
abrevedotbelow;1EB7
abrevegrave;1EB1
abrevehookabove;1EB3
abrevetilde;1EB5
acaron;01CE
acircle;24D0
acircumflex;00E2
acircumflexacute;1EA5
acircumflexdotbelow;1EAD
acircumflexgrave;1EA7
acircumflexhookabove;1EA9
acircumflextilde;1EAB
acute;00B4
acutebelowcmb;0317
acutecmb;0301
acutecomb;0301
acutedeva;0954
acutelowmod;02CF
acutetonecmb;0341
acyrillic;0430
adblgrave;0201
addakgurmukhi;0A71
adeva;0905
adieresis;00E4
adieresiscyrillic;04D3
adieresismacron;01DF
adotbelow;1EA1
adotmacron;01E1
ae;00E6
aeacute;01FD
aekorean;3150
aemacron;01E3
afii00208;2015
afii08941;20A4
afii10017;0410
afii10018;0411
afii10019;0412
afii10020;0413
afii10021;0414
afii10022;0415
afii10023;0401
afii10024;0416
afii10025;0417
afii10026;0418
afii10027;0419
afii10028;041A
afii10029;041B
afii10030;041C
afii10031;041D
afii10032;041E
afii10033;041F
afii10034;0420
afii10035;0421
afii10036;0422
afii10037;0423
afii10038;0424
afii10039;0425
afii10040;0426
afii10041;0427
afii10042;0428
afii10043;0429
afii10044;042A
afii10045;042B
afii10046;042C
afii10047;042D
afii10048;042E
afii10049;042F
afii10050;0490
afii10051;0402
afii10052;0403
afii10053;0404
afii10054;0405
afii10055;0406
afii10056;0407
afii10057;0408
afii10058;0409
afii10059;040A
afii10060;040B
afii10061;040C
afii10062;040E
afii10063;F6C4
afii10064;F6C5
afii10065;0430
afii10066;0431
afii10067;0432
afii10068;0433
afii10069;0434
afii10070;0435
afii10071;0451
afii10072;0436
afii10073;0437
afii10074;0438
afii10075;0439
afii10076;043A
afii10077;043B
afii10078;043C
afii10079;043D
afii10080;043E
afii10081;043F
afii10082;0440
afii10083;0441
afii10084;0442
afii10085;0443
afii10086;0444
afii10087;0445
afii10088;0446
afii10089;0447
afii10090;0448
afii10091;0449
afii10092;044A
afii10093;044B
afii10094;044C
afii10095;044D
afii10096;044E
afii10097;044F
afii10098;0491
afii10099;0452
afii10100;0453
afii10101;0454
afii10102;0455
afii10103;0456
afii10104;0457
afii10105;0458
afii10106;0459
afii10107;045A
afii10108;045B
afii10109;045C
afii10110;045E
afii10145;040F
afii10146;0462
afii10147;0472
afii10148;0474
afii10192;F6C6
afii10193;045F
afii10194;0463
afii10195;0473
afii10196;0475
afii10831;F6C7
afii10832;F6C8
afii10846;04D9
afii299;200E
afii300;200F
afii301;200D
afii57381;066A
afii57388;060C
afii57392;0660
afii57393;0661
afii57394;0662
afii57395;0663
afii57396;0664
afii57397;0665
afii57398;0666
afii57399;0667
afii57400;0668
afii57401;0669
afii57403;061B
afii57407;061F
afii57409;0621
afii57410;0622
afii57411;0623
afii57412;0624
afii57413;0625
afii57414;0626
afii57415;0627
afii57416;0628
afii57417;0629
afii57418;062A
afii57419;062B
afii57420;062C
afii57421;062D
afii57422;062E
afii57423;062F
afii57424;0630
afii57425;0631
afii57426;0632
afii57427;0633
afii57428;0634
afii57429;0635
afii57430;0636
afii57431;0637
afii57432;0638
afii57433;0639
afii57434;063A
afii57440;0640
afii57441;0641
afii57442;0642
afii57443;0643
afii57444;0644
afii57445;0645
afii57446;0646
afii57448;0648
afii57449;0649
afii57450;064A
afii57451;064B
afii57452;064C
afii57453;064D
afii57454;064E
afii57455;064F
afii57456;0650
afii57457;0651
afii57458;0652
afii57470;0647
afii57505;06A4
afii57506;067E
afii57507;0686
afii57508;0698
afii57509;06AF
afii57511;0679
afii57512;0688
afii57513;0691
afii57514;06BA
afii57519;06D2
afii57534;06D5
afii57636;20AA
afii57645;05BE
afii57658;05C3
afii57664;05D0
afii57665;05D1
afii57666;05D2
afii57667;05D3
afii57668;05D4
afii57669;05D5
afii57670;05D6
afii57671;05D7
afii57672;05D8
afii57673;05D9
afii57674;05DA
afii57675;05DB
afii57676;05DC
afii57677;05DD
afii57678;05DE
afii57679;05DF
afii57680;05E0
afii57681;05E1
afii57682;05E2
afii57683;05E3
afii57684;05E4
afii57685;05E5
afii57686;05E6
afii57687;05E7
afii57688;05E8
afii57689;05E9
afii57690;05EA
afii57694;FB2A
afii57695;FB2B
afii57700;FB4B
afii57705;FB1F
afii57716;05F0
afii57717;05F1
afii57718;05F2
afii57723;FB35
afii57793;05B4
afii57794;05B5
afii57795;05B6
afii57796;05BB
afii57797;05B8
afii57798;05B7
afii57799;05B0
afii57800;05B2
afii57801;05B1
afii57802;05B3
afii57803;05C2
afii57804;05C1
afii57806;05B9
afii57807;05BC
afii57839;05BD
afii57841;05BF
afii57842;05C0
afii57929;02BC
afii61248;2105
afii61289;2113
afii61352;2116
afii61573;202C
afii61574;202D
afii61575;202E
afii61664;200C
afii63167;066D
afii64937;02BD
agrave;00E0
agujarati;0A85
agurmukhi;0A05
ahiragana;3042
ahookabove;1EA3
aibengali;0990
aibopomofo;311E
aideva;0910
aiecyrillic;04D5
aigujarati;0A90
aigurmukhi;0A10
aimatragurmukhi;0A48
ainarabic;0639
ainfinalarabic;FECA
aininitialarabic;FECB
ainmedialarabic;FECC
ainvertedbreve;0203
aivowelsignbengali;09C8
aivowelsigndeva;0948
aivowelsigngujarati;0AC8
akatakana;30A2
akatakanahalfwidth;FF71
akorean;314F
alef;05D0
alefarabic;0627
alefdageshhebrew;FB30
aleffinalarabic;FE8E
alefhamzaabovearabic;0623
alefhamzaabovefinalarabic;FE84
alefhamzabelowarabic;0625
alefhamzabelowfinalarabic;FE88
alefhebrew;05D0
aleflamedhebrew;FB4F
alefmaddaabovearabic;0622
alefmaddaabovefinalarabic;FE82
alefmaksuraarabic;0649
alefmaksurafinalarabic;FEF0
alefmaksurainitialarabic;FEF3
alefmaksuramedialarabic;FEF4
alefpatahhebrew;FB2E
alefqamatshebrew;FB2F
aleph;2135
allequal;224C
alpha;03B1
alphatonos;03AC
amacron;0101
amonospace;FF41
ampersand;0026
ampersandmonospace;FF06
ampersandsmall;F726
amsquare;33C2
anbopomofo;3122
angbopomofo;3124
angkhankhuthai;0E5A
angle;2220
anglebracketleft;3008
anglebracketleftvertical;FE3F
anglebracketright;3009
anglebracketrightvertical;FE40
angleleft;2329
angleright;232A
angstrom;212B
anoteleia;0387
anudattadeva;0952
anusvarabengali;0982
anusvaradeva;0902
anusvaragujarati;0A82
aogonek;0105
apaatosquare;3300
aparen;249C
apostrophearmenian;055A
apostrophemod;02BC
apple;F8FF
approaches;2250
approxequal;2248
approxequalorimage;2252
approximatelyequal;2245
araeaekorean;318E
araeakorean;318D
arc;2312
arighthalfring;1E9A
aring;00E5
aringacute;01FB
aringbelow;1E01
arrowboth;2194
arrowdashdown;21E3
arrowdashleft;21E0
arrowdashright;21E2
arrowdashup;21E1
arrowdblboth;21D4
arrowdbldown;21D3
arrowdblleft;21D0
arrowdblright;21D2
arrowdblup;21D1
arrowdown;2193
arrowdownleft;2199
arrowdownright;2198
arrowdownwhite;21E9
arrowheaddownmod;02C5
arrowheadleftmod;02C2
arrowheadrightmod;02C3
arrowheadupmod;02C4
arrowhorizex;F8E7
arrowleft;2190
arrowleftdbl;21D0
arrowleftdblstroke;21CD
arrowleftoverright;21C6
arrowleftwhite;21E6
arrowright;2192
arrowrightdblstroke;21CF
arrowrightheavy;279E
arrowrightoverleft;21C4
arrowrightwhite;21E8
arrowtableft;21E4
arrowtabright;21E5
arrowup;2191
arrowupdn;2195
arrowupdnbse;21A8
arrowupdownbase;21A8
arrowupleft;2196
arrowupleftofdown;21C5
arrowupright;2197
arrowupwhite;21E7
arrowvertex;F8E6
asciicircum;005E
asciicircummonospace;FF3E
asciitilde;007E
asciitildemonospace;FF5E
ascript;0251
ascriptturned;0252
asmallhiragana;3041
asmallkatakana;30A1
asmallkatakanahalfwidth;FF67
asterisk;002A
asteriskaltonearabic;066D
asteriskarabic;066D
asteriskmath;2217
asteriskmonospace;FF0A
asterisksmall;FE61
asterism;2042
asuperior;F6E9
asymptoticallyequal;2243
at;0040
atilde;00E3
atmonospace;FF20
atsmall;FE6B
aturned;0250
aubengali;0994
aubopomofo;3120
audeva;0914
augujarati;0A94
augurmukhi;0A14
aulengthmarkbengali;09D7
aumatragurmukhi;0A4C
auvowelsignbengali;09CC
auvowelsigndeva;094C
auvowelsigngujarati;0ACC
avagrahadeva;093D
aybarmenian;0561
ayin;05E2
ayinaltonehebrew;FB20
ayinhebrew;05E2
b;0062
babengali;09AC
backslash;005C
backslashmonospace;FF3C
badeva;092C
bagujarati;0AAC
bagurmukhi;0A2C
bahiragana;3070
bahtthai;0E3F
bakatakana;30D0
bar;007C
barmonospace;FF5C
bbopomofo;3105
bcircle;24D1
bdotaccent;1E03
bdotbelow;1E05
beamedsixteenthnotes;266C
because;2235
becyrillic;0431
beharabic;0628
behfinalarabic;FE90
behinitialarabic;FE91
behiragana;3079
behmedialarabic;FE92
behmeeminitialarabic;FC9F
behmeemisolatedarabic;FC08
behnoonfinalarabic;FC6D
bekatakana;30D9
benarmenian;0562
bet;05D1
beta;03B2
betasymbolgreek;03D0
betdagesh;FB31
betdageshhebrew;FB31
bethebrew;05D1
betrafehebrew;FB4C
bhabengali;09AD
bhadeva;092D
bhagujarati;0AAD
bhagurmukhi;0A2D
bhook;0253
bihiragana;3073
bikatakana;30D3
bilabialclick;0298
bindigurmukhi;0A02
birusquare;3331
blackcircle;25CF
blackdiamond;25C6
blackdownpointingtriangle;25BC
blackleftpointingpointer;25C4
blackleftpointingtriangle;25C0
blacklenticularbracketleft;3010
blacklenticularbracketleftvertical;FE3B
blacklenticularbracketright;3011
blacklenticularbracketrightvertical;FE3C
blacklowerlefttriangle;25E3
blacklowerrighttriangle;25E2
blackrectangle;25AC
blackrightpointingpointer;25BA
blackrightpointingtriangle;25B6
blacksmallsquare;25AA
blacksmilingface;263B
blacksquare;25A0
blackstar;2605
blackupperlefttriangle;25E4
blackupperrighttriangle;25E5
blackuppointingsmalltriangle;25B4
blackuppointingtriangle;25B2
blank;2423
blinebelow;1E07
block;2588
bmonospace;FF42
bobaimaithai;0E1A
bohiragana;307C
bokatakana;30DC
bparen;249D
bqsquare;33C3
braceex;F8F4
braceleft;007B
braceleftbt;F8F3
braceleftmid;F8F2
braceleftmonospace;FF5B
braceleftsmall;FE5B
bracelefttp;F8F1
braceleftvertical;FE37
braceright;007D
bracerightbt;F8FE
bracerightmid;F8FD
bracerightmonospace;FF5D
bracerightsmall;FE5C
bracerighttp;F8FC
bracerightvertical;FE38
bracketleft;005B
bracketleftbt;F8F0
bracketleftex;F8EF
bracketleftmonospace;FF3B
bracketlefttp;F8EE
bracketright;005D
bracketrightbt;F8FB
bracketrightex;F8FA
bracketrightmonospace;FF3D
bracketrighttp;F8F9
breve;02D8
brevebelowcmb;032E
brevecmb;0306
breveinvertedbelowcmb;032F
breveinvertedcmb;0311
breveinverteddoublecmb;0361
bridgebelowcmb;032A
bridgeinvertedbelowcmb;033A
brokenbar;00A6
bstroke;0180
bsuperior;F6EA
btopbar;0183
buhiragana;3076
bukatakana;30D6
bullet;2022
bulletinverse;25D8
bulletoperator;2219
bullseye;25CE
c;0063
caarmenian;056E
cabengali;099A
cacute;0107
cadeva;091A
cagujarati;0A9A
cagurmukhi;0A1A
calsquare;3388
candrabindubengali;0981
candrabinducmb;0310
candrabindudeva;0901
candrabindugujarati;0A81
capslock;21EA
careof;2105
caron;02C7
caronbelowcmb;032C
caroncmb;030C
carriagereturn;21B5
cbopomofo;3118
ccaron;010D
ccedilla;00E7
ccedillaacute;1E09
ccircle;24D2
ccircumflex;0109
ccurl;0255
cdot;010B
cdotaccent;010B
cdsquare;33C5
cedilla;00B8
cedillacmb;0327
cent;00A2
centigrade;2103
centinferior;F6DF
centmonospace;FFE0
centoldstyle;F7A2
centsuperior;F6E0
chaarmenian;0579
chabengali;099B
chadeva;091B
chagujarati;0A9B
chagurmukhi;0A1B
chbopomofo;3114
cheabkhasiancyrillic;04BD
checkmark;2713
checyrillic;0447
chedescenderabkhasiancyrillic;04BF
chedescendercyrillic;04B7
chedieresiscyrillic;04F5
cheharmenian;0573
chekhakassiancyrillic;04CC
cheverticalstrokecyrillic;04B9
chi;03C7
chieuchacirclekorean;3277
chieuchaparenkorean;3217
chieuchcirclekorean;3269
chieuchkorean;314A
chieuchparenkorean;3209
chochangthai;0E0A
chochanthai;0E08
chochingthai;0E09
chochoethai;0E0C
chook;0188
cieucacirclekorean;3276
cieucaparenkorean;3216
cieuccirclekorean;3268
cieuckorean;3148
cieucparenkorean;3208
cieucuparenkorean;321C
circle;25CB
circlemultiply;2297
circleot;2299
circleplus;2295
circlepostalmark;3036
circlewithlefthalfblack;25D0
circlewithrighthalfblack;25D1
circumflex;02C6
circumflexbelowcmb;032D
circumflexcmb;0302
clear;2327
clickalveolar;01C2
clickdental;01C0
clicklateral;01C1
clickretroflex;01C3
club;2663
clubsuitblack;2663
clubsuitwhite;2667
cmcubedsquare;33A4
cmonospace;FF43
cmsquaredsquare;33A0
coarmenian;0581
colon;003A
colonmonetary;20A1
colonmonospace;FF1A
colonsign;20A1
colonsmall;FE55
colontriangularhalfmod;02D1
colontriangularmod;02D0
comma;002C
commaabovecmb;0313
commaaboverightcmb;0315
commaaccent;F6C3
commaarabic;060C
commaarmenian;055D
commainferior;F6E1
commamonospace;FF0C
commareversedabovecmb;0314
commareversedmod;02BD
commasmall;FE50
commasuperior;F6E2
commaturnedabovecmb;0312
commaturnedmod;02BB
compass;263C
congruent;2245
contourintegral;222E
control;2303
controlACK;0006
controlBEL;0007
controlBS;0008
controlCAN;0018
controlCR;000D
controlDC1;0011
controlDC2;0012
controlDC3;0013
controlDC4;0014
controlDEL;007F
controlDLE;0010
controlEM;0019
controlENQ;0005
controlEOT;0004
controlESC;001B
controlETB;0017
controlETX;0003
controlFF;000C
controlFS;001C
controlGS;001D
controlHT;0009
controlLF;000A
controlNAK;0015
controlRS;001E
controlSI;000F
controlSO;000E
controlSOT;0002
controlSTX;0001
controlSUB;001A
controlSYN;0016
controlUS;001F
controlVT;000B
copyright;00A9
copyrightsans;F8E9
copyrightserif;F6D9
cornerbracketleft;300C
cornerbracketlefthalfwidth;FF62
cornerbracketleftvertical;FE41
cornerbracketright;300D
cornerbracketrighthalfwidth;FF63
cornerbracketrightvertical;FE42
corporationsquare;337F
cosquare;33C7
coverkgsquare;33C6
cparen;249E
cruzeiro;20A2
cstretched;0297
curlyand;22CF
curlyor;22CE
currency;00A4
cyrBreve;F6D1
cyrFlex;F6D2
cyrbreve;F6D4
cyrflex;F6D5
d;0064
daarmenian;0564
dabengali;09A6
dadarabic;0636
dadeva;0926
dadfinalarabic;FEBE
dadinitialarabic;FEBF
dadmedialarabic;FEC0
dagesh;05BC
dageshhebrew;05BC
dagger;2020
daggerdbl;2021
dagujarati;0AA6
dagurmukhi;0A26
dahiragana;3060
dakatakana;30C0
dalarabic;062F
dalet;05D3
daletdagesh;FB33
daletdageshhebrew;FB33
dalethatafpatah;05D3 05B2
dalethatafpatahhebrew;05D3 05B2
dalethatafsegol;05D3 05B1
dalethatafsegolhebrew;05D3 05B1
dalethebrew;05D3
dalethiriq;05D3 05B4
dalethiriqhebrew;05D3 05B4
daletholam;05D3 05B9
daletholamhebrew;05D3 05B9
daletpatah;05D3 05B7
daletpatahhebrew;05D3 05B7
daletqamats;05D3 05B8
daletqamatshebrew;05D3 05B8
daletqubuts;05D3 05BB
daletqubutshebrew;05D3 05BB
daletsegol;05D3 05B6
daletsegolhebrew;05D3 05B6
daletsheva;05D3 05B0
daletshevahebrew;05D3 05B0
dalettsere;05D3 05B5
dalettserehebrew;05D3 05B5
dalfinalarabic;FEAA
dammaarabic;064F
dammalowarabic;064F
dammatanaltonearabic;064C
dammatanarabic;064C
danda;0964
dargahebrew;05A7
dargalefthebrew;05A7
dasiapneumatacyrilliccmb;0485
dblGrave;F6D3
dblanglebracketleft;300A
dblanglebracketleftvertical;FE3D
dblanglebracketright;300B
dblanglebracketrightvertical;FE3E
dblarchinvertedbelowcmb;032B
dblarrowleft;21D4
dblarrowright;21D2
dbldanda;0965
dblgrave;F6D6
dblgravecmb;030F
dblintegral;222C
dbllowline;2017
dbllowlinecmb;0333
dbloverlinecmb;033F
dblprimemod;02BA
dblverticalbar;2016
dblverticallineabovecmb;030E
dbopomofo;3109
dbsquare;33C8
dcaron;010F
dcedilla;1E11
dcircle;24D3
dcircumflexbelow;1E13
dcroat;0111
ddabengali;09A1
ddadeva;0921
ddagujarati;0AA1
ddagurmukhi;0A21
ddalarabic;0688
ddalfinalarabic;FB89
dddhadeva;095C
ddhabengali;09A2
ddhadeva;0922
ddhagujarati;0AA2
ddhagurmukhi;0A22
ddotaccent;1E0B
ddotbelow;1E0D
decimalseparatorarabic;066B
decimalseparatorpersian;066B
decyrillic;0434
degree;00B0
dehihebrew;05AD
dehiragana;3067
deicoptic;03EF
dekatakana;30C7
deleteleft;232B
deleteright;2326
delta;03B4
deltaturned;018D
denominatorminusonenumeratorbengali;09F8
dezh;02A4
dhabengali;09A7
dhadeva;0927
dhagujarati;0AA7
dhagurmukhi;0A27
dhook;0257
dialytikatonos;0385
dialytikatonoscmb;0344
diamond;2666
diamondsuitwhite;2662
dieresis;00A8
dieresisacute;F6D7
dieresisbelowcmb;0324
dieresiscmb;0308
dieresisgrave;F6D8
dieresistonos;0385
dihiragana;3062
dikatakana;30C2
dittomark;3003
divide;00F7
divides;2223
divisionslash;2215
djecyrillic;0452
dkshade;2593
dlinebelow;1E0F
dlsquare;3397
dmacron;0111
dmonospace;FF44
dnblock;2584
dochadathai;0E0E
dodekthai;0E14
dohiragana;3069
dokatakana;30C9
dollar;0024
dollarinferior;F6E3
dollarmonospace;FF04
dollaroldstyle;F724
dollarsmall;FE69
dollarsuperior;F6E4
dong;20AB
dorusquare;3326
dotaccent;02D9
dotaccentcmb;0307
dotbelowcmb;0323
dotbelowcomb;0323
dotkatakana;30FB
dotlessi;0131
dotlessj;F6BE
dotlessjstrokehook;0284
dotmath;22C5
dottedcircle;25CC
doubleyodpatah;FB1F
doubleyodpatahhebrew;FB1F
downtackbelowcmb;031E
downtackmod;02D5
dparen;249F
dsuperior;F6EB
dtail;0256
dtopbar;018C
duhiragana;3065
dukatakana;30C5
dz;01F3
dzaltone;02A3
dzcaron;01C6
dzcurl;02A5
dzeabkhasiancyrillic;04E1
dzecyrillic;0455
dzhecyrillic;045F
e;0065
eacute;00E9
earth;2641
ebengali;098F
ebopomofo;311C
ebreve;0115
ecandradeva;090D
ecandragujarati;0A8D
ecandravowelsigndeva;0945
ecandravowelsigngujarati;0AC5
ecaron;011B
ecedillabreve;1E1D
echarmenian;0565
echyiwnarmenian;0587
ecircle;24D4
ecircumflex;00EA
ecircumflexacute;1EBF
ecircumflexbelow;1E19
ecircumflexdotbelow;1EC7
ecircumflexgrave;1EC1
ecircumflexhookabove;1EC3
ecircumflextilde;1EC5
ecyrillic;0454
edblgrave;0205
edeva;090F
edieresis;00EB
edot;0117
edotaccent;0117
edotbelow;1EB9
eegurmukhi;0A0F
eematragurmukhi;0A47
efcyrillic;0444
egrave;00E8
egujarati;0A8F
eharmenian;0567
ehbopomofo;311D
ehiragana;3048
ehookabove;1EBB
eibopomofo;311F
eight;0038
eightarabic;0668
eightbengali;09EE
eightcircle;2467
eightcircleinversesansserif;2791
eightdeva;096E
eighteencircle;2471
eighteenparen;2485
eighteenperiod;2499
eightgujarati;0AEE
eightgurmukhi;0A6E
eighthackarabic;0668
eighthangzhou;3028
eighthnotebeamed;266B
eightideographicparen;3227
eightinferior;2088
eightmonospace;FF18
eightoldstyle;F738
eightparen;247B
eightperiod;248F
eightpersian;06F8
eightroman;2177
eightsuperior;2078
eightthai;0E58
einvertedbreve;0207
eiotifiedcyrillic;0465
ekatakana;30A8
ekatakanahalfwidth;FF74
ekonkargurmukhi;0A74
ekorean;3154
elcyrillic;043B
element;2208
elevencircle;246A
elevenparen;247E
elevenperiod;2492
elevenroman;217A
ellipsis;2026
ellipsisvertical;22EE
emacron;0113
emacronacute;1E17
emacrongrave;1E15
emcyrillic;043C
emdash;2014
emdashvertical;FE31
emonospace;FF45
emphasismarkarmenian;055B
emptyset;2205
enbopomofo;3123
encyrillic;043D
endash;2013
endashvertical;FE32
endescendercyrillic;04A3
eng;014B
engbopomofo;3125
enghecyrillic;04A5
enhookcyrillic;04C8
enspace;2002
eogonek;0119
eokorean;3153
eopen;025B
eopenclosed;029A
eopenreversed;025C
eopenreversedclosed;025E
eopenreversedhook;025D
eparen;24A0
epsilon;03B5
epsilontonos;03AD
equal;003D
equalmonospace;FF1D
equalsmall;FE66
equalsuperior;207C
equivalence;2261
erbopomofo;3126
ercyrillic;0440
ereversed;0258
ereversedcyrillic;044D
escyrillic;0441
esdescendercyrillic;04AB
esh;0283
eshcurl;0286
eshortdeva;090E
eshortvowelsigndeva;0946
eshreversedloop;01AA
eshsquatreversed;0285
esmallhiragana;3047
esmallkatakana;30A7
esmallkatakanahalfwidth;FF6A
estimated;212E
esuperior;F6EC
eta;03B7
etarmenian;0568
etatonos;03AE
eth;00F0
etilde;1EBD
etildebelow;1E1B
etnahtafoukhhebrew;0591
etnahtafoukhlefthebrew;0591
etnahtahebrew;0591
etnahtalefthebrew;0591
eturned;01DD
eukorean;3161
euro;20AC
evowelsignbengali;09C7
evowelsigndeva;0947
evowelsigngujarati;0AC7
exclam;0021
exclamarmenian;055C
exclamdbl;203C
exclamdown;00A1
exclamdownsmall;F7A1
exclammonospace;FF01
exclamsmall;F721
existential;2203
ezh;0292
ezhcaron;01EF
ezhcurl;0293
ezhreversed;01B9
ezhtail;01BA
f;0066
fadeva;095E
fagurmukhi;0A5E
fahrenheit;2109
fathaarabic;064E
fathalowarabic;064E
fathatanarabic;064B
fbopomofo;3108
fcircle;24D5
fdotaccent;1E1F
feharabic;0641
feharmenian;0586
fehfinalarabic;FED2
fehinitialarabic;FED3
fehmedialarabic;FED4
feicoptic;03E5
female;2640
ff;FB00
ffi;FB03
ffl;FB04
fi;FB01
fifteencircle;246E
fifteenparen;2482
fifteenperiod;2496
figuredash;2012
filledbox;25A0
filledrect;25AC
finalkaf;05DA
finalkafdagesh;FB3A
finalkafdageshhebrew;FB3A
finalkafhebrew;05DA
finalkafqamats;05DA 05B8
finalkafqamatshebrew;05DA 05B8
finalkafsheva;05DA 05B0
finalkafshevahebrew;05DA 05B0
finalmem;05DD
finalmemhebrew;05DD
finalnun;05DF
finalnunhebrew;05DF
finalpe;05E3
finalpehebrew;05E3
finaltsadi;05E5
finaltsadihebrew;05E5
firsttonechinese;02C9
fisheye;25C9
fitacyrillic;0473
five;0035
fivearabic;0665
fivebengali;09EB
fivecircle;2464
fivecircleinversesansserif;278E
fivedeva;096B
fiveeighths;215D
fivegujarati;0AEB
fivegurmukhi;0A6B
fivehackarabic;0665
fivehangzhou;3025
fiveideographicparen;3224
fiveinferior;2085
fivemonospace;FF15
fiveoldstyle;F735
fiveparen;2478
fiveperiod;248C
fivepersian;06F5
fiveroman;2174
fivesuperior;2075
fivethai;0E55
fl;FB02
florin;0192
fmonospace;FF46
fmsquare;3399
fofanthai;0E1F
fofathai;0E1D
fongmanthai;0E4F
forall;2200
four;0034
fourarabic;0664
fourbengali;09EA
fourcircle;2463
fourcircleinversesansserif;278D
fourdeva;096A
fourgujarati;0AEA
fourgurmukhi;0A6A
fourhackarabic;0664
fourhangzhou;3024
fourideographicparen;3223
fourinferior;2084
fourmonospace;FF14
fournumeratorbengali;09F7
fouroldstyle;F734
fourparen;2477
fourperiod;248B
fourpersian;06F4
fourroman;2173
foursuperior;2074
fourteencircle;246D
fourteenparen;2481
fourteenperiod;2495
fourthai;0E54
fourthtonechinese;02CB
fparen;24A1
fraction;2044
franc;20A3
g;0067
gabengali;0997
gacute;01F5
gadeva;0917
gafarabic;06AF
gaffinalarabic;FB93
gafinitialarabic;FB94
gafmedialarabic;FB95
gagujarati;0A97
gagurmukhi;0A17
gahiragana;304C
gakatakana;30AC
gamma;03B3
gammalatinsmall;0263
gammasuperior;02E0
gangiacoptic;03EB
gbopomofo;310D
gbreve;011F
gcaron;01E7
gcedilla;0123
gcircle;24D6
gcircumflex;011D
gcommaaccent;0123
gdot;0121
gdotaccent;0121
gecyrillic;0433
gehiragana;3052
gekatakana;30B2
geometricallyequal;2251
gereshaccenthebrew;059C
gereshhebrew;05F3
gereshmuqdamhebrew;059D
germandbls;00DF
gershayimaccenthebrew;059E
gershayimhebrew;05F4
getamark;3013
ghabengali;0998
ghadarmenian;0572
ghadeva;0918
ghagujarati;0A98
ghagurmukhi;0A18
ghainarabic;063A
ghainfinalarabic;FECE
ghaininitialarabic;FECF
ghainmedialarabic;FED0
ghemiddlehookcyrillic;0495
ghestrokecyrillic;0493
gheupturncyrillic;0491
ghhadeva;095A
ghhagurmukhi;0A5A
ghook;0260
ghzsquare;3393
gihiragana;304E
gikatakana;30AE
gimarmenian;0563
gimel;05D2
gimeldagesh;FB32
gimeldageshhebrew;FB32
gimelhebrew;05D2
gjecyrillic;0453
glottalinvertedstroke;01BE
glottalstop;0294
glottalstopinverted;0296
glottalstopmod;02C0
glottalstopreversed;0295
glottalstopreversedmod;02C1
glottalstopreversedsuperior;02E4
glottalstopstroke;02A1
glottalstopstrokereversed;02A2
gmacron;1E21
gmonospace;FF47
gohiragana;3054
gokatakana;30B4
gparen;24A2
gpasquare;33AC
gradient;2207
grave;0060
gravebelowcmb;0316
gravecmb;0300
gravecomb;0300
gravedeva;0953
gravelowmod;02CE
gravemonospace;FF40
gravetonecmb;0340
greater;003E
greaterequal;2265
greaterequalorless;22DB
greatermonospace;FF1E
greaterorequivalent;2273
greaterorless;2277
greateroverequal;2267
greatersmall;FE65
gscript;0261
gstroke;01E5
guhiragana;3050
guillemotleft;00AB
guillemotright;00BB
guilsinglleft;2039
guilsinglright;203A
gukatakana;30B0
guramusquare;3318
gysquare;33C9
h;0068
haabkhasiancyrillic;04A9
haaltonearabic;06C1
habengali;09B9
hadescendercyrillic;04B3
hadeva;0939
hagujarati;0AB9
hagurmukhi;0A39
haharabic;062D
hahfinalarabic;FEA2
hahinitialarabic;FEA3
hahiragana;306F
hahmedialarabic;FEA4
haitusquare;332A
hakatakana;30CF
hakatakanahalfwidth;FF8A
halantgurmukhi;0A4D
hamzaarabic;0621
hamzadammaarabic;0621 064F
hamzadammatanarabic;0621 064C
hamzafathaarabic;0621 064E
hamzafathatanarabic;0621 064B
hamzalowarabic;0621
hamzalowkasraarabic;0621 0650
hamzalowkasratanarabic;0621 064D
hamzasukunarabic;0621 0652
hangulfiller;3164
hardsigncyrillic;044A
harpoonleftbarbup;21BC
harpoonrightbarbup;21C0
hasquare;33CA
hatafpatah;05B2
hatafpatah16;05B2
hatafpatah23;05B2
hatafpatah2f;05B2
hatafpatahhebrew;05B2
hatafpatahnarrowhebrew;05B2
hatafpatahquarterhebrew;05B2
hatafpatahwidehebrew;05B2
hatafqamats;05B3
hatafqamats1b;05B3
hatafqamats28;05B3
hatafqamats34;05B3
hatafqamatshebrew;05B3
hatafqamatsnarrowhebrew;05B3
hatafqamatsquarterhebrew;05B3
hatafqamatswidehebrew;05B3
hatafsegol;05B1
hatafsegol17;05B1
hatafsegol24;05B1
hatafsegol30;05B1
hatafsegolhebrew;05B1
hatafsegolnarrowhebrew;05B1
hatafsegolquarterhebrew;05B1
hatafsegolwidehebrew;05B1
hbar;0127
hbopomofo;310F
hbrevebelow;1E2B
hcedilla;1E29
hcircle;24D7
hcircumflex;0125
hdieresis;1E27
hdotaccent;1E23
hdotbelow;1E25
he;05D4
heart;2665
heartsuitblack;2665
heartsuitwhite;2661
hedagesh;FB34
hedageshhebrew;FB34
hehaltonearabic;06C1
heharabic;0647
hehebrew;05D4
hehfinalaltonearabic;FBA7
hehfinalalttwoarabic;FEEA
hehfinalarabic;FEEA
hehhamzaabovefinalarabic;FBA5
hehhamzaaboveisolatedarabic;FBA4
hehinitialaltonearabic;FBA8
hehinitialarabic;FEEB
hehiragana;3078
hehmedialaltonearabic;FBA9
hehmedialarabic;FEEC
heiseierasquare;337B
hekatakana;30D8
hekatakanahalfwidth;FF8D
hekutaarusquare;3336
henghook;0267
herutusquare;3339
het;05D7
hethebrew;05D7
hhook;0266
hhooksuperior;02B1
hieuhacirclekorean;327B
hieuhaparenkorean;321B
hieuhcirclekorean;326D
hieuhkorean;314E
hieuhparenkorean;320D
hihiragana;3072
hikatakana;30D2
hikatakanahalfwidth;FF8B
hiriq;05B4
hiriq14;05B4
hiriq21;05B4
hiriq2d;05B4
hiriqhebrew;05B4
hiriqnarrowhebrew;05B4
hiriqquarterhebrew;05B4
hiriqwidehebrew;05B4
hlinebelow;1E96
hmonospace;FF48
hoarmenian;0570
hohipthai;0E2B
hohiragana;307B
hokatakana;30DB
hokatakanahalfwidth;FF8E
holam;05B9
holam19;05B9
holam26;05B9
holam32;05B9
holamhebrew;05B9
holamnarrowhebrew;05B9
holamquarterhebrew;05B9
holamwidehebrew;05B9
honokhukthai;0E2E
hookabovecomb;0309
hookcmb;0309
hookpalatalizedbelowcmb;0321
hookretroflexbelowcmb;0322
hoonsquare;3342
horicoptic;03E9
horizontalbar;2015
horncmb;031B
hotsprings;2668
house;2302
hparen;24A3
hsuperior;02B0
hturned;0265
huhiragana;3075
huiitosquare;3333
hukatakana;30D5
hukatakanahalfwidth;FF8C
hungarumlaut;02DD
hungarumlautcmb;030B
hv;0195
hyphen;002D
hypheninferior;F6E5
hyphenmonospace;FF0D
hyphensmall;FE63
hyphensuperior;F6E6
hyphentwo;2010
i;0069
iacute;00ED
iacyrillic;044F
ibengali;0987
ibopomofo;3127
ibreve;012D
icaron;01D0
icircle;24D8
icircumflex;00EE
icyrillic;0456
idblgrave;0209
ideographearthcircle;328F
ideographfirecircle;328B
ideographicallianceparen;323F
ideographiccallparen;323A
ideographiccentrecircle;32A5
ideographicclose;3006
ideographiccomma;3001
ideographiccommaleft;FF64
ideographiccongratulationparen;3237
ideographiccorrectcircle;32A3
ideographicearthparen;322F
ideographicenterpriseparen;323D
ideographicexcellentcircle;329D
ideographicfestivalparen;3240
ideographicfinancialcircle;3296
ideographicfinancialparen;3236
ideographicfireparen;322B
ideographichaveparen;3232
ideographichighcircle;32A4
ideographiciterationmark;3005
ideographiclaborcircle;3298
ideographiclaborparen;3238
ideographicleftcircle;32A7
ideographiclowcircle;32A6
ideographicmedicinecircle;32A9
ideographicmetalparen;322E
ideographicmoonparen;322A
ideographicnameparen;3234
ideographicperiod;3002
ideographicprintcircle;329E
ideographicreachparen;3243
ideographicrepresentparen;3239
ideographicresourceparen;323E
ideographicrightcircle;32A8
ideographicsecretcircle;3299
ideographicselfparen;3242
ideographicsocietyparen;3233
ideographicspace;3000
ideographicspecialparen;3235
ideographicstockparen;3231
ideographicstudyparen;323B
ideographicsunparen;3230
ideographicsuperviseparen;323C
ideographicwaterparen;322C
ideographicwoodparen;322D
ideographiczero;3007
ideographmetalcircle;328E
ideographmooncircle;328A
ideographnamecircle;3294
ideographsuncircle;3290
ideographwatercircle;328C
ideographwoodcircle;328D
ideva;0907
idieresis;00EF
idieresisacute;1E2F
idieresiscyrillic;04E5
idotbelow;1ECB
iebrevecyrillic;04D7
iecyrillic;0435
ieungacirclekorean;3275
ieungaparenkorean;3215
ieungcirclekorean;3267
ieungkorean;3147
ieungparenkorean;3207
igrave;00EC
igujarati;0A87
igurmukhi;0A07
ihiragana;3044
ihookabove;1EC9
iibengali;0988
iicyrillic;0438
iideva;0908
iigujarati;0A88
iigurmukhi;0A08
iimatragurmukhi;0A40
iinvertedbreve;020B
iishortcyrillic;0439
iivowelsignbengali;09C0
iivowelsigndeva;0940
iivowelsigngujarati;0AC0
ij;0133
ikatakana;30A4
ikatakanahalfwidth;FF72
ikorean;3163
ilde;02DC
iluyhebrew;05AC
imacron;012B
imacroncyrillic;04E3
imageorapproximatelyequal;2253
imatragurmukhi;0A3F
imonospace;FF49
increment;2206
infinity;221E
iniarmenian;056B
integral;222B
integralbottom;2321
integralbt;2321
integralex;F8F5
integraltop;2320
integraltp;2320
intersection;2229
intisquare;3305
invbullet;25D8
invcircle;25D9
invsmileface;263B
iocyrillic;0451
iogonek;012F
iota;03B9
iotadieresis;03CA
iotadieresistonos;0390
iotalatin;0269
iotatonos;03AF
iparen;24A4
irigurmukhi;0A72
ismallhiragana;3043
ismallkatakana;30A3
ismallkatakanahalfwidth;FF68
issharbengali;09FA
istroke;0268
isuperior;F6ED
iterationhiragana;309D
iterationkatakana;30FD
itilde;0129
itildebelow;1E2D
iubopomofo;3129
iucyrillic;044E
ivowelsignbengali;09BF
ivowelsigndeva;093F
ivowelsigngujarati;0ABF
izhitsacyrillic;0475
izhitsadblgravecyrillic;0477
j;006A
jaarmenian;0571
jabengali;099C
jadeva;091C
jagujarati;0A9C
jagurmukhi;0A1C
jbopomofo;3110
jcaron;01F0
jcircle;24D9
jcircumflex;0135
jcrossedtail;029D
jdotlessstroke;025F
jecyrillic;0458
jeemarabic;062C
jeemfinalarabic;FE9E
jeeminitialarabic;FE9F
jeemmedialarabic;FEA0
jeharabic;0698
jehfinalarabic;FB8B
jhabengali;099D
jhadeva;091D
jhagujarati;0A9D
jhagurmukhi;0A1D
jheharmenian;057B
jis;3004
jmonospace;FF4A
jparen;24A5
jsuperior;02B2
k;006B
kabashkircyrillic;04A1
kabengali;0995
kacute;1E31
kacyrillic;043A
kadescendercyrillic;049B
kadeva;0915
kaf;05DB
kafarabic;0643
kafdagesh;FB3B
kafdageshhebrew;FB3B
kaffinalarabic;FEDA
kafhebrew;05DB
kafinitialarabic;FEDB
kafmedialarabic;FEDC
kafrafehebrew;FB4D
kagujarati;0A95
kagurmukhi;0A15
kahiragana;304B
kahookcyrillic;04C4
kakatakana;30AB
kakatakanahalfwidth;FF76
kappa;03BA
kappasymbolgreek;03F0
kapyeounmieumkorean;3171
kapyeounphieuphkorean;3184
kapyeounpieupkorean;3178
kapyeounssangpieupkorean;3179
karoriisquare;330D
kashidaautoarabic;0640
kashidaautonosidebearingarabic;0640
kasmallkatakana;30F5
kasquare;3384
kasraarabic;0650
kasratanarabic;064D
kastrokecyrillic;049F
katahiraprolongmarkhalfwidth;FF70
kaverticalstrokecyrillic;049D
kbopomofo;310E
kcalsquare;3389
kcaron;01E9
kcedilla;0137
kcircle;24DA
kcommaaccent;0137
kdotbelow;1E33
keharmenian;0584
kehiragana;3051
kekatakana;30B1
kekatakanahalfwidth;FF79
kenarmenian;056F
kesmallkatakana;30F6
kgreenlandic;0138
khabengali;0996
khacyrillic;0445
khadeva;0916
khagujarati;0A96
khagurmukhi;0A16
khaharabic;062E
khahfinalarabic;FEA6
khahinitialarabic;FEA7
khahmedialarabic;FEA8
kheicoptic;03E7
khhadeva;0959
khhagurmukhi;0A59
khieukhacirclekorean;3278
khieukhaparenkorean;3218
khieukhcirclekorean;326A
khieukhkorean;314B
khieukhparenkorean;320A
khokhaithai;0E02
khokhonthai;0E05
khokhuatthai;0E03
khokhwaithai;0E04
khomutthai;0E5B
khook;0199
khorakhangthai;0E06
khzsquare;3391
kihiragana;304D
kikatakana;30AD
kikatakanahalfwidth;FF77
kiroguramusquare;3315
kiromeetorusquare;3316
kirosquare;3314
kiyeokacirclekorean;326E
kiyeokaparenkorean;320E
kiyeokcirclekorean;3260
kiyeokkorean;3131
kiyeokparenkorean;3200
kiyeoksioskorean;3133
kjecyrillic;045C
klinebelow;1E35
klsquare;3398
kmcubedsquare;33A6
kmonospace;FF4B
kmsquaredsquare;33A2
kohiragana;3053
kohmsquare;33C0
kokaithai;0E01
kokatakana;30B3
kokatakanahalfwidth;FF7A
kooposquare;331E
koppacyrillic;0481
koreanstandardsymbol;327F
koroniscmb;0343
kparen;24A6
kpasquare;33AA
ksicyrillic;046F
ktsquare;33CF
kturned;029E
kuhiragana;304F
kukatakana;30AF
kukatakanahalfwidth;FF78
kvsquare;33B8
kwsquare;33BE
l;006C
labengali;09B2
lacute;013A
ladeva;0932
lagujarati;0AB2
lagurmukhi;0A32
lakkhangyaothai;0E45
lamaleffinalarabic;FEFC
lamalefhamzaabovefinalarabic;FEF8
lamalefhamzaaboveisolatedarabic;FEF7
lamalefhamzabelowfinalarabic;FEFA
lamalefhamzabelowisolatedarabic;FEF9
lamalefisolatedarabic;FEFB
lamalefmaddaabovefinalarabic;FEF6
lamalefmaddaaboveisolatedarabic;FEF5
lamarabic;0644
lambda;03BB
lambdastroke;019B
lamed;05DC
lameddagesh;FB3C
lameddageshhebrew;FB3C
lamedhebrew;05DC
lamedholam;05DC 05B9
lamedholamdagesh;05DC 05B9 05BC
lamedholamdageshhebrew;05DC 05B9 05BC
lamedholamhebrew;05DC 05B9
lamfinalarabic;FEDE
lamhahinitialarabic;FCCA
laminitialarabic;FEDF
lamjeeminitialarabic;FCC9
lamkhahinitialarabic;FCCB
lamlamhehisolatedarabic;FDF2
lammedialarabic;FEE0
lammeemhahinitialarabic;FD88
lammeeminitialarabic;FCCC
lammeemjeeminitialarabic;FEDF FEE4 FEA0
lammeemkhahinitialarabic;FEDF FEE4 FEA8
largecircle;25EF
lbar;019A
lbelt;026C
lbopomofo;310C
lcaron;013E
lcedilla;013C
lcircle;24DB
lcircumflexbelow;1E3D
lcommaaccent;013C
ldot;0140
ldotaccent;0140
ldotbelow;1E37
ldotbelowmacron;1E39
leftangleabovecmb;031A
lefttackbelowcmb;0318
less;003C
lessequal;2264
lessequalorgreater;22DA
lessmonospace;FF1C
lessorequivalent;2272
lessorgreater;2276
lessoverequal;2266
lesssmall;FE64
lezh;026E
lfblock;258C
lhookretroflex;026D
lira;20A4
liwnarmenian;056C
lj;01C9
ljecyrillic;0459
ll;F6C0
lladeva;0933
llagujarati;0AB3
llinebelow;1E3B
llladeva;0934
llvocalicbengali;09E1
llvocalicdeva;0961
llvocalicvowelsignbengali;09E3
llvocalicvowelsigndeva;0963
lmiddletilde;026B
lmonospace;FF4C
lmsquare;33D0
lochulathai;0E2C
logicaland;2227
logicalnot;00AC
logicalnotreversed;2310
logicalor;2228
lolingthai;0E25
longs;017F
lowlinecenterline;FE4E
lowlinecmb;0332
lowlinedashed;FE4D
lozenge;25CA
lparen;24A7
lslash;0142
lsquare;2113
lsuperior;F6EE
ltshade;2591
luthai;0E26
lvocalicbengali;098C
lvocalicdeva;090C
lvocalicvowelsignbengali;09E2
lvocalicvowelsigndeva;0962
lxsquare;33D3
m;006D
mabengali;09AE
macron;00AF
macronbelowcmb;0331
macroncmb;0304
macronlowmod;02CD
macronmonospace;FFE3
macute;1E3F
madeva;092E
magujarati;0AAE
magurmukhi;0A2E
mahapakhhebrew;05A4
mahapakhlefthebrew;05A4
mahiragana;307E
maichattawalowleftthai;F895
maichattawalowrightthai;F894
maichattawathai;0E4B
maichattawaupperleftthai;F893
maieklowleftthai;F88C
maieklowrightthai;F88B
maiekthai;0E48
maiekupperleftthai;F88A
maihanakatleftthai;F884
maihanakatthai;0E31
maitaikhuleftthai;F889
maitaikhuthai;0E47
maitholowleftthai;F88F
maitholowrightthai;F88E
maithothai;0E49
maithoupperleftthai;F88D
maitrilowleftthai;F892
maitrilowrightthai;F891
maitrithai;0E4A
maitriupperleftthai;F890
maiyamokthai;0E46
makatakana;30DE
makatakanahalfwidth;FF8F
male;2642
mansyonsquare;3347
maqafhebrew;05BE
mars;2642
masoracirclehebrew;05AF
masquare;3383
mbopomofo;3107
mbsquare;33D4
mcircle;24DC
mcubedsquare;33A5
mdotaccent;1E41
mdotbelow;1E43
meemarabic;0645
meemfinalarabic;FEE2
meeminitialarabic;FEE3
meemmedialarabic;FEE4
meemmeeminitialarabic;FCD1
meemmeemisolatedarabic;FC48
meetorusquare;334D
mehiragana;3081
meizierasquare;337E
mekatakana;30E1
mekatakanahalfwidth;FF92
mem;05DE
memdagesh;FB3E
memdageshhebrew;FB3E
memhebrew;05DE
menarmenian;0574
merkhahebrew;05A5
merkhakefulahebrew;05A6
merkhakefulalefthebrew;05A6
merkhalefthebrew;05A5
mhook;0271
mhzsquare;3392
middledotkatakanahalfwidth;FF65
middot;00B7
mieumacirclekorean;3272
mieumaparenkorean;3212
mieumcirclekorean;3264
mieumkorean;3141
mieumpansioskorean;3170
mieumparenkorean;3204
mieumpieupkorean;316E
mieumsioskorean;316F
mihiragana;307F
mikatakana;30DF
mikatakanahalfwidth;FF90
minus;2212
minusbelowcmb;0320
minuscircle;2296
minusmod;02D7
minusplus;2213
minute;2032
miribaarusquare;334A
mirisquare;3349
mlonglegturned;0270
mlsquare;3396
mmcubedsquare;33A3
mmonospace;FF4D
mmsquaredsquare;339F
mohiragana;3082
mohmsquare;33C1
mokatakana;30E2
mokatakanahalfwidth;FF93
molsquare;33D6
momathai;0E21
moverssquare;33A7
moverssquaredsquare;33A8
mparen;24A8
mpasquare;33AB
mssquare;33B3
msuperior;F6EF
mturned;026F
mu;00B5
mu1;00B5
muasquare;3382
muchgreater;226B
muchless;226A
mufsquare;338C
mugreek;03BC
mugsquare;338D
muhiragana;3080
mukatakana;30E0
mukatakanahalfwidth;FF91
mulsquare;3395
multiply;00D7
mumsquare;339B
munahhebrew;05A3
munahlefthebrew;05A3
musicalnote;266A
musicalnotedbl;266B
musicflatsign;266D
musicsharpsign;266F
mussquare;33B2
muvsquare;33B6
muwsquare;33BC
mvmegasquare;33B9
mvsquare;33B7
mwmegasquare;33BF
mwsquare;33BD
n;006E
nabengali;09A8
nabla;2207
nacute;0144
nadeva;0928
nagujarati;0AA8
nagurmukhi;0A28
nahiragana;306A
nakatakana;30CA
nakatakanahalfwidth;FF85
napostrophe;0149
nasquare;3381
nbopomofo;310B
nbspace;00A0
ncaron;0148
ncedilla;0146
ncircle;24DD
ncircumflexbelow;1E4B
ncommaaccent;0146
ndotaccent;1E45
ndotbelow;1E47
nehiragana;306D
nekatakana;30CD
nekatakanahalfwidth;FF88
newsheqelsign;20AA
nfsquare;338B
ngabengali;0999
ngadeva;0919
ngagujarati;0A99
ngagurmukhi;0A19
ngonguthai;0E07
nhiragana;3093
nhookleft;0272
nhookretroflex;0273
nieunacirclekorean;326F
nieunaparenkorean;320F
nieuncieuckorean;3135
nieuncirclekorean;3261
nieunhieuhkorean;3136
nieunkorean;3134
nieunpansioskorean;3168
nieunparenkorean;3201
nieunsioskorean;3167
nieuntikeutkorean;3166
nihiragana;306B
nikatakana;30CB
nikatakanahalfwidth;FF86
nikhahitleftthai;F899
nikhahitthai;0E4D
nine;0039
ninearabic;0669
ninebengali;09EF
ninecircle;2468
ninecircleinversesansserif;2792
ninedeva;096F
ninegujarati;0AEF
ninegurmukhi;0A6F
ninehackarabic;0669
ninehangzhou;3029
nineideographicparen;3228
nineinferior;2089
ninemonospace;FF19
nineoldstyle;F739
nineparen;247C
nineperiod;2490
ninepersian;06F9
nineroman;2178
ninesuperior;2079
nineteencircle;2472
nineteenparen;2486
nineteenperiod;249A
ninethai;0E59
nj;01CC
njecyrillic;045A
nkatakana;30F3
nkatakanahalfwidth;FF9D
nlegrightlong;019E
nlinebelow;1E49
nmonospace;FF4E
nmsquare;339A
nnabengali;09A3
nnadeva;0923
nnagujarati;0AA3
nnagurmukhi;0A23
nnnadeva;0929
nohiragana;306E
nokatakana;30CE
nokatakanahalfwidth;FF89
nonbreakingspace;00A0
nonenthai;0E13
nonuthai;0E19
noonarabic;0646
noonfinalarabic;FEE6
noonghunnaarabic;06BA
noonghunnafinalarabic;FB9F
noonhehinitialarabic;FEE7 FEEC
nooninitialarabic;FEE7
noonjeeminitialarabic;FCD2
noonjeemisolatedarabic;FC4B
noonmedialarabic;FEE8
noonmeeminitialarabic;FCD5
noonmeemisolatedarabic;FC4E
noonnoonfinalarabic;FC8D
notcontains;220C
notelement;2209
notelementof;2209
notequal;2260
notgreater;226F
notgreaternorequal;2271
notgreaternorless;2279
notidentical;2262
notless;226E
notlessnorequal;2270
notparallel;2226
notprecedes;2280
notsubset;2284
notsucceeds;2281
notsuperset;2285
nowarmenian;0576
nparen;24A9
nssquare;33B1
nsuperior;207F
ntilde;00F1
nu;03BD
nuhiragana;306C
nukatakana;30CC
nukatakanahalfwidth;FF87
nuktabengali;09BC
nuktadeva;093C
nuktagujarati;0ABC
nuktagurmukhi;0A3C
numbersign;0023
numbersignmonospace;FF03
numbersignsmall;FE5F
numeralsigngreek;0374
numeralsignlowergreek;0375
numero;2116
nun;05E0
nundagesh;FB40
nundageshhebrew;FB40
nunhebrew;05E0
nvsquare;33B5
nwsquare;33BB
nyabengali;099E
nyadeva;091E
nyagujarati;0A9E
nyagurmukhi;0A1E
o;006F
oacute;00F3
oangthai;0E2D
obarred;0275
obarredcyrillic;04E9
obarreddieresiscyrillic;04EB
obengali;0993
obopomofo;311B
obreve;014F
ocandradeva;0911
ocandragujarati;0A91
ocandravowelsigndeva;0949
ocandravowelsigngujarati;0AC9
ocaron;01D2
ocircle;24DE
ocircumflex;00F4
ocircumflexacute;1ED1
ocircumflexdotbelow;1ED9
ocircumflexgrave;1ED3
ocircumflexhookabove;1ED5
ocircumflextilde;1ED7
ocyrillic;043E
odblacute;0151
odblgrave;020D
odeva;0913
odieresis;00F6
odieresiscyrillic;04E7
odotbelow;1ECD
oe;0153
oekorean;315A
ogonek;02DB
ogonekcmb;0328
ograve;00F2
ogujarati;0A93
oharmenian;0585
ohiragana;304A
ohookabove;1ECF
ohorn;01A1
ohornacute;1EDB
ohorndotbelow;1EE3
ohorngrave;1EDD
ohornhookabove;1EDF
ohorntilde;1EE1
ohungarumlaut;0151
oi;01A3
oinvertedbreve;020F
okatakana;30AA
okatakanahalfwidth;FF75
okorean;3157
olehebrew;05AB
omacron;014D
omacronacute;1E53
omacrongrave;1E51
omdeva;0950
omega;03C9
omega1;03D6
omegacyrillic;0461
omegalatinclosed;0277
omegaroundcyrillic;047B
omegatitlocyrillic;047D
omegatonos;03CE
omgujarati;0AD0
omicron;03BF
omicrontonos;03CC
omonospace;FF4F
one;0031
onearabic;0661
onebengali;09E7
onecircle;2460
onecircleinversesansserif;278A
onedeva;0967
onedotenleader;2024
oneeighth;215B
onefitted;F6DC
onegujarati;0AE7
onegurmukhi;0A67
onehackarabic;0661
onehalf;00BD
onehangzhou;3021
oneideographicparen;3220
oneinferior;2081
onemonospace;FF11
onenumeratorbengali;09F4
oneoldstyle;F731
oneparen;2474
oneperiod;2488
onepersian;06F1
onequarter;00BC
oneroman;2170
onesuperior;00B9
onethai;0E51
onethird;2153
oogonek;01EB
oogonekmacron;01ED
oogurmukhi;0A13
oomatragurmukhi;0A4B
oopen;0254
oparen;24AA
openbullet;25E6
option;2325
ordfeminine;00AA
ordmasculine;00BA
orthogonal;221F
oshortdeva;0912
oshortvowelsigndeva;094A
oslash;00F8
oslashacute;01FF
osmallhiragana;3049
osmallkatakana;30A9
osmallkatakanahalfwidth;FF6B
ostrokeacute;01FF
osuperior;F6F0
otcyrillic;047F
otilde;00F5
otildeacute;1E4D
otildedieresis;1E4F
oubopomofo;3121
overline;203E
overlinecenterline;FE4A
overlinecmb;0305
overlinedashed;FE49
overlinedblwavy;FE4C
overlinewavy;FE4B
overscore;00AF
ovowelsignbengali;09CB
ovowelsigndeva;094B
ovowelsigngujarati;0ACB
p;0070
paampssquare;3380
paasentosquare;332B
pabengali;09AA
pacute;1E55
padeva;092A
pagedown;21DF
pageup;21DE
pagujarati;0AAA
pagurmukhi;0A2A
pahiragana;3071
paiyannoithai;0E2F
pakatakana;30D1
palatalizationcyrilliccmb;0484
palochkacyrillic;04C0
pansioskorean;317F
paragraph;00B6
parallel;2225
parenleft;0028
parenleftaltonearabic;FD3E
parenleftbt;F8ED
parenleftex;F8EC
parenleftinferior;208D
parenleftmonospace;FF08
parenleftsmall;FE59
parenleftsuperior;207D
parenlefttp;F8EB
parenleftvertical;FE35
parenright;0029
parenrightaltonearabic;FD3F
parenrightbt;F8F8
parenrightex;F8F7
parenrightinferior;208E
parenrightmonospace;FF09
parenrightsmall;FE5A
parenrightsuperior;207E
parenrighttp;F8F6
parenrightvertical;FE36
partialdiff;2202
paseqhebrew;05C0
pashtahebrew;0599
pasquare;33A9
patah;05B7
patah11;05B7
patah1d;05B7
patah2a;05B7
patahhebrew;05B7
patahnarrowhebrew;05B7
patahquarterhebrew;05B7
patahwidehebrew;05B7
pazerhebrew;05A1
pbopomofo;3106
pcircle;24DF
pdotaccent;1E57
pe;05E4
pecyrillic;043F
pedagesh;FB44
pedageshhebrew;FB44
peezisquare;333B
pefinaldageshhebrew;FB43
peharabic;067E
peharmenian;057A
pehebrew;05E4
pehfinalarabic;FB57
pehinitialarabic;FB58
pehiragana;307A
pehmedialarabic;FB59
pekatakana;30DA
pemiddlehookcyrillic;04A7
perafehebrew;FB4E
percent;0025
percentarabic;066A
percentmonospace;FF05
percentsmall;FE6A
period;002E
periodarmenian;0589
periodcentered;00B7
periodhalfwidth;FF61
periodinferior;F6E7
periodmonospace;FF0E
periodsmall;FE52
periodsuperior;F6E8
perispomenigreekcmb;0342
perpendicular;22A5
perthousand;2030
peseta;20A7
pfsquare;338A
phabengali;09AB
phadeva;092B
phagujarati;0AAB
phagurmukhi;0A2B
phi;03C6
phi1;03D5
phieuphacirclekorean;327A
phieuphaparenkorean;321A
phieuphcirclekorean;326C
phieuphkorean;314D
phieuphparenkorean;320C
philatin;0278
phinthuthai;0E3A
phisymbolgreek;03D5
phook;01A5
phophanthai;0E1E
phophungthai;0E1C
phosamphaothai;0E20
pi;03C0
pieupacirclekorean;3273
pieupaparenkorean;3213
pieupcieuckorean;3176
pieupcirclekorean;3265
pieupkiyeokkorean;3172
pieupkorean;3142
pieupparenkorean;3205
pieupsioskiyeokkorean;3174
pieupsioskorean;3144
pieupsiostikeutkorean;3175
pieupthieuthkorean;3177
pieuptikeutkorean;3173
pihiragana;3074
pikatakana;30D4
pisymbolgreek;03D6
piwrarmenian;0583
plus;002B
plusbelowcmb;031F
pluscircle;2295
plusminus;00B1
plusmod;02D6
plusmonospace;FF0B
plussmall;FE62
plussuperior;207A
pmonospace;FF50
pmsquare;33D8
pohiragana;307D
pointingindexdownwhite;261F
pointingindexleftwhite;261C
pointingindexrightwhite;261E
pointingindexupwhite;261D
pokatakana;30DD
poplathai;0E1B
postalmark;3012
postalmarkface;3020
pparen;24AB
precedes;227A
prescription;211E
primemod;02B9
primereversed;2035
product;220F
projective;2305
prolongedkana;30FC
propellor;2318
propersubset;2282
propersuperset;2283
proportion;2237
proportional;221D
psi;03C8
psicyrillic;0471
psilipneumatacyrilliccmb;0486
pssquare;33B0
puhiragana;3077
pukatakana;30D7
pvsquare;33B4
pwsquare;33BA
q;0071
qadeva;0958
qadmahebrew;05A8
qafarabic;0642
qaffinalarabic;FED6
qafinitialarabic;FED7
qafmedialarabic;FED8
qamats;05B8
qamats10;05B8
qamats1a;05B8
qamats1c;05B8
qamats27;05B8
qamats29;05B8
qamats33;05B8
qamatsde;05B8
qamatshebrew;05B8
qamatsnarrowhebrew;05B8
qamatsqatanhebrew;05B8
qamatsqatannarrowhebrew;05B8
qamatsqatanquarterhebrew;05B8
qamatsqatanwidehebrew;05B8
qamatsquarterhebrew;05B8
qamatswidehebrew;05B8
qarneyparahebrew;059F
qbopomofo;3111
qcircle;24E0
qhook;02A0
qmonospace;FF51
qof;05E7
qofdagesh;FB47
qofdageshhebrew;FB47
qofhatafpatah;05E7 05B2
qofhatafpatahhebrew;05E7 05B2
qofhatafsegol;05E7 05B1
qofhatafsegolhebrew;05E7 05B1
qofhebrew;05E7
qofhiriq;05E7 05B4
qofhiriqhebrew;05E7 05B4
qofholam;05E7 05B9
qofholamhebrew;05E7 05B9
qofpatah;05E7 05B7
qofpatahhebrew;05E7 05B7
qofqamats;05E7 05B8
qofqamatshebrew;05E7 05B8
qofqubuts;05E7 05BB
qofqubutshebrew;05E7 05BB
qofsegol;05E7 05B6
qofsegolhebrew;05E7 05B6
qofsheva;05E7 05B0
qofshevahebrew;05E7 05B0
qoftsere;05E7 05B5
qoftserehebrew;05E7 05B5
qparen;24AC
quarternote;2669
qubuts;05BB
qubuts18;05BB
qubuts25;05BB
qubuts31;05BB
qubutshebrew;05BB
qubutsnarrowhebrew;05BB
qubutsquarterhebrew;05BB
qubutswidehebrew;05BB
question;003F
questionarabic;061F
questionarmenian;055E
questiondown;00BF
questiondownsmall;F7BF
questiongreek;037E
questionmonospace;FF1F
questionsmall;F73F
quotedbl;0022
quotedblbase;201E
quotedblleft;201C
quotedblmonospace;FF02
quotedblprime;301E
quotedblprimereversed;301D
quotedblright;201D
quoteleft;2018
quoteleftreversed;201B
quotereversed;201B
quoteright;2019
quoterightn;0149
quotesinglbase;201A
quotesingle;0027
quotesinglemonospace;FF07
r;0072
raarmenian;057C
rabengali;09B0
racute;0155
radeva;0930
radical;221A
radicalex;F8E5
radoverssquare;33AE
radoverssquaredsquare;33AF
radsquare;33AD
rafe;05BF
rafehebrew;05BF
ragujarati;0AB0
ragurmukhi;0A30
rahiragana;3089
rakatakana;30E9
rakatakanahalfwidth;FF97
ralowerdiagonalbengali;09F1
ramiddlediagonalbengali;09F0
ramshorn;0264
ratio;2236
rbopomofo;3116
rcaron;0159
rcedilla;0157
rcircle;24E1
rcommaaccent;0157
rdblgrave;0211
rdotaccent;1E59
rdotbelow;1E5B
rdotbelowmacron;1E5D
referencemark;203B
reflexsubset;2286
reflexsuperset;2287
registered;00AE
registersans;F8E8
registerserif;F6DA
reharabic;0631
reharmenian;0580
rehfinalarabic;FEAE
rehiragana;308C
rehyehaleflamarabic;0631 FEF3 FE8E 0644
rekatakana;30EC
rekatakanahalfwidth;FF9A
resh;05E8
reshdageshhebrew;FB48
reshhatafpatah;05E8 05B2
reshhatafpatahhebrew;05E8 05B2
reshhatafsegol;05E8 05B1
reshhatafsegolhebrew;05E8 05B1
reshhebrew;05E8
reshhiriq;05E8 05B4
reshhiriqhebrew;05E8 05B4
reshholam;05E8 05B9
reshholamhebrew;05E8 05B9
reshpatah;05E8 05B7
reshpatahhebrew;05E8 05B7
reshqamats;05E8 05B8
reshqamatshebrew;05E8 05B8
reshqubuts;05E8 05BB
reshqubutshebrew;05E8 05BB
reshsegol;05E8 05B6
reshsegolhebrew;05E8 05B6
reshsheva;05E8 05B0
reshshevahebrew;05E8 05B0
reshtsere;05E8 05B5
reshtserehebrew;05E8 05B5
reversedtilde;223D
reviahebrew;0597
reviamugrashhebrew;0597
revlogicalnot;2310
rfishhook;027E
rfishhookreversed;027F
rhabengali;09DD
rhadeva;095D
rho;03C1
rhook;027D
rhookturned;027B
rhookturnedsuperior;02B5
rhosymbolgreek;03F1
rhotichookmod;02DE
rieulacirclekorean;3271
rieulaparenkorean;3211
rieulcirclekorean;3263
rieulhieuhkorean;3140
rieulkiyeokkorean;313A
rieulkiyeoksioskorean;3169
rieulkorean;3139
rieulmieumkorean;313B
rieulpansioskorean;316C
rieulparenkorean;3203
rieulphieuphkorean;313F
rieulpieupkorean;313C
rieulpieupsioskorean;316B
rieulsioskorean;313D
rieulthieuthkorean;313E
rieultikeutkorean;316A
rieulyeorinhieuhkorean;316D
rightangle;221F
righttackbelowcmb;0319
righttriangle;22BF
rihiragana;308A
rikatakana;30EA
rikatakanahalfwidth;FF98
ring;02DA
ringbelowcmb;0325
ringcmb;030A
ringhalfleft;02BF
ringhalfleftarmenian;0559
ringhalfleftbelowcmb;031C
ringhalfleftcentered;02D3
ringhalfright;02BE
ringhalfrightbelowcmb;0339
ringhalfrightcentered;02D2
rinvertedbreve;0213
rittorusquare;3351
rlinebelow;1E5F
rlongleg;027C
rlonglegturned;027A
rmonospace;FF52
rohiragana;308D
rokatakana;30ED
rokatakanahalfwidth;FF9B
roruathai;0E23
rparen;24AD
rrabengali;09DC
rradeva;0931
rragurmukhi;0A5C
rreharabic;0691
rrehfinalarabic;FB8D
rrvocalicbengali;09E0
rrvocalicdeva;0960
rrvocalicgujarati;0AE0
rrvocalicvowelsignbengali;09C4
rrvocalicvowelsigndeva;0944
rrvocalicvowelsigngujarati;0AC4
rsuperior;F6F1
rtblock;2590
rturned;0279
rturnedsuperior;02B4
ruhiragana;308B
rukatakana;30EB
rukatakanahalfwidth;FF99
rupeemarkbengali;09F2
rupeesignbengali;09F3
rupiah;F6DD
ruthai;0E24
rvocalicbengali;098B
rvocalicdeva;090B
rvocalicgujarati;0A8B
rvocalicvowelsignbengali;09C3
rvocalicvowelsigndeva;0943
rvocalicvowelsigngujarati;0AC3
s;0073
sabengali;09B8
sacute;015B
sacutedotaccent;1E65
sadarabic;0635
sadeva;0938
sadfinalarabic;FEBA
sadinitialarabic;FEBB
sadmedialarabic;FEBC
sagujarati;0AB8
sagurmukhi;0A38
sahiragana;3055
sakatakana;30B5
sakatakanahalfwidth;FF7B
sallallahoualayhewasallamarabic;FDFA
samekh;05E1
samekhdagesh;FB41
samekhdageshhebrew;FB41
samekhhebrew;05E1
saraaathai;0E32
saraaethai;0E41
saraaimaimalaithai;0E44
saraaimaimuanthai;0E43
saraamthai;0E33
saraathai;0E30
saraethai;0E40
saraiileftthai;F886
saraiithai;0E35
saraileftthai;F885
saraithai;0E34
saraothai;0E42
saraueeleftthai;F888
saraueethai;0E37
saraueleftthai;F887
sarauethai;0E36
sarauthai;0E38
sarauuthai;0E39
sbopomofo;3119
scaron;0161
scarondotaccent;1E67
scedilla;015F
schwa;0259
schwacyrillic;04D9
schwadieresiscyrillic;04DB
schwahook;025A
scircle;24E2
scircumflex;015D
scommaaccent;0219
sdotaccent;1E61
sdotbelow;1E63
sdotbelowdotaccent;1E69
seagullbelowcmb;033C
second;2033
secondtonechinese;02CA
section;00A7
seenarabic;0633
seenfinalarabic;FEB2
seeninitialarabic;FEB3
seenmedialarabic;FEB4
segol;05B6
segol13;05B6
segol1f;05B6
segol2c;05B6
segolhebrew;05B6
segolnarrowhebrew;05B6
segolquarterhebrew;05B6
segoltahebrew;0592
segolwidehebrew;05B6
seharmenian;057D
sehiragana;305B
sekatakana;30BB
sekatakanahalfwidth;FF7E
semicolon;003B
semicolonarabic;061B
semicolonmonospace;FF1B
semicolonsmall;FE54
semivoicedmarkkana;309C
semivoicedmarkkanahalfwidth;FF9F
sentisquare;3322
sentosquare;3323
seven;0037
sevenarabic;0667
sevenbengali;09ED
sevencircle;2466
sevencircleinversesansserif;2790
sevendeva;096D
seveneighths;215E
sevengujarati;0AED
sevengurmukhi;0A6D
sevenhackarabic;0667
sevenhangzhou;3027
sevenideographicparen;3226
seveninferior;2087
sevenmonospace;FF17
sevenoldstyle;F737
sevenparen;247A
sevenperiod;248E
sevenpersian;06F7
sevenroman;2176
sevensuperior;2077
seventeencircle;2470
seventeenparen;2484
seventeenperiod;2498
seventhai;0E57
sfthyphen;00AD
shaarmenian;0577
shabengali;09B6
shacyrillic;0448
shaddaarabic;0651
shaddadammaarabic;FC61
shaddadammatanarabic;FC5E
shaddafathaarabic;FC60
shaddafathatanarabic;0651 064B
shaddakasraarabic;FC62
shaddakasratanarabic;FC5F
shade;2592
shadedark;2593
shadelight;2591
shademedium;2592
shadeva;0936
shagujarati;0AB6
shagurmukhi;0A36
shalshelethebrew;0593
shbopomofo;3115
shchacyrillic;0449
sheenarabic;0634
sheenfinalarabic;FEB6
sheeninitialarabic;FEB7
sheenmedialarabic;FEB8
sheicoptic;03E3
sheqel;20AA
sheqelhebrew;20AA
sheva;05B0
sheva115;05B0
sheva15;05B0
sheva22;05B0
sheva2e;05B0
shevahebrew;05B0
shevanarrowhebrew;05B0
shevaquarterhebrew;05B0
shevawidehebrew;05B0
shhacyrillic;04BB
shimacoptic;03ED
shin;05E9
shindagesh;FB49
shindageshhebrew;FB49
shindageshshindot;FB2C
shindageshshindothebrew;FB2C
shindageshsindot;FB2D
shindageshsindothebrew;FB2D
shindothebrew;05C1
shinhebrew;05E9
shinshindot;FB2A
shinshindothebrew;FB2A
shinsindot;FB2B
shinsindothebrew;FB2B
shook;0282
sigma;03C3
sigma1;03C2
sigmafinal;03C2
sigmalunatesymbolgreek;03F2
sihiragana;3057
sikatakana;30B7
sikatakanahalfwidth;FF7C
siluqhebrew;05BD
siluqlefthebrew;05BD
similar;223C
sindothebrew;05C2
siosacirclekorean;3274
siosaparenkorean;3214
sioscieuckorean;317E
sioscirclekorean;3266
sioskiyeokkorean;317A
sioskorean;3145
siosnieunkorean;317B
siosparenkorean;3206
siospieupkorean;317D
siostikeutkorean;317C
six;0036
sixarabic;0666
sixbengali;09EC
sixcircle;2465
sixcircleinversesansserif;278F
sixdeva;096C
sixgujarati;0AEC
sixgurmukhi;0A6C
sixhackarabic;0666
sixhangzhou;3026
sixideographicparen;3225
sixinferior;2086
sixmonospace;FF16
sixoldstyle;F736
sixparen;2479
sixperiod;248D
sixpersian;06F6
sixroman;2175
sixsuperior;2076
sixteencircle;246F
sixteencurrencydenominatorbengali;09F9
sixteenparen;2483
sixteenperiod;2497
sixthai;0E56
slash;002F
slashmonospace;FF0F
slong;017F
slongdotaccent;1E9B
smileface;263A
smonospace;FF53
sofpasuqhebrew;05C3
softhyphen;00AD
softsigncyrillic;044C
sohiragana;305D
sokatakana;30BD
sokatakanahalfwidth;FF7F
soliduslongoverlaycmb;0338
solidusshortoverlaycmb;0337
sorusithai;0E29
sosalathai;0E28
sosothai;0E0B
sosuathai;0E2A
space;0020
spacehackarabic;0020
spade;2660
spadesuitblack;2660
spadesuitwhite;2664
sparen;24AE
squarebelowcmb;033B
squarecc;33C4
squarecm;339D
squarediagonalcrosshatchfill;25A9
squarehorizontalfill;25A4
squarekg;338F
squarekm;339E
squarekmcapital;33CE
squareln;33D1
squarelog;33D2
squaremg;338E
squaremil;33D5
squaremm;339C
squaremsquared;33A1
squareorthogonalcrosshatchfill;25A6
squareupperlefttolowerrightfill;25A7
squareupperrighttolowerleftfill;25A8
squareverticalfill;25A5
squarewhitewithsmallblack;25A3
srsquare;33DB
ssabengali;09B7
ssadeva;0937
ssagujarati;0AB7
ssangcieuckorean;3149
ssanghieuhkorean;3185
ssangieungkorean;3180
ssangkiyeokkorean;3132
ssangnieunkorean;3165
ssangpieupkorean;3143
ssangsioskorean;3146
ssangtikeutkorean;3138
ssuperior;F6F2
sterling;00A3
sterlingmonospace;FFE1
strokelongoverlaycmb;0336
strokeshortoverlaycmb;0335
subset;2282
subsetnotequal;228A
subsetorequal;2286
succeeds;227B
suchthat;220B
suhiragana;3059
sukatakana;30B9
sukatakanahalfwidth;FF7D
sukunarabic;0652
summation;2211
sun;263C
superset;2283
supersetnotequal;228B
supersetorequal;2287
svsquare;33DC
syouwaerasquare;337C
t;0074
tabengali;09A4
tackdown;22A4
tackleft;22A3
tadeva;0924
tagujarati;0AA4
tagurmukhi;0A24
taharabic;0637
tahfinalarabic;FEC2
tahinitialarabic;FEC3
tahiragana;305F
tahmedialarabic;FEC4
taisyouerasquare;337D
takatakana;30BF
takatakanahalfwidth;FF80
tatweelarabic;0640
tau;03C4
tav;05EA
tavdages;FB4A
tavdagesh;FB4A
tavdageshhebrew;FB4A
tavhebrew;05EA
tbar;0167
tbopomofo;310A
tcaron;0165
tccurl;02A8
tcedilla;0163
tcheharabic;0686
tchehfinalarabic;FB7B
tchehinitialarabic;FB7C
tchehmedialarabic;FB7D
tchehmeeminitialarabic;FB7C FEE4
tcircle;24E3
tcircumflexbelow;1E71
tcommaaccent;0163
tdieresis;1E97
tdotaccent;1E6B
tdotbelow;1E6D
tecyrillic;0442
tedescendercyrillic;04AD
teharabic;062A
tehfinalarabic;FE96
tehhahinitialarabic;FCA2
tehhahisolatedarabic;FC0C
tehinitialarabic;FE97
tehiragana;3066
tehjeeminitialarabic;FCA1
tehjeemisolatedarabic;FC0B
tehmarbutaarabic;0629
tehmarbutafinalarabic;FE94
tehmedialarabic;FE98
tehmeeminitialarabic;FCA4
tehmeemisolatedarabic;FC0E
tehnoonfinalarabic;FC73
tekatakana;30C6
tekatakanahalfwidth;FF83
telephone;2121
telephoneblack;260E
telishagedolahebrew;05A0
telishaqetanahebrew;05A9
tencircle;2469
tenideographicparen;3229
tenparen;247D
tenperiod;2491
tenroman;2179
tesh;02A7
tet;05D8
tetdagesh;FB38
tetdageshhebrew;FB38
tethebrew;05D8
tetsecyrillic;04B5
tevirhebrew;059B
tevirlefthebrew;059B
thabengali;09A5
thadeva;0925
thagujarati;0AA5
thagurmukhi;0A25
thalarabic;0630
thalfinalarabic;FEAC
thanthakhatlowleftthai;F898
thanthakhatlowrightthai;F897
thanthakhatthai;0E4C
thanthakhatupperleftthai;F896
theharabic;062B
thehfinalarabic;FE9A
thehinitialarabic;FE9B
thehmedialarabic;FE9C
thereexists;2203
therefore;2234
theta;03B8
theta1;03D1
thetasymbolgreek;03D1
thieuthacirclekorean;3279
thieuthaparenkorean;3219
thieuthcirclekorean;326B
thieuthkorean;314C
thieuthparenkorean;320B
thirteencircle;246C
thirteenparen;2480
thirteenperiod;2494
thonangmonthothai;0E11
thook;01AD
thophuthaothai;0E12
thorn;00FE
thothahanthai;0E17
thothanthai;0E10
thothongthai;0E18
thothungthai;0E16
thousandcyrillic;0482
thousandsseparatorarabic;066C
thousandsseparatorpersian;066C
three;0033
threearabic;0663
threebengali;09E9
threecircle;2462
threecircleinversesansserif;278C
threedeva;0969
threeeighths;215C
threegujarati;0AE9
threegurmukhi;0A69
threehackarabic;0663
threehangzhou;3023
threeideographicparen;3222
threeinferior;2083
threemonospace;FF13
threenumeratorbengali;09F6
threeoldstyle;F733
threeparen;2476
threeperiod;248A
threepersian;06F3
threequarters;00BE
threequartersemdash;F6DE
threeroman;2172
threesuperior;00B3
threethai;0E53
thzsquare;3394
tihiragana;3061
tikatakana;30C1
tikatakanahalfwidth;FF81
tikeutacirclekorean;3270
tikeutaparenkorean;3210
tikeutcirclekorean;3262
tikeutkorean;3137
tikeutparenkorean;3202
tilde;02DC
tildebelowcmb;0330
tildecmb;0303
tildecomb;0303
tildedoublecmb;0360
tildeoperator;223C
tildeoverlaycmb;0334
tildeverticalcmb;033E
timescircle;2297
tipehahebrew;0596
tipehalefthebrew;0596
tippigurmukhi;0A70
titlocyrilliccmb;0483
tiwnarmenian;057F
tlinebelow;1E6F
tmonospace;FF54
toarmenian;0569
tohiragana;3068
tokatakana;30C8
tokatakanahalfwidth;FF84
tonebarextrahighmod;02E5
tonebarextralowmod;02E9
tonebarhighmod;02E6
tonebarlowmod;02E8
tonebarmidmod;02E7
tonefive;01BD
tonesix;0185
tonetwo;01A8
tonos;0384
tonsquare;3327
topatakthai;0E0F
tortoiseshellbracketleft;3014
tortoiseshellbracketleftsmall;FE5D
tortoiseshellbracketleftvertical;FE39
tortoiseshellbracketright;3015
tortoiseshellbracketrightsmall;FE5E
tortoiseshellbracketrightvertical;FE3A
totaothai;0E15
tpalatalhook;01AB
tparen;24AF
trademark;2122
trademarksans;F8EA
trademarkserif;F6DB
tretroflexhook;0288
triagdn;25BC
triaglf;25C4
triagrt;25BA
triagup;25B2
ts;02A6
tsadi;05E6
tsadidagesh;FB46
tsadidageshhebrew;FB46
tsadihebrew;05E6
tsecyrillic;0446
tsere;05B5
tsere12;05B5
tsere1e;05B5
tsere2b;05B5
tserehebrew;05B5
tserenarrowhebrew;05B5
tserequarterhebrew;05B5
tserewidehebrew;05B5
tshecyrillic;045B
tsuperior;F6F3
ttabengali;099F
ttadeva;091F
ttagujarati;0A9F
ttagurmukhi;0A1F
tteharabic;0679
ttehfinalarabic;FB67
ttehinitialarabic;FB68
ttehmedialarabic;FB69
tthabengali;09A0
tthadeva;0920
tthagujarati;0AA0
tthagurmukhi;0A20
tturned;0287
tuhiragana;3064
tukatakana;30C4
tukatakanahalfwidth;FF82
tusmallhiragana;3063
tusmallkatakana;30C3
tusmallkatakanahalfwidth;FF6F
twelvecircle;246B
twelveparen;247F
twelveperiod;2493
twelveroman;217B
twentycircle;2473
twentyhangzhou;5344
twentyparen;2487
twentyperiod;249B
two;0032
twoarabic;0662
twobengali;09E8
twocircle;2461
twocircleinversesansserif;278B
twodeva;0968
twodotenleader;2025
twodotleader;2025
twodotleadervertical;FE30
twogujarati;0AE8
twogurmukhi;0A68
twohackarabic;0662
twohangzhou;3022
twoideographicparen;3221
twoinferior;2082
twomonospace;FF12
twonumeratorbengali;09F5
twooldstyle;F732
twoparen;2475
twoperiod;2489
twopersian;06F2
tworoman;2171
twostroke;01BB
twosuperior;00B2
twothai;0E52
twothirds;2154
u;0075
uacute;00FA
ubar;0289
ubengali;0989
ubopomofo;3128
ubreve;016D
ucaron;01D4
ucircle;24E4
ucircumflex;00FB
ucircumflexbelow;1E77
ucyrillic;0443
udattadeva;0951
udblacute;0171
udblgrave;0215
udeva;0909
udieresis;00FC
udieresisacute;01D8
udieresisbelow;1E73
udieresiscaron;01DA
udieresiscyrillic;04F1
udieresisgrave;01DC
udieresismacron;01D6
udotbelow;1EE5
ugrave;00F9
ugujarati;0A89
ugurmukhi;0A09
uhiragana;3046
uhookabove;1EE7
uhorn;01B0
uhornacute;1EE9
uhorndotbelow;1EF1
uhorngrave;1EEB
uhornhookabove;1EED
uhorntilde;1EEF
uhungarumlaut;0171
uhungarumlautcyrillic;04F3
uinvertedbreve;0217
ukatakana;30A6
ukatakanahalfwidth;FF73
ukcyrillic;0479
ukorean;315C
umacron;016B
umacroncyrillic;04EF
umacrondieresis;1E7B
umatragurmukhi;0A41
umonospace;FF55
underscore;005F
underscoredbl;2017
underscoremonospace;FF3F
underscorevertical;FE33
underscorewavy;FE4F
union;222A
universal;2200
uogonek;0173
uparen;24B0
upblock;2580
upperdothebrew;05C4
upsilon;03C5
upsilondieresis;03CB
upsilondieresistonos;03B0
upsilonlatin;028A
upsilontonos;03CD
uptackbelowcmb;031D
uptackmod;02D4
uragurmukhi;0A73
uring;016F
ushortcyrillic;045E
usmallhiragana;3045
usmallkatakana;30A5
usmallkatakanahalfwidth;FF69
ustraightcyrillic;04AF
ustraightstrokecyrillic;04B1
utilde;0169
utildeacute;1E79
utildebelow;1E75
uubengali;098A
uudeva;090A
uugujarati;0A8A
uugurmukhi;0A0A
uumatragurmukhi;0A42
uuvowelsignbengali;09C2
uuvowelsigndeva;0942
uuvowelsigngujarati;0AC2
uvowelsignbengali;09C1
uvowelsigndeva;0941
uvowelsigngujarati;0AC1
v;0076
vadeva;0935
vagujarati;0AB5
vagurmukhi;0A35
vakatakana;30F7
vav;05D5
vavdagesh;FB35
vavdagesh65;FB35
vavdageshhebrew;FB35
vavhebrew;05D5
vavholam;FB4B
vavholamhebrew;FB4B
vavvavhebrew;05F0
vavyodhebrew;05F1
vcircle;24E5
vdotbelow;1E7F
vecyrillic;0432
veharabic;06A4
vehfinalarabic;FB6B
vehinitialarabic;FB6C
vehmedialarabic;FB6D
vekatakana;30F9
venus;2640
verticalbar;007C
verticallineabovecmb;030D
verticallinebelowcmb;0329
verticallinelowmod;02CC
verticallinemod;02C8
vewarmenian;057E
vhook;028B
vikatakana;30F8
viramabengali;09CD
viramadeva;094D
viramagujarati;0ACD
visargabengali;0983
visargadeva;0903
visargagujarati;0A83
vmonospace;FF56
voarmenian;0578
voicediterationhiragana;309E
voicediterationkatakana;30FE
voicedmarkkana;309B
voicedmarkkanahalfwidth;FF9E
vokatakana;30FA
vparen;24B1
vtilde;1E7D
vturned;028C
vuhiragana;3094
vukatakana;30F4
w;0077
wacute;1E83
waekorean;3159
wahiragana;308F
wakatakana;30EF
wakatakanahalfwidth;FF9C
wakorean;3158
wasmallhiragana;308E
wasmallkatakana;30EE
wattosquare;3357
wavedash;301C
wavyunderscorevertical;FE34
wawarabic;0648
wawfinalarabic;FEEE
wawhamzaabovearabic;0624
wawhamzaabovefinalarabic;FE86
wbsquare;33DD
wcircle;24E6
wcircumflex;0175
wdieresis;1E85
wdotaccent;1E87
wdotbelow;1E89
wehiragana;3091
weierstrass;2118
wekatakana;30F1
wekorean;315E
weokorean;315D
wgrave;1E81
whitebullet;25E6
whitecircle;25CB
whitecircleinverse;25D9
whitecornerbracketleft;300E
whitecornerbracketleftvertical;FE43
whitecornerbracketright;300F
whitecornerbracketrightvertical;FE44
whitediamond;25C7
whitediamondcontainingblacksmalldiamond;25C8
whitedownpointingsmalltriangle;25BF
whitedownpointingtriangle;25BD
whiteleftpointingsmalltriangle;25C3
whiteleftpointingtriangle;25C1
whitelenticularbracketleft;3016
whitelenticularbracketright;3017
whiterightpointingsmalltriangle;25B9
whiterightpointingtriangle;25B7
whitesmallsquare;25AB
whitesmilingface;263A
whitesquare;25A1
whitestar;2606
whitetelephone;260F
whitetortoiseshellbracketleft;3018
whitetortoiseshellbracketright;3019
whiteuppointingsmalltriangle;25B5
whiteuppointingtriangle;25B3
wihiragana;3090
wikatakana;30F0
wikorean;315F
wmonospace;FF57
wohiragana;3092
wokatakana;30F2
wokatakanahalfwidth;FF66
won;20A9
wonmonospace;FFE6
wowaenthai;0E27
wparen;24B2
wring;1E98
wsuperior;02B7
wturned;028D
wynn;01BF
x;0078
xabovecmb;033D
xbopomofo;3112
xcircle;24E7
xdieresis;1E8D
xdotaccent;1E8B
xeharmenian;056D
xi;03BE
xmonospace;FF58
xparen;24B3
xsuperior;02E3
y;0079
yaadosquare;334E
yabengali;09AF
yacute;00FD
yadeva;092F
yaekorean;3152
yagujarati;0AAF
yagurmukhi;0A2F
yahiragana;3084
yakatakana;30E4
yakatakanahalfwidth;FF94
yakorean;3151
yamakkanthai;0E4E
yasmallhiragana;3083
yasmallkatakana;30E3
yasmallkatakanahalfwidth;FF6C
yatcyrillic;0463
ycircle;24E8
ycircumflex;0177
ydieresis;00FF
ydotaccent;1E8F
ydotbelow;1EF5
yeharabic;064A
yehbarreearabic;06D2
yehbarreefinalarabic;FBAF
yehfinalarabic;FEF2
yehhamzaabovearabic;0626
yehhamzaabovefinalarabic;FE8A
yehhamzaaboveinitialarabic;FE8B
yehhamzaabovemedialarabic;FE8C
yehinitialarabic;FEF3
yehmedialarabic;FEF4
yehmeeminitialarabic;FCDD
yehmeemisolatedarabic;FC58
yehnoonfinalarabic;FC94
yehthreedotsbelowarabic;06D1
yekorean;3156
yen;00A5
yenmonospace;FFE5
yeokorean;3155
yeorinhieuhkorean;3186
yerahbenyomohebrew;05AA
yerahbenyomolefthebrew;05AA
yericyrillic;044B
yerudieresiscyrillic;04F9
yesieungkorean;3181
yesieungpansioskorean;3183
yesieungsioskorean;3182
yetivhebrew;059A
ygrave;1EF3
yhook;01B4
yhookabove;1EF7
yiarmenian;0575
yicyrillic;0457
yikorean;3162
yinyang;262F
yiwnarmenian;0582
ymonospace;FF59
yod;05D9
yoddagesh;FB39
yoddageshhebrew;FB39
yodhebrew;05D9
yodyodhebrew;05F2
yodyodpatahhebrew;FB1F
yohiragana;3088
yoikorean;3189
yokatakana;30E8
yokatakanahalfwidth;FF96
yokorean;315B
yosmallhiragana;3087
yosmallkatakana;30E7
yosmallkatakanahalfwidth;FF6E
yotgreek;03F3
yoyaekorean;3188
yoyakorean;3187
yoyakthai;0E22
yoyingthai;0E0D
yparen;24B4
ypogegrammeni;037A
ypogegrammenigreekcmb;0345
yr;01A6
yring;1E99
ysuperior;02B8
ytilde;1EF9
yturned;028E
yuhiragana;3086
yuikorean;318C
yukatakana;30E6
yukatakanahalfwidth;FF95
yukorean;3160
yusbigcyrillic;046B
yusbigiotifiedcyrillic;046D
yuslittlecyrillic;0467
yuslittleiotifiedcyrillic;0469
yusmallhiragana;3085
yusmallkatakana;30E5
yusmallkatakanahalfwidth;FF6D
yuyekorean;318B
yuyeokorean;318A
yyabengali;09DF
yyadeva;095F
z;007A
zaarmenian;0566
zacute;017A
zadeva;095B
zagurmukhi;0A5B
zaharabic;0638
zahfinalarabic;FEC6
zahinitialarabic;FEC7
zahiragana;3056
zahmedialarabic;FEC8
zainarabic;0632
zainfinalarabic;FEB0
zakatakana;30B6
zaqefgadolhebrew;0595
zaqefqatanhebrew;0594
zarqahebrew;0598
zayin;05D6
zayindagesh;FB36
zayindageshhebrew;FB36
zayinhebrew;05D6
zbopomofo;3117
zcaron;017E
zcircle;24E9
zcircumflex;1E91
zcurl;0291
zdot;017C
zdotaccent;017C
zdotbelow;1E93
zecyrillic;0437
zedescendercyrillic;0499
zedieresiscyrillic;04DF
zehiragana;305C
zekatakana;30BC
zero;0030
zeroarabic;0660
zerobengali;09E6
zerodeva;0966
zerogujarati;0AE6
zerogurmukhi;0A66
zerohackarabic;0660
zeroinferior;2080
zeromonospace;FF10
zerooldstyle;F730
zeropersian;06F0
zerosuperior;2070
zerothai;0E50
zerowidthjoiner;FEFF
zerowidthnonjoiner;200C
zerowidthspace;200B
zeta;03B6
zhbopomofo;3113
zhearmenian;056A
zhebrevecyrillic;04C2
zhecyrillic;0436
zhedescendercyrillic;0497
zhedieresiscyrillic;04DD
zihiragana;3058
zikatakana;30B8
zinorhebrew;05AE
zlinebelow;1E95
zmonospace;FF5A
zohiragana;305E
zokatakana;30BE
zparen;24B5
zretroflexhook;0290
zstroke;01B6
zuhiragana;305A
zukatakana;30BA
"""
# string table management
#
class StringTable:
def __init__( self, name_list, master_table_name ):
self.names = name_list
self.master_table = master_table_name
self.indices = {}
index = 0
for name in name_list:
self.indices[name] = index
index += len( name ) + 1
self.total = index
def dump( self, file ):
write = file.write
write( " static const char " + self.master_table +
"[" + repr( self.total ) + "] =\n" )
write( " {\n" )
line = ""
for name in self.names:
line += " '"
line += string.join( ( re.findall( ".", name ) ), "','" )
line += "', 0,\n"
write( line + " };\n\n\n" )
def dump_sublist( self, file, table_name, macro_name, sublist ):
write = file.write
write( "#define " + macro_name + " " + repr( len( sublist ) ) + "\n\n" )
write( " /* Values are offsets into the `" +
self.master_table + "' table */\n\n" )
write( " static const short " + table_name +
"[" + macro_name + "] =\n" )
write( " {\n" )
line = " "
comma = ""
col = 0
for name in sublist:
line += comma
line += "%4d" % self.indices[name]
col += 1
comma = ","
if col == 14:
col = 0
comma = ",\n "
write( line + "\n };\n\n\n" )
# We now store the Adobe Glyph List in compressed form. The list is put
# into a data structure called `trie' (because it has a tree-like
# appearance). Consider, for example, that you want to store the
# following name mapping:
#
# A => 1
# Aacute => 6
# Abalon => 2
# Abstract => 4
#
# It is possible to store the entries as follows.
#
# A => 1
# |
# +-acute => 6
# |
# +-b
# |
# +-alon => 2
# |
# +-stract => 4
#
# We see that each node in the trie has:
#
# - one or more `letters'
# - an optional value
# - zero or more child nodes
#
# The first step is to call
#
# root = StringNode( "", 0 )
# for word in map.values():
# root.add( word, map[word] )
#
# which creates a large trie where each node has only one children.
#
# Executing
#
# root = root.optimize()
#
# optimizes the trie by merging the letters of successive nodes whenever
# possible.
#
# Each node of the trie is stored as follows.
#
# - First the node's letter, according to the following scheme. We
# use the fact that in the AGL no name contains character codes > 127.
#
# name bitsize description
# ----------------------------------------------------------------
# notlast 1 Set to 1 if this is not the last letter
# in the word.
# ascii 7 The letter's ASCII value.
#
# - The letter is followed by a children count and the value of the
# current key (if any). Again we can do some optimization because all
# AGL entries are from the BMP; this means that 16 bits are sufficient
# to store its Unicode values. Additionally, no node has more than
# 127 children.
#
# name bitsize description
# -----------------------------------------
# hasvalue 1 Set to 1 if a 16-bit Unicode value follows.
# num_children 7 Number of children. Can be 0 only if
# `hasvalue' is set to 1.
# value 16 Optional Unicode value.
#
# - A node is finished by a list of 16bit absolute offsets to the
# children, which must be sorted in increasing order of their first
# letter.
#
# For simplicity, all 16bit quantities are stored in big-endian order.
#
# The root node has first letter = 0, and no value.
#
class StringNode:
def __init__( self, letter, value ):
self.letter = letter
self.value = value
self.children = {}
def __cmp__( self, other ):
return ord( self.letter[0] ) - ord( other.letter[0] )
def add( self, word, value ):
if len( word ) == 0:
self.value = value
return
letter = word[0]
word = word[1:]
if self.children.has_key( letter ):
child = self.children[letter]
else:
child = StringNode( letter, 0 )
self.children[letter] = child
child.add( word, value )
def optimize( self ):
# optimize all children first
children = self.children.values()
self.children = {}
for child in children:
self.children[child.letter[0]] = child.optimize()
# don't optimize if there's a value,
# if we don't have any child or if we
# have more than one child
if ( self.value != 0 ) or ( not children ) or len( children ) > 1:
return self
child = children[0]
self.letter += child.letter
self.value = child.value
self.children = child.children
return self
def dump_debug( self, write, margin ):
# this is used during debugging
line = margin + "+-"
if len( self.letter ) == 0:
line += "<NOLETTER>"
else:
line += self.letter
if self.value:
line += " => " + repr( self.value )
write( line + "\n" )
if self.children:
margin += "| "
for child in self.children.values():
child.dump_debug( write, margin )
def locate( self, index ):
self.index = index
if len( self.letter ) > 0:
index += len( self.letter ) + 1
else:
index += 2
if self.value != 0:
index += 2
children = self.children.values()
children.sort()
index += 2 * len( children )
for child in children:
index = child.locate( index )
return index
def store( self, storage ):
# write the letters
l = len( self.letter )
if l == 0:
storage += struct.pack( "B", 0 )
else:
for n in range( l ):
val = ord( self.letter[n] )
if n < l - 1:
val += 128
storage += struct.pack( "B", val )
# write the count
children = self.children.values()
children.sort()
count = len( children )
if self.value != 0:
storage += struct.pack( "!BH", count + 128, self.value )
else:
storage += struct.pack( "B", count )
for child in children:
storage += struct.pack( "!H", child.index )
for child in children:
storage = child.store( storage )
return storage
def adobe_glyph_values():
"""return the list of glyph names and their unicode values"""
lines = string.split( adobe_glyph_list, '\n' )
glyphs = []
values = []
for line in lines:
if line:
fields = string.split( line, ';' )
# print fields[1] + ' - ' + fields[0]
subfields = string.split( fields[1], ' ' )
if len( subfields ) == 1:
glyphs.append( fields[0] )
values.append( fields[1] )
return glyphs, values
def filter_glyph_names( alist, filter ):
"""filter `alist' by taking _out_ all glyph names that are in `filter'"""
count = 0
extras = []
for name in alist:
try:
filtered_index = filter.index( name )
except:
extras.append( name )
return extras
def dump_encoding( file, encoding_name, encoding_list ):
"""dump a given encoding"""
write = file.write
write( " /* the following are indices into the SID name table */\n" )
write( " static const unsigned short " + encoding_name +
"[" + repr( len( encoding_list ) ) + "] =\n" )
write( " {\n" )
line = " "
comma = ""
col = 0
for value in encoding_list:
line += comma
line += "%3d" % value
comma = ","
col += 1
if col == 16:
col = 0
comma = ",\n "
write( line + "\n };\n\n\n" )
def dump_array( the_array, write, array_name ):
"""dumps a given encoding"""
write( " static const unsigned char " + array_name +
"[" + repr( len( the_array ) ) + "] =\n" )
write( " {\n" )
line = ""
comma = " "
col = 0
for value in the_array:
line += comma
line += "%3d" % ord( value )
comma = ","
col += 1
if col == 16:
col = 0
comma = ",\n "
if len( line ) > 1024:
write( line )
line = ""
write( line + "\n };\n\n\n" )
def main():
"""main program body"""
if len( sys.argv ) != 2:
print __doc__ % sys.argv[0]
sys.exit( 1 )
file = open( sys.argv[1], "w\n" )
write = file.write
count_sid = len( sid_standard_names )
# `mac_extras' contains the list of glyph names in the Macintosh standard
# encoding which are not in the SID Standard Names.
#
mac_extras = filter_glyph_names( mac_standard_names, sid_standard_names )
# `base_list' contains the names of our final glyph names table.
# It consists of the `mac_extras' glyph names, followed by the SID
# standard names.
#
mac_extras_count = len( mac_extras )
base_list = mac_extras + sid_standard_names
write( "/***************************************************************************/\n" )
write( "/* */\n" )
write( "/* %-71s*/\n" % os.path.basename( sys.argv[1] ) )
write( "/* */\n" )
write( "/* PostScript glyph names. */\n" )
write( "/* */\n" )
write( "/* Copyright 2005 by */\n" )
write( "/* David Turner, Robert Wilhelm, and Werner Lemberg. */\n" )
write( "/* */\n" )
write( "/* This file is part of the FreeType project, and may only be used, */\n" )
write( "/* modified, and distributed under the terms of the FreeType project */\n" )
write( "/* license, LICENSE.TXT. By continuing to use, modify, or distribute */\n" )
write( "/* this file you indicate that you have read the license and */\n" )
write( "/* understand and accept it fully. */\n" )
write( "/* */\n" )
write( "/***************************************************************************/\n" )
write( "\n" )
write( "\n" )
write( " /* This file has been generated automatically -- do not edit! */\n" )
write( "\n" )
write( "\n" )
# dump final glyph list (mac extras + sid standard names)
#
st = StringTable( base_list, "ft_standard_glyph_names" )
st.dump( file )
st.dump_sublist( file, "ft_mac_names",
"FT_NUM_MAC_NAMES", mac_standard_names )
st.dump_sublist( file, "ft_sid_names",
"FT_NUM_SID_NAMES", sid_standard_names )
dump_encoding( file, "t1_standard_encoding", t1_standard_encoding )
dump_encoding( file, "t1_expert_encoding", t1_expert_encoding )
# dump the AGL in its compressed form
#
agl_glyphs, agl_values = adobe_glyph_values()
dict = StringNode( "", 0 )
for g in range( len( agl_glyphs ) ):
dict.add( agl_glyphs[g], eval( "0x" + agl_values[g] ) )
dict = dict.optimize()
dict_len = dict.locate( 0 )
dict_array = dict.store( "" )
write( """\
/*
* This table is a compressed version of the Adobe Glyph List (AGL),
* optimized for efficient searching. It has been generated by the
* `glnames.py' python script located in the `src/tools' directory.
*
* The lookup function to get the Unicode value for a given string
* is defined below the table.
*/
""" )
dump_array( dict_array, write, "ft_adobe_glyph_list" )
# write the lookup routine now
#
write( """\
/*
* This function searches the compressed table efficiently.
*/
static unsigned long
ft_get_adobe_glyph_index( const char* name,
const char* limit )
{
int c = 0;
int count, min, max;
const unsigned char* p = ft_adobe_glyph_list;
if ( name == 0 || name >= limit )
goto NotFound;
c = *name++;
count = p[1];
p += 2;
min = 0;
max = count;
while ( min < max )
{
int mid = ( min + max ) >> 1;
const unsigned char* q = p + mid * 2;
int c2;
q = ft_adobe_glyph_list + ( ( (int)q[0] << 8 ) | q[1] );
c2 = q[0] & 127;
if ( c2 == c )
{
p = q;
goto Found;
}
if ( c2 < c )
min = mid + 1;
else
max = mid;
}
goto NotFound;
Found:
for (;;)
{
/* assert (*p & 127) == c */
if ( name >= limit )
{
if ( (p[0] & 128) == 0 &&
(p[1] & 128) != 0 )
return (unsigned long)( ( (int)p[2] << 8 ) | p[3] );
goto NotFound;
}
c = *name++;
if ( p[0] & 128 )
{
p++;
if ( c != (p[0] & 127) )
goto NotFound;
continue;
}
p++;
count = p[0] & 127;
if ( p[0] & 128 )
p += 2;
p++;
for ( ; count > 0; count--, p += 2 )
{
int offset = ( (int)p[0] << 8 ) | p[1];
const unsigned char* q = ft_adobe_glyph_list + offset;
if ( c == ( q[0] & 127 ) )
{
p = q;
goto NextIter;
}
}
goto NotFound;
NextIter:
;
}
NotFound:
return 0;
}
""" )
if 0: # generate unit test, or don't
#
# now write the unit test to check that everything works OK
#
write( "#ifdef TEST\n\n" )
write( "static const char* const the_names[] = {\n" )
for name in agl_glyphs:
write( ' "' + name + '",\n' )
write( " 0\n};\n" )
write( "static const unsigned long the_values[] = {\n" )
for val in agl_values:
write( ' 0x' + val + ',\n' )
write( " 0\n};\n" )
write( """
#include <stdlib.h>
#include <stdio.h>
int
main( void )
{
int result = 0;
const char* const* names = the_names;
const unsigned long* values = the_values;
for ( ; *names; names++, values++ )
{
const char* name = *names;
unsigned long reference = *values;
unsigned long value;
value = ft_get_adobe_glyph_index( name, name + strlen( name ) );
if ( value != reference )
{
result = 1;
fprintf( stderr, "name '%s' => %04x instead of %04x\\n",
name, value, reference );
}
}
return result;
}
""" )
write( "#endif /* TEST */\n" )
write("\n/* END */\n")
# Now run the main routine
#
main()
# END
| lgpl-2.1 |
lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_10_01/models/connectivity_hop.py | 1 | 2114 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class ConnectivityHop(Model):
"""Information about a hop between the source and the destination.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar type: The type of the hop.
:vartype type: str
:ivar id: The ID of the hop.
:vartype id: str
:ivar address: The IP address of the hop.
:vartype address: str
:ivar resource_id: The ID of the resource corresponding to this hop.
:vartype resource_id: str
:ivar next_hop_ids: List of next hop identifiers.
:vartype next_hop_ids: list[str]
:ivar issues: List of issues.
:vartype issues:
list[~azure.mgmt.network.v2017_10_01.models.ConnectivityIssue]
"""
_validation = {
'type': {'readonly': True},
'id': {'readonly': True},
'address': {'readonly': True},
'resource_id': {'readonly': True},
'next_hop_ids': {'readonly': True},
'issues': {'readonly': True},
}
_attribute_map = {
'type': {'key': 'type', 'type': 'str'},
'id': {'key': 'id', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
'resource_id': {'key': 'resourceId', 'type': 'str'},
'next_hop_ids': {'key': 'nextHopIds', 'type': '[str]'},
'issues': {'key': 'issues', 'type': '[ConnectivityIssue]'},
}
def __init__(self, **kwargs):
super(ConnectivityHop, self).__init__(**kwargs)
self.type = None
self.id = None
self.address = None
self.resource_id = None
self.next_hop_ids = None
self.issues = None
| mit |
nhmc/xastropy | xastropy/obs/x_getsdssimg.py | 1 | 4285 | #;+
#; NAME:
#; x_getsdssimg
#; Version 1.1
#;
#; PURPOSE:
#; Returns an Image by querying the SDSS website
#; Will use DSS2-red as a backup
#;
#; CALLING SEQUENCE:
#;
#; INPUTS:
#;
#; RETURNS:
#;
#; OUTPUTS:
#;
#; OPTIONAL KEYWORDS:
#;
#; OPTIONAL OUTPUTS:
#;
#; COMMENTS:
#;
#; EXAMPLES:
#;
#; PROCEDURES/FUNCTIONS CALLED:
#;
#; REVISION HISTORY:
#; 23-Apr-2014 Written by JXP
#;-
#;------------------------------------------------------------------------------
# Import libraries
from __future__ import print_function, absolute_import, division#, unicode_literals
import requests
from cStringIO import StringIO
from astroquery.sdss import SDSS
from astropy.coordinates import SkyCoord
from astropy import units as u
from xastropy.xutils import xdebug as xdb
# Generate the SDSS URL (default is 202" on a side)
def sdsshttp(ra, dec, imsize, scale=0.39612, grid=None, label=None, invert=None):#, xs, ys):
# Pixels
npix = round(imsize*60./scale)
xs = npix
ys = npix
#from StringIO import StringIO
# Generate the http call
name1='http://skyservice.pha.jhu.edu/DR12/ImgCutout/'
name='getjpeg.aspx?ra='
name+=str(ra) #setting the ra
name+='&dec='
name+=str(dec) #setting the declination
name+='&scale='
name+=str(scale) #setting the scale
name+='&width='
name+=str(int(xs)) #setting the width
name+='&height='
name+=str(int(ys)) #setting the height
#------ Options
options = ''
if grid != None:
options+='G'
if label != None:
options+='L'
if invert != None:
options+='I'
if len(options) > 0:
name+='&opt='+options
name+='&query='
url = name1+name
return url
# Generate the SDSS URL (default is 202" on a side)
def dsshttp(ra, dec, imsize):
#https://archive.stsci.edu/cgi-bin/dss_search?v=poss2ukstu_red&r=00:42:44.35&d=+41:16:08.6&e=J2000&h=15.0&w=15.0&f=gif&c=none&fov=NONE&v3=
Equinox = 'J2000'
dss = 'poss2ukstu_red'
url = "http://archive.stsci.edu/cgi-bin/dss_search?"
url += "v="+dss+'&r='+str(ra)+'&d='+str(dec)
url += "&e="+Equinox
url += '&h='+str(imsize)+"&w="+str(imsize)
url += "&f=gif"
url += "&c=none"
url += "&fov=NONE"
url += "&v3="
return url
# ##########################################
def getimg(ira, idec, imsize, BW=False, DSS=None):
''' Grab an SDSS image from the given URL, if possible
Parameters:
----------
ira: (float or Quantity) RA in decimal degrees
idec: (float or Quantity) DEC in decimal degrees
'''
import PIL
from PIL import Image
# Strip units as need be
try:
ra = ira.value
except AttributeError:
ra = ira
dec = idec
else:
dec = idec.value
# Get URL
if DSS == None: # Default
url = sdsshttp(ra,dec,imsize)
else:
url = dsshttp(ra,dec,imsize) # DSS
# Request
rtv = requests.get(url)
# Query for photometry
coord = SkyCoord(ra=ra*u.degree, dec=dec*u.degree)
phot = SDSS.query_region(coord, radius=0.02*u.deg)
if phot is None:
print('getimg: Pulling from DSS instead of SDSS')
BW = 1
url = dsshttp(ra,dec,imsize) # DSS
rtv = requests.get(url)
img = Image.open(StringIO(rtv.content))
# B&W ?
if BW:
import PIL.ImageOps
img2 = img.convert("L")
img2 = PIL.ImageOps.invert(img2)
img = img2
return img, BW
# ##########################################
def get_spec_img(ra, dec):
from PIL import Image
from cStringIO import StringIO
# Coord
if hasattr(ra,'unit'):
coord = SkyCoord(ra=ra, dec=dec)
else:
coord = SkyCoord(ra=ra*u.degree, dec=dec*u.degree)
# Query database
radius = 1*u.arcsec
spec_catalog = SDSS.query_region(coord,spectro=True, radius=radius.to('degree'))
# Request
url = 'http://skyserver.sdss.org/dr12/en/get/SpecById.ashx?id='+str(int(spec_catalog['specobjid']))
rtv = requests.get(url)
img = Image.open(StringIO(rtv.content))
return img
# #############
# Call with RA/DEC (decimal degrees)
def radecd(ra, dec):
import x_getsdssimg as x_gsdss
img = x_gsdss.getimg(ra,dec)
return img
| bsd-3-clause |
sanguinariojoe/FreeCAD | src/Mod/Draft/draftfunctions/mirror.py | 9 | 4578 | # ***************************************************************************
# * Copyright (c) 2009, 2010 Yorik van Havre <[email protected]> *
# * Copyright (c) 2009, 2010 Ken Cline <[email protected]> *
# * Copyright (c) 2020 Carlo Pavan <[email protected]> *
# * Copyright (c) 2020 Eliud Cabrera Castillo <[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 *
# * *
# ***************************************************************************
"""Provides functions to produce a mirrored object.
It just creates a `Part::Mirroring` object, and sets the appropriate
`Source` and `Normal` properties.
"""
## @package mirror
# \ingroup draftfunctions
# \brief Provides functions to produce a mirrored object.
## \addtogroup draftfuctions
# @{
import FreeCAD as App
import draftutils.utils as utils
import draftutils.gui_utils as gui_utils
from draftutils.messages import _err
from draftutils.translate import translate
if App.GuiUp:
import FreeCADGui as Gui
def mirror(objlist, p1, p2):
"""Create a mirror object from the provided list and line.
It creates a `Part::Mirroring` object from the given `objlist` using
a plane that is defined by the two given points `p1` and `p2`,
and either
- the Draft working plane normal, or
- the negative normal provided by the camera direction
if the working plane normal does not exist and the graphical interface
is available.
If neither of these two is available, it uses as normal the +Z vector.
Parameters
----------
objlist: single object or a list of objects
A single object or a list of objects.
p1: Base::Vector3
Point 1 of the mirror plane. It is also used as the `Placement.Base`
of the resulting object.
p2: Base::Vector3
Point 1 of the mirror plane.
Returns
-------
None
If the operation fails.
list
List of `Part::Mirroring` objects, or a single one
depending on the input `objlist`.
To Do
-----
Implement a mirror tool specific to the workbench that does not
just use `Part::Mirroring`. It should create a derived object,
that is, it should work similar to `Draft.offset`.
"""
utils.print_header('mirror', "Create mirror")
if not objlist:
_err(translate("draft","No object given"))
return
if p1 == p2:
_err(translate("draft","The two points are coincident"))
return
if not isinstance(objlist, list):
objlist = [objlist]
if hasattr(App, "DraftWorkingPlane"):
norm = App.DraftWorkingPlane.getNormal()
elif App.GuiUp:
norm = Gui.ActiveDocument.ActiveView.getViewDirection().negative()
else:
norm = App.Vector(0, 0, 1)
pnorm = p2.sub(p1).cross(norm).normalize()
result = []
for obj in objlist:
mir = App.ActiveDocument.addObject("Part::Mirroring", "mirror")
mir.Label = obj.Label + " (" + translate("draft","mirrored") + ") "
mir.Source = obj
mir.Base = p1
mir.Normal = pnorm
gui_utils.format_object(mir, obj)
result.append(mir)
if len(result) == 1:
result = result[0]
gui_utils.select(result)
return result
## @}
| lgpl-2.1 |
GoogleCloudPlatform/PerfKitBenchmarker | perfkitbenchmarker/data/edw/multistream_multiprofile_driver.py | 1 | 2591 | """Driver for running multiple profiles concurrently against a cluster.
The list of profiles are passed via flag each of which are defined in the
profile_details module.
"""
__author__ = '[email protected]'
import json
import logging
from multiprocessing import Process
from multiprocessing import Queue
import time
from absl import app
from absl import flags
import unistream_profile_driver
flags.DEFINE_list('profile_list', None, 'List of profiles. Each will be run on '
'its own process to simulate '
'concurrency.')
flags.mark_flags_as_required(['profile_list'])
FLAGS = flags.FLAGS
def process_profile(profile, response_q):
"""Method to execute a profile (list of sql scripts) on a cluster.
Args:
profile: The profile to run.
response_q: Communication channel between processes.
"""
profile_output = unistream_profile_driver.execute_profile(profile)
response_q.put([profile, profile_output])
def manage_streams():
"""Method to launch concurrent execution of multiple profiles.
Returns:
A dictionary containing
1. wall_time: Total time taken for all the profiles to complete execution.
2. profile details:
2.1. profile_execution_time: Time taken for all scripts in the profile to
complete execution.
2.2. Individual script metrics: script name and its execution time (-1 if
the script fails)
"""
profile_handling_process_list = []
profile_performance = Queue()
start_time = time.time()
for profile in FLAGS.profile_list:
profile_handling_process = Process(target=process_profile,
args=(profile, profile_performance,))
profile_handling_process.start()
profile_handling_process_list.append(profile_handling_process)
for profile_handling_process in profile_handling_process_list:
profile_handling_process.join()
# All processes have joined, implying all profiles have been completed
execution_time = round((time.time() - start_time), 2)
num_profiles = len(FLAGS.profile_list)
overall_performance = {}
while num_profiles:
temp_performance_response = profile_performance.get()
profile = temp_performance_response[0]
overall_performance[profile] = json.loads(temp_performance_response[1])
num_profiles -= 1
overall_performance['wall_time'] = execution_time
return json.dumps(overall_performance)
def main(argv):
del argv
print(manage_streams())
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
app.run(main)
| apache-2.0 |
RiccardoPecora/MP | Lib/encodings/cp775.py | 93 | 35429 | """ Python Character Mapping Codec cp775 generated from 'VENDORS/MICSFT/PC/CP775.TXT' with gencodec.py.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_map)
def decode(self,input,errors='strict'):
return codecs.charmap_decode(input,errors,decoding_table)
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input, final=False):
return codecs.charmap_encode(input,self.errors,encoding_map)[0]
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
### encodings module API
def getregentry():
return codecs.CodecInfo(
name='cp775',
encode=Codec().encode,
decode=Codec().decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamreader=StreamReader,
streamwriter=StreamWriter,
)
### Decoding Map
decoding_map = codecs.make_identity_dict(range(256))
decoding_map.update({
0x0080: 0x0106, # LATIN CAPITAL LETTER C WITH ACUTE
0x0081: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS
0x0082: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE
0x0083: 0x0101, # LATIN SMALL LETTER A WITH MACRON
0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS
0x0085: 0x0123, # LATIN SMALL LETTER G WITH CEDILLA
0x0086: 0x00e5, # LATIN SMALL LETTER A WITH RING ABOVE
0x0087: 0x0107, # LATIN SMALL LETTER C WITH ACUTE
0x0088: 0x0142, # LATIN SMALL LETTER L WITH STROKE
0x0089: 0x0113, # LATIN SMALL LETTER E WITH MACRON
0x008a: 0x0156, # LATIN CAPITAL LETTER R WITH CEDILLA
0x008b: 0x0157, # LATIN SMALL LETTER R WITH CEDILLA
0x008c: 0x012b, # LATIN SMALL LETTER I WITH MACRON
0x008d: 0x0179, # LATIN CAPITAL LETTER Z WITH ACUTE
0x008e: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS
0x008f: 0x00c5, # LATIN CAPITAL LETTER A WITH RING ABOVE
0x0090: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE
0x0091: 0x00e6, # LATIN SMALL LIGATURE AE
0x0092: 0x00c6, # LATIN CAPITAL LIGATURE AE
0x0093: 0x014d, # LATIN SMALL LETTER O WITH MACRON
0x0094: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS
0x0095: 0x0122, # LATIN CAPITAL LETTER G WITH CEDILLA
0x0096: 0x00a2, # CENT SIGN
0x0097: 0x015a, # LATIN CAPITAL LETTER S WITH ACUTE
0x0098: 0x015b, # LATIN SMALL LETTER S WITH ACUTE
0x0099: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS
0x009a: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS
0x009b: 0x00f8, # LATIN SMALL LETTER O WITH STROKE
0x009c: 0x00a3, # POUND SIGN
0x009d: 0x00d8, # LATIN CAPITAL LETTER O WITH STROKE
0x009e: 0x00d7, # MULTIPLICATION SIGN
0x009f: 0x00a4, # CURRENCY SIGN
0x00a0: 0x0100, # LATIN CAPITAL LETTER A WITH MACRON
0x00a1: 0x012a, # LATIN CAPITAL LETTER I WITH MACRON
0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE
0x00a3: 0x017b, # LATIN CAPITAL LETTER Z WITH DOT ABOVE
0x00a4: 0x017c, # LATIN SMALL LETTER Z WITH DOT ABOVE
0x00a5: 0x017a, # LATIN SMALL LETTER Z WITH ACUTE
0x00a6: 0x201d, # RIGHT DOUBLE QUOTATION MARK
0x00a7: 0x00a6, # BROKEN BAR
0x00a8: 0x00a9, # COPYRIGHT SIGN
0x00a9: 0x00ae, # REGISTERED SIGN
0x00aa: 0x00ac, # NOT SIGN
0x00ab: 0x00bd, # VULGAR FRACTION ONE HALF
0x00ac: 0x00bc, # VULGAR FRACTION ONE QUARTER
0x00ad: 0x0141, # LATIN CAPITAL LETTER L WITH STROKE
0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00b0: 0x2591, # LIGHT SHADE
0x00b1: 0x2592, # MEDIUM SHADE
0x00b2: 0x2593, # DARK SHADE
0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL
0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT
0x00b5: 0x0104, # LATIN CAPITAL LETTER A WITH OGONEK
0x00b6: 0x010c, # LATIN CAPITAL LETTER C WITH CARON
0x00b7: 0x0118, # LATIN CAPITAL LETTER E WITH OGONEK
0x00b8: 0x0116, # LATIN CAPITAL LETTER E WITH DOT ABOVE
0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT
0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL
0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT
0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT
0x00bd: 0x012e, # LATIN CAPITAL LETTER I WITH OGONEK
0x00be: 0x0160, # LATIN CAPITAL LETTER S WITH CARON
0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT
0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT
0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL
0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT
0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL
0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
0x00c6: 0x0172, # LATIN CAPITAL LETTER U WITH OGONEK
0x00c7: 0x016a, # LATIN CAPITAL LETTER U WITH MACRON
0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT
0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT
0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL
0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL
0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
0x00cf: 0x017d, # LATIN CAPITAL LETTER Z WITH CARON
0x00d0: 0x0105, # LATIN SMALL LETTER A WITH OGONEK
0x00d1: 0x010d, # LATIN SMALL LETTER C WITH CARON
0x00d2: 0x0119, # LATIN SMALL LETTER E WITH OGONEK
0x00d3: 0x0117, # LATIN SMALL LETTER E WITH DOT ABOVE
0x00d4: 0x012f, # LATIN SMALL LETTER I WITH OGONEK
0x00d5: 0x0161, # LATIN SMALL LETTER S WITH CARON
0x00d6: 0x0173, # LATIN SMALL LETTER U WITH OGONEK
0x00d7: 0x016b, # LATIN SMALL LETTER U WITH MACRON
0x00d8: 0x017e, # LATIN SMALL LETTER Z WITH CARON
0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT
0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT
0x00db: 0x2588, # FULL BLOCK
0x00dc: 0x2584, # LOWER HALF BLOCK
0x00dd: 0x258c, # LEFT HALF BLOCK
0x00de: 0x2590, # RIGHT HALF BLOCK
0x00df: 0x2580, # UPPER HALF BLOCK
0x00e0: 0x00d3, # LATIN CAPITAL LETTER O WITH ACUTE
0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S (GERMAN)
0x00e2: 0x014c, # LATIN CAPITAL LETTER O WITH MACRON
0x00e3: 0x0143, # LATIN CAPITAL LETTER N WITH ACUTE
0x00e4: 0x00f5, # LATIN SMALL LETTER O WITH TILDE
0x00e5: 0x00d5, # LATIN CAPITAL LETTER O WITH TILDE
0x00e6: 0x00b5, # MICRO SIGN
0x00e7: 0x0144, # LATIN SMALL LETTER N WITH ACUTE
0x00e8: 0x0136, # LATIN CAPITAL LETTER K WITH CEDILLA
0x00e9: 0x0137, # LATIN SMALL LETTER K WITH CEDILLA
0x00ea: 0x013b, # LATIN CAPITAL LETTER L WITH CEDILLA
0x00eb: 0x013c, # LATIN SMALL LETTER L WITH CEDILLA
0x00ec: 0x0146, # LATIN SMALL LETTER N WITH CEDILLA
0x00ed: 0x0112, # LATIN CAPITAL LETTER E WITH MACRON
0x00ee: 0x0145, # LATIN CAPITAL LETTER N WITH CEDILLA
0x00ef: 0x2019, # RIGHT SINGLE QUOTATION MARK
0x00f0: 0x00ad, # SOFT HYPHEN
0x00f1: 0x00b1, # PLUS-MINUS SIGN
0x00f2: 0x201c, # LEFT DOUBLE QUOTATION MARK
0x00f3: 0x00be, # VULGAR FRACTION THREE QUARTERS
0x00f4: 0x00b6, # PILCROW SIGN
0x00f5: 0x00a7, # SECTION SIGN
0x00f6: 0x00f7, # DIVISION SIGN
0x00f7: 0x201e, # DOUBLE LOW-9 QUOTATION MARK
0x00f8: 0x00b0, # DEGREE SIGN
0x00f9: 0x2219, # BULLET OPERATOR
0x00fa: 0x00b7, # MIDDLE DOT
0x00fb: 0x00b9, # SUPERSCRIPT ONE
0x00fc: 0x00b3, # SUPERSCRIPT THREE
0x00fd: 0x00b2, # SUPERSCRIPT TWO
0x00fe: 0x25a0, # BLACK SQUARE
0x00ff: 0x00a0, # NO-BREAK SPACE
})
### Decoding Table
decoding_table = (
u'\x00' # 0x0000 -> NULL
u'\x01' # 0x0001 -> START OF HEADING
u'\x02' # 0x0002 -> START OF TEXT
u'\x03' # 0x0003 -> END OF TEXT
u'\x04' # 0x0004 -> END OF TRANSMISSION
u'\x05' # 0x0005 -> ENQUIRY
u'\x06' # 0x0006 -> ACKNOWLEDGE
u'\x07' # 0x0007 -> BELL
u'\x08' # 0x0008 -> BACKSPACE
u'\t' # 0x0009 -> HORIZONTAL TABULATION
u'\n' # 0x000a -> LINE FEED
u'\x0b' # 0x000b -> VERTICAL TABULATION
u'\x0c' # 0x000c -> FORM FEED
u'\r' # 0x000d -> CARRIAGE RETURN
u'\x0e' # 0x000e -> SHIFT OUT
u'\x0f' # 0x000f -> SHIFT IN
u'\x10' # 0x0010 -> DATA LINK ESCAPE
u'\x11' # 0x0011 -> DEVICE CONTROL ONE
u'\x12' # 0x0012 -> DEVICE CONTROL TWO
u'\x13' # 0x0013 -> DEVICE CONTROL THREE
u'\x14' # 0x0014 -> DEVICE CONTROL FOUR
u'\x15' # 0x0015 -> NEGATIVE ACKNOWLEDGE
u'\x16' # 0x0016 -> SYNCHRONOUS IDLE
u'\x17' # 0x0017 -> END OF TRANSMISSION BLOCK
u'\x18' # 0x0018 -> CANCEL
u'\x19' # 0x0019 -> END OF MEDIUM
u'\x1a' # 0x001a -> SUBSTITUTE
u'\x1b' # 0x001b -> ESCAPE
u'\x1c' # 0x001c -> FILE SEPARATOR
u'\x1d' # 0x001d -> GROUP SEPARATOR
u'\x1e' # 0x001e -> RECORD SEPARATOR
u'\x1f' # 0x001f -> UNIT SEPARATOR
u' ' # 0x0020 -> SPACE
u'!' # 0x0021 -> EXCLAMATION MARK
u'"' # 0x0022 -> QUOTATION MARK
u'#' # 0x0023 -> NUMBER SIGN
u'$' # 0x0024 -> DOLLAR SIGN
u'%' # 0x0025 -> PERCENT SIGN
u'&' # 0x0026 -> AMPERSAND
u"'" # 0x0027 -> APOSTROPHE
u'(' # 0x0028 -> LEFT PARENTHESIS
u')' # 0x0029 -> RIGHT PARENTHESIS
u'*' # 0x002a -> ASTERISK
u'+' # 0x002b -> PLUS SIGN
u',' # 0x002c -> COMMA
u'-' # 0x002d -> HYPHEN-MINUS
u'.' # 0x002e -> FULL STOP
u'/' # 0x002f -> SOLIDUS
u'0' # 0x0030 -> DIGIT ZERO
u'1' # 0x0031 -> DIGIT ONE
u'2' # 0x0032 -> DIGIT TWO
u'3' # 0x0033 -> DIGIT THREE
u'4' # 0x0034 -> DIGIT FOUR
u'5' # 0x0035 -> DIGIT FIVE
u'6' # 0x0036 -> DIGIT SIX
u'7' # 0x0037 -> DIGIT SEVEN
u'8' # 0x0038 -> DIGIT EIGHT
u'9' # 0x0039 -> DIGIT NINE
u':' # 0x003a -> COLON
u';' # 0x003b -> SEMICOLON
u'<' # 0x003c -> LESS-THAN SIGN
u'=' # 0x003d -> EQUALS SIGN
u'>' # 0x003e -> GREATER-THAN SIGN
u'?' # 0x003f -> QUESTION MARK
u'@' # 0x0040 -> COMMERCIAL AT
u'A' # 0x0041 -> LATIN CAPITAL LETTER A
u'B' # 0x0042 -> LATIN CAPITAL LETTER B
u'C' # 0x0043 -> LATIN CAPITAL LETTER C
u'D' # 0x0044 -> LATIN CAPITAL LETTER D
u'E' # 0x0045 -> LATIN CAPITAL LETTER E
u'F' # 0x0046 -> LATIN CAPITAL LETTER F
u'G' # 0x0047 -> LATIN CAPITAL LETTER G
u'H' # 0x0048 -> LATIN CAPITAL LETTER H
u'I' # 0x0049 -> LATIN CAPITAL LETTER I
u'J' # 0x004a -> LATIN CAPITAL LETTER J
u'K' # 0x004b -> LATIN CAPITAL LETTER K
u'L' # 0x004c -> LATIN CAPITAL LETTER L
u'M' # 0x004d -> LATIN CAPITAL LETTER M
u'N' # 0x004e -> LATIN CAPITAL LETTER N
u'O' # 0x004f -> LATIN CAPITAL LETTER O
u'P' # 0x0050 -> LATIN CAPITAL LETTER P
u'Q' # 0x0051 -> LATIN CAPITAL LETTER Q
u'R' # 0x0052 -> LATIN CAPITAL LETTER R
u'S' # 0x0053 -> LATIN CAPITAL LETTER S
u'T' # 0x0054 -> LATIN CAPITAL LETTER T
u'U' # 0x0055 -> LATIN CAPITAL LETTER U
u'V' # 0x0056 -> LATIN CAPITAL LETTER V
u'W' # 0x0057 -> LATIN CAPITAL LETTER W
u'X' # 0x0058 -> LATIN CAPITAL LETTER X
u'Y' # 0x0059 -> LATIN CAPITAL LETTER Y
u'Z' # 0x005a -> LATIN CAPITAL LETTER Z
u'[' # 0x005b -> LEFT SQUARE BRACKET
u'\\' # 0x005c -> REVERSE SOLIDUS
u']' # 0x005d -> RIGHT SQUARE BRACKET
u'^' # 0x005e -> CIRCUMFLEX ACCENT
u'_' # 0x005f -> LOW LINE
u'`' # 0x0060 -> GRAVE ACCENT
u'a' # 0x0061 -> LATIN SMALL LETTER A
u'b' # 0x0062 -> LATIN SMALL LETTER B
u'c' # 0x0063 -> LATIN SMALL LETTER C
u'd' # 0x0064 -> LATIN SMALL LETTER D
u'e' # 0x0065 -> LATIN SMALL LETTER E
u'f' # 0x0066 -> LATIN SMALL LETTER F
u'g' # 0x0067 -> LATIN SMALL LETTER G
u'h' # 0x0068 -> LATIN SMALL LETTER H
u'i' # 0x0069 -> LATIN SMALL LETTER I
u'j' # 0x006a -> LATIN SMALL LETTER J
u'k' # 0x006b -> LATIN SMALL LETTER K
u'l' # 0x006c -> LATIN SMALL LETTER L
u'm' # 0x006d -> LATIN SMALL LETTER M
u'n' # 0x006e -> LATIN SMALL LETTER N
u'o' # 0x006f -> LATIN SMALL LETTER O
u'p' # 0x0070 -> LATIN SMALL LETTER P
u'q' # 0x0071 -> LATIN SMALL LETTER Q
u'r' # 0x0072 -> LATIN SMALL LETTER R
u's' # 0x0073 -> LATIN SMALL LETTER S
u't' # 0x0074 -> LATIN SMALL LETTER T
u'u' # 0x0075 -> LATIN SMALL LETTER U
u'v' # 0x0076 -> LATIN SMALL LETTER V
u'w' # 0x0077 -> LATIN SMALL LETTER W
u'x' # 0x0078 -> LATIN SMALL LETTER X
u'y' # 0x0079 -> LATIN SMALL LETTER Y
u'z' # 0x007a -> LATIN SMALL LETTER Z
u'{' # 0x007b -> LEFT CURLY BRACKET
u'|' # 0x007c -> VERTICAL LINE
u'}' # 0x007d -> RIGHT CURLY BRACKET
u'~' # 0x007e -> TILDE
u'\x7f' # 0x007f -> DELETE
u'\u0106' # 0x0080 -> LATIN CAPITAL LETTER C WITH ACUTE
u'\xfc' # 0x0081 -> LATIN SMALL LETTER U WITH DIAERESIS
u'\xe9' # 0x0082 -> LATIN SMALL LETTER E WITH ACUTE
u'\u0101' # 0x0083 -> LATIN SMALL LETTER A WITH MACRON
u'\xe4' # 0x0084 -> LATIN SMALL LETTER A WITH DIAERESIS
u'\u0123' # 0x0085 -> LATIN SMALL LETTER G WITH CEDILLA
u'\xe5' # 0x0086 -> LATIN SMALL LETTER A WITH RING ABOVE
u'\u0107' # 0x0087 -> LATIN SMALL LETTER C WITH ACUTE
u'\u0142' # 0x0088 -> LATIN SMALL LETTER L WITH STROKE
u'\u0113' # 0x0089 -> LATIN SMALL LETTER E WITH MACRON
u'\u0156' # 0x008a -> LATIN CAPITAL LETTER R WITH CEDILLA
u'\u0157' # 0x008b -> LATIN SMALL LETTER R WITH CEDILLA
u'\u012b' # 0x008c -> LATIN SMALL LETTER I WITH MACRON
u'\u0179' # 0x008d -> LATIN CAPITAL LETTER Z WITH ACUTE
u'\xc4' # 0x008e -> LATIN CAPITAL LETTER A WITH DIAERESIS
u'\xc5' # 0x008f -> LATIN CAPITAL LETTER A WITH RING ABOVE
u'\xc9' # 0x0090 -> LATIN CAPITAL LETTER E WITH ACUTE
u'\xe6' # 0x0091 -> LATIN SMALL LIGATURE AE
u'\xc6' # 0x0092 -> LATIN CAPITAL LIGATURE AE
u'\u014d' # 0x0093 -> LATIN SMALL LETTER O WITH MACRON
u'\xf6' # 0x0094 -> LATIN SMALL LETTER O WITH DIAERESIS
u'\u0122' # 0x0095 -> LATIN CAPITAL LETTER G WITH CEDILLA
u'\xa2' # 0x0096 -> CENT SIGN
u'\u015a' # 0x0097 -> LATIN CAPITAL LETTER S WITH ACUTE
u'\u015b' # 0x0098 -> LATIN SMALL LETTER S WITH ACUTE
u'\xd6' # 0x0099 -> LATIN CAPITAL LETTER O WITH DIAERESIS
u'\xdc' # 0x009a -> LATIN CAPITAL LETTER U WITH DIAERESIS
u'\xf8' # 0x009b -> LATIN SMALL LETTER O WITH STROKE
u'\xa3' # 0x009c -> POUND SIGN
u'\xd8' # 0x009d -> LATIN CAPITAL LETTER O WITH STROKE
u'\xd7' # 0x009e -> MULTIPLICATION SIGN
u'\xa4' # 0x009f -> CURRENCY SIGN
u'\u0100' # 0x00a0 -> LATIN CAPITAL LETTER A WITH MACRON
u'\u012a' # 0x00a1 -> LATIN CAPITAL LETTER I WITH MACRON
u'\xf3' # 0x00a2 -> LATIN SMALL LETTER O WITH ACUTE
u'\u017b' # 0x00a3 -> LATIN CAPITAL LETTER Z WITH DOT ABOVE
u'\u017c' # 0x00a4 -> LATIN SMALL LETTER Z WITH DOT ABOVE
u'\u017a' # 0x00a5 -> LATIN SMALL LETTER Z WITH ACUTE
u'\u201d' # 0x00a6 -> RIGHT DOUBLE QUOTATION MARK
u'\xa6' # 0x00a7 -> BROKEN BAR
u'\xa9' # 0x00a8 -> COPYRIGHT SIGN
u'\xae' # 0x00a9 -> REGISTERED SIGN
u'\xac' # 0x00aa -> NOT SIGN
u'\xbd' # 0x00ab -> VULGAR FRACTION ONE HALF
u'\xbc' # 0x00ac -> VULGAR FRACTION ONE QUARTER
u'\u0141' # 0x00ad -> LATIN CAPITAL LETTER L WITH STROKE
u'\xab' # 0x00ae -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
u'\xbb' # 0x00af -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
u'\u2591' # 0x00b0 -> LIGHT SHADE
u'\u2592' # 0x00b1 -> MEDIUM SHADE
u'\u2593' # 0x00b2 -> DARK SHADE
u'\u2502' # 0x00b3 -> BOX DRAWINGS LIGHT VERTICAL
u'\u2524' # 0x00b4 -> BOX DRAWINGS LIGHT VERTICAL AND LEFT
u'\u0104' # 0x00b5 -> LATIN CAPITAL LETTER A WITH OGONEK
u'\u010c' # 0x00b6 -> LATIN CAPITAL LETTER C WITH CARON
u'\u0118' # 0x00b7 -> LATIN CAPITAL LETTER E WITH OGONEK
u'\u0116' # 0x00b8 -> LATIN CAPITAL LETTER E WITH DOT ABOVE
u'\u2563' # 0x00b9 -> BOX DRAWINGS DOUBLE VERTICAL AND LEFT
u'\u2551' # 0x00ba -> BOX DRAWINGS DOUBLE VERTICAL
u'\u2557' # 0x00bb -> BOX DRAWINGS DOUBLE DOWN AND LEFT
u'\u255d' # 0x00bc -> BOX DRAWINGS DOUBLE UP AND LEFT
u'\u012e' # 0x00bd -> LATIN CAPITAL LETTER I WITH OGONEK
u'\u0160' # 0x00be -> LATIN CAPITAL LETTER S WITH CARON
u'\u2510' # 0x00bf -> BOX DRAWINGS LIGHT DOWN AND LEFT
u'\u2514' # 0x00c0 -> BOX DRAWINGS LIGHT UP AND RIGHT
u'\u2534' # 0x00c1 -> BOX DRAWINGS LIGHT UP AND HORIZONTAL
u'\u252c' # 0x00c2 -> BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
u'\u251c' # 0x00c3 -> BOX DRAWINGS LIGHT VERTICAL AND RIGHT
u'\u2500' # 0x00c4 -> BOX DRAWINGS LIGHT HORIZONTAL
u'\u253c' # 0x00c5 -> BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
u'\u0172' # 0x00c6 -> LATIN CAPITAL LETTER U WITH OGONEK
u'\u016a' # 0x00c7 -> LATIN CAPITAL LETTER U WITH MACRON
u'\u255a' # 0x00c8 -> BOX DRAWINGS DOUBLE UP AND RIGHT
u'\u2554' # 0x00c9 -> BOX DRAWINGS DOUBLE DOWN AND RIGHT
u'\u2569' # 0x00ca -> BOX DRAWINGS DOUBLE UP AND HORIZONTAL
u'\u2566' # 0x00cb -> BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
u'\u2560' # 0x00cc -> BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
u'\u2550' # 0x00cd -> BOX DRAWINGS DOUBLE HORIZONTAL
u'\u256c' # 0x00ce -> BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
u'\u017d' # 0x00cf -> LATIN CAPITAL LETTER Z WITH CARON
u'\u0105' # 0x00d0 -> LATIN SMALL LETTER A WITH OGONEK
u'\u010d' # 0x00d1 -> LATIN SMALL LETTER C WITH CARON
u'\u0119' # 0x00d2 -> LATIN SMALL LETTER E WITH OGONEK
u'\u0117' # 0x00d3 -> LATIN SMALL LETTER E WITH DOT ABOVE
u'\u012f' # 0x00d4 -> LATIN SMALL LETTER I WITH OGONEK
u'\u0161' # 0x00d5 -> LATIN SMALL LETTER S WITH CARON
u'\u0173' # 0x00d6 -> LATIN SMALL LETTER U WITH OGONEK
u'\u016b' # 0x00d7 -> LATIN SMALL LETTER U WITH MACRON
u'\u017e' # 0x00d8 -> LATIN SMALL LETTER Z WITH CARON
u'\u2518' # 0x00d9 -> BOX DRAWINGS LIGHT UP AND LEFT
u'\u250c' # 0x00da -> BOX DRAWINGS LIGHT DOWN AND RIGHT
u'\u2588' # 0x00db -> FULL BLOCK
u'\u2584' # 0x00dc -> LOWER HALF BLOCK
u'\u258c' # 0x00dd -> LEFT HALF BLOCK
u'\u2590' # 0x00de -> RIGHT HALF BLOCK
u'\u2580' # 0x00df -> UPPER HALF BLOCK
u'\xd3' # 0x00e0 -> LATIN CAPITAL LETTER O WITH ACUTE
u'\xdf' # 0x00e1 -> LATIN SMALL LETTER SHARP S (GERMAN)
u'\u014c' # 0x00e2 -> LATIN CAPITAL LETTER O WITH MACRON
u'\u0143' # 0x00e3 -> LATIN CAPITAL LETTER N WITH ACUTE
u'\xf5' # 0x00e4 -> LATIN SMALL LETTER O WITH TILDE
u'\xd5' # 0x00e5 -> LATIN CAPITAL LETTER O WITH TILDE
u'\xb5' # 0x00e6 -> MICRO SIGN
u'\u0144' # 0x00e7 -> LATIN SMALL LETTER N WITH ACUTE
u'\u0136' # 0x00e8 -> LATIN CAPITAL LETTER K WITH CEDILLA
u'\u0137' # 0x00e9 -> LATIN SMALL LETTER K WITH CEDILLA
u'\u013b' # 0x00ea -> LATIN CAPITAL LETTER L WITH CEDILLA
u'\u013c' # 0x00eb -> LATIN SMALL LETTER L WITH CEDILLA
u'\u0146' # 0x00ec -> LATIN SMALL LETTER N WITH CEDILLA
u'\u0112' # 0x00ed -> LATIN CAPITAL LETTER E WITH MACRON
u'\u0145' # 0x00ee -> LATIN CAPITAL LETTER N WITH CEDILLA
u'\u2019' # 0x00ef -> RIGHT SINGLE QUOTATION MARK
u'\xad' # 0x00f0 -> SOFT HYPHEN
u'\xb1' # 0x00f1 -> PLUS-MINUS SIGN
u'\u201c' # 0x00f2 -> LEFT DOUBLE QUOTATION MARK
u'\xbe' # 0x00f3 -> VULGAR FRACTION THREE QUARTERS
u'\xb6' # 0x00f4 -> PILCROW SIGN
u'\xa7' # 0x00f5 -> SECTION SIGN
u'\xf7' # 0x00f6 -> DIVISION SIGN
u'\u201e' # 0x00f7 -> DOUBLE LOW-9 QUOTATION MARK
u'\xb0' # 0x00f8 -> DEGREE SIGN
u'\u2219' # 0x00f9 -> BULLET OPERATOR
u'\xb7' # 0x00fa -> MIDDLE DOT
u'\xb9' # 0x00fb -> SUPERSCRIPT ONE
u'\xb3' # 0x00fc -> SUPERSCRIPT THREE
u'\xb2' # 0x00fd -> SUPERSCRIPT TWO
u'\u25a0' # 0x00fe -> BLACK SQUARE
u'\xa0' # 0x00ff -> NO-BREAK SPACE
)
### Encoding Map
encoding_map = {
0x0000: 0x0000, # NULL
0x0001: 0x0001, # START OF HEADING
0x0002: 0x0002, # START OF TEXT
0x0003: 0x0003, # END OF TEXT
0x0004: 0x0004, # END OF TRANSMISSION
0x0005: 0x0005, # ENQUIRY
0x0006: 0x0006, # ACKNOWLEDGE
0x0007: 0x0007, # BELL
0x0008: 0x0008, # BACKSPACE
0x0009: 0x0009, # HORIZONTAL TABULATION
0x000a: 0x000a, # LINE FEED
0x000b: 0x000b, # VERTICAL TABULATION
0x000c: 0x000c, # FORM FEED
0x000d: 0x000d, # CARRIAGE RETURN
0x000e: 0x000e, # SHIFT OUT
0x000f: 0x000f, # SHIFT IN
0x0010: 0x0010, # DATA LINK ESCAPE
0x0011: 0x0011, # DEVICE CONTROL ONE
0x0012: 0x0012, # DEVICE CONTROL TWO
0x0013: 0x0013, # DEVICE CONTROL THREE
0x0014: 0x0014, # DEVICE CONTROL FOUR
0x0015: 0x0015, # NEGATIVE ACKNOWLEDGE
0x0016: 0x0016, # SYNCHRONOUS IDLE
0x0017: 0x0017, # END OF TRANSMISSION BLOCK
0x0018: 0x0018, # CANCEL
0x0019: 0x0019, # END OF MEDIUM
0x001a: 0x001a, # SUBSTITUTE
0x001b: 0x001b, # ESCAPE
0x001c: 0x001c, # FILE SEPARATOR
0x001d: 0x001d, # GROUP SEPARATOR
0x001e: 0x001e, # RECORD SEPARATOR
0x001f: 0x001f, # UNIT SEPARATOR
0x0020: 0x0020, # SPACE
0x0021: 0x0021, # EXCLAMATION MARK
0x0022: 0x0022, # QUOTATION MARK
0x0023: 0x0023, # NUMBER SIGN
0x0024: 0x0024, # DOLLAR SIGN
0x0025: 0x0025, # PERCENT SIGN
0x0026: 0x0026, # AMPERSAND
0x0027: 0x0027, # APOSTROPHE
0x0028: 0x0028, # LEFT PARENTHESIS
0x0029: 0x0029, # RIGHT PARENTHESIS
0x002a: 0x002a, # ASTERISK
0x002b: 0x002b, # PLUS SIGN
0x002c: 0x002c, # COMMA
0x002d: 0x002d, # HYPHEN-MINUS
0x002e: 0x002e, # FULL STOP
0x002f: 0x002f, # SOLIDUS
0x0030: 0x0030, # DIGIT ZERO
0x0031: 0x0031, # DIGIT ONE
0x0032: 0x0032, # DIGIT TWO
0x0033: 0x0033, # DIGIT THREE
0x0034: 0x0034, # DIGIT FOUR
0x0035: 0x0035, # DIGIT FIVE
0x0036: 0x0036, # DIGIT SIX
0x0037: 0x0037, # DIGIT SEVEN
0x0038: 0x0038, # DIGIT EIGHT
0x0039: 0x0039, # DIGIT NINE
0x003a: 0x003a, # COLON
0x003b: 0x003b, # SEMICOLON
0x003c: 0x003c, # LESS-THAN SIGN
0x003d: 0x003d, # EQUALS SIGN
0x003e: 0x003e, # GREATER-THAN SIGN
0x003f: 0x003f, # QUESTION MARK
0x0040: 0x0040, # COMMERCIAL AT
0x0041: 0x0041, # LATIN CAPITAL LETTER A
0x0042: 0x0042, # LATIN CAPITAL LETTER B
0x0043: 0x0043, # LATIN CAPITAL LETTER C
0x0044: 0x0044, # LATIN CAPITAL LETTER D
0x0045: 0x0045, # LATIN CAPITAL LETTER E
0x0046: 0x0046, # LATIN CAPITAL LETTER F
0x0047: 0x0047, # LATIN CAPITAL LETTER G
0x0048: 0x0048, # LATIN CAPITAL LETTER H
0x0049: 0x0049, # LATIN CAPITAL LETTER I
0x004a: 0x004a, # LATIN CAPITAL LETTER J
0x004b: 0x004b, # LATIN CAPITAL LETTER K
0x004c: 0x004c, # LATIN CAPITAL LETTER L
0x004d: 0x004d, # LATIN CAPITAL LETTER M
0x004e: 0x004e, # LATIN CAPITAL LETTER N
0x004f: 0x004f, # LATIN CAPITAL LETTER O
0x0050: 0x0050, # LATIN CAPITAL LETTER P
0x0051: 0x0051, # LATIN CAPITAL LETTER Q
0x0052: 0x0052, # LATIN CAPITAL LETTER R
0x0053: 0x0053, # LATIN CAPITAL LETTER S
0x0054: 0x0054, # LATIN CAPITAL LETTER T
0x0055: 0x0055, # LATIN CAPITAL LETTER U
0x0056: 0x0056, # LATIN CAPITAL LETTER V
0x0057: 0x0057, # LATIN CAPITAL LETTER W
0x0058: 0x0058, # LATIN CAPITAL LETTER X
0x0059: 0x0059, # LATIN CAPITAL LETTER Y
0x005a: 0x005a, # LATIN CAPITAL LETTER Z
0x005b: 0x005b, # LEFT SQUARE BRACKET
0x005c: 0x005c, # REVERSE SOLIDUS
0x005d: 0x005d, # RIGHT SQUARE BRACKET
0x005e: 0x005e, # CIRCUMFLEX ACCENT
0x005f: 0x005f, # LOW LINE
0x0060: 0x0060, # GRAVE ACCENT
0x0061: 0x0061, # LATIN SMALL LETTER A
0x0062: 0x0062, # LATIN SMALL LETTER B
0x0063: 0x0063, # LATIN SMALL LETTER C
0x0064: 0x0064, # LATIN SMALL LETTER D
0x0065: 0x0065, # LATIN SMALL LETTER E
0x0066: 0x0066, # LATIN SMALL LETTER F
0x0067: 0x0067, # LATIN SMALL LETTER G
0x0068: 0x0068, # LATIN SMALL LETTER H
0x0069: 0x0069, # LATIN SMALL LETTER I
0x006a: 0x006a, # LATIN SMALL LETTER J
0x006b: 0x006b, # LATIN SMALL LETTER K
0x006c: 0x006c, # LATIN SMALL LETTER L
0x006d: 0x006d, # LATIN SMALL LETTER M
0x006e: 0x006e, # LATIN SMALL LETTER N
0x006f: 0x006f, # LATIN SMALL LETTER O
0x0070: 0x0070, # LATIN SMALL LETTER P
0x0071: 0x0071, # LATIN SMALL LETTER Q
0x0072: 0x0072, # LATIN SMALL LETTER R
0x0073: 0x0073, # LATIN SMALL LETTER S
0x0074: 0x0074, # LATIN SMALL LETTER T
0x0075: 0x0075, # LATIN SMALL LETTER U
0x0076: 0x0076, # LATIN SMALL LETTER V
0x0077: 0x0077, # LATIN SMALL LETTER W
0x0078: 0x0078, # LATIN SMALL LETTER X
0x0079: 0x0079, # LATIN SMALL LETTER Y
0x007a: 0x007a, # LATIN SMALL LETTER Z
0x007b: 0x007b, # LEFT CURLY BRACKET
0x007c: 0x007c, # VERTICAL LINE
0x007d: 0x007d, # RIGHT CURLY BRACKET
0x007e: 0x007e, # TILDE
0x007f: 0x007f, # DELETE
0x00a0: 0x00ff, # NO-BREAK SPACE
0x00a2: 0x0096, # CENT SIGN
0x00a3: 0x009c, # POUND SIGN
0x00a4: 0x009f, # CURRENCY SIGN
0x00a6: 0x00a7, # BROKEN BAR
0x00a7: 0x00f5, # SECTION SIGN
0x00a9: 0x00a8, # COPYRIGHT SIGN
0x00ab: 0x00ae, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00ac: 0x00aa, # NOT SIGN
0x00ad: 0x00f0, # SOFT HYPHEN
0x00ae: 0x00a9, # REGISTERED SIGN
0x00b0: 0x00f8, # DEGREE SIGN
0x00b1: 0x00f1, # PLUS-MINUS SIGN
0x00b2: 0x00fd, # SUPERSCRIPT TWO
0x00b3: 0x00fc, # SUPERSCRIPT THREE
0x00b5: 0x00e6, # MICRO SIGN
0x00b6: 0x00f4, # PILCROW SIGN
0x00b7: 0x00fa, # MIDDLE DOT
0x00b9: 0x00fb, # SUPERSCRIPT ONE
0x00bb: 0x00af, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00bc: 0x00ac, # VULGAR FRACTION ONE QUARTER
0x00bd: 0x00ab, # VULGAR FRACTION ONE HALF
0x00be: 0x00f3, # VULGAR FRACTION THREE QUARTERS
0x00c4: 0x008e, # LATIN CAPITAL LETTER A WITH DIAERESIS
0x00c5: 0x008f, # LATIN CAPITAL LETTER A WITH RING ABOVE
0x00c6: 0x0092, # LATIN CAPITAL LIGATURE AE
0x00c9: 0x0090, # LATIN CAPITAL LETTER E WITH ACUTE
0x00d3: 0x00e0, # LATIN CAPITAL LETTER O WITH ACUTE
0x00d5: 0x00e5, # LATIN CAPITAL LETTER O WITH TILDE
0x00d6: 0x0099, # LATIN CAPITAL LETTER O WITH DIAERESIS
0x00d7: 0x009e, # MULTIPLICATION SIGN
0x00d8: 0x009d, # LATIN CAPITAL LETTER O WITH STROKE
0x00dc: 0x009a, # LATIN CAPITAL LETTER U WITH DIAERESIS
0x00df: 0x00e1, # LATIN SMALL LETTER SHARP S (GERMAN)
0x00e4: 0x0084, # LATIN SMALL LETTER A WITH DIAERESIS
0x00e5: 0x0086, # LATIN SMALL LETTER A WITH RING ABOVE
0x00e6: 0x0091, # LATIN SMALL LIGATURE AE
0x00e9: 0x0082, # LATIN SMALL LETTER E WITH ACUTE
0x00f3: 0x00a2, # LATIN SMALL LETTER O WITH ACUTE
0x00f5: 0x00e4, # LATIN SMALL LETTER O WITH TILDE
0x00f6: 0x0094, # LATIN SMALL LETTER O WITH DIAERESIS
0x00f7: 0x00f6, # DIVISION SIGN
0x00f8: 0x009b, # LATIN SMALL LETTER O WITH STROKE
0x00fc: 0x0081, # LATIN SMALL LETTER U WITH DIAERESIS
0x0100: 0x00a0, # LATIN CAPITAL LETTER A WITH MACRON
0x0101: 0x0083, # LATIN SMALL LETTER A WITH MACRON
0x0104: 0x00b5, # LATIN CAPITAL LETTER A WITH OGONEK
0x0105: 0x00d0, # LATIN SMALL LETTER A WITH OGONEK
0x0106: 0x0080, # LATIN CAPITAL LETTER C WITH ACUTE
0x0107: 0x0087, # LATIN SMALL LETTER C WITH ACUTE
0x010c: 0x00b6, # LATIN CAPITAL LETTER C WITH CARON
0x010d: 0x00d1, # LATIN SMALL LETTER C WITH CARON
0x0112: 0x00ed, # LATIN CAPITAL LETTER E WITH MACRON
0x0113: 0x0089, # LATIN SMALL LETTER E WITH MACRON
0x0116: 0x00b8, # LATIN CAPITAL LETTER E WITH DOT ABOVE
0x0117: 0x00d3, # LATIN SMALL LETTER E WITH DOT ABOVE
0x0118: 0x00b7, # LATIN CAPITAL LETTER E WITH OGONEK
0x0119: 0x00d2, # LATIN SMALL LETTER E WITH OGONEK
0x0122: 0x0095, # LATIN CAPITAL LETTER G WITH CEDILLA
0x0123: 0x0085, # LATIN SMALL LETTER G WITH CEDILLA
0x012a: 0x00a1, # LATIN CAPITAL LETTER I WITH MACRON
0x012b: 0x008c, # LATIN SMALL LETTER I WITH MACRON
0x012e: 0x00bd, # LATIN CAPITAL LETTER I WITH OGONEK
0x012f: 0x00d4, # LATIN SMALL LETTER I WITH OGONEK
0x0136: 0x00e8, # LATIN CAPITAL LETTER K WITH CEDILLA
0x0137: 0x00e9, # LATIN SMALL LETTER K WITH CEDILLA
0x013b: 0x00ea, # LATIN CAPITAL LETTER L WITH CEDILLA
0x013c: 0x00eb, # LATIN SMALL LETTER L WITH CEDILLA
0x0141: 0x00ad, # LATIN CAPITAL LETTER L WITH STROKE
0x0142: 0x0088, # LATIN SMALL LETTER L WITH STROKE
0x0143: 0x00e3, # LATIN CAPITAL LETTER N WITH ACUTE
0x0144: 0x00e7, # LATIN SMALL LETTER N WITH ACUTE
0x0145: 0x00ee, # LATIN CAPITAL LETTER N WITH CEDILLA
0x0146: 0x00ec, # LATIN SMALL LETTER N WITH CEDILLA
0x014c: 0x00e2, # LATIN CAPITAL LETTER O WITH MACRON
0x014d: 0x0093, # LATIN SMALL LETTER O WITH MACRON
0x0156: 0x008a, # LATIN CAPITAL LETTER R WITH CEDILLA
0x0157: 0x008b, # LATIN SMALL LETTER R WITH CEDILLA
0x015a: 0x0097, # LATIN CAPITAL LETTER S WITH ACUTE
0x015b: 0x0098, # LATIN SMALL LETTER S WITH ACUTE
0x0160: 0x00be, # LATIN CAPITAL LETTER S WITH CARON
0x0161: 0x00d5, # LATIN SMALL LETTER S WITH CARON
0x016a: 0x00c7, # LATIN CAPITAL LETTER U WITH MACRON
0x016b: 0x00d7, # LATIN SMALL LETTER U WITH MACRON
0x0172: 0x00c6, # LATIN CAPITAL LETTER U WITH OGONEK
0x0173: 0x00d6, # LATIN SMALL LETTER U WITH OGONEK
0x0179: 0x008d, # LATIN CAPITAL LETTER Z WITH ACUTE
0x017a: 0x00a5, # LATIN SMALL LETTER Z WITH ACUTE
0x017b: 0x00a3, # LATIN CAPITAL LETTER Z WITH DOT ABOVE
0x017c: 0x00a4, # LATIN SMALL LETTER Z WITH DOT ABOVE
0x017d: 0x00cf, # LATIN CAPITAL LETTER Z WITH CARON
0x017e: 0x00d8, # LATIN SMALL LETTER Z WITH CARON
0x2019: 0x00ef, # RIGHT SINGLE QUOTATION MARK
0x201c: 0x00f2, # LEFT DOUBLE QUOTATION MARK
0x201d: 0x00a6, # RIGHT DOUBLE QUOTATION MARK
0x201e: 0x00f7, # DOUBLE LOW-9 QUOTATION MARK
0x2219: 0x00f9, # BULLET OPERATOR
0x2500: 0x00c4, # BOX DRAWINGS LIGHT HORIZONTAL
0x2502: 0x00b3, # BOX DRAWINGS LIGHT VERTICAL
0x250c: 0x00da, # BOX DRAWINGS LIGHT DOWN AND RIGHT
0x2510: 0x00bf, # BOX DRAWINGS LIGHT DOWN AND LEFT
0x2514: 0x00c0, # BOX DRAWINGS LIGHT UP AND RIGHT
0x2518: 0x00d9, # BOX DRAWINGS LIGHT UP AND LEFT
0x251c: 0x00c3, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT
0x2524: 0x00b4, # BOX DRAWINGS LIGHT VERTICAL AND LEFT
0x252c: 0x00c2, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
0x2534: 0x00c1, # BOX DRAWINGS LIGHT UP AND HORIZONTAL
0x253c: 0x00c5, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
0x2550: 0x00cd, # BOX DRAWINGS DOUBLE HORIZONTAL
0x2551: 0x00ba, # BOX DRAWINGS DOUBLE VERTICAL
0x2554: 0x00c9, # BOX DRAWINGS DOUBLE DOWN AND RIGHT
0x2557: 0x00bb, # BOX DRAWINGS DOUBLE DOWN AND LEFT
0x255a: 0x00c8, # BOX DRAWINGS DOUBLE UP AND RIGHT
0x255d: 0x00bc, # BOX DRAWINGS DOUBLE UP AND LEFT
0x2560: 0x00cc, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
0x2563: 0x00b9, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT
0x2566: 0x00cb, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
0x2569: 0x00ca, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL
0x256c: 0x00ce, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
0x2580: 0x00df, # UPPER HALF BLOCK
0x2584: 0x00dc, # LOWER HALF BLOCK
0x2588: 0x00db, # FULL BLOCK
0x258c: 0x00dd, # LEFT HALF BLOCK
0x2590: 0x00de, # RIGHT HALF BLOCK
0x2591: 0x00b0, # LIGHT SHADE
0x2592: 0x00b1, # MEDIUM SHADE
0x2593: 0x00b2, # DARK SHADE
0x25a0: 0x00fe, # BLACK SQUARE
}
| gpl-3.0 |
StephaneP/volatility | volatility/plugins/mac/arp.py | 58 | 1398 | # Volatility
# Copyright (C) 2007-2013 Volatility Foundation
#
# This file is part of Volatility.
#
# Volatility is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Volatility is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Volatility. If not, see <http://www.gnu.org/licenses/>.
#
"""
@author: Andrew Case
@license: GNU General Public License 2.0
@contact: [email protected]
@organization:
"""
import volatility.obj as obj
import volatility.plugins.mac.common as common
import volatility.plugins.mac.route as route
class mac_arp(route.mac_route):
""" Prints the arp table """
def calculate(self):
common.set_plugin_members(self)
arp_addr = self.addr_space.profile.get_symbol("_llinfo_arp")
ptr = obj.Object("Pointer", offset = arp_addr, vm = self.addr_space)
ent = ptr.dereference_as("llinfo_arp")
while ent:
yield ent.la_rt
ent = ent.la_le.le_next
| gpl-2.0 |
nicolashainaux/mathmaker | tests/00_libs/test_anglessets.py | 1 | 5684 | # -*- coding: utf-8 -*-
# Mathmaker creates automatically maths exercises sheets
# with their answers
# Copyright 2006-2017 Nicolas Hainaux <[email protected]>
# This file is part of Mathmaker.
# Mathmaker 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
# any later version.
# Mathmaker 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 Mathmaker; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
import pytest
from mathmaker.lib.tools.generators.anglessets import AnglesSetGenerator
@pytest.fixture()
def AG(): return AnglesSetGenerator()
def test_AnglesSetGenerator(AG):
"""Check normal use cases."""
AG.generate(codename='2_1', name='FLUOR',
labels=[(1, 36), (2, 40)], variant=0)
def test_1_1(AG):
"""Check 1_1 generation proceeds as expected."""
with pytest.raises(ValueError) as excinfo:
AG._1_1()
assert str(excinfo.value) == 'variant must be 0 (not \'None\')'
AG._1_1(variant=0, labels=[(1, 27), (1, 37)], name='FIVE',
subvariant_nb=1)
AG._1_1(variant=0, labels=[(1, 27), (1, 37)], name='FIVE',
subvariant_nb=2)
AG._1_1(variant=0, labels=[(1, 27), (1, 37)], name='FIVE',
subvariant_nb=3)
def test_1_1r(AG):
"""Check 1_1r generation proceeds as expected."""
with pytest.raises(ValueError) as excinfo:
AG._1_1r()
assert str(excinfo.value) == 'variant must be 0 or 1 (not \'None\')'
AG._1_1r(variant=0, labels=[(1, 27), (1, 90)], name='FIVE',
subvariant_nb=1)
AG._1_1r(variant=0, labels=[(1, 27), (1, 90)], name='FIVE',
subvariant_nb=2)
AG._1_1r(variant=0, labels=[(1, 27), (1, 90)], name='FIVE',
subvariant_nb=3)
AG._1_1r(variant=1, labels=[(1, 27), (1, 90)], name='FIVE',
subvariant_nb=1)
AG._1_1r(variant=1, labels=[(1, 27), (1, 90)], name='FIVE',
subvariant_nb=2)
AG._1_1r(variant=1, labels=[(1, 27), (1, 90)], name='FIVE',
subvariant_nb=3)
AG._1_1r(variant=1, labels=[(1, 27), (1, 90)], name='FIVE',
subvariant_nb=1, subtr_shapes=True)
AG._1_1r(variant=1, labels=[(1, 27), (1, 90)], name='FIVE',
subvariant_nb=2, subtr_shapes=True)
AG._1_1r(variant=1, labels=[(1, 27), (1, 90)], name='FIVE',
subvariant_nb=3, subtr_shapes=True)
def test_2(AG):
"""Check 2 generation proceeds as expected."""
with pytest.raises(ValueError) as excinfo:
AG._2()
assert str(excinfo.value) == 'variant must be 0 (not \'None\')'
AG._2(variant=0, labels=[(2, 27)], name='FIVE', subvariant_nb=1)
AG._2(variant=0, labels=[(2, 27)], name='FIVE', subvariant_nb=2)
AG._2(variant=0, labels=[(2, 27)], name='FIVE', subvariant_nb=3)
def test_1_1_1(AG):
"""Check 1_1_1 generation proceeds as expected."""
with pytest.raises(ValueError) as excinfo:
AG._1_1_1()
assert str(excinfo.value) == 'variant must be 0 (not \'None\')'
AG._1_1_1(variant=0, labels=[(1, 27), (1, 37), (1, 46)], name='FLUOR',
subvariant_nb=1)
AG._1_1_1(variant=0, labels=[(1, 27), (1, 37), (1, 46)], name='FLUOR',
subvariant_nb=2)
AG._1_1_1(variant=0, labels=[(1, 27), (1, 37), (1, 46)], name='FLUOR',
subvariant_nb=3)
def test_1_1_1r(AG):
"""Check 1_1_1r generation proceeds as expected."""
with pytest.raises(ValueError) as excinfo:
AG._1_1_1r()
assert str(excinfo.value) == "variant must be in [0, 1, 2] (found 'None')"
AG._1_1_1r(variant=0, labels=[(1, 27), (1, 37), (1, 90)], name='FLUOR',
subvariant_nb=1)
AG._1_1_1r(variant=1, labels=[(1, 27), (1, 37), (1, 90)], name='FLUOR',
subvariant_nb=1)
AG._1_1_1r(variant=2, labels=[(1, 27), (1, 37), (1, 90)], name='FLUOR',
subvariant_nb=1)
def test_2_1(AG):
"""Check 2_1 generation proceeds as expected."""
with pytest.raises(ValueError) as excinfo:
AG._2_1()
assert str(excinfo.value) == "variant must be in [0, 1, 2] (found 'None')"
AG._2_1(variant=0, labels=[(2, 27), (1, 37)], name='FLUOR',
subvariant_nb=1)
AG._2_1(variant=1, labels=[(2, 27), (1, 37)], name='FLUOR',
subvariant_nb=1)
AG._2_1(variant=2, labels=[(2, 27), (1, 37)], name='FLUOR',
subvariant_nb=1)
def test_2_1r(AG):
"""Check 2_1r generation proceeds as expected."""
with pytest.raises(ValueError) as excinfo:
AG._2_1r()
assert str(excinfo.value) == "variant must be in [0, 1, 2] (found 'None')"
AG._2_1r(variant=0, labels=[(2, 27), (1, 90)], name='FLUOR',
subvariant_nb=1)
AG._2_1r(variant=1, labels=[(2, 27), (1, 90)], name='FLUOR',
subvariant_nb=1)
AG._2_1r(variant=2, labels=[(2, 27), (1, 90)], name='FLUOR',
subvariant_nb=1)
def test_3(AG):
"""Check 3 generation proceeds as expected."""
with pytest.raises(ValueError) as excinfo:
AG._3()
assert str(excinfo.value) == 'variant must be 0 (not \'None\')'
AG._3(variant=0, labels=[(3, 27)], name='FLOPS', subvariant_nb=1)
AG._3(variant=0, labels=[(3, 27)], name='FLOPS', subvariant_nb=2)
AG._3(variant=0, labels=[(3, 27)], name='FLOPS', subvariant_nb=3)
| gpl-3.0 |
dvliman/jaikuengine | .google_appengine/lib/cherrypy/cherrypy/scaffold/__init__.py | 80 | 1859 | """<MyProject>, a CherryPy application.
Use this as a base for creating new CherryPy applications. When you want
to make a new app, copy and paste this folder to some other location
(maybe site-packages) and rename it to the name of your project,
then tweak as desired.
Even before any tweaking, this should serve a few demonstration pages.
Change to this directory and run:
../cherryd -c site.conf
"""
import cherrypy
from cherrypy import tools, url
import os
local_dir = os.path.join(os.getcwd(), os.path.dirname(__file__))
class Root:
_cp_config = {'tools.log_tracebacks.on': True,
}
def index(self):
return """<html>
<body>Try some <a href='%s?a=7'>other</a> path,
or a <a href='%s?n=14'>default</a> path.<br />
Or, just look at the pretty picture:<br />
<img src='%s' />
</body></html>""" % (url("other"), url("else"),
url("files/made_with_cherrypy_small.png"))
index.exposed = True
def default(self, *args, **kwargs):
return "args: %s kwargs: %s" % (args, kwargs)
default.exposed = True
def other(self, a=2, b='bananas', c=None):
cherrypy.response.headers['Content-Type'] = 'text/plain'
if c is None:
return "Have %d %s." % (int(a), b)
else:
return "Have %d %s, %s." % (int(a), b, c)
other.exposed = True
files = cherrypy.tools.staticdir.handler(
section="/files",
dir=os.path.join(local_dir, "static"),
# Ignore .php files, etc.
match=r'\.(css|gif|html?|ico|jpe?g|js|png|swf|xml)$',
)
root = Root()
# Uncomment the following to use your own favicon instead of CP's default.
#favicon_path = os.path.join(local_dir, "favicon.ico")
#root.favicon_ico = tools.staticfile.handler(filename=favicon_path)
| apache-2.0 |
davechallis/gensim | gensim/models/ldamulticore.py | 9 | 12566 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: Jan Zikes, Radim Rehurek
# Copyright (C) 2014 Radim Rehurek <[email protected]>
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""
Latent Dirichlet Allocation (LDA) in Python, using all CPU cores to parallelize and
speed up model training.
The parallelization uses multiprocessing; in case this doesn't work for you for
some reason, try the :class:`gensim.models.ldamodel.LdaModel` class which is an
equivalent, but more straightforward and single-core implementation.
The training algorithm:
* is **streamed**: training documents may come in sequentially, no random access required,
* runs in **constant memory** w.r.t. the number of documents: size of the
training corpus does not affect memory footprint, can process corpora larger than RAM
Wall-clock `performance on the English Wikipedia <http://radimrehurek.com/gensim/wiki.html>`_
(2G corpus positions, 3.5M documents, 100K features, 0.54G non-zero entries in the final
bag-of-words matrix), requesting 100 topics:
====================================================== ==============
algorithm training time
====================================================== ==============
LdaMulticore(workers=1) 2h30m
LdaMulticore(workers=2) 1h24m
LdaMulticore(workers=3) 1h6m
old LdaModel() 3h44m
simply iterating over input corpus = I/O overhead 20m
====================================================== ==============
(Measured on `this i7 server <http://www.hetzner.de/en/hosting/produkte_rootserver/ex40ssd>`_
with 4 physical cores, so that optimal `workers=3`, one less than the number of cores.)
This module allows both LDA model estimation from a training corpus and inference of topic
distribution on new, unseen documents. The model can also be updated with new documents
for online training.
The core estimation code is based on the `onlineldavb.py` script by M. Hoffman [1]_, see
**Hoffman, Blei, Bach: Online Learning for Latent Dirichlet Allocation, NIPS 2010.**
.. [1] http://www.cs.princeton.edu/~mdhoffma
"""
import logging
from gensim import utils
from gensim.models.ldamodel import LdaModel, LdaState
import six
from six.moves import queue, xrange
from multiprocessing import Pool, Queue, cpu_count
logger = logging.getLogger(__name__)
class LdaMulticore(LdaModel):
"""
The constructor estimates Latent Dirichlet Allocation model parameters based
on a training corpus:
>>> lda = LdaMulticore(corpus, num_topics=10)
You can then infer topic distributions on new, unseen documents, with
>>> doc_lda = lda[doc_bow]
The model can be updated (trained) with new documents via
>>> lda.update(other_corpus)
Model persistency is achieved through its `load`/`save` methods.
"""
def __init__(self, corpus=None, num_topics=100, id2word=None, workers=None,
chunksize=2000, passes=1, batch=False, alpha='symmetric',
eta=None, decay=0.5, offset=1.0, eval_every=10, iterations=50,
gamma_threshold=0.001):
"""
If given, start training from the iterable `corpus` straight away. If not given,
the model is left untrained (presumably because you want to call `update()` manually).
`num_topics` is the number of requested latent topics to be extracted from
the training corpus.
`id2word` is a mapping from word ids (integers) to words (strings). It is
used to determine the vocabulary size, as well as for debugging and topic
printing.
`workers` is the number of extra processes to use for parallelization. Uses
all available cores by default: `workers=cpu_count()-1`. **Note**: for
hyper-threaded CPUs, `cpu_count()` returns a useless number -- set `workers`
directly to the number of your **real** cores (not hyperthreads) minus one,
for optimal performance.
If `batch` is not set, perform online training by updating the model once
every `workers * chunksize` documents (online training). Otherwise,
run batch LDA, updating model only once at the end of each full corpus pass.
`alpha` and `eta` are hyperparameters that affect sparsity of the document-topic
(theta) and topic-word (lambda) distributions. Both default to a symmetric
1.0/num_topics prior.
`alpha` can be set to an explicit array = prior of your choice. It also
support special values of 'asymmetric' and 'auto': the former uses a fixed
normalized asymmetric 1.0/topicno prior, the latter learns an asymmetric
prior directly from your data.
`eta` can be a scalar for a symmetric prior over topic/word
distributions, or a matrix of shape num_topics x num_words,
which can be used to impose asymmetric priors over the word
distribution on a per-topic basis. This may be useful if you
want to seed certain topics with particular words by boosting
the priors for those words.
Calculate and log perplexity estimate from the latest mini-batch once every
`eval_every` documents. Set to `None` to disable perplexity estimation (faster),
or to `0` to only evaluate perplexity once, at the end of each corpus pass.
`decay` and `offset` parameters are the same as Kappa and Tau_0 in
Hoffman et al, respectively.
Example:
>>> lda = LdaMulticore(corpus, id2word=id2word, num_topics=100) # train model
>>> print(lda[doc_bow]) # get topic probability distribution for a document
>>> lda.update(corpus2) # update the LDA model with additional documents
>>> print(lda[doc_bow])
"""
self.workers = max(1, cpu_count() - 1) if workers is None else workers
self.batch = batch
if isinstance(alpha, six.string_types) and alpha == 'auto':
raise NotImplementedError("auto-tuning alpha not implemented in multicore LDA; use plain LdaModel.")
super(LdaMulticore, self).__init__(corpus=corpus, num_topics=num_topics,
id2word=id2word, chunksize=chunksize, passes=passes, alpha=alpha, eta=eta,
decay=decay, offset=offset, eval_every=eval_every, iterations=iterations,
gamma_threshold=gamma_threshold)
def update(self, corpus, chunks_as_numpy=False):
"""
Train the model with new documents, by EM-iterating over `corpus` until
the topics converge (or until the maximum number of allowed iterations
is reached). `corpus` must be an iterable (repeatable stream of documents),
The E-step is distributed into the several processes.
This update also supports updating an already trained model (`self`)
with new documents from `corpus`; the two models are then merged in
proportion to the number of old vs. new documents. This feature is still
experimental for non-stationary input streams.
For stationary input (no topic drift in new documents), on the other hand,
this equals the online update of Hoffman et al. and is guaranteed to
converge for any `decay` in (0.5, 1.0>.
"""
try:
lencorpus = len(corpus)
except:
logger.warning("input corpus stream has no len(); counting documents")
lencorpus = sum(1 for _ in corpus)
if lencorpus == 0:
logger.warning("LdaMulticore.update() called with an empty corpus")
return
self.state.numdocs += lencorpus
if not self.batch:
updatetype = "online"
updateafter = self.chunksize * self.workers
else:
updatetype = "batch"
updateafter = lencorpus
evalafter = min(lencorpus, (self.eval_every or 0) * updateafter)
updates_per_pass = max(1, lencorpus / updateafter)
logger.info("running %s LDA training, %s topics, %i passes over the"
" supplied corpus of %i documents, updating every %i documents,"
" evaluating every ~%i documents, iterating %ix with a convergence threshold of %f",
updatetype, self.num_topics, self.passes, lencorpus, updateafter, evalafter,
self.iterations, self.gamma_threshold)
if updates_per_pass * self.passes < 10:
logger.warning("too few updates, training might not converge; consider "
"increasing the number of passes or iterations to improve accuracy")
job_queue = Queue(maxsize=2 * self.workers)
result_queue = Queue()
# rho is the "speed" of updating; TODO try other fncs
# pass_ + num_updates handles increasing the starting t for each pass,
# while allowing it to "reset" on the first pass of each update
def rho():
return pow(self.offset + pass_ + (self.num_updates / self.chunksize), -self.decay)
logger.info("training LDA model using %i processes", self.workers)
pool = Pool(self.workers, worker_e_step, (job_queue, result_queue,))
for pass_ in xrange(self.passes):
queue_size, reallen = [0], 0
other = LdaState(self.eta, self.state.sstats.shape)
def process_result_queue(force=False):
"""
Clear the result queue, merging all intermediate results, and update the
LDA model if necessary.
"""
merged_new = False
while not result_queue.empty():
other.merge(result_queue.get())
queue_size[0] -= 1
merged_new = True
if (force and merged_new and queue_size[0] == 0) or (not self.batch and (other.numdocs >= updateafter)):
self.do_mstep(rho(), other, pass_ > 0)
other.reset()
if self.eval_every is not None and ((force and queue_size[0] == 0) or (self.eval_every != 0 and (self.num_updates / updateafter) % self.eval_every == 0)):
self.log_perplexity(chunk, total_docs=lencorpus)
chunk_stream = utils.grouper(corpus, self.chunksize, as_numpy=chunks_as_numpy)
for chunk_no, chunk in enumerate(chunk_stream):
reallen += len(chunk) # keep track of how many documents we've processed so far
# put the chunk into the workers' input job queue
chunk_put = False
while not chunk_put:
try:
job_queue.put((chunk_no, chunk, self), block=False, timeout=0.1)
chunk_put = True
queue_size[0] += 1
logger.info('PROGRESS: pass %i, dispatched chunk #%i = '
'documents up to #%i/%i, outstanding queue size %i',
pass_, chunk_no, chunk_no * self.chunksize + len(chunk), lencorpus, queue_size[0])
except queue.Full:
# in case the input job queue is full, keep clearing the
# result queue, to make sure we don't deadlock
process_result_queue()
process_result_queue()
#endfor single corpus pass
# wait for all outstanding jobs to finish
while queue_size[0] > 0:
process_result_queue(force=True)
if reallen != lencorpus:
raise RuntimeError("input corpus size changed during training (don't use generators as input)")
#endfor entire update
pool.terminate()
def worker_e_step(input_queue, result_queue):
"""
Perform E-step for each (chunk_no, chunk, model) 3-tuple from the
input queue, placing the resulting state into the result queue.
"""
logger.debug("worker process entering E-step loop")
while True:
logger.debug("getting a new job")
chunk_no, chunk, worker_lda = input_queue.get()
logger.debug("processing chunk #%i of %i documents", chunk_no, len(chunk))
worker_lda.state.reset()
worker_lda.do_estep(chunk) # TODO: auto-tune alpha?
del chunk
logger.debug("processed chunk, queuing the result")
result_queue.put(worker_lda.state)
del worker_lda # free up some memory
logger.debug("result put")
| lgpl-2.1 |
vgupta6/Project-2 | modules/tests/inv/helper.py | 2 | 16414 | __all__ = ["send",
"track_send_item",
"send_shipment",
"receive",
"track_recv_item",
"recv_shipment",
"recv_sent_shipment",
"send_rec",
"send_get_id",
"send_get_ref",
"recv_rec",
"recv_get_id",
"dbcallback_getStockLevels",
]
from gluon import current
from s3 import s3_debug
from tests.web2unittest import SeleniumUnitTest
class InvTestFunctions(SeleniumUnitTest):
def send(self, user, data):
"""
@case: INV
@description: Functions which runs specific workflows for Inventory tes
@TestDoc: https://docs.google.com/spreadsheet/ccc?key=0AmB3hMcgB-3idG1XNGhhRG9QWF81dUlKLXpJaFlCMFE
@Test Wiki: http://eden.sahanafoundation.org/wiki/DeveloperGuidelines/Testing
"""
print "\n"
"""
Helper method to add a inv_send record by the given user
"""
self.login(account=user, nexturl="inv/send/create")
table = "inv_send"
result = self.create(table, data)
s3_debug("WB reference: %s" % self.send_get_ref(result))
return result
# -------------------------------------------------------------------------
def track_send_item(self, user, send_id, data, removed=True):
"""
Helper method to add a track item to the inv_send with the
given send_id by the given user
"""
try:
add_btn = self.browser.find_element_by_id("show-add-btn")
if add_btn.is_displayed():
add_btn.click()
except:
pass
self.login(account=user, nexturl="inv/send/%s/track_item" % send_id)
table = "inv_track_item"
result = self.create(table, data, dbcallback = self.dbcallback_getStockLevels)
# Get the last record in the before & after
# this will give the stock record which has been added to the end by
# the getStockLevels callback
if removed:
qnty = 0
for line in data:
if line[0] == "quantity":
qnty = float(line[1])
break
stock_before = result["before"].records[len(result["before"])-1].quantity
stock_after = result["after"].records[len(result["after"])-1].quantity
stock_shipped = qnty
self.assertTrue( stock_before - stock_after == stock_shipped, "Warehouse stock not properly adjusted, was %s should be %s but is recorded as %s" % (stock_before, stock_after, stock_before - stock_shipped))
s3_debug ("Stock level before %s, stock level after %s" % (stock_before, stock_after))
return result
# -------------------------------------------------------------------------
def send_shipment(self, user, send_id):
"""
Helper method to send a shipment with id of send_id
"""
db = current.db
s3db = current.s3db
stable = s3db.inv_send
ititable = s3db.inv_track_item
# Get the current status
query = (stable.id == send_id)
record = db(query).select(stable.status,
limitby=(0, 1)).first()
send_status = record.status
query = (ititable.send_id == send_id)
item_records = db(query).select(ititable.status)
# check that the status is correct
self.assertTrue(send_status == 0, "Shipment is not status preparing")
s3_debug("Shipment status is: preparing")
for rec in item_records:
self.assertTrue(rec.status == 1, "Shipment item is not status preparing")
s3_debug("Shipment items are all of status: preparing")
# Now send the shipment on its way
self.login(account=user, nexturl="inv/send_process/%s" % send_id)
# Get the current status
query = (stable.id == send_id)
record = db(query).select(stable.status,
limitby=(0, 1)).first()
send_status = record.status
query = (ititable.send_id == send_id)
item_records = db(query).select(ititable.status)
# check that the status is correct
self.assertTrue(send_status == 2, "Shipment is not status sent")
s3_debug("Shipment status is: sent")
for rec in item_records:
self.assertTrue(rec.status == 2, "Shipment item is not status sent")
s3_debug("Shipment items are all of status: sent")
# -------------------------------------------------------------------------
def confirm_received_shipment(self, user, send_id):
"""
Helper method to confirm that a shipment has been received
outside of the system. This means that the items in the
shipment will not be recorded as being at a site but
the status of the shipment will be modified.
"""
db = current.db
s3db = current.s3db
stable = s3db.inv_send
ititable = s3db.inv_track_item
# Get the current status
query = (stable.id == send_id)
record = db(query).select(stable.status,
limitby=(0, 1)).first()
send_status = record.status
query = (ititable.send_id == send_id)
item_records = db(query).select(ititable.status)
# check that the status is correct
self.assertTrue(send_status == 2, "Shipment is not status sent")
s3_debug("Shipment status is: preparing")
for rec in item_records:
self.assertTrue(rec.status == 2, "Shipment item is not status sent")
s3_debug("Shipment items are all of status: sent")
# Now send the shipment on its way
self.login(account=user, nexturl="inv/send/%s?received=True" % send_id)
# Get the current status
query = (stable.id == send_id)
record = db(query).select(stable.status,
limitby=(0, 1)).first()
send_status = record.status
query = (ititable.send_id == send_id)
item_records = db(query).select(ititable.status)
# check that the status is correct
self.assertTrue(send_status == 1, "Shipment is not status received")
s3_debug("Shipment status is: sent")
for rec in item_records:
self.assertTrue(rec.status == 4, "Shipment item is not status arrived")
s3_debug("Shipment items are all of status: arrived")
# -------------------------------------------------------------------------
def receive(self, user, data):
"""
Helper method to add a inv_send record by the given user
"""
self.login(account=user, nexturl="inv/recv/create")
table = "inv_recv"
result = self.create(table, data)
return result
# -------------------------------------------------------------------------
def track_recv_item(self, user, recv_id, data, removed=True):
"""
Helper method to add a track item to the inv_recv with the
given recv_id
"""
try:
add_btn = self.browser.find_element_by_id("show-add-btn")
if add_btn.is_displayed():
add_btn.click()
except:
pass
self.login(account=user, nexturl="inv/recv/%s/track_item" % recv_id)
table = "inv_track_item"
result = self.create(table, data)
return result
# -------------------------------------------------------------------------
def recv_shipment(self, user, recv_id, data):
"""
Helper method that will receive the shipment, adding the
totals that arrived
It will get the stock in the warehouse before and then after
and check that the stock levels have been properly increased
"""
db = current.db
s3db = current.s3db
rvtable = s3db.inv_recv
iitable = s3db.inv_inv_item
# First get the site_id
query = (rvtable.id == recv_id)
record = db(query).select(rvtable.site_id,
limitby=(0, 1)).first()
site_id = record.site_id
# Now get all the inventory items for the site
query = (iitable.site_id == site_id)
before = db(query).select(orderby=iitable.id)
self.login(account=user, nexturl="inv/recv_process/%s" % recv_id)
query = (iitable.site_id == site_id)
after = db(query).select(orderby=iitable.id)
# Find the differences between the before and the after
changes = []
for a_rec in after:
found = False
for b_rec in before:
if a_rec.id == b_rec.id:
if a_rec.quantity != b_rec.quantity:
changes.append(
(a_rec.item_id,
a_rec.item_pack_id,
a_rec.quantity - b_rec.quantity)
)
found = True
break
if not found:
changes.append(
(a_rec.item_id,
a_rec.item_pack_id,
a_rec.quantity)
)
# changes now contains the list of changed or new records
# these should match the records received
# first check are the lengths the same?
self.assertTrue(len(data) == len(changes),
"The number of changed inventory items (%s) doesn't match the number of items received (%s)." %
(len(changes), len(data))
)
for line in data:
rec = line["record"]
found = False
for change in changes:
if rec.inv_track_item.item_id == change[0] and \
rec.inv_track_item.item_pack_id == change[1] and \
rec.inv_track_item.quantity == change[2]:
found = True
break
if found:
s3_debug("%s accounted for." % line["text"])
else:
s3_debug("%s not accounted for." % line["text"])
# -------------------------------------------------------------------------
def recv_sent_shipment(self, method, user, WB_ref, item_list):
"""
Helper method that will receive the sent shipment.
This supports two methods:
method = "warehouse"
====================
This requires going to the receiving warehouse
Selecting the shipment (using the WB reference)
Opening each item and selecting the received totals
Then receive the shipment
method = "search"
====================
Search for all received shipments
Select the matching WB reference
Opening each item and selecting the received totals
Then receive the shipment
Finally:
It will get the stock in the warehouse before and then after
and check that the stock levels have been properly increased
"""
browser = self.browser
if method == "search":
self.login(account=user, nexturl="inv/recv/search")
# Find the WB reference in the dataTable (filter so only one is displayed)
el = browser.find_element_by_id("recv_search_simple")
el.send_keys(WB_ref)
# Submit the search
browser.find_element_by_css_selector("input[type='submit']").submit()
# Select the only row in the dataTable
if not self.dt_action():
fail("Unable to select the incoming shipment with reference %s" % WB_ref)
elif method == "warehouse":
return # not yet implemented
else:
fail("Unknown method of %s" % method)
return # invalid method
#####################################################
# We are now viewing the details of the receive item
#####################################################
# Now get the recv id from the url
url = browser.current_url
url_parts = url.split("/")
try:
recv_id = int(url_parts[-1])
except:
recv_id = int(url_parts[-2])
# Click on the items tab
self.login(account=user, nexturl="inv/recv/%s/track_item" % recv_id)
data = []
for item in item_list:
# Find the item in the dataTable
self.dt_filter(item[0])
self.dt_action()
el = browser.find_element_by_id("inv_track_item_recv_quantity")
el.send_keys(item[1])
text = "%s %s" % (item[1], item[0])
data.append({"text" : text,
"record" : item[2]})
# Save the form
browser.find_element_by_css_selector("input[type='submit']").submit()
# Now receive the shipment and check the totals
self.recv_shipment(user, recv_id, data)
# -------------------------------------------------------------------------
# Functions which extract data from the create results
#
def send_rec(self, result):
"""
Simple helper function to get the newly created inv_send row
"""
# The newly created inv_send will be the first record in the "after" list
if len(result["after"]) > 0:
new_inv_send = result["after"].records[0]
return new_inv_send.inv_send
return None
def send_get_id(self, result):
"""
Simple helper function to get the record id of the newly
created inv_send row so it can be used to open the record
"""
# The newly created inv_send will be the first record in the "after" list
if len(result["after"]) > 0:
new_inv_send = result["after"].records[0]
return new_inv_send.inv_send.id
return None
def send_get_ref(self, result):
"""
Simple helper function to get the waybill reference of the newly
created inv_send row so it can be used to filter dataTables
"""
# The newly created inv_send will be the first record in the "after" list
if len(result["after"]) > 0:
new_inv_send = result["after"].records[0]
return new_inv_send.inv_send.send_ref
return None
# -------------------------------------------------------------------------
def recv_rec(self, result):
"""
Simple helper function to get the newly created inv_recv row
"""
# The newly created inv_recv will be the first record in the "after" list
if len(result["after"]) > 0:
new_inv_recv = result["after"].records[0]
return new_inv_recv.inv_recv
return None
# -------------------------------------------------------------------------
def recv_get_id(self, result):
"""
Simple helper function to get the record id of the newly
created inv_recv row so it can be used to open the record
"""
# The newly created inv_recv will be the first record in the "after" list
if len(result["after"]) > 0:
new_inv_recv = result["after"].records[0]
return new_inv_recv.inv_recv.id
return None
# -------------------------------------------------------------------------
# Callback used to retrieve additional data to the create results
#
def dbcallback_getStockLevels(self, table, data, rows):
"""
Callback to add the total in stock for the selected item.
This can then be used to look at the value before and after
to ensure that the totals have been removed from the warehouse.
The stock row will be added to the *end* of the list of rows
"""
table = current.s3db["inv_inv_item"]
for details in data:
if details[0] == "send_inv_item_id":
inv_item_id = details[1]
break
stock_row = table[inv_item_id]
rows.records.append(stock_row)
return rows
# END =========================================================================
| mit |
Pike/elmo | apps/shipping/forms.py | 2 | 1261 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from __future__ import absolute_import
from __future__ import unicode_literals
from django import forms
from shipping.models import AppVersion
class ModelInstanceField(forms.fields.Field):
def __init__(self, model, key='pk', *args, **kwargs):
self.model = model
self.key = key
self._instance = None
super(ModelInstanceField, self).__init__(*args, **kwargs)
def to_python(self, value):
"return the model instance if a value is supplied"
if value:
try:
return self.model.objects.get(**{self.key: value})
except self.model.DoesNotExist:
raise forms.ValidationError(self.model._meta.verbose_name)
class SignoffFilterForm(forms.Form):
av = ModelInstanceField(AppVersion, key='code')
up_until = forms.fields.DateTimeField(required=False)
class SignoffsPaginationForm(forms.Form):
push_date = forms.DateTimeField(
input_formats=forms.DateTimeField.input_formats + [
'%Y-%m-%dT%H:%M:%S', # isoformat
]
)
| mpl-2.0 |
Creworker/FreeCAD | src/Mod/OpenSCAD/colorcodeshapes.py | 29 | 4659 | #***************************************************************************
#* *
#* Copyright (c) 2012 Sebastian Hoogen <[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 *
#* *
#***************************************************************************
__title__="FreeCAD OpenSCAD Workbench - 2D helper fuctions"
__author__ = "Sebastian Hoogen"
__url__ = ["http://www.freecadweb.org"]
'''
This Script includes python functions to find out the most basic shape type
in a compound and to change the color of shapes according to their shape type
'''
import FreeCAD
def shapedict(shapelst):
return dict([(shape.hashCode(),shape) for shape in shapelst])
def shapeset(shapelst):
return set([shape.hashCode() for shape in shapelst])
def mostbasiccompound(comp):
'''searches fo the most basic shape in a Compound'''
solids=shapeset(comp.Solids)
shells=shapeset(comp.Shells)
faces=shapeset(comp.Faces)
wires=shapeset(comp.Wires)
edges=shapeset(comp.Edges)
vertexes=shapeset(comp.Vertexes)
#FreeCAD.Console.PrintMessage('%s\n' % (str((len(solids),len(shells),len(faces),len(wires),len(edges),len(vertexes)))))
for shape in comp.Solids:
shells -= shapeset(shape.Shells)
faces -= shapeset(shape.Faces)
wires -= shapeset(shape.Wires)
edges -= shapeset(shape.Edges)
vertexes -= shapeset(shape.Vertexes)
for shape in comp.Shells:
faces -= shapeset(shape.Faces)
wires -= shapeset(shape.Wires)
edges -= shapeset(shape.Edges)
vertexes -= shapeset(shape.Vertexes)
for shape in comp.Faces:
wires -= shapeset(shape.Wires)
edges -= shapeset(shape.Edges)
vertexes -= shapeset(shape.Vertexes)
for shape in comp.Wires:
edges -= shapeset(shape.Edges)
vertexes -= shapeset(shape.Vertexes)
for shape in comp.Edges:
vertexes -= shapeset(shape.Vertexes)
#FreeCAD.Console.PrintMessage('%s\n' % (str((len(solids),len(shells),len(faces),len(wires),len(edges),len(vertexes)))))
#return len(solids),len(shells),len(faces),len(wires),len(edges),len(vertexes)
if vertexes:
return "Vertex"
elif edges:
return "Edge"
elif wires:
return "Wire"
elif faces:
return "Face"
elif shells:
return "Shell"
elif solids:
return "Solid"
def colorcodeshapes(objs):
shapecolors={
"Compound":(0.3,0.3,0.4),
"CompSolid":(0.1,0.5,0.0),
"Solid":(0.0,0.8,0.0),
"Shell":(0.8,0.0,0.0),
"Face":(0.6,0.6,0.0),
"Wire":(0.1,0.1,0.1),
"Edge":(1.0,1.0,1.0),
"Vertex":(8.0,8.0,8.0),
"Shape":(0.0,0.0,1.0),
None:(0.0,0.0,0.0)}
for obj in objs:
if hasattr(obj,'Shape'):
try:
if obj.Shape.isNull():
continue
if not obj.Shape.isValid():
color=(1.0,0.4,0.4)
else:
st=obj.Shape.ShapeType
if st in ["Compound","CompSolid"]:
st = mostbasiccompound(obj.Shape)
color=shapecolors[st]
obj.ViewObject.ShapeColor = color
except:
raise
#colorcodeshapes(App.ActiveDocument.Objects)
| lgpl-2.1 |
Sw4T/Warband-Development | mb_warband_module_system_1166/Module_system 1.166/module_game_menus.py | 1 | 622820 | from compiler import *
####################################################################################################################
# (menu-id, menu-flags, menu_text, mesh-name, [<operations>], [<options>]),
#
# Each game menu is a tuple that contains the following fields:
#
# 1) Game-menu id (string): used for referencing game-menus in other files.
# The prefix menu_ is automatically added before each game-menu-id
#
# 2) Game-menu flags (int). See header_game_menus.py for a list of available flags.
# You can also specify menu text color here, with the menu_text_color macro
# 3) Game-menu text (string).
# 4) mesh-name (string). Not currently used. Must be the string "none"
# 5) Operations block (list). A list of operations. See header_operations.py for reference.
# The operations block is executed when the game menu is activated.
# 6) List of Menu options (List).
# Each menu-option record is a tuple containing the following fields:
# 6.1) Menu-option-id (string) used for referencing game-menus in other files.
# The prefix mno_ is automatically added before each menu-option.
# 6.2) Conditions block (list). This must be a valid operation block. See header_operations.py for reference.
# The conditions are executed for each menu option to decide whether the option will be shown to the player or not.
# 6.3) Menu-option text (string).
# 6.4) Consequences block (list). This must be a valid operation block. See header_operations.py for reference.
# The consequences are executed for the menu option that has been selected by the player.
#
#
# Note: The first Menu is the initial character creation menu.
####################################################################################################################
game_menus = [
("start_game_0",menu_text_color(0xFF000000)|mnf_disable_all_keys,
"Welcome, adventurer, to Mount and Blade: Warband. Before beginning the game you must create your character. Remember that in the traditional medieval society depicted in the game, war and politics are usually dominated by male members of the nobility. That does not however mean that you should not choose to play a female character, or one who is not of noble birth. Male nobles may have a somewhat easier start, but women and commoners can attain all of the same goals -- and in fact may have a much more interesting if more challenging early game.",
"none",
[],
[
("continue",[],"Continue...",
[(jump_to_menu, "mnu_start_game_1"),
]
),
("go_back",[],"Go back",
[
(change_screen_quit),
]),
]
),
("start_phase_2",mnf_disable_all_keys,
"You hear about Calradia, a land torn between rival kingdoms battling each other for supremacy,\
a haven for knights and mercenaries, cutthroats and adventurers, all willing to risk their lives in pursuit of fortune, power, or glory...\
In this land which holds great dangers and even greater opportunities, you believe you may leave your past behind and start a new life.\
You feel that finally, you hold the key of your destiny in your hands, free to choose as you will,\
and that whatever course you take, great adventures will await you. Drawn by the stories you hear about Calradia and its kingdoms, you...",
"none",
[],
[
("town_1",[(eq, "$current_startup_quest_phase", 0),],"join a caravan to Praven, in the Kingdom of Swadia.",
[
(assign, "$current_town", "p_town_6"),
(assign, "$g_starting_town", "$current_town"),
(assign, "$g_journey_string", "str_journey_to_praven"),
(jump_to_menu, "mnu_start_phase_2_5"),
# (party_relocate_near_party, "p_main_party", "$g_starting_town", 2),
# (change_screen_return),
]),
("town_2",[(eq, "$current_startup_quest_phase", 0),],"join a caravan to Reyvadin, in the Kingdom of the Vaegirs.",
[
(assign, "$current_town", "p_town_8"),
(assign, "$g_starting_town", "$current_town"),
(assign, "$g_journey_string", "str_journey_to_reyvadin"),
(jump_to_menu, "mnu_start_phase_2_5"),
# (party_relocate_near_party, "p_main_party", "$g_starting_town", 2),
# (change_screen_return),
]),
("town_3",[(eq, "$current_startup_quest_phase", 0),],"join a caravan to Tulga, in the Khergit Khanate.",
[
(assign, "$current_town", "p_town_10"),
(assign, "$g_starting_town", "$current_town"),
(assign, "$g_journey_string", "str_journey_to_tulga"),
(jump_to_menu, "mnu_start_phase_2_5"),
# (party_relocate_near_party, "p_main_party", "$g_starting_town", 2),
# (change_screen_return),
]),
("town_4",[(eq, "$current_startup_quest_phase", 0),],"take a ship to Sargoth, in the Kingdom of the Nords.",
[
(assign, "$current_town", "p_town_1"),
(assign, "$g_starting_town", "$current_town"),
(assign, "$g_journey_string", "str_journey_to_sargoth"),
(jump_to_menu, "mnu_start_phase_2_5"),
# (party_relocate_near_party, "p_main_party", "$g_starting_town", 2),
# (change_screen_return),
]),
("town_5",[(eq, "$current_startup_quest_phase", 0),],"take a ship to Jelkala, in the Kingdom of the Rhodoks.",
[
(assign, "$current_town", "p_town_5"),
(assign, "$g_starting_town", "$current_town"),
(assign, "$g_journey_string", "str_journey_to_jelkala"),
(jump_to_menu, "mnu_start_phase_2_5"),
# (party_relocate_near_party, "p_main_party", "$g_starting_town", 2),
# (change_screen_return),
]),
("town_6",[(eq, "$current_startup_quest_phase", 0),],"join a caravan to Shariz, in the Sarranid Sultanate.",
[
(assign, "$current_town", "p_town_19"),
(assign, "$g_starting_town", "$current_town"),
(assign, "$g_journey_string", "str_journey_to_shariz"),
(jump_to_menu, "mnu_start_phase_2_5"),
# (party_relocate_near_party, "p_main_party", "$g_starting_town", 2),
# (change_screen_return),
]),
("tutorial_cheat",[(eq,1,0)],"{!}CHEAT!",
[
(change_screen_return),
(assign, "$cheat_mode", 1),
(set_show_messages, 0),
(add_xp_to_troop, 15000, "trp_player"),
(troop_raise_skill, "trp_player", skl_leadership, 7),
(troop_raise_skill, "trp_player", skl_prisoner_management, 5),
(troop_raise_skill, "trp_player", skl_inventory_management, 10),
(party_add_members, "p_main_party", "trp_swadian_knight", 10),
(party_add_members, "p_main_party", "trp_vaegir_knight", 10),
(party_add_members, "p_main_party", "trp_vaegir_archer", 10),
(party_add_members, "p_main_party", "trp_swadian_sharpshooter", 10),
(troop_add_item, "trp_player","itm_scale_armor",0),
(troop_add_item, "trp_player","itm_full_helm",0),
(troop_add_item, "trp_player","itm_hafted_blade_b",0),
(troop_add_item, "trp_player","itm_hafted_blade_a",0),
(troop_add_item, "trp_player","itm_morningstar",0),
(troop_add_item, "trp_player","itm_tutorial_spear",0),
(troop_add_item, "trp_player","itm_tutorial_staff",0),
(troop_add_item, "trp_player","itm_tutorial_staff_no_attack",0),
(troop_add_item, "trp_player","itm_arena_lance",0),
(troop_add_item, "trp_player","itm_practice_staff",0),
(troop_add_item, "trp_player","itm_practice_lance",0),
(troop_add_item, "trp_player","itm_practice_javelin",0),
(troop_add_item, "trp_player","itm_scythe",0),
(troop_add_item, "trp_player","itm_pitch_fork",0),
(troop_add_item, "trp_player","itm_military_fork",0),
(troop_add_item, "trp_player","itm_battle_fork",0),
(troop_add_item, "trp_player","itm_boar_spear",0),
(troop_add_item, "trp_player","itm_jousting_lance",0),
(troop_add_item, "trp_player","itm_double_sided_lance",0),
(troop_add_item, "trp_player","itm_glaive",0),
(troop_add_item, "trp_player","itm_poleaxe",0),
(troop_add_item, "trp_player","itm_polehammer",0),
(troop_add_item, "trp_player","itm_staff",0),
(troop_add_item, "trp_player","itm_quarter_staff",0),
(troop_add_item, "trp_player","itm_iron_staff",0),
(troop_add_item, "trp_player","itm_shortened_spear",0),
(troop_add_item, "trp_player","itm_spear",0),
(troop_add_item, "trp_player","itm_war_spear",0),
(troop_add_item, "trp_player","itm_military_scythe",0),
(troop_add_item, "trp_player","itm_light_lance",0),
(troop_add_item, "trp_player","itm_lance",0),
(troop_add_item, "trp_player","itm_heavy_lance",0),
(troop_add_item, "trp_player","itm_great_lance",0),
(troop_add_item, "trp_player","itm_pike",0),
(troop_add_item, "trp_player","itm_ashwood_pike",0),
(troop_add_item, "trp_player","itm_awlpike",0),
(troop_add_item, "trp_player","itm_throwing_spears",0),
(troop_add_item, "trp_player","itm_javelin",0),
(troop_add_item, "trp_player","itm_jarid",0),
(troop_add_item, "trp_player","itm_long_axe_b",0),
(set_show_messages, 1),
(try_for_range, ":cur_place", scenes_begin, scenes_end),
(scene_set_slot, ":cur_place", slot_scene_visited, 1),
(try_end),
(call_script, "script_get_player_party_morale_values"),
(party_set_morale, "p_main_party", reg0),
]
),
]
),
(
"start_game_3",mnf_disable_all_keys,
"Choose your scenario:",
"none",
[
(assign, "$g_custom_battle_scenario", 0),
(assign, "$g_custom_battle_scenario", "$g_custom_battle_scenario"),
## #Default banners
## (troop_set_slot, "trp_banner_background_color_array", 126, 0xFF212221),
## (troop_set_slot, "trp_banner_background_color_array", 127, 0xFF212221),
## (troop_set_slot, "trp_banner_background_color_array", 128, 0xFF2E3B10),
## (troop_set_slot, "trp_banner_background_color_array", 129, 0xFF425D7B),
## (troop_set_slot, "trp_banner_background_color_array", 130, 0xFF394608),
],
[
## ("custom_battle_scenario_1",[], "Skirmish 1",
## [
## (assign, "$g_custom_battle_scenario", 0),
## (jump_to_menu, "mnu_custom_battle_2"),
##
## ]
## ),
#### ("custom_battle_scenario_2",[],"Siege Attack 1",
#### [
#### (assign, "$g_custom_battle_scenario", 1),
#### (jump_to_menu, "mnu_custom_battle_2"),
####
#### ]
#### ),
## ("custom_battle_scenario_3",[],"Skirmish 2",
## [
## (assign, "$g_custom_battle_scenario", 1),
## (jump_to_menu, "mnu_custom_battle_2"),
##
## ]
## ),
## ("custom_battle_scenario_4",[],"Siege Defense",
## [
## (assign, "$g_custom_battle_scenario", 2),
## (jump_to_menu, "mnu_custom_battle_2"),
## ]
## ),
## ("custom_battle_scenario_5",[],"Skirmish 3",
## [
## (assign, "$g_custom_battle_scenario", 3),
## (jump_to_menu, "mnu_custom_battle_2"),
## ]
## ),
## ("custom_battle_scenario_6",[],"Siege Attack",
## [
## (assign, "$g_custom_battle_scenario", 4),
## (jump_to_menu, "mnu_custom_battle_2"),
##
## ]
## ),
("go_back",[],"Go back",
[(change_screen_quit),
]
),
]
),
## ("start_game_3",mnf_disable_all_keys,
## "Choose your scenario:",
## "none",
## [
## (assign, "$g_custom_battle_scenario", 0),
## (assign, "$g_custom_battle_scenario", "$g_custom_battle_scenario"),
#### #Default banners
#### (troop_set_slot, "trp_banner_background_color_array", 126, 0xFF212221),
#### (troop_set_slot, "trp_banner_background_color_array", 127, 0xFF212221),
#### (troop_set_slot, "trp_banner_background_color_array", 128, 0xFF2E3B10),
#### (troop_set_slot, "trp_banner_background_color_array", 129, 0xFF425D7B),
#### (troop_set_slot, "trp_banner_background_color_array", 130, 0xFF394608),
## ],
## [
#### ("custom_battle_scenario_1",[], "Skirmish 1",
#### [
#### (assign, "$g_custom_battle_scenario", 0),
#### (jump_to_menu, "mnu_custom_battle_2"),
####
#### ]
#### ),
###### ("custom_battle_scenario_2",[],"Siege Attack 1",
###### [
###### (assign, "$g_custom_battle_scenario", 1),
###### (jump_to_menu, "mnu_custom_battle_2"),
######
###### ]
###### ),
#### ("custom_battle_scenario_3",[],"Skirmish 2",
#### [
#### (assign, "$g_custom_battle_scenario", 1),
#### (jump_to_menu, "mnu_custom_battle_2"),
####
#### ]
#### ),
#### ("custom_battle_scenario_4",[],"Siege Defense",
#### [
#### (assign, "$g_custom_battle_scenario", 2),
#### (jump_to_menu, "mnu_custom_battle_2"),
#### ]
#### ),
#### ("custom_battle_scenario_5",[],"Skirmish 3",
#### [
#### (assign, "$g_custom_battle_scenario", 3),
#### (jump_to_menu, "mnu_custom_battle_2"),
#### ]
#### ),
#### ("custom_battle_scenario_6",[],"Siege Attack",
#### [
#### (assign, "$g_custom_battle_scenario", 4),
#### (jump_to_menu, "mnu_custom_battle_2"),
####
#### ]
#### ),
## ("go_back",[],"Go back",
## [(change_screen_quit),
## ]
## ),
## ]
## ),
(
"tutorial",mnf_disable_all_keys,
"You approach a field where the locals are training with weapons. You can practice here to improve your combat skills.",
"none",
[
(try_begin),
(eq, "$g_tutorial_entered", 1),
(change_screen_quit),
(else_try),
(set_passage_menu, "mnu_tutorial"),
## (try_begin),
## (eq, "$tutorial_1_finished", 1),
## (str_store_string, s1, "str_finished"),
## (else_try),
## (str_store_string, s1, "str_empty_string"),
## (try_end),
## (try_begin),
## (eq, "$tutorial_2_finished", 1),
## (str_store_string, s2, "str_finished"),
## (else_try),
## (str_store_string, s2, "str_empty_string"),
## (try_end),
## (try_begin),
## (eq, "$tutorial_3_finished", 1),
## (str_store_string, s3, "str_finished"),
## (else_try),
## (str_store_string, s3, "str_empty_string"),
## (try_end),
## (try_begin),
## (eq, "$tutorial_4_finished", 1),
## (str_store_string, s4, "str_finished"),
## (else_try),
## (str_store_string, s4, "str_empty_string"),
## (try_end),
## (try_begin),
## (eq, "$tutorial_5_finished", 1),
## (str_store_string, s5, "str_finished"),
## (else_try),
## (str_store_string, s5, "str_empty_string"),
## (try_end),
(assign, "$g_tutorial_entered", 1),
(try_end),
],
[
## ("tutorial_1",
## [(eq,1,0),],
## "Tutorial #1: Basic movement and weapon selection. {s1}",
## [
## #(modify_visitors_at_site,"scn_tutorial_1"),(reset_visitors,0),
#### (set_jump_mission,"mt_tutorial_1"),
#### (jump_to_scene,"scn_tutorial_1"),(change_screen_mission)]),
## ]),
##
## ("tutorial_2",[(eq,1,0),],"Tutorial #2: Fighting with a shield. {s2}",[
#### (modify_visitors_at_site,"scn_tutorial_2"),(reset_visitors,0),
#### (set_visitor,1,"trp_tutorial_maceman"),
#### (set_visitor,2,"trp_tutorial_archer"),
#### (set_jump_mission,"mt_tutorial_2"),
#### (jump_to_scene,"scn_tutorial_2"),(change_screen_mission)]),
## (modify_visitors_at_site,"scn_tutorial_training_ground"),
## (reset_visitors, 0),
## (set_player_troop, "trp_player"),
## (set_visitor,0,"trp_player"),
## (set_jump_mission,"mt_ai_training"),
## (jump_to_scene,"scn_tutorial_training_ground"),
## (change_screen_mission)]),
##
## ("tutorial_3",[(eq,1,0),],"Tutorial #3: Fighting without a shield. {s3}",[
## (modify_visitors_at_site,"scn_tutorial_3"),(reset_visitors,0),
## (set_visitor,1,"trp_tutorial_maceman"),
## (set_visitor,2,"trp_tutorial_swordsman"),
## (set_jump_mission,"mt_tutorial_3"),
## (jump_to_scene,"scn_tutorial_3"),(change_screen_mission)]),
## ("tutorial_3b",[(eq,0,1)],"Tutorial 3 b",[(try_begin),
## (ge, "$tutorial_3_state", 12),
## (modify_visitors_at_site,"scn_tutorial_3"),(reset_visitors,0),
## (set_visitor,1,"trp_tutorial_maceman"),
## (set_visitor,2,"trp_tutorial_swordsman"),
## (set_jump_mission,"mt_tutorial_3_2"),
## (jump_to_scene,"scn_tutorial_3"),
## (change_screen_mission),
## (else_try),
## (display_message,"str_door_locked",0xFFFFAAAA),
## (try_end)], "Next level"),
## ("tutorial_4",[(eq,1,0),],"Tutorial #4: Riding a horse. {s4}",[
## (modify_visitors_at_site,"scn_tutorial_training_ground"),
## (reset_visitors, 0),
## (set_player_troop, "trp_player"),
## (assign, "$g_player_troop", "trp_player"),
## (troop_raise_attribute, "$g_player_troop", ca_strength, 12),
## (troop_raise_attribute, "$g_player_troop", ca_agility, 9),
## (troop_raise_attribute, "$g_player_troop", ca_charisma, 5),
## (troop_raise_skill, "$g_player_troop", skl_shield, 3),
## (troop_raise_skill, "$g_player_troop", skl_athletics, 2),
## (troop_raise_skill, "$g_player_troop", skl_riding, 3),
## (troop_raise_skill, "$g_player_troop", skl_power_strike, 1),
## (troop_raise_skill, "$g_player_troop", skl_power_draw, 5),
## (troop_raise_skill, "$g_player_troop", skl_weapon_master, 4),
## (troop_raise_skill, "$g_player_troop", skl_ironflesh, 1),
## (troop_raise_skill, "$g_player_troop", skl_horse_archery, 6),
## (troop_raise_proficiency_linear, "$g_player_troop", wpt_one_handed_weapon, 70),
## (troop_raise_proficiency_linear, "$g_player_troop", wpt_two_handed_weapon, 70),
## (troop_raise_proficiency_linear, "$g_player_troop", wpt_polearm, 70),
## (troop_raise_proficiency_linear, "$g_player_troop", wpt_crossbow, 70),
## (troop_raise_proficiency_linear, "$g_player_troop", wpt_throwing, 70),
##
## (troop_clear_inventory, "$g_player_troop"),
## (troop_add_item, "$g_player_troop","itm_leather_jerkin",0),
## (troop_add_item, "$g_player_troop","itm_leather_boots",0),
## (troop_add_item, "$g_player_troop","itm_practice_sword",0),
## (troop_add_item, "$g_player_troop","itm_quarter_staff",0),
## (troop_equip_items, "$g_player_troop"),
## (set_visitor,0,"trp_player"),
## (set_visitor,32,"trp_tutorial_fighter_1"),
## (set_visitor,33,"trp_tutorial_fighter_2"),
## (set_visitor,34,"trp_tutorial_fighter_3"),
## (set_visitor,35,"trp_tutorial_fighter_4"),
## (set_visitor,40,"trp_tutorial_master_archer"),
## (set_visitor,41,"trp_tutorial_archer_1"),
## (set_visitor,42,"trp_tutorial_archer_1"),
## (set_visitor,60,"trp_tutorial_master_horseman"),
## (set_visitor,61,"trp_tutorial_rider_1"),
## (set_visitor,62,"trp_tutorial_rider_1"),
## (set_visitor,63,"trp_tutorial_rider_2"),
## (set_visitor,64,"trp_tutorial_rider_2"),
## (set_jump_mission,"mt_tutorial_training_ground"),
## (jump_to_scene,"scn_tutorial_training_ground"),
## (change_screen_mission),
## ]),
##
## ("tutorial_5",
## [
## (eq,1,0),
## ],
## "Tutorial #5: Commanding a band of soldiers. {s5}",
## [
## (modify_visitors_at_site,"scn_tutorial_5"),(reset_visitors,0),
## (set_visitor,0,"trp_player"),
## (set_visitor,1,"trp_vaegir_infantry"),
## (set_visitor,2,"trp_vaegir_infantry"),
## (set_visitor,3,"trp_vaegir_infantry"),
## (set_visitor,4,"trp_vaegir_infantry"),
## (set_jump_mission,"mt_tutorial_5"),
## (jump_to_scene,"scn_tutorial_5"),
## (change_screen_mission),
## ]),
##
## ("tutorial_edit_custom_battle_scenes",
## [(eq,1,0),],
## "(NO TRANSLATE) tutorial_edit_custom_battle_scenes",
## [
## (jump_to_menu,"mnu_custom_battle_scene"),
## ]),
("continue",[],"Continue...",
[
(modify_visitors_at_site,"scn_tutorial_training_ground"),
(reset_visitors, 0),
(set_player_troop, "trp_player"),
(assign, "$g_player_troop", "trp_player"),
(troop_raise_attribute, "$g_player_troop", ca_strength, 12),
(troop_raise_attribute, "$g_player_troop", ca_agility, 9),
(troop_raise_attribute, "$g_player_troop", ca_charisma, 5),
(troop_raise_skill, "$g_player_troop", skl_shield, 3),
(troop_raise_skill, "$g_player_troop", skl_athletics, 2),
(troop_raise_skill, "$g_player_troop", skl_riding, 3),
(troop_raise_skill, "$g_player_troop", skl_power_strike, 1),
(troop_raise_skill, "$g_player_troop", skl_power_draw, 5),
(troop_raise_skill, "$g_player_troop", skl_weapon_master, 4),
(troop_raise_skill, "$g_player_troop", skl_ironflesh, 1),
(troop_raise_skill, "$g_player_troop", skl_horse_archery, 6),
(troop_raise_proficiency_linear, "$g_player_troop", wpt_one_handed_weapon, 70),
(troop_raise_proficiency_linear, "$g_player_troop", wpt_two_handed_weapon, 70),
(troop_raise_proficiency_linear, "$g_player_troop", wpt_polearm, 70),
(troop_raise_proficiency_linear, "$g_player_troop", wpt_crossbow, 70),
(troop_raise_proficiency_linear, "$g_player_troop", wpt_throwing, 70),
(troop_clear_inventory, "$g_player_troop"),
(troop_add_item, "$g_player_troop","itm_leather_jerkin",0),
(troop_add_item, "$g_player_troop","itm_leather_boots",0),
(troop_add_item, "$g_player_troop","itm_practice_sword",0),
(troop_add_item, "$g_player_troop","itm_quarter_staff",0),
(troop_equip_items, "$g_player_troop"),
(set_visitor,0,"trp_player"),
(set_visitor,32,"trp_tutorial_fighter_1"),
(set_visitor,33,"trp_tutorial_fighter_2"),
(set_visitor,34,"trp_tutorial_fighter_3"),
(set_visitor,35,"trp_tutorial_fighter_4"),
(set_visitor,40,"trp_tutorial_master_archer"),
(set_visitor,41,"trp_tutorial_archer_1"),
(set_visitor,42,"trp_tutorial_archer_1"),
(set_visitor,60,"trp_tutorial_master_horseman"),
(set_visitor,61,"trp_tutorial_rider_1"),
(set_visitor,62,"trp_tutorial_rider_1"),
(set_visitor,63,"trp_tutorial_rider_2"),
(set_visitor,64,"trp_tutorial_rider_2"),
(set_jump_mission,"mt_tutorial_training_ground"),
(jump_to_scene,"scn_tutorial_training_ground"),
(change_screen_mission),
]),
("go_back_dot",
[],
"Go back.",
[
(change_screen_quit),
]),
]
),
("reports",0,
"Character Renown: {reg5}^Honor Rating: {reg6}^Party Morale: {reg8}^Party Size Limit: {reg7}^",
"none",
[(call_script, "script_game_get_party_companion_limit"),
(assign, ":party_size_limit", reg0),
(troop_get_slot, ":renown", "trp_player", slot_troop_renown),
(assign, reg5, ":renown"),
(assign, reg6, "$player_honor"),
(assign, reg7, ":party_size_limit"),
#(call_script, "script_get_player_party_morale_values"),
#(party_set_morale, "p_main_party", reg0),
(party_get_morale, reg8, "p_main_party"),
],
[
("cheat_faction_orders",[(ge,"$cheat_mode",1)],"{!}Cheat: Faction orders.",
[(jump_to_menu, "mnu_faction_orders"),
]
),
("view_character_report",[],"View character report.",
[(jump_to_menu, "mnu_character_report"),
]
),
("view_party_size_report",[],"View party size report.",
[(jump_to_menu, "mnu_party_size_report"),
]
),
("view_npc_mission_report",[],"View companion mission report.",
[(jump_to_menu, "mnu_companion_report"),
]
),
("view_weekly_budget_report",[],"View weekly budget report.",
[
(assign, "$g_apply_budget_report_to_gold", 0),
(start_presentation, "prsnt_budget_report"),
]
),
("view_morale_report",[],"View party morale report.",
[(jump_to_menu, "mnu_morale_report"),
]
),
#NPC companion changes begin
("lord_relations",[],"View list of known lords by relation.",
[
(jump_to_menu, "mnu_lord_relations"),
]
),
("courtship_relations",[],"View courtship relations.",
[
(jump_to_menu, "mnu_courtship_relations"),
]
),
("status_check",[(eq,"$cheat_mode",1)],"{!}NPC status check.",
[
(try_for_range, ":npc", companions_begin, companions_end),
(main_party_has_troop, ":npc"),
(str_store_troop_name, 4, ":npc"),
(troop_get_slot, reg3, ":npc", slot_troop_morality_state),
(troop_get_slot, reg4, ":npc", slot_troop_2ary_morality_state),
(troop_get_slot, reg5, ":npc", slot_troop_personalityclash_state),
(troop_get_slot, reg6, ":npc", slot_troop_personalityclash2_state),
(troop_get_slot, reg7, ":npc", slot_troop_personalitymatch_state),
(display_message, "@{!}{s4}: M{reg3}, 2M{reg4}, PC{reg5}, 2PC{reg6}, PM{reg7}"),
(try_end),
]
),
#NPC companion changes end
("view_faction_relations_report",[],"View faction relations report.",
[(jump_to_menu, "mnu_faction_relations_report"),
]
),
("resume_travelling",[],"Resume travelling.",
[(change_screen_return),
]
),
]
),
(
"custom_battle_scene",menu_text_color(0xFF000000)|mnf_disable_all_keys,
"(NO_TRANS)",
"none",
[],
[
("quick_battle_scene_1",[],"{!}quick_battle_scene_1",
[
(set_jump_mission,"mt_ai_training"),
(jump_to_scene,"scn_quick_battle_scene_1"),(change_screen_mission)
]
),
("quick_battle_scene_2",[],"{!}quick_battle_scene_2",
[
(set_jump_mission,"mt_ai_training"),
(jump_to_scene,"scn_quick_battle_scene_2"),(change_screen_mission)
]
),
("quick_battle_scene_3",[],"{!}quick_battle_scene_3",
[
(set_jump_mission,"mt_ai_training"),
(jump_to_scene,"scn_quick_battle_scene_3"),(change_screen_mission)
]
),
("quick_battle_scene_4",[],"{!}quick_battle_scene_4",
[
(set_jump_mission,"mt_ai_training"),
(jump_to_scene,"scn_quick_battle_scene_4"),(change_screen_mission)
]
),
("quick_battle_scene_5",[],"{!}quick_battle_scene_5",
[
(set_jump_mission,"mt_ai_training"),
(jump_to_scene,"scn_quick_battle_scene_5"),(change_screen_mission)
]
),
("go_back",[],"{!}Go back",
[(change_screen_quit),
]
),
]
),
#depreciated
## (
## "custom_battle_2",mnf_disable_all_keys,
## "{s16}",
## "none",
## [
## (assign, "$g_battle_result", 0),
## (set_show_messages, 0),
##
## (troop_clear_inventory, "trp_player"),
## (troop_raise_attribute, "trp_player", ca_strength, -1000),
## (troop_raise_attribute, "trp_player", ca_agility, -1000),
## (troop_raise_attribute, "trp_player", ca_charisma, -1000),
## (troop_raise_attribute, "trp_player", ca_intelligence, -1000),
## (troop_raise_skill, "trp_player", skl_shield, -1000),
## (troop_raise_skill, "trp_player", skl_athletics, -1000),
## (troop_raise_skill, "trp_player", skl_riding, -1000),
## (troop_raise_skill, "trp_player", skl_power_strike, -1000),
## (troop_raise_skill, "trp_player", skl_power_throw, -1000),
## (troop_raise_skill, "trp_player", skl_weapon_master, -1000),
## (troop_raise_skill, "trp_player", skl_horse_archery, -1000),
## (troop_raise_skill, "trp_player", skl_ironflesh, -1000),
## (troop_raise_proficiency_linear, "trp_player", wpt_one_handed_weapon, -10000),
## (troop_raise_proficiency_linear, "trp_player", wpt_two_handed_weapon, -10000),
## (troop_raise_proficiency_linear, "trp_player", wpt_polearm, -10000),
## (troop_raise_proficiency_linear, "trp_player", wpt_archery, -10000),
## (troop_raise_proficiency_linear, "trp_player", wpt_crossbow, -10000),
## (troop_raise_proficiency_linear, "trp_player", wpt_throwing, -10000),
##
## (reset_visitors),
#### Scene 1 Start "Shalow Lake War"
## (try_begin),
## (eq, "$g_custom_battle_scenario", 0),
## (assign, "$g_player_troop", "trp_knight_1_15"),
## (set_player_troop, "$g_player_troop"),
##
## (assign, "$g_custom_battle_scene", "scn_quick_battle_1"),
## (modify_visitors_at_site, "$g_custom_battle_scene"),
## (set_visitor, 0, "$g_player_troop"),
##
### (troop_add_item, "trp_player","itm_bascinet",0),
### (troop_add_item, "trp_player","itm_mail_with_surcoat",0),
### (troop_add_item, "trp_player","itm_bastard_sword_a",0),
### (troop_add_item, "trp_player","itm_war_bow",0),
### (troop_add_item, "trp_player","itm_khergit_arrows",0),
### (troop_add_item, "trp_player","itm_kite_shield",0),
### (troop_add_item, "trp_player","itm_hunter",0),
### (troop_add_item, "trp_player","itm_mail_chausses",0),
### (troop_equip_items, "trp_player"),
##
## (set_visitors, 1, "trp_farmer", 13),
## (set_visitors, 2, "trp_swadian_sergeant", 5),
## (set_visitors, 3, "trp_swadian_sharpshooter", 4),
## (set_visitors, 4, "trp_swadian_man_at_arms", 8),
## (set_visitors, 5, "trp_swadian_knight", 3),
## (set_visitors, 6, "trp_peasant_woman", 7),
##
#### Enemy
## (set_visitors, 16, "trp_vaegir_infantry", 6),
## (set_visitors, 17, "trp_vaegir_archer", 6),
## (set_visitors, 18, "trp_vaegir_horseman", 4),
## (set_visitors, 19, "trp_vaegir_knight", 10),
## (set_visitors, 20, "trp_vaegir_guard", 6),
## (str_store_string, s16, "str_custom_battle_1"),
##
#### SCENE 3 Start "Mountain Bandit Hunt"
## (else_try),
## (eq, "$g_custom_battle_scenario", 1),
## (assign, "$g_player_troop", "trp_knight_2_5"),
## (set_player_troop, "$g_player_troop"),
##
## (assign, "$g_custom_battle_scene", "scn_quick_battle_3"),
## (modify_visitors_at_site, "$g_custom_battle_scene"),
## (set_visitor, 0, "$g_player_troop"),
##
## (set_visitors, 1, "trp_vaegir_archer", 4),
## (set_visitors, 2, "trp_vaegir_archer", 5),
## (set_visitors, 3, "trp_vaegir_veteran", 4),
## (set_visitors, 4, "trp_vaegir_horseman", 4),
## (set_visitors, 5, "trp_vaegir_footman", 2),
## (set_visitors, 6, "trp_vaegir_knight", 4),
#### ENEMY
##
## (set_visitors, 16, "trp_mountain_bandit", 4),
## (set_visitors, 17, "trp_bandit", 8),
## (set_visitors, 18, "trp_mountain_bandit", 8),
## (set_visitors, 19, "trp_mountain_bandit", 6),
## (set_visitors, 20, "trp_sea_raider", 5),
## (set_visitors, 21, "trp_mountain_bandit", 4),
## (set_visitors, 22, "trp_brigand", 6),
## (set_visitors, 23, "trp_sea_raider", 8),
## (set_visitors, 25, "trp_brigand", 10),
## (str_store_string, s16, "str_custom_battle_2"),
##
#### SCENE 4 Start "Grand Stand"
## (else_try),
## (eq, "$g_custom_battle_scenario", 2),
## (assign, "$g_player_troop", "trp_kingdom_5_lady_1"),
## (set_player_troop, "$g_player_troop"),
##
## (troop_raise_attribute, "$g_player_troop", ca_strength, 12),
## (troop_raise_attribute, "$g_player_troop", ca_agility, 9),
## (troop_raise_attribute, "$g_player_troop", ca_charisma, 5),
## (troop_raise_attribute, "$g_player_troop", ca_intelligence, 5),
## (troop_raise_skill, "$g_player_troop", skl_shield, 3),
## (troop_raise_skill, "$g_player_troop", skl_athletics, 2),
## (troop_raise_skill, "$g_player_troop", skl_riding, 3),
## (troop_raise_skill, "$g_player_troop", skl_power_strike, 4),
## (troop_raise_skill, "$g_player_troop", skl_power_draw, 5),
## (troop_raise_skill, "$g_player_troop", skl_weapon_master, 4),
## (troop_raise_skill, "$g_player_troop", skl_ironflesh, 6),
## (troop_raise_proficiency_linear, "$g_player_troop", wpt_one_handed_weapon, 100),
## (troop_raise_proficiency_linear, "$g_player_troop", wpt_two_handed_weapon, 30),
## (troop_raise_proficiency_linear, "$g_player_troop", wpt_polearm, 20),
## (troop_raise_proficiency_linear, "$g_player_troop", wpt_crossbow, 110),
## (troop_raise_proficiency_linear, "$g_player_troop", wpt_throwing, 10),
##
## (assign, "$g_custom_battle_scene", "scn_quick_battle_4"),
## (modify_visitors_at_site, "$g_custom_battle_scene"),
## (set_visitor, 0, "$g_player_troop"),
##
## (troop_clear_inventory, "$g_player_troop"),
## (troop_add_item, "$g_player_troop","itm_helmet_with_neckguard",0),
## (troop_add_item, "$g_player_troop","itm_plate_armor",0),
## (troop_add_item, "$g_player_troop","itm_iron_greaves",0),
## (troop_add_item, "$g_player_troop","itm_mail_chausses",0),
## (troop_add_item, "$g_player_troop","itm_tab_shield_small_round_c",0),
## (troop_add_item, "$g_player_troop","itm_heavy_crossbow",0),
## (troop_add_item, "$g_player_troop","itm_bolts",0),
## (troop_add_item, "$g_player_troop","itm_sword_medieval_b_small",0),
## (troop_equip_items, "$g_player_troop"),
#### US
## (set_visitors, 1, "trp_vaegir_infantry", 4),
## (set_visitors, 2, "trp_vaegir_archer", 3),
## (set_visitors, 3, "trp_vaegir_infantry", 4),
## (set_visitors, 4, "trp_vaegir_archer", 3),
## (set_visitors, 5, "trp_vaegir_infantry", 3),
## (set_visitors, 6, "trp_vaegir_footman", 5),
## (set_visitors, 7, "trp_vaegir_footman", 4),
## (set_visitors, 8, "trp_vaegir_archer", 3),
##
#### ENEMY
## (set_visitors, 16, "trp_swadian_footman", 8),
## (set_visitors, 17, "trp_swadian_crossbowman", 9),
## (set_visitors, 18, "trp_swadian_sergeant", 7),
## (set_visitors, 19, "trp_swadian_sharpshooter", 8),
## (set_visitors, 20, "trp_swadian_militia", 13),
## (str_store_string, s16, "str_custom_battle_3"),
##
#### Scene 5 START
## (else_try),
## (eq, "$g_custom_battle_scenario", 3),
## (assign, "$g_player_troop", "trp_knight_1_10"),
## (set_player_troop, "$g_player_troop"),
##
## (assign, "$g_custom_battle_scene", "scn_quick_battle_5"),
## (modify_visitors_at_site, "$g_custom_battle_scene"),
## (set_visitor, 0, "$g_player_troop"),
##
#### US
## (set_visitors, 1, "trp_swadian_knight", 3),
## (set_visitors, 2, "trp_swadian_sergeant", 4),
## (set_visitors, 3, "trp_swadian_sharpshooter", 8),
## (set_visitors, 4, "trp_swadian_man_at_arms", 8),
## (set_visitors, 5, "trp_swadian_knight", 2),
##
#### enemy
## (set_visitors, 16, "trp_vaegir_infantry", 8),
## (set_visitors, 17, "trp_vaegir_archer", 10),
## (set_visitors, 18, "trp_vaegir_horseman", 4),
## (set_visitors, 19, "trp_vaegir_knight", 10),
## (set_visitors, 20, "trp_vaegir_guard", 7),
## (str_store_string, s16, "str_custom_battle_4"),
##
## (else_try),
## (eq, "$g_custom_battle_scenario", 4),
##
#### (assign, "$g_custom_battle_scene", "scn_quick_battle_6"),
## (assign, "$g_custom_battle_scene", "scn_quick_battle_7"),
##
### Player Wear
## (assign, "$g_player_troop", "trp_knight_4_9"),
## (set_player_troop, "$g_player_troop"),
##
## (modify_visitors_at_site, "$g_custom_battle_scene"),
## (set_visitor, 0, "$g_player_troop"),
##
## (set_visitors, 1, "trp_nord_archer", 4),
## (set_visitors, 2, "trp_nord_archer", 4),
## (set_visitors, 3, "trp_nord_champion", 4),
## (set_visitors, 4, "trp_nord_veteran", 5),
## (set_visitors, 5, "trp_nord_warrior", 5),
## (set_visitors, 6, "trp_nord_trained_footman", 8),
##
#### ENEMY
## (set_visitors, 11, "trp_vaegir_knight", 2),
## (set_visitors, 12, "trp_vaegir_guard", 6),
## (set_visitors, 13, "trp_vaegir_infantry", 8),
## (set_visitors, 14, "trp_vaegir_veteran", 10),
## (set_visitors, 16, "trp_vaegir_skirmisher", 5),
## (set_visitors, 17, "trp_vaegir_archer", 4),
## (set_visitors, 18, "trp_vaegir_marksman", 2),
## (set_visitors, 19, "trp_vaegir_skirmisher", 4),
## (set_visitors, 20, "trp_vaegir_skirmisher", 3),
## (set_visitors, 21, "trp_vaegir_skirmisher", 3),
## (set_visitors, 22, "trp_vaegir_skirmisher", 3),
## (set_visitors, 23, "trp_vaegir_archer", 2),
## (str_store_string, s16, "str_custom_battle_5"),
## (try_end),
## (set_show_messages, 1),
## ],
##
## [
## ("custom_battle_go",[],"Start.",
## [(try_begin),
## (eq, "$g_custom_battle_scenario", 2),
#### (set_jump_mission,"mt_custom_battle_siege"),
## (else_try),
## (eq, "$g_custom_battle_scenario", 4),
#### (set_jump_mission,"mt_custom_battle_5"),
## (else_try),
#### (set_jump_mission,"mt_custom_battle"),
## (try_end),
## (jump_to_menu, "mnu_custom_battle_end"),
## (jump_to_scene,"$g_custom_battle_scene"),
## (change_screen_mission),
## ]
## ),
## ("leave_custom_battle_2",[],"Cancel.",
## [(jump_to_menu, "mnu_start_game_3"),
## ]
## ),
## ]
## ),
(
"custom_battle_end",mnf_disable_all_keys,
"The battle is over. {s1} Your side killed {reg5} enemies and lost {reg6} troops over the battle. You personally slew {reg7} men in the fighting.",
"none",
[(music_set_situation, 0),
(assign, reg5, "$g_custom_battle_team2_death_count"),
(assign, reg6, "$g_custom_battle_team1_death_count"),
(get_player_agent_kill_count, ":kill_count"),
(get_player_agent_kill_count, ":wound_count", 1),
(store_add, reg7, ":kill_count", ":wound_count"),
(try_begin),
(eq, "$g_battle_result", 1),
(str_store_string, s1, "str_battle_won"),
(else_try),
(str_store_string, s1, "str_battle_lost"),
(try_end),
(try_begin),
(ge, "$g_custom_battle_team2_death_count", 100),
(unlock_achievement, ACHIEVEMENT_LOOK_AT_THE_BONES),
(try_end),
],
[
("continue",[],"Continue.",
[(change_screen_quit),
]
),
]
),
("start_game_1",menu_text_color(0xFF000000)|mnf_disable_all_keys,
"Select your character's gender.",
"none",
[],
[
("start_male",[],"Male",
[
(troop_set_type,"trp_player", 0),
(assign,"$character_gender",tf_male),
(jump_to_menu,"mnu_start_character_1"),
]
),
("start_female",[],"Female",
[
(troop_set_type, "trp_player", 1),
(assign, "$character_gender", tf_female),
(jump_to_menu, "mnu_start_character_1"),
]
),
("go_back",[],"Go back",
[
(jump_to_menu,"mnu_start_game_0"),
]),
]
),
(
"start_character_1",mnf_disable_all_keys,
"You were born years ago, in a land far away. Your father was...",
"none",
[
(str_clear,s10),
(str_clear,s11),
(str_clear,s12),
(str_clear,s13),
(str_clear,s14),
(str_clear,s15),
],
[
("start_noble",[],"An impoverished noble.",[
(assign,"$background_type",cb_noble),
(assign, reg3, "$character_gender"),
(str_store_string,s10,"@You came into the world a {reg3?daughter:son} of declining nobility,\
owning only the house in which they lived. However, despite your family's hardships,\
they afforded you a good education and trained you from childhood for the rigors of aristocracy and life at court."),
(jump_to_menu,"mnu_start_character_2"),
]),
("start_merchant",[],"A travelling merchant.",[
(assign,"$background_type",cb_merchant),
(assign, reg3, "$character_gender"),
(str_store_string,s10,"@You were born the {reg3?daughter:son} of travelling merchants,\
always moving from place to place in search of a profit. Although your parents were wealthier than most\
and educated you as well as they could, you found little opportunity to make friends on the road,\
living mostly for the moments when you could sell something to somebody."),
(jump_to_menu,"mnu_start_character_2"),
]),
("start_guard",[],"A veteran warrior.",[
(assign,"$background_type",cb_guard),
(assign, reg3, "$character_gender"),
(str_store_string,s10,"@As a child, your family scrabbled out a meagre living from your father's wages\
as a guardsman to the local lord. It was not an easy existence, and you were too poor to get much of an\
education. You learned mainly how to defend yourself on the streets, with or without a weapon in hand."),
(jump_to_menu,"mnu_start_character_2"),
]),
("start_forester",[],"A hunter.",[
(assign,"$background_type",cb_forester),
(assign, reg3, "$character_gender"),
(str_store_string,s11,"@{reg3?daughter:son}"),
(str_store_string,s10,"@You were the {reg3?daughter:son} of a family who lived off the woods,\
doing whatever they needed to make ends meet. Hunting, woodcutting, making arrows,\
even a spot of poaching whenever things got tight. Winter was never a good time for your family\
as the cold took animals and people alike, but you always lived to see another dawn,\
though your brothers and sisters might not be so fortunate."),
(jump_to_menu,"mnu_start_character_2"),
]),
("start_nomad",[],"A steppe nomad.",[
(assign,"$background_type",cb_nomad),
(assign, reg3, "$character_gender"),
(str_store_string,s11,"@{reg3?daughter:son}"),
(str_store_string,s10,"@You were a child of the steppe, born to a tribe of wandering nomads who lived\
in great camps throughout the arid grasslands.\
Like the other tribesmen, your family revered horses above almost everything else, and they taught you\
how to ride almost before you learned how to walk. "),
(jump_to_menu,"mnu_start_character_2"),
]),
("start_thief",[],"A thief.",[
(assign,"$background_type",cb_thief),
(assign, reg3, "$character_gender"),
(str_store_string,s10,"@As the {reg3?daughter:son} of a thief, you had very little 'formal' education.\
Instead you were out on the street, begging until you learned how to cut purses, cutting purses\
until you learned how to pick locks, all the way through your childhood.\
Still, these long years made you streetwise and sharp to the secrets of cities and shadowy backways."),
(jump_to_menu,"mnu_start_character_2"),
]),
## ("start_priest",[],"Priests.",[
## (assign,"$background_type",cb_priest),
## (assign, reg3, "$character_gender"),
## (str_store_string,s10,"@A {reg3?daughter:son} that nobody wanted, you were left to the church as a baby,\
## a foundling raised by the priests and nuns to their own traditions.\
## You were only one of many other foundlings and orphans, but you nonetheless received a lot of attention\
## as well as many years of study in the church library and before the altar. They taught you many things.\
## Gradually, faith became such a part of your life that it was no different from the blood coursing through your veins."),
## (jump_to_menu,"mnu_start_character_2"),
## ]),
("go_back",[],"Go back",
[(jump_to_menu,"mnu_start_game_1"),
]),
]
),
(
"start_character_2",0,
"{s10}^^ You started to learn about the world almost as soon as you could walk and talk. You spent your early life as...",
"none",
[],
[
("page",[
],"A page at a nobleman's court.",[
(assign,"$background_answer_2", cb2_page),
(assign, reg3, "$character_gender"),
(str_store_string,s11,"@As a {reg3?girl:boy} growing out of childhood,\
you were sent to live in the court of one of the nobles of the land.\
There, your first lessons were in humility, as you waited upon the lords and ladies of the household.\
But from their chess games, their gossip, even the poetry of great deeds and courtly love, you quickly began to learn about the adult world of conflict\
and competition. You also learned from the rough games of the other children, who battered at each other with sticks in imitation of their elders' swords."),
(jump_to_menu,"mnu_start_character_3"),
]),
("apprentice",[
],"A craftsman's apprentice.",[
(assign,"$background_answer_2", cb2_apprentice),
(assign, reg3, "$character_gender"),
(str_store_string,s11,"@As a {reg3?girl:boy} growing out of childhood,\
you apprenticed with a local craftsman to learn a trade. After years of hard work and study under your\
new master, he promoted you to journeyman and employed you as a fully paid craftsman for as long as\
you wished to stay."),
(jump_to_menu,"mnu_start_character_3"),
]),
("stockboy",[
],"A shop assistant.",[
(assign,"$background_answer_2",cb2_merchants_helper),
(assign, reg3, "$character_gender"),
(str_store_string,s11,"@As a {reg3?girl:boy} growing out of childhood,\
you apprenticed to a wealthy merchant, picking up the trade over years of working shops and driving caravans.\
You soon became adept at the art of buying low, selling high, and leaving the customer thinking they'd\
got the better deal."),
(jump_to_menu,"mnu_start_character_3"),
]),
("urchin",[
],"A street urchin.",[
(assign,"$background_answer_2",cb2_urchin),
(assign, reg3, "$character_gender"),
(str_store_string,s11,"@As a {reg3?girl:boy} growing out of childhood,\
you took to the streets, doing whatever you must to survive.\
Begging, thieving and working for gangs to earn your bread, you lived from day to day in this violent world,\
always one step ahead of the law and those who wished you ill."),
(jump_to_menu,"mnu_start_character_3"),
]),
("nomad",[
],"A steppe child.",[
(assign,"$background_answer_2",cb2_steppe_child),
(assign, reg3, "$character_gender"),
(str_store_string,s11,"@As a {reg3?girl:boy} growing out of childhood,\
you rode the great steppes on a horse of your own, learning the ways of the grass and the desert.\
Although you sometimes went hungry, you became a skillful hunter and pathfinder in this trackless country.\
Your body too started to harden with muscle as you grew into the life of a nomad {reg3?woman:man}."),
(jump_to_menu,"mnu_start_character_3"),
]),
## ("mummer",[],"Mummer.",[
## (assign,"$background_answer_2",5),
## (assign, reg3, "$character_gender"),
## (str_store_string,s13,"@{reg3?woman:man}"),
## (str_store_string,s12,"@{reg3?girl:boy}"),
## (str_store_string,s11,"@As a {s12} growing out of childhood,\
## you attached yourself to a troupe of wandering entertainers, going from town to town setting up mummer's\
## shows. It was a life of hard work, selling, begging and stealing your living from the punters who flocked\
## to watch your antics. Over time you became a performer well capable of attracting a crowd."),
## (jump_to_menu,"mnu_start_character_3"),
## ]),
## ("courtier",[],"Courtier.",[
## (assign,"$background_answer_2",6),
## (assign, reg3, "$character_gender"),
## (str_store_string,s13,"@{reg3?woman:man}"),
## (str_store_string,s12,"@{reg3?girl:boy}"),
## (str_store_string,s11,"@As a {s12} growing out of childhood,\
## you spent much of your life at court, inserting yourself into the tightly-knit circles of nobility.\
## With the years you became more and more involved with the politics and intrigue demanded of a high-born {s13}.\
## You could not afford to remain a stranger to backstabbing and political violence, even if you wanted to."),
## (jump_to_menu,"mnu_start_character_3"),
## ]),
## ("noble",[],"Noble in training.",[
## (assign,"$background_answer_2",7),
## (assign, reg3, "$character_gender"),
## (str_store_string,s13,"@{reg3?woman:man}"),
## (str_store_string,s12,"@{reg3?girl:boy}"),
## (try_begin),
## (eq,"$character_gender",tf_male),
## (str_store_string,s11,"@As a {s12} growing out of childhood,\
## you were trained and educated to perform the duties and wield the rights of a noble landowner.\
## The managing of taxes and rents were equally important in your education as diplomacy and even\
## personal defence. You learned everything you needed to become a lord of your own hall."),
## (else_try),
## (str_store_string,s11,"@As a {s12} growing out of childhood,\
## you were trained and educated to the duties of a noble {s13}. You learned much about the household arts,\
## but even more about diplomacy and decorum, and all the things that a future husband might choose to speak of.\
## Truly, you became every inch as shrewd as any lord, though it would be rude to admit it aloud."),
## (try_end),
## (jump_to_menu,"mnu_start_character_3"),
## ]),
## ("acolyte",[],"Cleric acolyte.",[
## (assign,"$background_answer_2",8),
## (assign, reg3, "$character_gender"),
## (str_store_string,s13,"@{reg3?woman:man}"),
## (str_store_string,s12,"@{reg3?girl:boy}"),
## (str_store_string,s11,"@As a {s12} growing out of childhood,\
## you became an acolyte in the church, the lowest rank on the way to priesthood.\
## Years of rigorous learning and hard work followed. You were one of several acolytes,\
## performing most of the menial labour in the church in addition to being trained for more holy tasks.\
## On the night of your adulthood you were allowed to conduct your first service.\
## After that you were no longer an acolyte {s12}, but a {s13} waiting to take your vows into the service of God."),
## (jump_to_menu,"mnu_start_character_3"),
## ]),
("go_back",[],"Go back.",
[(jump_to_menu,"mnu_start_character_1"),
]),
]
),
(
"start_character_3",mnf_disable_all_keys,
"{s11}^^ Then, as a young adult, life changed as it always does. You became...",
"none",
[(assign, reg3, "$character_gender"),],
[
## ("bravo",[],"A travelling bravo.",[
## (assign,"$background_answer_3",1),
## (str_store_string,s14,"@{reg3?daughter:man}"),
## (str_store_string,s13,"@{reg3?woman:man}"),
## (str_store_string,s12,"@Though the distinction felt sudden to you,\
## somewhere along the way you had become a {s13}, and the whole world seemed to change around you.\
## You left your old life behind to travel the roads as a mercenary, a bravo, guarding caravans for coppers\
## or bashing in heads for silvers. You became a {s14} of the open road, working with bandits as often as against.\
## Going from fight to fight, you grew experienced at battle, and you learned what it was to kill."),
## (jump_to_menu,"mnu_start_character_4"),
## ]),
## ("merc",[],"A sellsword in foreign lands.",[
## (assign,"$background_answer_3",2),
## (str_store_string,s14,"@{reg3?daughter:man}"),
## (str_store_string,s13,"@{reg3?woman:man}"),
## (str_store_string,s12,"@Though the distinction felt sudden to you,\
## somewhere along the way you had become a {s13}, and the whole world seemed to change around you.\
## You signed on with a mercenary company and travelled far from your home. The life you found was rough and\
## ready, marching to the beat of strange drums and learning unusual ways of fighting.\
## There were men who taught you how to wield any weapon you desired, and plenty of battles to hone your skills.\
## You were one of the charmed few who survived through every campaign in which you marched."),
## (jump_to_menu,"mnu_start_character_4"),
## ]),
("squire",[(eq,"$character_gender",tf_male)],"A squire.",[
(assign,"$background_answer_3",cb3_squire),
(str_store_string,s14,"@{reg3?daughter:man}"),
(str_store_string,s12,"@Though the distinction felt sudden to you,\
somewhere along the way you had become a {reg3?woman:man}, and the whole world seemed to change around you.\
When you were named squire to a noble at court, you practiced long hours with weapons,\
learning how to deal out hard knocks and how to take them, too.\
You were instructed in your obligations to your lord, and of your duties to those who might one day be your vassals.\
But in addition to learning the chivalric ideal, you also learned about the less uplifting side\
-- old warriors' stories of ruthless power politics, of betrayals and usurpations,\
of men who used guile as well as valor to achieve their aims."),
(jump_to_menu,"mnu_start_character_4"),
]),
("lady",[(eq,"$character_gender",tf_female)],"A lady-in-waiting.",[
(assign,"$background_answer_3",cb3_lady_in_waiting),
(str_store_string,s14,"@{reg3?daughter:man}"),
(str_store_string,s13,"@{reg3?woman:man}"),
(str_store_string,s12,"@Though the distinction felt sudden to you,\
somewhere along the way you had become a {s13}, and the whole world seemed to change around you.\
You joined the tightly-knit circle of women at court, ladies who all did proper ladylike things,\
the wives and mistresses of noble men as well as maidens who had yet to find a husband.\
However, even here you found politics at work as the ladies schemed for prominence and fought each other\
bitterly to catch the eye of whatever unmarried man was in fashion at court.\
You soon learned ways of turning these situations and goings-on to your advantage. With it came the\
realisation that you yourself could wield great influence in the world, if only you applied yourself\
with a little bit of subtlety."),
(jump_to_menu,"mnu_start_character_4"),
]),
("troubadour",[],"A troubadour.",[
(assign,"$background_answer_3",cb3_troubadour),
(str_store_string,s14,"@{reg3?daughter:man}"),
(str_store_string,s13,"@{reg3?woman:man}"),
(str_store_string,s12,"@Though the distinction felt sudden to you,\
somewhere along the way you had become a {s13}, and the whole world seemed to change around you.\
You set out on your own with nothing except the instrument slung over your back and your own voice.\
It was a poor existence, with many a hungry night when people failed to appreciate your play,\
but you managed to survive on your music alone. As the years went by you became adept at playing the\
drunken crowds in your taverns, and even better at talking anyone out of anything you wanted."),
(jump_to_menu,"mnu_start_character_4"),
]),
("student",[],"A university student.",[
(assign,"$background_answer_3",cb3_student),
(str_store_string,s12,"@Though the distinction felt sudden to you,\
somewhere along the way you had become a {reg3?woman:man}, and the whole world seemed to change around you.\
You found yourself as a student in the university of one of the great cities,\
where you studied theology, philosophy, and medicine.\
But not all your lessons were learned in the lecture halls.\
You may or may not have joined in with your fellows as they roamed the alleys in search of wine, women, and a good fight.\
However, you certainly were able to observe how a broken jaw is set,\
or how an angry townsman can be persuaded to set down his club and accept cash compensation for the destruction of his shop."),
(jump_to_menu,"mnu_start_character_4"),
]),
("peddler",[],"A goods peddler.",[
(assign,"$background_answer_3",cb3_peddler),
(str_store_string,s14,"@{reg3?daughter:man}"),
(str_store_string,s13,"@{reg3?woman:man}"),
(str_store_string,s12,"@Though the distinction felt sudden to you,\
somewhere along the way you had become a {s13}, and the whole world seemed to change around you.\
Heeding the call of the open road, you travelled from village to village buying and selling what you could.\
It was not a rich existence, but you became a master at haggling even the most miserly elders into\
giving you a good price. Soon, you knew, you would be well-placed to start your own trading empire..."),
(jump_to_menu,"mnu_start_character_4"),
]),
("craftsman",[],"A smith.",[
(assign,"$background_answer_3", cb3_craftsman),
(str_store_string,s14,"@{reg3?daughter:man}"),
(str_store_string,s13,"@{reg3?woman:man}"),
(str_store_string,s12,"@Though the distinction felt sudden to you,\
somewhere along the way you had become a {s13}, and the whole world seemed to change around you.\
You pursued a career as a smith, crafting items of function and beauty out of simple metal.\
As time wore on you became a master of your trade, and fine work started to fetch fine prices.\
With food in your belly and logs on your fire, you could take pride in your work and your growing reputation."),
(jump_to_menu,"mnu_start_character_4"),
]),
("poacher",[],"A game poacher.",[
(assign,"$background_answer_3", cb3_poacher),
(str_store_string,s14,"@{reg3?daughter:man}"),
(str_store_string,s13,"@{reg3?woman:man}"),
(str_store_string,s12,"@Though the distinction felt sudden to you,\
somewhere along the way you had become a {s13}, and the whole world seemed to change around you.\
Dissatisfied with common men's desperate scrabble for coin, you took to your local lord's own forests\
and decided to help yourself to its bounty, laws be damned. You hunted stags, boars and geese and sold\
the precious meat under the table. You cut down trees right under the watchmen's noses and turned them into\
firewood that warmed many freezing homes during winter. All for a few silvers, of course."),
(jump_to_menu,"mnu_start_character_4"),
]),
## ("preacher",[],"Itinerant preacher.",[
## (assign,"$background_answer_3",6),
## (str_store_string,s14,"@{reg3?daughter:man}"),
## (str_store_string,s13,"@{reg3?woman:man}"),
## (str_store_string,s12,"@Though the distinction felt sudden to you,\
## somewhere along the way you had become a {s13}, and the whole world seemed to change around you.\
## You packed your few belongings and went out into the world to spread the word of God. You preached to\
## anyone who would listen, and impressed many with the passion of your sermons. Though you had taken a vow\
## to remain in poverty through your itinerant years, you never lacked for food, drink or shelter; the\
## hospitality of the peasantry was always generous to a rising {s13} of God."),
## (jump_to_menu,"mnu_start_character_4"),
## ]),
("go_back",[],"Go back.",
[(jump_to_menu,"mnu_start_character_2"),
]
),
]
),
(
"start_character_4",mnf_disable_all_keys,
"{s12}^^But soon everything changed and you decided to strike out on your own as an adventurer. What made you take this decision was...",
#Finally, what made you decide to strike out on your own as an adventurer?",
"none",
[],
[
("revenge",[],"Personal revenge.",[
(assign,"$background_answer_4", cb4_revenge),
(str_store_string,s13,"@Only you know exactly what caused you to give up your old life and become an adventurer.\
Still, it was not a difficult choice to leave, with the rage burning brightly in your heart.\
You want vengeance. You want justice. What was done to you cannot be undone,\
and these debts can only be paid in blood..."),
(jump_to_menu,"mnu_choose_skill"),
]),
("death",[],"The loss of a loved one.",[
(assign,"$background_answer_4",cb4_loss),
(str_store_string,s13,"@Only you know exactly what caused you to give up your old life and become an adventurer.\
All you can say is that you couldn't bear to stay, not with the memories of those you loved so close and so\
painful. Perhaps your new life will let you forget,\
or honour the name that you can no longer bear to speak..."),
(jump_to_menu,"mnu_choose_skill"),
]),
("wanderlust",[],"Wanderlust.",[
(assign,"$background_answer_4",cb4_wanderlust),
(str_store_string,s13,"@Only you know exactly what caused you to give up your old life and become an adventurer.\
You're not even sure when your home became a prison, when the familiar became mundane, but your dreams of\
wandering have taken over your life. Whether you yearn for some faraway place or merely for the open road and the\
freedom to travel, you could no longer bear to stay in the same place. You simply went and never looked back..."),
(jump_to_menu,"mnu_choose_skill"),
]),
## ("fervor",[],"Religious fervor.",[
## (assign,"$background_answer_4",4),
## (str_store_string,s13,"@Only you know exactly what caused you to give up your old life and become an adventurer.\
## Regardless, the intense faith burning in your soul would not let you find peace in any single place.\
## There were others in the world, souls to be washed in the light of God. Now you preach wherever you go,\
## seeking to bring salvation and revelation to the masses, be they faithful or pagan. They will all know the\
## glory of God by the time you're done..."),
## (jump_to_menu,"mnu_choose_skill"),
## ]),
("disown",[],"Being forced out of your home.",[
(assign,"$background_answer_4",cb4_disown),
(str_store_string,s13,"@Only you know exactly what caused you to give up your old life and become an adventurer.\
However, you know you cannot go back. There's nothing to go back to. Whatever home you may have had is gone\
now, and you must face the fact that you're out in the wide wide world. Alone to sink or swim..."),
(jump_to_menu,"mnu_choose_skill"),
]),
("greed",[],"Lust for money and power.",[
(assign,"$background_answer_4",cb4_greed),
(str_store_string,s13,"@Only you know exactly what caused you to give up your old life and become an adventurer.\
To everyone else, it's clear that you're now motivated solely by personal gain.\
You want to be rich, powerful, respected, feared.\
You want to be the one whom others hurry to obey.\
You want people to know your name, and tremble whenever it is spoken.\
You want everything, and you won't let anyone stop you from having it..."),
(jump_to_menu,"mnu_choose_skill"),
]),
("go_back",[],"Go back.",
[(jump_to_menu,"mnu_start_character_3"),
]
),
]
),
(
"choose_skill",mnf_disable_all_keys,
"{s13}",
"none",
[(assign,"$current_string_reg",10),
(assign, ":difficulty", 0),
(try_begin),
(eq, "$character_gender", tf_female),
(str_store_string, s14, "str_woman"),
(val_add, ":difficulty", 1),
(else_try),
(str_store_string, s14, "str_man"),
(try_end),
(try_begin),
(eq,"$background_type",cb_noble),
(str_store_string, s15, "str_noble"),
(val_sub, ":difficulty", 1),
(else_try),
(str_store_string, s15, "str_common"),
(try_end),
(try_begin),
(eq, ":difficulty", -1),
(str_store_string, s16, "str_may_find_that_you_are_able_to_take_your_place_among_calradias_great_lords_relatively_quickly"),
(else_try),
(eq, ":difficulty", 0),
(str_store_string, s16, "str_may_face_some_difficulties_establishing_yourself_as_an_equal_among_calradias_great_lords"),
(else_try),
(eq, ":difficulty", 1),
(str_store_string, s16, "str_may_face_great_difficulties_establishing_yourself_as_an_equal_among_calradias_great_lords"),
(try_end),
],
[
## ("start_swordsman",[],"Swordsmanship.",[
## (assign, "$starting_skill", 1),
## (str_store_string, s14, "@You are particularly talented at swordsmanship."),
## (jump_to_menu,"mnu_past_life_explanation"),
## ]),
## ("start_archer",[],"Archery.",[
## (assign, "$starting_skill", 2),
## (str_store_string, s14, "@You are particularly talented at archery."),
## (jump_to_menu,"mnu_past_life_explanation"),
## ]),
## ("start_medicine",[],"Medicine.",[
## (assign, "$starting_skill", 3),
## (str_store_string, s14, "@You are particularly talented at medicine."),
## (jump_to_menu,"mnu_past_life_explanation"),
## ]),
("begin_adventuring",[],"Become an adventurer and ride to your destiny.",[
(set_show_messages, 0),
(try_begin),
(eq,"$character_gender",0),
(troop_raise_attribute, "trp_player",ca_strength,1),
(troop_raise_attribute, "trp_player",ca_charisma,1),
(else_try),
(troop_raise_attribute, "trp_player",ca_agility,1),
(troop_raise_attribute, "trp_player",ca_intelligence,1),
(try_end),
(troop_raise_attribute, "trp_player",ca_strength,1),
(troop_raise_attribute, "trp_player",ca_agility,1),
(troop_raise_attribute, "trp_player",ca_charisma,1),
(troop_raise_skill, "trp_player","skl_leadership",1),
(troop_raise_skill, "trp_player","skl_riding",1),
## (try_begin),
## (eq, "$starting_skill", 1),
## (troop_raise_attribute, "trp_player",ca_agility,1),
## (troop_raise_attribute, "trp_player",ca_strength,1),
## (troop_raise_skill, "trp_player",skl_power_strike,2),
## (troop_raise_proficiency, "trp_player",0,30),
## (troop_raise_proficiency, "trp_player",1,20),
## (else_try),
## (eq, "$starting_skill", 2),
## (troop_raise_attribute, "trp_player",ca_strength,2),
## (troop_raise_skill, "trp_player",skl_power_draw,2),
## (troop_raise_proficiency, "trp_player",3,50),
## (else_try),
## (troop_raise_attribute, "trp_player",ca_intelligence,1),
## (troop_raise_attribute, "trp_player",ca_charisma,1),
## (troop_raise_skill, "trp_player",skl_first_aid,1),
## (troop_raise_skill, "trp_player",skl_wound_treatment,1),
## (troop_add_item, "trp_player","itm_winged_mace",0),
## (troop_raise_proficiency, "trp_player",0,15),
## (troop_raise_proficiency, "trp_player",1,15),
## (troop_raise_proficiency, "trp_player",2,15),
## (try_end),
(try_begin),
(eq,"$background_type",cb_noble),
(eq,"$character_gender",tf_male),
(troop_raise_attribute, "trp_player",ca_intelligence,1),
(troop_raise_attribute, "trp_player",ca_charisma,2),
(troop_raise_skill, "trp_player",skl_weapon_master,1),
(troop_raise_skill, "trp_player",skl_power_strike,1),
(troop_raise_skill, "trp_player",skl_riding,1),
(troop_raise_skill, "trp_player",skl_tactics,1),
(troop_raise_skill, "trp_player",skl_leadership,1),
(troop_raise_proficiency, "trp_player",wpt_one_handed_weapon,10),
(troop_raise_proficiency, "trp_player",wpt_two_handed_weapon,10),
(troop_raise_proficiency, "trp_player",wpt_polearm,10),
(troop_add_item, "trp_player","itm_tab_shield_round_a",imod_battered),
(troop_set_slot, "trp_player", slot_troop_renown, 100),
(call_script, "script_change_player_honor", 3),
## (troop_add_item, "trp_player","itm_red_gambeson",imod_plain),
## (troop_add_item, "trp_player","itm_sword",imod_plain),
## (troop_add_item, "trp_player","itm_dagger",imod_balanced),
## (troop_add_item, "trp_player","itm_woolen_hose",0),
## (troop_add_item, "trp_player","itm_dried_meat",0),
## (troop_add_item, "trp_player","itm_saddle_horse",imod_plain),
(troop_add_gold, "trp_player", 100),
(else_try),
(eq,"$background_type",cb_noble),
(eq,"$character_gender",tf_female),
(troop_raise_attribute, "trp_player",ca_intelligence,2),
(troop_raise_attribute, "trp_player",ca_charisma,1),
(troop_raise_skill, "trp_player",skl_wound_treatment,1),
(troop_raise_skill, "trp_player",skl_riding,2),
(troop_raise_skill, "trp_player",skl_first_aid,1),
(troop_raise_skill, "trp_player",skl_leadership,1),
(troop_raise_proficiency, "trp_player",wpt_one_handed_weapon,20),
(troop_set_slot, "trp_player", slot_troop_renown, 50),
(troop_add_item, "trp_player","itm_tab_shield_round_a",imod_battered),
## (troop_add_item, "trp_player","itm_dress",imod_sturdy),
## (troop_add_item, "trp_player","itm_dagger",imod_watered_steel),
## (troop_add_item, "trp_player","itm_woolen_hose",0),
## (troop_add_item, "trp_player","itm_hunting_crossbow",0),
## (troop_add_item, "trp_player","itm_bolts",0),
## (troop_add_item, "trp_player","itm_smoked_fish",0),
## (troop_add_item, "trp_player","itm_courser",imod_spirited),
(troop_add_gold, "trp_player", 100),
(else_try),
(eq,"$background_type",cb_merchant),
(troop_raise_attribute, "trp_player",ca_intelligence,2),
(troop_raise_attribute, "trp_player",ca_charisma,1),
(troop_raise_skill, "trp_player",skl_riding,1),
(troop_raise_skill, "trp_player",skl_leadership,1),
(troop_raise_skill, "trp_player",skl_trade,2),
(troop_raise_skill, "trp_player",skl_inventory_management,1),
(troop_raise_proficiency, "trp_player",wpt_two_handed_weapon,10),
## (troop_add_item, "trp_player","itm_leather_jacket",0),
## (troop_add_item, "trp_player","itm_leather_boots",0),
## (troop_add_item, "trp_player","itm_fur_hat",0),
## (troop_add_item, "trp_player","itm_dagger",0),
## (troop_add_item, "trp_player","itm_hunting_crossbow",0),
## (troop_add_item, "trp_player","itm_bolts",0),
## (troop_add_item, "trp_player","itm_smoked_fish",0),
## (troop_add_item, "trp_player","itm_saddle_horse",0),
## (troop_add_item, "trp_player","itm_sumpter_horse",0),
## (troop_add_item, "trp_player","itm_salt",0),
## (troop_add_item, "trp_player","itm_salt",0),
## (troop_add_item, "trp_player","itm_salt",0),
## (troop_add_item, "trp_player","itm_pottery",0),
## (troop_add_item, "trp_player","itm_pottery",0),
(troop_add_gold, "trp_player", 250),
(troop_set_slot, "trp_player", slot_troop_renown, 20),
(else_try),
(eq,"$background_type",cb_guard),
(troop_raise_attribute, "trp_player",ca_strength,1),
(troop_raise_attribute, "trp_player",ca_agility,1),
(troop_raise_attribute, "trp_player",ca_charisma,1),
(troop_raise_skill, "trp_player","skl_ironflesh",1),
(troop_raise_skill, "trp_player","skl_power_strike",1),
(troop_raise_skill, "trp_player","skl_weapon_master",1),
(troop_raise_skill, "trp_player","skl_leadership",1),
(troop_raise_skill, "trp_player","skl_trainer",1),
(troop_raise_proficiency, "trp_player",wpt_one_handed_weapon,10),
(troop_raise_proficiency, "trp_player",wpt_two_handed_weapon,15),
(troop_raise_proficiency, "trp_player",wpt_polearm,20),
(troop_raise_proficiency, "trp_player",wpt_throwing,10),
(troop_add_item, "trp_player","itm_tab_shield_kite_b",imod_battered),
## (troop_add_item, "trp_player","itm_leather_jerkin",imod_ragged),
## (troop_add_item, "trp_player","itm_skullcap",imod_rusty),
## (troop_add_item, "trp_player","itm_spear",0),
## (troop_add_item, "trp_player","itm_arming_sword",imod_chipped),
## (troop_add_item, "trp_player","itm_hunting_crossbow",0),
## (troop_add_item, "trp_player","itm_hunter_boots",0),
## (troop_add_item, "trp_player","itm_leather_gloves",imod_ragged),
## (troop_add_item, "trp_player","itm_bolts",0),
## (troop_add_item, "trp_player","itm_smoked_fish",0),
## (troop_add_item, "trp_player","itm_saddle_horse",imod_swaybacked),
(troop_add_gold, "trp_player", 50),
(troop_set_slot, "trp_player", slot_troop_renown, 10),
(else_try),
(eq,"$background_type",cb_forester),
(troop_raise_attribute, "trp_player",ca_strength,1),
(troop_raise_attribute, "trp_player",ca_agility,2),
(troop_raise_skill, "trp_player","skl_power_draw",1),
(troop_raise_skill, "trp_player","skl_tracking",1),
(troop_raise_skill, "trp_player","skl_pathfinding",1),
(troop_raise_skill, "trp_player","skl_spotting",1),
(troop_raise_skill, "trp_player","skl_athletics",1),
(troop_raise_proficiency, "trp_player",wpt_two_handed_weapon,10),
(troop_raise_proficiency, "trp_player",wpt_archery,30),
## (troop_add_item, "trp_player","itm_short_bow",imod_bent),
## (troop_add_item, "trp_player","itm_arrows",0),
## (troop_add_item, "trp_player","itm_axe",imod_chipped),
## (troop_add_item, "trp_player","itm_rawhide_coat",0),
## (troop_add_item, "trp_player","itm_hide_boots",0),
## (troop_add_item, "trp_player","itm_dried_meat",0),
## (troop_add_item, "trp_player","itm_sumpter_horse",imod_heavy),
## (troop_add_item, "trp_player","itm_furs",0),
(troop_add_gold, "trp_player", 30),
(else_try),
(eq,"$background_type",cb_nomad),
(eq,"$character_gender",tf_male),
(troop_raise_attribute, "trp_player",ca_strength,1),
(troop_raise_attribute, "trp_player",ca_agility,1),
(troop_raise_attribute, "trp_player",ca_intelligence,1),
(troop_raise_skill, "trp_player","skl_power_draw",1),
(troop_raise_skill, "trp_player","skl_horse_archery",1),
(troop_raise_skill, "trp_player","skl_pathfinding",1),
(troop_raise_skill, "trp_player","skl_riding",2),
(troop_raise_proficiency, "trp_player",wpt_one_handed_weapon,10),
(troop_raise_proficiency, "trp_player",wpt_archery,30),
(troop_raise_proficiency, "trp_player",wpt_throwing,10),
(troop_add_item, "trp_player","itm_tab_shield_small_round_a",imod_battered),
## (troop_add_item, "trp_player","itm_javelin",imod_bent),
## (troop_add_item, "trp_player","itm_sword_khergit_1",imod_rusty),
## (troop_add_item, "trp_player","itm_nomad_armor",0),
## (troop_add_item, "trp_player","itm_hide_boots",0),
## (troop_add_item, "trp_player","itm_horse_meat",0),
## (troop_add_item, "trp_player","itm_steppe_horse",0),
(troop_add_gold, "trp_player", 15),
(troop_set_slot, "trp_player", slot_troop_renown, 10),
(else_try),
(eq,"$background_type",cb_nomad),
(eq,"$character_gender",tf_female),
(troop_raise_attribute, "trp_player",ca_strength,1),
(troop_raise_attribute, "trp_player",ca_agility,1),
(troop_raise_attribute, "trp_player",ca_intelligence,1),
(troop_raise_skill, "trp_player","skl_wound_treatment",1),
(troop_raise_skill, "trp_player","skl_first_aid",1),
(troop_raise_skill, "trp_player","skl_pathfinding",1),
(troop_raise_skill, "trp_player","skl_riding",2),
(troop_raise_proficiency, "trp_player",wpt_one_handed_weapon,5),
(troop_raise_proficiency, "trp_player",wpt_archery,20),
(troop_raise_proficiency, "trp_player",wpt_throwing,5),
(troop_add_item, "trp_player","itm_tab_shield_small_round_a",imod_battered),
## (troop_add_item, "trp_player","itm_javelin",imod_bent),
## (troop_add_item, "trp_player","itm_sickle",imod_plain),
## (troop_add_item, "trp_player","itm_nomad_armor",0),
## (troop_add_item, "trp_player","itm_hide_boots",0),
## (troop_add_item, "trp_player","itm_steppe_horse",0),
## (troop_add_item, "trp_player","itm_grain",0),
(troop_add_gold, "trp_player", 20),
(else_try),
(eq,"$background_type",cb_thief),
(troop_raise_attribute, "trp_player",ca_agility,3),
(troop_raise_skill, "trp_player","skl_athletics",2),
(troop_raise_skill, "trp_player","skl_power_throw",1),
(troop_raise_skill, "trp_player","skl_inventory_management",1),
(troop_raise_skill, "trp_player","skl_looting",1),
(troop_raise_proficiency, "trp_player",wpt_one_handed_weapon,20),
(troop_raise_proficiency, "trp_player",wpt_throwing,20),
(troop_add_item, "trp_player","itm_throwing_knives",0),
## (troop_add_item, "trp_player","itm_stones",0),
## (troop_add_item, "trp_player","itm_cudgel",imod_plain),
## (troop_add_item, "trp_player","itm_dagger",imod_rusty),
## (troop_add_item, "trp_player","itm_shirt",imod_tattered),
## (troop_add_item, "trp_player","itm_black_hood",imod_tattered),
## (troop_add_item, "trp_player","itm_wrapping_boots",imod_ragged),
(troop_add_gold, "trp_player", 25),
## (else_try),
## (eq,"$background_type",cb_priest),
## (troop_raise_attribute, "trp_player",ca_strength,1),
## (troop_raise_attribute, "trp_player",ca_intelligence,2),
## (troop_raise_attribute, "trp_player",ca_charisma,1),
## (troop_raise_skill, "trp_player",skl_wound_treatment,1),
## (troop_raise_skill, "trp_player",skl_leadership,1),
## (troop_raise_skill, "trp_player",skl_prisoner_management,1),
## (troop_raise_proficiency, "trp_player",0,10),
## (troop_add_item, "trp_player","itm_robe",0),
## (troop_add_item, "trp_player","itm_wrapping_boots",0),
## (troop_add_item, "trp_player","itm_club",0),
## (troop_add_item, "trp_player","itm_smoked_fish",0),
## (troop_add_item, "trp_player","itm_sumpter_horse",0),
## (troop_add_gold, "trp_player", 10),
## (troop_set_slot, "trp_player", slot_troop_renown, 10),
(try_end),
(try_begin),
(eq,"$background_answer_2",cb2_page),
(troop_raise_attribute, "trp_player",ca_charisma,1),
(troop_raise_attribute, "trp_player",ca_strength,1),
(troop_raise_skill, "trp_player","skl_power_strike",1),
(troop_raise_skill, "trp_player","skl_persuasion",1),
(troop_raise_proficiency, "trp_player",wpt_one_handed_weapon,15),
(troop_raise_proficiency, "trp_player",wpt_polearm,5),
(else_try),
(eq,"$background_answer_2",cb2_apprentice),
(troop_raise_attribute, "trp_player",ca_intelligence,1),
(troop_raise_attribute, "trp_player",ca_strength,1),
(troop_raise_skill, "trp_player","skl_engineer",1),
(troop_raise_skill, "trp_player","skl_trade",1),
(else_try),
(eq,"$background_answer_2",cb2_urchin),
(troop_raise_attribute, "trp_player",ca_agility,1),
(troop_raise_attribute, "trp_player",ca_intelligence,1),
(troop_raise_skill, "trp_player","skl_spotting",1),
(troop_raise_skill, "trp_player","skl_looting",1),
(troop_raise_proficiency, "trp_player",wpt_one_handed_weapon,15),
(troop_raise_proficiency, "trp_player",wpt_throwing,5),
(else_try),
(eq,"$background_answer_2",cb2_steppe_child),
(troop_raise_attribute, "trp_player",ca_strength,1),
(troop_raise_attribute, "trp_player",ca_agility,1),
(troop_raise_skill, "trp_player","skl_horse_archery",1),
(troop_raise_skill, "trp_player","skl_power_throw",1),
(troop_raise_proficiency, "trp_player",wpt_archery,15),
(call_script,"script_change_troop_renown", "trp_player", 5),
(else_try),
(eq,"$background_answer_2",cb2_merchants_helper),
(troop_raise_attribute, "trp_player",ca_intelligence,1),
(troop_raise_attribute, "trp_player",ca_charisma,1),
(troop_raise_skill, "trp_player","skl_inventory_management",1),
(troop_raise_skill, "trp_player","skl_trade",1),
## (else_try),
## (eq,"$background_answer_2",5),
## (troop_raise_attribute, "trp_player",ca_intelligence,1),
## (troop_raise_attribute, "trp_player",ca_charisma,1),
## (troop_raise_skill, "trp_player",skl_leadership,1),
## (troop_raise_skill, "trp_player",skl_athletics,1),
## (troop_raise_skill, "trp_player",skl_riding,1),
## (troop_raise_proficiency, "trp_player",1,5),
## (troop_raise_proficiency, "trp_player",2,5),
## (call_script,"script_change_troop_renown", "trp_player", 15),
## (else_try),
## (eq,"$background_answer_2",6),
## (troop_raise_attribute, "trp_player",ca_charisma,3),
## (troop_raise_attribute, "trp_player",ca_agility,1),
## (troop_raise_skill, "trp_player",skl_weapon_master,1),
## (troop_raise_proficiency, "trp_player",0,15),
## (troop_raise_proficiency, "trp_player",2,10),
## (troop_raise_proficiency, "trp_player",4,10),
## (call_script,"script_change_troop_renown", "trp_player", 20),
## (else_try),
## (eq,"$background_answer_2",7),
## (troop_raise_attribute, "trp_player",ca_intelligence,1),
## (troop_raise_attribute, "trp_player",ca_charisma,2),
## (troop_raise_skill, "trp_player",skl_leadership,1),
## (troop_raise_skill, "trp_player",skl_tactics,1),
## (troop_raise_proficiency, "trp_player",0,10),
## (troop_raise_proficiency, "trp_player",1,10),
## (call_script,"script_change_troop_renown", "trp_player", 15),
## (else_try),
## (eq,"$background_answer_2",8),
## (troop_raise_attribute, "trp_player",ca_agility,1),
## (troop_raise_attribute, "trp_player",ca_intelligence,1),
## (troop_raise_attribute, "trp_player",ca_charisma,1),
## (troop_raise_skill, "trp_player",skl_leadership,1),
## (troop_raise_skill, "trp_player",skl_surgery,1),
## (troop_raise_skill, "trp_player",skl_first_aid,1),
## (troop_raise_proficiency, "trp_player",2,10),
## (call_script,"script_change_troop_renown", "trp_player", 5),
(try_end),
(try_begin),
## (eq,"$background_answer_3",1),
## (troop_raise_attribute, "trp_player",ca_strength,1),
## (troop_raise_skill, "trp_player",skl_power_strike,1),
## (troop_raise_skill, "trp_player",skl_shield,1),
## (troop_add_gold, "trp_player", 10),
## (try_begin),
## (this_or_next|player_has_item,"itm_sword"),
## (troop_has_item_equipped,"trp_player","itm_sword"),
## (troop_remove_item, "trp_player","itm_sword"),
## (try_end),
## (try_begin),
## (this_or_next|player_has_item,"itm_arming_sword"),
## (troop_has_item_equipped,"trp_player","itm_arming_sword"),
## (troop_remove_item, "trp_player","itm_arming_sword"),
## (try_end),
## (troop_add_item, "trp_player","itm_short_sword",0),
## (troop_add_item, "trp_player","itm_wooden_shield",imod_battered),
## (troop_raise_proficiency, "trp_player",0,10),
## (troop_raise_proficiency, "trp_player",4,10),
## (else_try),
## (eq,"$background_answer_3",2),
## (troop_raise_attribute, "trp_player",ca_agility,1),
## (troop_raise_skill, "trp_player",skl_weapon_master,1),
## (troop_raise_skill, "trp_player",skl_shield,1),
## (try_begin),
## (this_or_next|player_has_item,"itm_hide_boots"),
## (troop_has_item_equipped,"trp_player","itm_hide_boots"),
## (troop_remove_item, "trp_player","itm_hide_boots"),
## (try_end),
## (troop_add_item, "trp_player","itm_khergit_guard_helmet",imod_crude),
## (troop_add_item, "trp_player","itm_mail_chausses",imod_crude),
## (troop_add_item, "trp_player","itm_sword_khergit_1",imod_plain),
## (troop_add_gold, "trp_player", 20),
## (troop_raise_proficiency, "trp_player",2,20),
## (else_try),
(eq,"$background_answer_3",cb3_poacher),
(troop_raise_attribute, "trp_player",ca_strength,1),
(troop_raise_attribute, "trp_player",ca_agility,1),
(troop_raise_skill, "trp_player","skl_power_draw",1),
(troop_raise_skill, "trp_player","skl_tracking",1),
(troop_raise_skill, "trp_player","skl_spotting",1),
(troop_raise_skill, "trp_player","skl_athletics",1),
(troop_add_gold, "trp_player", 10),
(troop_raise_proficiency, "trp_player",wpt_polearm,10),
(troop_raise_proficiency, "trp_player",wpt_archery,35),
(troop_add_item, "trp_player","itm_axe",imod_chipped),
(troop_add_item, "trp_player","itm_rawhide_coat",0),
(troop_add_item, "trp_player","itm_hide_boots",0),
(troop_add_item, "trp_player","itm_hunting_bow",0),
(troop_add_item, "trp_player","itm_barbed_arrows",0),
(troop_add_item, "trp_player","itm_sumpter_horse",imod_heavy),
(troop_add_item, "trp_player","itm_dried_meat",0),
(troop_add_item, "trp_player","itm_dried_meat",0),
(troop_add_item, "trp_player","itm_furs",0),
(troop_add_item, "trp_player","itm_furs",0),
(else_try),
(eq,"$background_answer_3",cb3_craftsman),
(troop_raise_attribute, "trp_player",ca_strength,1),
(troop_raise_attribute, "trp_player",ca_intelligence,1),
(troop_raise_skill, "trp_player","skl_weapon_master",1),
(troop_raise_skill, "trp_player","skl_engineer",1),
(troop_raise_skill, "trp_player","skl_tactics",1),
(troop_raise_skill, "trp_player","skl_trade",1),
(troop_raise_proficiency, "trp_player",wpt_one_handed_weapon,15),
(troop_add_gold, "trp_player", 100),
(troop_add_item, "trp_player","itm_leather_boots",imod_ragged),
(troop_add_item, "trp_player","itm_coarse_tunic",0),
(troop_add_item, "trp_player","itm_sword_medieval_b", imod_balanced),
(troop_add_item, "trp_player","itm_hunting_crossbow",0),
(troop_add_item, "trp_player","itm_bolts",0),
(troop_add_item, "trp_player","itm_tools",0),
(troop_add_item, "trp_player","itm_saddle_horse",0),
(troop_add_item, "trp_player","itm_smoked_fish",0),
(else_try),
(eq,"$background_answer_3",cb3_peddler),
(troop_raise_attribute, "trp_player",ca_charisma,1),
(troop_raise_attribute, "trp_player",ca_intelligence,1),
(troop_raise_skill, "trp_player","skl_riding",1),
(troop_raise_skill, "trp_player","skl_trade",1),
(troop_raise_skill, "trp_player","skl_pathfinding",1),
(troop_raise_skill, "trp_player","skl_inventory_management",1),
(troop_add_item, "trp_player","itm_leather_gloves",imod_plain),
(troop_add_gold, "trp_player", 90),
(troop_raise_proficiency, "trp_player",wpt_polearm,15),
(troop_add_item, "trp_player","itm_leather_jacket",0),
(troop_add_item, "trp_player","itm_leather_boots",imod_ragged),
(troop_add_item, "trp_player","itm_fur_hat",0),
(troop_add_item, "trp_player","itm_staff",0),
(troop_add_item, "trp_player","itm_hunting_crossbow",0),
(troop_add_item, "trp_player","itm_bolts",0),
(troop_add_item, "trp_player","itm_saddle_horse",0),
(troop_add_item, "trp_player","itm_sumpter_horse",0),
(troop_add_item, "trp_player","itm_linen",0),
(troop_add_item, "trp_player","itm_pottery",0),
(troop_add_item, "trp_player","itm_wool",0),
(troop_add_item, "trp_player","itm_wool",0),
(troop_add_item, "trp_player","itm_smoked_fish",0),
## (else_try),
## (eq,"$background_answer_3",6),
## (troop_raise_attribute, "trp_player",ca_strength,1),
## (troop_raise_attribute, "trp_player",ca_charisma,1),
## (troop_raise_skill, "trp_player",skl_shield,1),
## (troop_raise_skill, "trp_player",skl_wound_treatment,1),
## (troop_raise_skill, "trp_player",skl_first_aid,1),
## (troop_raise_skill, "trp_player",skl_surgery,1),
## (troop_add_item, "trp_player","itm_leather_gloves",imod_ragged),
## (troop_add_item, "trp_player","itm_quarter_staff",imod_heavy),
## (troop_add_item, "trp_player","itm_black_hood",0),
## (troop_add_gold, "trp_player", 10),
## (troop_raise_proficiency, "trp_player",2,20),
(else_try),
(eq,"$background_answer_3",cb3_troubadour),
(troop_raise_attribute, "trp_player",ca_charisma,2),
(troop_raise_skill, "trp_player","skl_weapon_master",1),
(troop_raise_skill, "trp_player","skl_persuasion",1),
(troop_raise_skill, "trp_player","skl_leadership",1),
(troop_raise_skill, "trp_player","skl_pathfinding",1),
(troop_add_gold, "trp_player", 80),
(troop_raise_proficiency, "trp_player",wpt_one_handed_weapon,25),
(troop_raise_proficiency, "trp_player",wpt_crossbow,10),
(troop_add_item, "trp_player","itm_tabard",imod_sturdy),
(troop_add_item, "trp_player","itm_leather_boots",imod_ragged),
(troop_add_item, "trp_player","itm_sword_medieval_a", imod_rusty),
(troop_add_item, "trp_player","itm_hunting_crossbow", 0),
(troop_add_item, "trp_player","itm_bolts", 0),
(troop_add_item, "trp_player","itm_saddle_horse",imod_swaybacked),
(troop_add_item, "trp_player","itm_smoked_fish",0),
(else_try),
(eq,"$background_answer_3",cb3_squire),
(troop_raise_attribute, "trp_player",ca_strength,1),
(troop_raise_attribute, "trp_player",ca_agility,1),
(troop_raise_skill, "trp_player","skl_riding",1),
(troop_raise_skill, "trp_player","skl_weapon_master",1),
(troop_raise_skill, "trp_player","skl_power_strike",1),
(troop_raise_skill, "trp_player","skl_leadership",1),
(troop_add_gold, "trp_player", 20),
(troop_raise_proficiency, "trp_player",wpt_one_handed_weapon,30),
(troop_raise_proficiency, "trp_player",wpt_two_handed_weapon,30),
(troop_raise_proficiency, "trp_player",wpt_polearm,30),
(troop_raise_proficiency, "trp_player",wpt_archery,10),
(troop_raise_proficiency, "trp_player",wpt_crossbow,10),
(troop_raise_proficiency, "trp_player",wpt_throwing,10),
(troop_add_item, "trp_player","itm_leather_jerkin",imod_ragged),
(troop_add_item, "trp_player","itm_leather_boots",imod_tattered),
(troop_add_item, "trp_player","itm_sword_medieval_a", imod_rusty),
(troop_add_item, "trp_player","itm_hunting_crossbow",0),
(troop_add_item, "trp_player","itm_bolts",0),
(troop_add_item, "trp_player","itm_saddle_horse",imod_swaybacked),
(troop_add_item, "trp_player","itm_smoked_fish",0),
(else_try),
(eq,"$background_answer_3",cb3_lady_in_waiting),
(eq,"$character_gender",tf_female),
(troop_raise_attribute, "trp_player",ca_intelligence,1),
(troop_raise_attribute, "trp_player",ca_charisma,1),
(troop_raise_skill, "trp_player","skl_persuasion",2),
(troop_raise_skill, "trp_player","skl_riding",1),
(troop_raise_skill, "trp_player","skl_wound_treatment",1),
(troop_add_item, "trp_player","itm_dagger", 0),
(troop_add_item, "trp_player","itm_hunting_crossbow",0),
(troop_add_item, "trp_player","itm_bolts",0),
(troop_add_item, "trp_player","itm_courser", imod_spirited),
(troop_add_item, "trp_player","itm_woolen_hood",imod_sturdy),
(troop_add_item, "trp_player","itm_woolen_dress",imod_sturdy),
(troop_add_gold, "trp_player", 100),
(troop_raise_proficiency, "trp_player",wpt_one_handed_weapon,10),
(troop_raise_proficiency, "trp_player",wpt_crossbow,15),
(troop_add_item, "trp_player","itm_smoked_fish",0),
(else_try),
(eq,"$background_answer_3",cb3_student),
(troop_raise_attribute, "trp_player",ca_intelligence,2),
(troop_raise_skill, "trp_player","skl_weapon_master",1),
(troop_raise_skill, "trp_player","skl_surgery",1),
(troop_raise_skill, "trp_player","skl_wound_treatment",1),
(troop_raise_skill, "trp_player","skl_persuasion",1),
(troop_add_gold, "trp_player", 80),
(troop_raise_proficiency, "trp_player",wpt_one_handed_weapon,20),
(troop_raise_proficiency, "trp_player",wpt_crossbow,20),
(troop_add_item, "trp_player","itm_linen_tunic",imod_sturdy),
(troop_add_item, "trp_player","itm_woolen_hose",0),
(troop_add_item, "trp_player","itm_sword_medieval_a", imod_rusty),
(troop_add_item, "trp_player","itm_hunting_crossbow", 0),
(troop_add_item, "trp_player","itm_bolts", 0),
(troop_add_item, "trp_player","itm_saddle_horse",imod_swaybacked),
(troop_add_item, "trp_player","itm_smoked_fish",0),
(store_random_in_range, ":book_no", books_begin, books_end),
(troop_add_item, "trp_player",":book_no",0),
(try_end),
(try_begin),
(eq,"$background_answer_4",cb4_revenge),
(troop_raise_attribute, "trp_player",ca_strength,2),
(troop_raise_skill, "trp_player","skl_power_strike",1),
(else_try),
(eq,"$background_answer_4",cb4_loss),
(troop_raise_attribute, "trp_player",ca_charisma,2),
(troop_raise_skill, "trp_player","skl_ironflesh",1),
(else_try),
(eq,"$background_answer_4",cb4_wanderlust),
(troop_raise_attribute, "trp_player",ca_agility,2),
(troop_raise_skill, "trp_player","skl_pathfinding",1),
## (else_try),
## (eq,"$background_answer_4",4),
## (troop_raise_attribute, "trp_player",ca_charisma,1),
## (troop_raise_skill, "trp_player",skl_wound_treatment,1),
## (troop_raise_proficiency, "trp_player",5,10),
(else_try),
(eq,"$background_answer_4",cb4_disown),
(troop_raise_attribute, "trp_player",ca_strength,1),
(troop_raise_attribute, "trp_player",ca_intelligence,1),
(troop_raise_skill, "trp_player","skl_weapon_master",1),
(else_try),
(eq,"$background_answer_4",cb4_greed),
(troop_raise_attribute, "trp_player",ca_agility,1),
(troop_raise_attribute, "trp_player",ca_intelligence,1),
(troop_raise_skill, "trp_player","skl_looting",1),
(try_end),
(try_begin),
(eq, "$background_type", cb_noble),
(jump_to_menu, "mnu_auto_return"),
#normal_banner_begin
(start_presentation, "prsnt_banner_selection"),
#custom_banner_begin
# (start_presentation, "prsnt_custom_banner"),
(else_try),
(change_screen_return, 0),
(try_end),
(set_show_messages, 1),
]),
("go_back_dot",[],"Go back.",[
(jump_to_menu,"mnu_start_character_4"),
]),
]
),
(
"past_life_explanation",mnf_disable_all_keys,
"{s3}",
"none",
[
(try_begin),
(gt,"$current_string_reg",14),
(assign,"$current_string_reg",10),
(try_end),
(str_store_string_reg,s3,"$current_string_reg"),
(try_begin),
(ge,"$current_string_reg",14),
(str_store_string,s5,"@Back to the beginning..."),
(else_try),
(str_store_string,s5,"@View next segment..."),
(try_end),
],
[
("view_next",[],"{s5}",[
(val_add,"$current_string_reg",1),
(jump_to_menu, "mnu_past_life_explanation"),
]),
("continue",[],"Continue...",
[
]),
("go_back_dot",[],"Go back.",[
(jump_to_menu, "mnu_choose_skill"),
]),
]
),
(
"auto_return",0,
"{!}This menu automatically returns to caller.",
"none",
[(change_screen_return, 0)],
[
]
),
("morale_report",0,
"{s1}",
"none",
[
(call_script, "script_get_player_party_morale_values"),
(assign, ":target_morale", reg0),
(assign, reg1, "$g_player_party_morale_modifier_party_size"),
(try_begin),
(gt, reg1, 0),
(str_store_string, s2, "@{!} -"),
(else_try),
(str_store_string, s2, "str_space"),
(try_end),
(assign, reg2, "$g_player_party_morale_modifier_leadership"),
(try_begin),
(gt, reg2, 0),
(str_store_string, s3, "@{!} +"),
(else_try),
(str_store_string, s3, "str_space"),
(try_end),
(try_begin),
(gt, "$g_player_party_morale_modifier_no_food", 0),
(assign, reg7, "$g_player_party_morale_modifier_no_food"),
(str_store_string, s5, "@^No food: -{reg7}"),
(else_try),
(str_store_string, s5, "str_space"),
(try_end),
(assign, reg3, "$g_player_party_morale_modifier_food"),
(try_begin),
(gt, reg3, 0),
(str_store_string, s4, "@{!} +"),
(else_try),
(str_store_string, s4, "str_space"),
(try_end),
(try_begin),
(gt, "$g_player_party_morale_modifier_debt", 0),
(assign, reg6, "$g_player_party_morale_modifier_debt"),
(str_store_string, s6, "@^Wage debt: -{reg6}"),
(else_try),
(str_store_string, s6, "str_space"),
(try_end),
(party_get_morale, reg5, "p_main_party"),
(store_sub, reg4, reg5, ":target_morale"),
(try_begin),
(gt, reg4, 0),
(str_store_string, s7, "@{!} +"),
(else_try),
(str_store_string, s7, "str_space"),
(try_end),
(assign, reg6, 50),
(str_store_string, s1, "str_current_party_morale_is_reg5_current_party_morale_modifiers_are__base_morale__50_party_size_s2reg1_leadership_s3reg2_food_variety_s4reg3s5s6_recent_events_s7reg4_total__reg5___"),
(try_for_range, ":kingdom_no", npc_kingdoms_begin, npc_kingdoms_end),
(faction_get_slot, ":faction_morale", ":kingdom_no", slot_faction_morale_of_player_troops),
(val_div, ":faction_morale", 100),
(neq, ":faction_morale", 0),
(assign, reg6, ":faction_morale"),
(str_store_faction_name, s9, ":kingdom_no"),
(str_store_string, s1, "str_s1extra_morale_for_s9_troops__reg6_"),
(try_end),
],
[
("continue",[],"Continue...",
[
(jump_to_menu, "mnu_reports"),
]),
]
),
("courtship_relations",0,
"{s1}",
"none",
[(str_store_string, s1, "str_courtships_in_progress_"),
(try_for_range, ":lady", kingdom_ladies_begin, kingdom_ladies_end),
(troop_slot_eq, ":lady", slot_troop_met, 2),
(call_script, "script_troop_get_relation_with_troop", "trp_player", ":lady"),
(gt, reg0, 0),
(assign, reg3, reg0),
(str_store_troop_name, s2, ":lady"),
(store_current_hours, ":hours_since_last_visit"),
(troop_get_slot, ":last_visit_hour", ":lady", slot_troop_last_talk_time),
(val_sub, ":hours_since_last_visit", ":last_visit_hour"),
(store_div, ":days_since_last_visit", ":hours_since_last_visit", 24),
(assign, reg4, ":days_since_last_visit"),
(str_store_string, s1, "str_s1_s2_relation_reg3_last_visit_reg4_days_ago"),
(try_end),
(str_store_string, s1, "str_s1__poems_known"),
(try_begin),
(gt, "$allegoric_poem_recitations", 0),
(str_store_string, s1, "str_s1_storming_the_castle_of_love_allegoric"),
(try_end),
(try_begin),
(gt, "$tragic_poem_recitations", 0),
(str_store_string, s1, "str_s1_kais_and_layali_tragic"),
(try_end),
(try_begin),
(gt, "$comic_poem_recitations", 0),
(str_store_string, s1, "str_s1_a_conversation_in_the_garden_comic"),
(try_end),
(try_begin),
(gt, "$heroic_poem_recitations", 0),
(str_store_string, s1, "str_s1_helgered_and_kara_epic"),
(try_end),
(try_begin),
(gt, "$mystic_poem_recitations", 0),
(str_store_string, s1, "str_s1_a_hearts_desire_mystic"),
(try_end),
],
[
("continue",[],"Continue...",
[(jump_to_menu, "mnu_reports"),
]
),
]
),
("lord_relations",0,
"{s1}",
"none",
[
(try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
(troop_set_slot, ":active_npc", slot_troop_temp_slot, 0),
(try_end),
(str_clear, s1),
(try_for_range, ":unused", active_npcs_begin, active_npcs_end),
(assign, ":score_to_beat", -100),
(assign, ":best_relation_remaining_npc", -1),
(try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
(troop_slot_eq, ":active_npc", slot_troop_temp_slot, 0),
(troop_slot_eq, ":active_npc", slot_troop_occupation, slto_kingdom_hero),
(troop_slot_ge, ":active_npc", slot_troop_met, 1),
(call_script, "script_troop_get_player_relation", ":active_npc"),
(assign, ":relation_with_player", reg0),
(ge, ":relation_with_player", ":score_to_beat"),
(assign, ":score_to_beat", ":relation_with_player"),
(assign, ":best_relation_remaining_npc", ":active_npc"),
(try_end),
(gt, ":best_relation_remaining_npc", -1),
(str_store_troop_name_link, s4, ":best_relation_remaining_npc"),
(assign, reg4, ":score_to_beat"),
(str_store_string, s1, "@{!}{s1}^{s4}: {reg4}"),
(troop_set_slot, ":best_relation_remaining_npc", slot_troop_temp_slot, 1),
(try_end),
],
[
("continue",[],"Continue...",
[(jump_to_menu, "mnu_reports"),
]
),
]
),
("companion_report",0,
"{s7}{s1}",
"none",
[
(str_clear, s1),
(str_store_string, s7, "str_no_companions_in_service"),
(try_begin),
(troop_get_slot, ":spouse_or_betrothed", "trp_player", slot_troop_spouse),
(try_begin),
(troop_get_type, ":is_female", "trp_player"),
(eq, ":is_female", 1),
(str_store_string, s8, "str_husband"),
(else_try),
(str_store_string, s8, "str_wife"),
(try_end),
(try_begin),
(le, ":spouse_or_betrothed", 0),
(troop_get_slot, ":spouse_or_betrothed", "trp_player", slot_troop_betrothed),
(str_store_string, s8, "str_betrothed"),
(try_end),
(gt, ":spouse_or_betrothed", 0),
(str_store_troop_name, s4, ":spouse_or_betrothed"),
(troop_get_slot, ":cur_center", ":spouse_or_betrothed", slot_troop_cur_center),
(try_begin),
(is_between, ":cur_center", centers_begin, centers_end),
(str_store_party_name, s5, ":cur_center"),
(else_try),
(troop_slot_eq, ":spouse_or_betrothed", slot_troop_occupation, slto_kingdom_hero),
(str_store_string, s5, "str_leading_party"),
(else_try),
(str_store_string, s5, "str_whereabouts_unknown"),
(try_end),
(str_store_string, s3, "str_s4_s8_s5"),
(str_store_string, s2, s1),
(str_store_string, s1, "str_s2_s3"),
(try_end),
(try_begin),
(ge, "$cheat_mode", 1),
(ge, "$npc_to_rejoin_party", 0),
(str_store_troop_name, s5, "$npc_to_rejoin_party"),
(str_store_string, s1, "@{!}DEBUG -- {s1}^NPC in rejoin queue: {s5}^"),
(try_end),
(try_for_range, ":companion", companions_begin, companions_end),
(str_clear, s2),
(str_clear, s3),
(try_begin),
(troop_get_slot, ":days_left", ":companion", slot_troop_days_on_mission),
(troop_slot_eq, ":companion", slot_troop_occupation, slto_player_companion),
(str_store_troop_name, s4, ":companion"),
(try_begin),
(troop_slot_eq, ":companion", slot_troop_current_mission, npc_mission_kingsupport),
(str_store_string, s8, "str_gathering_support"),
(try_begin),
(eq, ":days_left", 1),
(str_store_string, s5, "str_expected_back_imminently"),
(else_try),
(assign, reg3, ":days_left"),
(str_store_string, s5, "str_expected_back_in_approximately_reg3_days"),
(try_end),
(else_try),
(troop_slot_eq, ":companion", slot_troop_current_mission, npc_mission_gather_intel),
(troop_get_slot, ":town_with_contacts", ":companion", slot_troop_town_with_contacts),
(str_store_party_name, s11, ":town_with_contacts"),
(str_store_string, s8, "str_gathering_intelligence"),
(try_begin),
(eq, ":days_left", 1),
(str_store_string, s5, "str_expected_back_imminently"),
(else_try),
(assign, reg3, ":days_left"),
(str_store_string, s5, "str_expected_back_in_approximately_reg3_days"),
(try_end),
(else_try), #This covers most diplomatic missions
(troop_slot_ge, ":companion", slot_troop_current_mission, npc_mission_peace_request),
(neg|troop_slot_ge, ":companion", slot_troop_current_mission, 8),
(troop_get_slot, ":faction", ":companion", slot_troop_mission_object),
(str_store_faction_name, s9, ":faction"),
(str_store_string, s8, "str_diplomatic_embassy_to_s9"),
(try_begin),
(eq, ":days_left", 1),
(str_store_string, s5, "str_expected_back_imminently"),
(else_try),
(assign, reg3, ":days_left"),
(str_store_string, s5, "str_expected_back_in_approximately_reg3_days"),
(try_end),
(else_try),
(eq, ":companion", "$g_player_minister"),
(str_store_string, s8, "str_serving_as_minister"),
(try_begin),
(is_between, "$g_player_court", centers_begin, centers_end),
(str_store_party_name, s9, "$g_player_court"),
(str_store_string, s5, "str_in_your_court_at_s9"),
(else_try),
(str_store_string, s5, "str_whereabouts_unknown"),
(try_end),
(else_try),
(main_party_has_troop, ":companion"),
(str_store_string, s8, "str_under_arms"),
(str_store_string, s5, "str_in_your_party"),
(else_try),
(troop_slot_eq, ":companion", slot_troop_current_mission, npc_mission_rejoin_when_possible),
(str_store_string, s8, "str_attempting_to_rejoin_party"),
(str_store_string, s5, "str_whereabouts_unknown"),
(else_try), #Companions who are in a center
(troop_slot_ge, ":companion", slot_troop_cur_center, 1),
(str_store_string, s8, "str_separated_from_party"),
(str_store_string, s5, "str_whereabouts_unknown"),
(else_try), #Excludes companions who have occupation = retirement
(try_begin),
(check_quest_active, "qst_lend_companion"),
(quest_slot_eq, "qst_lend_companion", slot_quest_target_troop, ":companion"),
(str_store_string, s8, "@On loan,"),
(else_try),
(check_quest_active, "qst_lend_surgeon"),
(quest_slot_eq, "qst_lend_surgeon", slot_quest_target_troop, ":companion"),
(str_store_string, s8, "@On loan,"),
(else_try),
(troop_set_slot, ":companion", slot_troop_current_mission, npc_mission_rejoin_when_possible),
(str_store_string, s8, "str_attempting_to_rejoin_party"),
(try_end),
(str_store_string, s5, "str_whereabouts_unknown"),
(try_begin),
(ge, "$cheat_mode", 1),
(troop_get_slot, reg2, ":companion", slot_troop_current_mission),
(troop_get_slot, reg3, ":companion", slot_troop_days_on_mission),
(troop_get_slot, reg4, ":companion", slot_troop_prisoner_of_party),
(troop_get_slot, reg4, ":companion", slot_troop_playerparty_history),
(display_message, "@{!}DEBUG: {s4} current mission: {reg2}, days on mission: {reg3}, prisoner: {reg4}, pphistory: {reg5}"),
(try_end),
(try_end),
(str_store_string, s3, "str_s4_s8_s5"),
(str_store_string, s2, s1),
(str_store_string, s1, "str_s2_s3"),
(str_clear, s7), #"no companions in service"
(else_try),
(neg|troop_slot_eq, ":companion", slot_troop_occupation, slto_kingdom_hero),
(troop_slot_ge, ":companion", slot_troop_prisoner_of_party, centers_begin),
(str_store_troop_name, s4, ":companion"),
(str_store_string, s8, "str_missing_after_battle"),
(str_store_string, s5, "str_whereabouts_unknown"),
(str_store_string, s3, "str_s4_s8_s5"),
(str_store_string, s2, s1),
(str_store_string, s1, "str_s2_s3"),
(str_clear, s7), #"no companions in service"
(try_end),
(try_end),
],
[
("continue",[],"Continue...",
[(jump_to_menu, "mnu_reports"),
]
),
]
),
("faction_orders",0,
"{!}{s9}",
"none",
[
(str_clear, s9),
(store_current_hours, ":cur_hours"),
(try_for_range, ":faction_no", kingdoms_begin, kingdoms_end),
(faction_slot_eq, ":faction_no", slot_faction_state, sfs_active),
(neq, ":faction_no", "fac_player_supporters_faction"),
(faction_get_slot, ":old_faction_ai_state", ":faction_no", slot_faction_ai_state),
(try_begin),
(faction_get_slot, ":faction_marshal", ":faction_no", slot_faction_marshall),
(gt, ":faction_marshal", -1),
(assign, ":faction_ai_decider", ":faction_marshal"),
(else_try),
(faction_get_slot, ":faction_ai_decider", ":faction_no", slot_faction_leader),
(try_end),
#(*1) these two lines moved to here from (*2)
(call_script, "script_npc_decision_checklist_faction_ai_alt", ":faction_ai_decider"),
(assign, ":new_strategy", reg0),
(str_store_string, s26, s14),
#(3*) these three lines moved to here from (*4)
(faction_get_slot, ":faction_ai_state", ":faction_no", slot_faction_ai_state),
(faction_get_slot, ":faction_ai_object", ":faction_no", slot_faction_ai_object),
(faction_get_slot, ":faction_marshall", ":faction_no", slot_faction_marshall),
(faction_get_slot, ":faction_ai_offensive_max_followers", ":faction_no", slot_faction_ai_offensive_max_followers),
(str_store_faction_name, s10, ":faction_no"),
(try_begin),
(faction_get_slot, ":faction_issue", ":faction_no", slot_faction_political_issue),
(try_begin),
(eq, ":faction_issue", 1),
(str_store_string, s11, "@Appoint next marshal"),
(else_try),
(is_between, ":faction_issue", centers_begin, centers_end),
(str_store_party_name, s12, ":faction_issue"),
(str_store_string, s11, "@Award {s12} as fief"),
(else_try),
(eq, ":faction_issue", 0),
(str_store_string, s11, "@None"),
(else_try),
(assign, reg3, ":faction_issue"),
(str_store_string, s11, "@{!}Error ({reg3})"),
(try_end),
(store_current_hours, reg4),
(faction_get_slot, ":faction_issue_put_on_agenda", ":faction_no", slot_faction_political_issue_time),
(val_sub, reg4, ":faction_issue_put_on_agenda"),
(str_store_string, s10, "@{!}{s10}^Faction political issue: {s11}"),
(try_begin),
(faction_slot_ge, ":faction_no", slot_faction_political_issue, 1),
(str_store_string, s10, "@{!}{s10} (on agenda {reg4} hours)"),
(try_end),
(try_end),
(assign, reg2, ":faction_ai_offensive_max_followers"),
(try_begin),
(eq, ":faction_ai_state", sfai_default),
(str_store_string, s11, "@{!}Defending"),
(else_try),
(eq, ":faction_ai_state", sfai_gathering_army),
(str_store_string, s11, "@{!}Gathering army"),
(else_try),
(eq, ":faction_ai_state", sfai_attacking_center),
(str_store_party_name, s11, ":faction_ai_object"),
(str_store_string, s11, "@{!}Besieging {s11}"),
(else_try),
(eq, ":faction_ai_state", sfai_raiding_village),
(str_store_party_name, s11, ":faction_ai_object"),
(str_store_string, s11, "@{!}Raiding {s11}"),
(else_try),
(eq, ":faction_ai_state", sfai_attacking_enemy_army),
(str_store_party_name, s11, ":faction_ai_object"),
(str_store_string, s11, "str_attacking_enemy_army_near_s11"),
(else_try),
(eq, ":faction_ai_state", sfai_feast),
(str_store_party_name, s11, ":faction_ai_object"),
(str_store_string, s11, "str_holding_feast_at_s11"),
(else_try),
(eq, ":faction_ai_state", sfai_attacking_enemies_around_center),
(str_store_party_name, s11, ":faction_ai_object"),
(str_store_string, s11, "@{!}Attacking enemies around {s11}"),
(else_try),
(assign, reg4, ":faction_ai_state"),
(str_store_string, s11, "str_sfai_reg4"),
(try_end),
(try_begin),
(lt, ":faction_marshall", 0),
(str_store_string, s12, "@No one"),
(else_try),
(str_store_troop_name, s12, ":faction_marshall"),
(troop_get_slot, reg21, ":faction_marshall", slot_troop_controversy),
(str_store_string, s12, "@{!}{s12} (controversy: {reg21})"),
(try_end),
(try_for_parties, ":screen_party"),
(party_slot_eq, ":screen_party", slot_party_ai_state, spai_screening_army),
(store_faction_of_party, ":screen_party_faction", ":screen_party"),
(eq, ":screen_party_faction", ":faction_no"),
(str_store_party_name, s38, ":screen_party"),
(str_store_string, s12, "@{!}{s12}^Screening party: {s38}"),
(try_end),
#(*2) these two lines moved to up (look *1)
#(call_script, "script_npc_decision_checklist_faction_ai", ":faction_no"),
#(assign, ":new_strategy", reg0),
#(try_begin),
# (this_or_next|eq, ":new_strategy", sfai_default),
# (eq, ":new_strategy", sfai_feast),
#
# (store_current_hours, ":hours"),
# (faction_set_slot, ":faction_no", slot_faction_ai_last_rest_time, ":hours"),
#(try_end),
(try_begin),
#new condition to rest, (a faction's new strategy should be feast or default) and (":hours_at_current_state" > 20)
(this_or_next|eq, ":new_strategy", sfai_default),
(eq, ":new_strategy", sfai_feast),
(store_current_hours, ":hours_at_current_state"),
(faction_get_slot, ":current_state_started", ":faction_no", slot_faction_ai_current_state_started),
(val_sub, ":hours_at_current_state", ":current_state_started"),
(ge, ":hours_at_current_state", 18),
(store_current_hours, ":hours"),
(faction_set_slot, ":faction_no", slot_faction_ai_last_rest_time, ":hours"),
(try_end),
#Change of strategy
(try_begin),
(neq, ":new_strategy", ":old_faction_ai_state"),
(store_current_hours, ":hours"),
(faction_set_slot, ":faction_no", slot_faction_ai_current_state_started, ":hours"),
(try_end),
(call_script, "script_evaluate_realm_stability", ":faction_no"),
(assign, ":disgruntled_lords", reg0),
(assign, ":restless_lords", reg1),
(faction_get_slot, ":last_feast_ended", ":faction_no", slot_faction_last_feast_start_time),
(store_sub, ":hours_since_last_feast", ":cur_hours", ":last_feast_ended"),
(val_sub, ":hours_since_last_feast", 72),
(faction_get_slot, ":current_state_started", ":faction_no", slot_faction_ai_current_state_started),
(store_sub, ":hours_at_current_state", ":cur_hours", ":current_state_started"),
(faction_get_slot, ":faction_ai_last_offensive_time", ":faction_no", slot_faction_last_offensive_concluded),
(store_sub, ":hours_since_last_offensive", ":cur_hours", ":faction_ai_last_offensive_time"),
(faction_get_slot, ":faction_ai_last_rest", ":faction_no", slot_faction_ai_last_rest_time),
(store_sub, ":hours_since_last_rest", ":cur_hours", ":faction_ai_last_rest"),
(faction_get_slot, ":faction_ai_last_decisive_event", ":faction_no", slot_faction_ai_last_decisive_event),
(store_sub, ":hours_since_last_decisive_event", ":cur_hours", ":faction_ai_last_decisive_event"),
(assign, reg3, ":hours_at_current_state"),
(assign, reg4, ":hours_since_last_offensive"),
(assign, reg5, ":hours_since_last_feast"),
(assign, reg7, ":disgruntled_lords"),
(assign, reg8, ":restless_lords"),
(assign, reg9, ":hours_since_last_rest"),
(assign, reg10, ":hours_since_last_decisive_event"),
(str_store_string, s14, s26),
(str_store_string, s9, "str_s9s10_current_state_s11_hours_at_current_state_reg3_current_strategic_thinking_s14_marshall_s12_since_the_last_offensive_ended_reg4_hours_since_the_decisive_event_reg10_hours_since_the_last_rest_reg9_hours_since_the_last_feast_ended_reg5_hours_percent_disgruntled_lords_reg7_percent_restless_lords_reg8__"),
(try_end),
(try_begin),
(neg|is_between, "$g_cheat_selected_faction", kingdoms_begin, kingdoms_end),
(call_script, "script_get_next_active_kingdom", kingdoms_end),
(assign, "$g_cheat_selected_faction", reg0),
(try_end),
(str_store_faction_name, s10, "$g_cheat_selected_faction"),
(str_store_string, s9, "@Selected faction is: {s10}^^{s9}"),
],
[
("faction_orders_next_faction", [],"{!}Select next faction.",
[
(call_script, "script_get_next_active_kingdom", "$g_cheat_selected_faction"),
(assign, "$g_cheat_selected_faction", reg0),
(jump_to_menu, "mnu_faction_orders"),
]
),
("faction_orders_political_collapse", [],"{!}CHEAT - Cause all lords in faction to fall out with their liege.",
[
(try_for_range, ":lord", active_npcs_begin, active_npcs_end),
(troop_slot_eq, ":lord", slot_troop_occupation, slto_kingdom_hero),
(store_faction_of_troop, ":troop_faction", ":lord"),
(eq, ":troop_faction", "$g_cheat_selected_faction"),
(faction_get_slot, ":faction_liege", ":troop_faction", slot_faction_leader),
(call_script, "script_troop_change_relation_with_troop", ":lord", ":faction_liege", -200),
(try_end),
]
),
("faction_orders_defend", [],"{!}Force defend.",
[
(faction_set_slot, "$g_cheat_selected_faction", slot_faction_ai_state, sfai_default),
(faction_set_slot, "$g_cheat_selected_faction", slot_faction_ai_object, -1),
(jump_to_menu, "mnu_faction_orders"),
]
),
("faction_orders_feast", [],"{!}Force feast.",
[
(assign, ":location_high_score", 0),
(try_for_range, ":location", walled_centers_begin, walled_centers_end),
(neg|party_slot_ge, ":location", slot_center_is_besieged_by, 1),
(store_faction_of_party, ":location_faction", ":location"),
(eq, ":location_faction", "$g_cheat_selected_faction"),
(party_get_slot, ":location_lord", ":location", slot_town_lord),
(troop_get_slot, ":location_score", ":location_lord", slot_troop_renown),
(store_random_in_range, ":random", 0, 1000), #will probably be king or senior lord
(val_add, ":location_score", ":random"),
(gt, ":location_score", ":location_high_score"),
(assign, ":location_high_score", ":location_score"),
(assign, ":location_feast", ":location"),
(try_end),
(try_begin),
(gt, ":location_feast", centers_begin),
(faction_set_slot, "$g_cheat_selected_faction", slot_faction_ai_state, sfai_feast),
(faction_set_slot, "$g_cheat_selected_faction", slot_faction_ai_object, ":location_feast"),
(try_begin),
(eq, "$g_player_eligible_feast_center_no", ":location_feast"),
(assign, "$g_player_eligible_feast_center_no", -1),
(try_end),
(store_current_hours, ":hours"),
(faction_set_slot, "$g_cheat_selected_faction", slot_faction_last_feast_start_time, ":hours"),
(try_end),
(jump_to_menu, "mnu_faction_orders"),
]
),
("faction_orders_gather", [],"{!}Force gather army.",
[
(store_current_hours, ":cur_hours"),
(faction_set_slot, "$g_cheat_selected_faction", slot_faction_ai_state, sfai_gathering_army),
(faction_set_slot, "$g_cheat_selected_faction", slot_faction_last_offensive_concluded, ":cur_hours"),
(faction_set_slot, "$g_cheat_selected_faction", slot_faction_ai_offensive_max_followers, 1),
(faction_set_slot, "$g_cheat_selected_faction", slot_faction_ai_object, -1),
(jump_to_menu, "mnu_faction_orders"),
]
),
("faction_orders_increase_time", [],"{!}Increase last offensive time by 24 hours.",
[
(faction_get_slot, ":faction_ai_last_offensive_time", "$g_cheat_selected_faction", slot_faction_last_offensive_concluded),
(val_sub, ":faction_ai_last_offensive_time", 24),
(faction_set_slot, "$g_cheat_selected_faction", slot_faction_last_offensive_concluded, ":faction_ai_last_offensive_time"),
(jump_to_menu, "mnu_faction_orders"),
]
),
("faction_orders_rethink", [],"{!}Force rethink.",
[
(call_script, "script_init_ai_calculation"),
(call_script, "script_decide_faction_ai", "$g_cheat_selected_faction"),
(jump_to_menu, "mnu_faction_orders"),
]
),
("faction_orders_rethink_all", [],"{!}Force rethink for all factions.",
[
(call_script, "script_recalculate_ais"),
(jump_to_menu, "mnu_faction_orders"),
]
),
("enable_alt_ai",[(eq, "$g_use_alternative_ai", 2),],"{!}CHEAT! - enable alternative ai",
[
(assign, "$g_use_alternative_ai", 1),
(jump_to_menu, "mnu_faction_orders"),
]
),
("disable_alt_ai",[(eq, "$g_use_alternative_ai", 2)],"{!}CHEAT! - disable alternative ai",
[
(assign, "$g_use_alternative_ai", 0),
(jump_to_menu, "mnu_faction_orders"),
]
),
("faction_orders_init_econ", [],"{!}Initialize economic stats.",
[
(call_script, "script_initialize_economic_information"),
(jump_to_menu, "mnu_faction_orders"),
]
),
("go_back_dot",[],"{!}Go back.",
[(jump_to_menu, "mnu_reports"),
]
),
]
),
("character_report",0,
"{s9}",
"none",
[(try_begin),
(gt, "$g_player_reading_book", 0),
(player_has_item, "$g_player_reading_book"),
(str_store_item_name, s8, "$g_player_reading_book"),
(str_store_string, s9, "@You are currently reading {s8}."),
(else_try),
(assign, "$g_player_reading_book", 0),
(str_store_string, s9, "@You are not reading any books."),
(try_end),
(assign, ":num_friends", 0),
(assign, ":num_enemies", 0),
(str_store_string, s6, "@none"),
(str_store_string, s8, "@none"),
(try_for_range, ":troop_no", active_npcs_begin, active_npcs_end),
(this_or_next|troop_slot_eq, ":troop_no", slot_troop_occupation, slto_kingdom_hero),
(troop_slot_eq, ":troop_no", slot_troop_occupation, slto_inactive_pretender),
(call_script, "script_troop_get_player_relation", ":troop_no"),
(assign, ":player_relation", reg0),
#(troop_get_slot, ":player_relation", ":troop_no", slot_troop_player_relation),
(try_begin),
(gt, ":player_relation", 20),
(try_begin),
(eq, ":num_friends", 0),
(str_store_troop_name, s8, ":troop_no"),
(else_try),
(eq, ":num_friends", 1),
(str_store_troop_name, s7, ":troop_no"),
(str_store_string, s8, "@{s7} and {s8}"),
(else_try),
(str_store_troop_name, s7, ":troop_no"),
(str_store_string, s8, "@{!}{s7}, {s8}"),
(try_end),
(val_add, ":num_friends", 1),
(else_try),
(lt, ":player_relation", -20),
(try_begin),
(eq, ":num_enemies", 0),
(str_store_troop_name, s6, ":troop_no"),
(else_try),
(eq, ":num_enemies", 1),
(str_store_troop_name, s5, ":troop_no"),
(str_store_string, s6, "@{s5} and {s6}"),
(else_try),
(str_store_troop_name, s5, ":troop_no"),
(str_store_string, s6, "@{!}{s5}, {s6}"),
(try_end),
(val_add, ":num_enemies", 1),
(try_end),
(try_end),
#lord recruitment changes begin
(str_clear, s12),
(try_begin),
(gt, "$player_right_to_rule", 0),
(assign, reg12, "$player_right_to_rule"),
(str_store_string, s12, "str__right_to_rule_reg12"),
(try_end),
(str_clear, s15),
(try_begin),
(this_or_next|gt, "$claim_arguments_made", 0),
(this_or_next|gt, "$ruler_arguments_made", 0),
(this_or_next|gt, "$victory_arguments_made", 0),
(this_or_next|gt, "$lords_arguments_made", 0),
(eq, 1, 0),
(assign, reg3, "$claim_arguments_made"),
(assign, reg4, "$ruler_arguments_made"),
(assign, reg5, "$victory_arguments_made"),
(assign, reg6, "$lords_arguments_made"),
(assign, reg7, "$benefit_arguments_made"),
(str_store_string, s15, "str_political_arguments_made_legality_reg3_rights_of_lords_reg4_unificationpeace_reg5_rights_of_commons_reg6_fief_pledges_reg7"),
(try_end),
#lord recruitment changes begin
(assign, reg3, "$player_honor"),
(troop_get_slot, reg2, "trp_player", slot_troop_renown),
(str_store_string, s9, "str_renown_reg2_honour_rating_reg3s12_friends_s8_enemies_s6_s9"),
(call_script, "script_get_number_of_hero_centers", "trp_player"),
(assign, ":no_centers", reg0),
(try_begin),
(gt, ":no_centers", 0),
(try_for_range, ":i_center", 0, ":no_centers"),
(call_script, "script_troop_get_leaded_center_with_index", "trp_player", ":i_center"),
(assign, ":cur_center", reg0),
(try_begin),
(eq, ":i_center", 0),
(str_store_party_name, s8, ":cur_center"),
(else_try),
(eq, ":i_center", 1),
(str_store_party_name, s7, ":cur_center"),
(str_store_string, s8, "@{s7} and {s8}"),
(else_try),
(str_store_party_name, s7, ":cur_center"),
(str_store_string, s8, "@{!}{s7}, {s8}"),
(try_end),
(try_end),
(str_store_string, s9, "@Your estates are: {s8}.^{s9}"),
(try_end),
(try_begin),
(gt, "$players_kingdom", 0),
(str_store_faction_name, s8, "$players_kingdom"),
(try_begin),
(this_or_next|is_between, "$players_kingdom", npc_kingdoms_begin, npc_kingdoms_end),
(neg|faction_slot_eq, "fac_player_supporters_faction", slot_faction_leader, "trp_player"),
#(str_store_string, s9, "@You are a lord of {s8}.^{s9}"),
(str_store_string, s9, "str_you_are_a_lord_lady_of_s8_s9"),
(else_try),
(str_store_string, s9, "str_you_are_king_queen_of_s8_s9"),
(try_end),
(try_end),
],
[
#lord recruitment changes begin
("continue",[(eq,"$cheat_mode",1)],"{!}CHEAT! - increase Right to Rule",
[
(val_add, "$player_right_to_rule", 10),
(jump_to_menu, "mnu_character_report"),
]
),
("continue",[(eq,"$cheat_mode",1),
(str_store_troop_name, s14, "$g_talk_troop"),
],"{!}CHEAT! - increase your relation with {s14}",
[
(call_script, "script_change_player_relation_with_troop", "$g_talk_troop", 10),
(jump_to_menu, "mnu_character_report"),
]
),
("continue",[(eq,"$cheat_mode",1)],"{!}CHEAT! - increase honor",
[
(val_add, "$player_honor", 10),
(jump_to_menu, "mnu_character_report"),
]
),
("continue",[(eq,"$cheat_mode",1)],"{!}CHEAT! - increase renown",
[
(troop_get_slot, ":renown", "trp_player", slot_troop_renown),
(val_add, ":renown", 50),
(troop_set_slot, "trp_player", slot_troop_renown, ":renown"),
(jump_to_menu, "mnu_character_report"),
]
),
("continue",[(eq,"$cheat_mode",1)],"{!}CHEAT! - increase persuasion",
[
(troop_raise_skill, "trp_player", "skl_persuasion", 1),
(jump_to_menu, "mnu_character_report"),
]
),
("continue",[],"Continue...",
[(jump_to_menu, "mnu_reports"),
]
),
#lord recruitment changes end
]
),
("party_size_report",0,
"{s1}",
"none",
[(call_script, "script_game_get_party_companion_limit"),
(assign, ":party_size_limit", reg0),
(store_skill_level, ":leadership", "skl_leadership", "trp_player"),
(val_mul, ":leadership", 5),
(store_attribute_level, ":charisma", "trp_player", ca_charisma),
(troop_get_slot, ":renown", "trp_player", slot_troop_renown),
(val_div, ":renown", 25),
(try_begin),
(gt, ":leadership", 0),
(str_store_string, s2, "@{!} +"),
(else_try),
(str_store_string, s2, "str_space"),
(try_end),
(try_begin),
(gt, ":charisma", 0),
(str_store_string, s3, "@{!} +"),
(else_try),
(str_store_string, s3, "str_space"),
(try_end),
(try_begin),
(gt, ":renown", 0),
(str_store_string, s4, "@{!} +"),
(else_try),
(str_store_string, s4, "str_space"),
(try_end),
(assign, reg5, ":party_size_limit"),
(assign, reg1, ":leadership"),
(assign, reg2, ":charisma"),
(assign, reg3, ":renown"),
(str_store_string, s1, "@Current party size limit is {reg5}.^Current party size modifiers are:^^Base size: +30^Leadership: {s2}{reg1}^Charisma: {s3}{reg2}^Renown: {s4}{reg3}^TOTAL: {reg5}"),
],
[
("continue",[],"Continue...",
[(jump_to_menu, "mnu_reports"),
]
),
]
),
("faction_relations_report",0,
"{s1}",
"none",
[(str_clear, s2),
(try_for_range, ":cur_kingdom", kingdoms_begin, kingdoms_end),
(faction_slot_eq, ":cur_kingdom", slot_faction_state, sfs_active),
(neq, ":cur_kingdom", "fac_player_supporters_faction"),
(store_relation, ":cur_relation", "fac_player_supporters_faction", ":cur_kingdom"),
(try_begin),
(ge, ":cur_relation", 90),
(str_store_string, s3, "@Loyal"),
(else_try),
(ge, ":cur_relation", 80),
(str_store_string, s3, "@Devoted"),
(else_try),
(ge, ":cur_relation", 70),
(str_store_string, s3, "@Fond"),
(else_try),
(ge, ":cur_relation", 60),
(str_store_string, s3, "@Gracious"),
(else_try),
(ge, ":cur_relation", 50),
(str_store_string, s3, "@Friendly"),
(else_try),
(ge, ":cur_relation", 40),
(str_store_string, s3, "@Supportive"),
(else_try),
(ge, ":cur_relation", 30),
(str_store_string, s3, "@Favorable"),
(else_try),
(ge, ":cur_relation", 20),
(str_store_string, s3, "@Cooperative"),
(else_try),
(ge, ":cur_relation", 10),
(str_store_string, s3, "@Accepting"),
(else_try),
(ge, ":cur_relation", 0),
(str_store_string, s3, "@Indifferent"),
(else_try),
(ge, ":cur_relation", -10),
(str_store_string, s3, "@Suspicious"),
(else_try),
(ge, ":cur_relation", -20),
(str_store_string, s3, "@Grumbling"),
(else_try),
(ge, ":cur_relation", -30),
(str_store_string, s3, "@Hostile"),
(else_try),
(ge, ":cur_relation", -40),
(str_store_string, s3, "@Resentful"),
(else_try),
(ge, ":cur_relation", -50),
(str_store_string, s3, "@Angry"),
(else_try),
(ge, ":cur_relation", -60),
(str_store_string, s3, "@Hateful"),
(else_try),
(ge, ":cur_relation", -70),
(str_store_string, s3, "@Revengeful"),
(else_try),
(str_store_string, s3, "@Vengeful"),
(try_end),
(str_store_faction_name, s4, ":cur_kingdom"),
(assign, reg1, ":cur_relation"),
(str_store_string, s2, "@{!}{s2}^{s4}: {reg1} ({s3})"),
(try_end),
(str_store_string, s1, "@Your relation with the factions are:^{s2}"),
],
[
("continue",[],"Continue...",
[(jump_to_menu, "mnu_reports"),
]
),
]
),
("camp",mnf_scale_picture,
"You set up camp. What do you want to do?",
"none",
[
(assign, "$g_player_icon_state", pis_normal),
(set_background_mesh, "mesh_pic_camp"),
],
[
("camp_action_1",[(eq,"$cheat_mode",1)],"{!}Cheat: Walk around.",
[(set_jump_mission,"mt_ai_training"),
(call_script, "script_setup_random_scene"),
(change_screen_mission),
]
),
("camp_action",[],"Take an action.",
[(jump_to_menu, "mnu_camp_action"),
]
),
("camp_wait_here",[],"Wait here for some time.",
[
(assign,"$g_camp_mode", 1),
(assign, "$g_infinite_camping", 0),
(assign, "$g_player_icon_state", pis_camping),
(try_begin),
(party_is_active, "p_main_party"),
(party_get_current_terrain, ":cur_terrain", "p_main_party"),
(try_begin),
(eq, ":cur_terrain", rt_desert),
(unlock_achievement, ACHIEVEMENT_SARRANIDIAN_NIGHTS),
(try_end),
(try_end),
(rest_for_hours_interactive, 24 * 365, 5, 1), #rest while attackable
(change_screen_return),
]
),
("camp_cheat",
[(ge, "$cheat_mode", 1)
], "CHEAT MENU!",
[(jump_to_menu, "mnu_camp_cheat"),
],
),
("resume_travelling",[],"Resume travelling.",
[
(change_screen_return),
]
),
]
),
("camp_cheat",0,
"Select a cheat:",
"none",
[
],
[
("camp_cheat_find_item",[], "Find an item...",
[
(jump_to_menu, "mnu_cheat_find_item"),
]
),
("camp_cheat_find_item",[], "Change weather..",
[
(jump_to_menu, "mnu_cheat_change_weather"),
]
),
("camp_cheat_1",[],"{!}Increase player renown.",
[
(str_store_string, s1, "@Player renown is increased by 100. "),
(call_script, "script_change_troop_renown", "trp_player", 100),
(jump_to_menu, "mnu_camp_cheat"),
]
),
("camp_cheat_2",[],"{!}Increase player honor.",
[
(assign, reg7, "$player_honor"),
(val_add, reg7, 1),
(display_message, "@Player honor is increased by 1 and it is now {reg7}."),
(val_add, "$player_honor", 1),
(jump_to_menu, "mnu_camp_cheat"),
]
),
("camp_cheat_3",[],"{!}Update political notes.",
[
(try_for_range, ":hero", active_npcs_begin, active_npcs_end),
(troop_slot_eq, ":hero", slot_troop_occupation, slto_kingdom_hero),
(call_script, "script_update_troop_political_notes", ":hero"),
(try_end),
(try_for_range, ":kingdom", kingdoms_begin, kingdoms_end),
(call_script, "script_update_faction_political_notes", ":kingdom"),
(try_end),
]
),
("camp_cheat_4",[],"{!}Update troop notes.",
[
(try_for_range, ":hero", active_npcs_begin, active_npcs_end),
(troop_slot_eq, ":hero", slot_troop_occupation, slto_kingdom_hero),
(call_script, "script_update_troop_notes", ":hero"),
(try_end),
(try_for_range, ":lady", kingdom_ladies_begin, kingdom_ladies_end),
(call_script, "script_update_troop_notes", ":lady"),
(call_script, "script_update_troop_political_notes", ":lady"),
(call_script, "script_update_troop_location_notes", ":lady", 0),
(try_end),
]
),
("camp_cheat_5",[],"{!}Scramble minstrels.",
[
(call_script, "script_update_tavern_minstrels"),
]
),
("camp_cheat_6",[],"{!}Infinite camp",
[
(assign,"$g_camp_mode", 1),
(assign, "$g_infinite_camping", 1),
(assign, "$g_player_icon_state", pis_camping),
(rest_for_hours_interactive, 10 * 24 * 365, 20), #10 year rest while not attackable with 20x speed
(change_screen_return),
]
),
("cheat_faction_orders",[(ge,"$cheat_mode",1)],
"{!}Cheat: Set Debug messages to All.",
[(assign,"$cheat_mode",1),
(jump_to_menu, "mnu_camp_cheat"),
]
),
("cheat_faction_orders",[
(ge, "$cheat_mode", 1),
(neq,"$cheat_mode",3)],"{!}Cheat: Set Debug messages to Econ Only.",
[(assign,"$cheat_mode",3),
(jump_to_menu, "mnu_camp_cheat"),
]
),
("cheat_faction_orders",[
(ge, "$cheat_mode", 1),
(neq,"$cheat_mode",4)],"{!}Cheat: Set Debug messages to Political Only.",
[(assign,"$cheat_mode",4),
(jump_to_menu, "mnu_camp_cheat"),
]
),
("back_to_camp_menu",[],"{!}Back to camp menu.",
[
(jump_to_menu, "mnu_camp"),
]
),
]
),
("cheat_find_item",0,
"{!}Current item range: {reg5} to {reg6}",
"none",
[
(assign, reg5, "$cheat_find_item_range_begin"),
(store_add, reg6, "$cheat_find_item_range_begin", max_inventory_items),
(val_min, reg6, "itm_items_end"),
(val_sub, reg6, 1),
],
[
("cheat_find_item_next_range",[], "{!}Move to next item range.",
[
(val_add, "$cheat_find_item_range_begin", max_inventory_items),
(try_begin),
(ge, "$cheat_find_item_range_begin", "itm_items_end"),
(assign, "$cheat_find_item_range_begin", 0),
(try_end),
(jump_to_menu, "mnu_cheat_find_item"),
]
),
("cheat_find_item_choose_this",[], "{!}Choose from this range.",
[
(troop_clear_inventory, "trp_find_item_cheat"),
(store_add, ":max_item", "$cheat_find_item_range_begin", max_inventory_items),
(val_min, ":max_item", "itm_items_end"),
(store_sub, ":num_items_to_add", ":max_item", "$cheat_find_item_range_begin"),
(try_for_range, ":i_slot", 0, ":num_items_to_add"),
(store_add, ":item_id", "$cheat_find_item_range_begin", ":i_slot"),
(troop_add_items, "trp_find_item_cheat", ":item_id", 1),
(try_end),
(change_screen_trade, "trp_find_item_cheat"),
]
),
("camp_action_4",[],"{!}Back to camp menu.",
[(jump_to_menu, "mnu_camp"),
]
),
]
),
("cheat_change_weather",0,
"{!}Current cloud amount: {reg5}^Current Fog Strength: {reg6}",
"none",
[
(get_global_cloud_amount, reg5),
(get_global_haze_amount, reg6),
],
[
("cheat_increase_cloud",[], "{!}Increase Cloud Amount.",
[
(get_global_cloud_amount, ":cur_cloud_amount"),
(val_add, ":cur_cloud_amount", 5),
(val_min, ":cur_cloud_amount", 100),
(set_global_cloud_amount, ":cur_cloud_amount"),
]
),
("cheat_decrease_cloud",[], "{!}Decrease Cloud Amount.",
[
(get_global_cloud_amount, ":cur_cloud_amount"),
(val_sub, ":cur_cloud_amount", 5),
(val_max, ":cur_cloud_amount", 0),
(set_global_cloud_amount, ":cur_cloud_amount"),
]
),
("cheat_increase_fog",[], "{!}Increase Fog Amount.",
[
(get_global_haze_amount, ":cur_fog_amount"),
(val_add, ":cur_fog_amount", 5),
(val_min, ":cur_fog_amount", 100),
(set_global_haze_amount, ":cur_fog_amount"),
]
),
("cheat_decrease_fog",[], "{!}Decrease Fog Amount.",
[
(get_global_haze_amount, ":cur_fog_amount"),
(val_sub, ":cur_fog_amount", 5),
(val_max, ":cur_fog_amount", 0),
(set_global_haze_amount, ":cur_fog_amount"),
]
),
("camp_action_4",[],"{!}Back to camp menu.",
[(jump_to_menu, "mnu_camp"),
]
),
]
),
("camp_action",0,
"Choose an action:",
"none",
[
],
[
("camp_recruit_prisoners",
[(troops_can_join, 1),
(store_current_hours, ":cur_time"),
(val_sub, ":cur_time", 24),
(gt, ":cur_time", "$g_prisoner_recruit_last_time"),
(try_begin),
(gt, "$g_prisoner_recruit_last_time", 0),
(assign, "$g_prisoner_recruit_troop_id", 0),
(assign, "$g_prisoner_recruit_size", 0),
(assign, "$g_prisoner_recruit_last_time", 0),
(try_end),
], "Recruit some of your prisoners to your party.",
[(jump_to_menu, "mnu_camp_recruit_prisoners"),
],
),
("action_read_book",[],"Select a book to read.",
[(jump_to_menu, "mnu_camp_action_read_book"),
]
),
("action_rename_kingdom",
[
(eq, "$players_kingdom_name_set", 1),
(faction_slot_eq, "fac_player_supporters_faction", slot_faction_state, sfs_active),
(faction_slot_eq, "fac_player_supporters_faction", slot_faction_leader, "trp_player"),
],"Rename your kingdom.",
[(start_presentation, "prsnt_name_kingdom"),
]
),
("action_modify_banner",[(eq, "$cheat_mode", 1)],"{!}Cheat: Modify your banner.",
[
(start_presentation, "prsnt_banner_selection"),
#(start_presentation, "prsnt_custom_banner"),
]
),
("action_retire",[],"Retire from adventuring.",
[(jump_to_menu, "mnu_retirement_verify"),
]
),
("camp_action_4",[],"Back to camp menu.",
[(jump_to_menu, "mnu_camp"),
]
),
]
),
("camp_recruit_prisoners",0,
"You offer your prisoners freedom if they agree to join you as soldiers. {s18}",
"none",
[(assign, ":num_regular_prisoner_slots", 0),
(party_get_num_prisoner_stacks, ":num_stacks", "p_main_party"),
(try_for_range, ":cur_stack", 0, ":num_stacks"),
(party_prisoner_stack_get_troop_id, ":cur_troop_id", "p_main_party", ":cur_stack"),
(neg|troop_is_hero, ":cur_troop_id"),
(val_add, ":num_regular_prisoner_slots", 1),
(try_end),
(try_begin),
(eq, ":num_regular_prisoner_slots", 0),
(jump_to_menu, "mnu_camp_no_prisoners"),
(else_try),
(eq, "$g_prisoner_recruit_troop_id", 0),
(store_current_hours, "$g_prisoner_recruit_last_time"),
(store_random_in_range, ":rand", 0, 100),
(store_skill_level, ":persuasion_level", "skl_persuasion", "trp_player"),
(store_sub, ":reject_chance", 15, ":persuasion_level"),
(val_mul, ":reject_chance", 4),
(try_begin),
(lt, ":rand", ":reject_chance"),
(assign, "$g_prisoner_recruit_troop_id", -7),
(else_try),
(assign, ":num_regular_prisoner_slots", 0),
(party_get_num_prisoner_stacks, ":num_stacks", "p_main_party"),
(try_for_range, ":cur_stack", 0, ":num_stacks"),
(party_prisoner_stack_get_troop_id, ":cur_troop_id", "p_main_party", ":cur_stack"),
(neg|troop_is_hero, ":cur_troop_id"),
(val_add, ":num_regular_prisoner_slots", 1),
(try_end),
(store_random_in_range, ":random_prisoner_slot", 0, ":num_regular_prisoner_slots"),
(try_for_range, ":cur_stack", 0, ":num_stacks"),
(party_prisoner_stack_get_troop_id, ":cur_troop_id", "p_main_party", ":cur_stack"),
(neg|troop_is_hero, ":cur_troop_id"),
(val_sub, ":random_prisoner_slot", 1),
(lt, ":random_prisoner_slot", 0),
(assign, ":num_stacks", 0),
(assign, "$g_prisoner_recruit_troop_id", ":cur_troop_id"),
(party_prisoner_stack_get_size, "$g_prisoner_recruit_size", "p_main_party", ":cur_stack"),
(try_end),
(try_end),
(try_begin),
(gt, "$g_prisoner_recruit_troop_id", 0),
(party_get_free_companions_capacity, ":capacity", "p_main_party"),
(val_min, "$g_prisoner_recruit_size", ":capacity"),
(assign, reg1, "$g_prisoner_recruit_size"),
(gt, "$g_prisoner_recruit_size", 0),
(try_begin),
(gt, "$g_prisoner_recruit_size", 1),
(assign, reg2, 1),
(else_try),
(assign, reg2, 0),
(try_end),
(str_store_troop_name_by_count, s1, "$g_prisoner_recruit_troop_id", "$g_prisoner_recruit_size"),
(str_store_string, s18, "@{reg1} {s1} {reg2?accept:accepts} the offer."),
(else_try),
(str_store_string, s18, "@No one accepts the offer."),
(try_end),
(try_end),
],
[
("camp_recruit_prisoners_accept",[(gt, "$g_prisoner_recruit_troop_id", 0)],"Take them.",
[(remove_troops_from_prisoners, "$g_prisoner_recruit_troop_id", "$g_prisoner_recruit_size"),
(party_add_members, "p_main_party", "$g_prisoner_recruit_troop_id", "$g_prisoner_recruit_size"),
(store_mul, ":morale_change", -3, "$g_prisoner_recruit_size"),
(call_script, "script_change_player_party_morale", ":morale_change"),
(jump_to_menu, "mnu_camp"),
]
),
("camp_recruit_prisoners_reject",[(gt, "$g_prisoner_recruit_troop_id", 0)],"Reject them.",
[(jump_to_menu, "mnu_camp"),
(assign, "$g_prisoner_recruit_troop_id", 0),
(assign, "$g_prisoner_recruit_size", 0),
]
),
("continue",[(le, "$g_prisoner_recruit_troop_id", 0)],"Go back.",
[(jump_to_menu, "mnu_camp"),
]
),
]
),
("camp_no_prisoners",0,
"You have no prisoners to recruit from.",
"none",
[],
[
("continue",[],"Continue...",
[(jump_to_menu, "mnu_camp"),
]
),
]
),
("camp_action_read_book",0,
"Choose a book to read:",
"none",
[],
[
("action_read_book_1",[(player_has_item, "itm_book_tactics"),
(item_slot_eq, "itm_book_tactics", slot_item_book_read, 0),
(str_store_item_name, s1, "itm_book_tactics"),
],"{s1}.",
[(assign, "$temp", "itm_book_tactics"),
(jump_to_menu, "mnu_camp_action_read_book_start"),
]
),
("action_read_book_2",[(player_has_item, "itm_book_persuasion"),
(item_slot_eq, "itm_book_persuasion", slot_item_book_read, 0),
(str_store_item_name, s1, "itm_book_persuasion"),
],"{s1}.",
[(assign, "$temp", "itm_book_persuasion"),
(jump_to_menu, "mnu_camp_action_read_book_start"),
]
),
("action_read_book_3",[(player_has_item, "itm_book_leadership"),
(item_slot_eq, "itm_book_leadership", slot_item_book_read, 0),
(str_store_item_name, s1, "itm_book_leadership"),
],"{s1}.",
[(assign, "$temp", "itm_book_leadership"),
(jump_to_menu, "mnu_camp_action_read_book_start"),
]
),
("action_read_book_4",[(player_has_item, "itm_book_intelligence"),
(item_slot_eq, "itm_book_intelligence", slot_item_book_read, 0),
(str_store_item_name, s1, "itm_book_intelligence"),
],"{s1}.",
[(assign, "$temp", "itm_book_intelligence"),
(jump_to_menu, "mnu_camp_action_read_book_start"),
]
),
("action_read_book_5",[(player_has_item, "itm_book_trade"),
(item_slot_eq, "itm_book_trade", slot_item_book_read, 0),
(str_store_item_name, s1, "itm_book_trade"),
],"{s1}.",
[(assign, "$temp", "itm_book_trade"),
(jump_to_menu, "mnu_camp_action_read_book_start"),
]
),
("action_read_book_6",[(player_has_item, "itm_book_weapon_mastery"),
(item_slot_eq, "itm_book_weapon_mastery", slot_item_book_read, 0),
(str_store_item_name, s1, "itm_book_weapon_mastery"),
],"{s1}.",
[(assign, "$temp", "itm_book_weapon_mastery"),
(jump_to_menu, "mnu_camp_action_read_book_start"),
]
),
("action_read_book_7",[(player_has_item, "itm_book_engineering"),
(item_slot_eq, "itm_book_engineering", slot_item_book_read, 0),
(str_store_item_name, s1, "itm_book_engineering"),
],"{s1}.",
[(assign, "$temp", "itm_book_engineering"),
(jump_to_menu, "mnu_camp_action_read_book_start"),
]
),
("camp_action_4",[],"Back to camp menu.",
[(jump_to_menu, "mnu_camp"),
]
),
]
),
("camp_action_read_book_start",0,
"{s1}",
"none",
[(assign, ":new_book", "$temp"),
(str_store_item_name, s2, ":new_book"),
(try_begin),
(store_attribute_level, ":int", "trp_player", ca_intelligence),
(item_get_slot, ":int_req", ":new_book", slot_item_intelligence_requirement),
(le, ":int_req", ":int"),
(str_store_string, s1, "@You start reading {s2}. After a few pages,\
you feel you could learn a lot from this book. You decide to keep it close by and read whenever you have the time."),
(assign, "$g_player_reading_book", ":new_book"),
(else_try),
(str_store_string, s1, "@You flip through the pages of {s2}, but you find the text confusing and difficult to follow.\
Try as you might, it soon gives you a headache, and you're forced to give up the attempt."),
(try_end),],
[
("continue",[],"Continue...",
[(jump_to_menu, "mnu_camp"),
]
),
]
),
("retirement_verify",0,
"You are at day {reg0}. Your current luck is {reg1}. Are you sure you want to retire?",
"none",
[
(store_current_day, reg0),
(assign, reg1, "$g_player_luck"),
],
[
("retire_yes",[],"Yes.",
[
(start_presentation, "prsnt_retirement"),
]
),
("retire_no",[],"No.",
[
(jump_to_menu, "mnu_camp"),
]
),
]
),
("end_game",0,
"The decision is made, and you resolve to give up your adventurer's\
life and settle down. You sell off your weapons and armour, gather up\
all your money, and ride off into the sunset....",
"none",
[],
[
("end_game_bye",[],"Farewell.",
[
(change_screen_quit),
]
),
]
),
("cattle_herd",mnf_scale_picture,
"You encounter a herd of cattle.",
"none",
[(play_sound, "snd_cow_moo"),
(set_background_mesh, "mesh_pic_cattle"),
],
[
("cattle_drive_away",[],"Drive the cattle onward.",
[
(party_set_slot, "$g_encountered_party", slot_cattle_driven_by_player, 1),
(party_set_ai_behavior, "$g_encountered_party", ai_bhvr_driven_by_party),
(party_set_ai_object,"$g_encountered_party", "p_main_party"),
(change_screen_return),
]
),
("cattle_stop",[],"Bring the herd to a stop.",
[
(party_set_slot, "$g_encountered_party", slot_cattle_driven_by_player, 0),
(party_set_ai_behavior, "$g_encountered_party", ai_bhvr_hold),
(change_screen_return),
]
),
("cattle_kill",[(assign, ":continue", 1),
(try_begin),
(check_quest_active, "qst_move_cattle_herd"),
(quest_slot_eq, "qst_move_cattle_herd", slot_quest_target_party, "$g_encountered_party"),
(assign, ":continue", 0),
(try_end),
(eq, ":continue", 1)],"Slaughter some of the animals.",
[(jump_to_menu, "mnu_cattle_herd_kill"),
]
),
("leave",[],"Leave.",
[(change_screen_return),
]
),
]
),
("cattle_herd_kill",0,
"How many animals do you want to slaughter?",
"none",
[(party_get_num_companions, reg5, "$g_encountered_party")],
[
("cattle_kill_1",[(ge, reg5, 1),],"One.",
[(call_script, "script_kill_cattle_from_herd", "$g_encountered_party", 1),
(jump_to_menu, "mnu_cattle_herd_kill_end"),
(change_screen_loot, "trp_temp_troop"),
(play_sound, "snd_cow_slaughter"),
]
),
("cattle_kill_2",[(ge, reg5, 2),],"Two.",
[(call_script, "script_kill_cattle_from_herd", "$g_encountered_party", 2),
(jump_to_menu, "mnu_cattle_herd_kill_end"),
(change_screen_loot, "trp_temp_troop"),
(play_sound, "snd_cow_slaughter"),
]
),
("cattle_kill_3",[(ge, reg5, 3),],"Three.",
[(call_script, "script_kill_cattle_from_herd", "$g_encountered_party", 3),
(jump_to_menu, "mnu_cattle_herd_kill_end"),
(change_screen_loot, "trp_temp_troop"),
(play_sound, "snd_cow_slaughter"),
]
),
("cattle_kill_4",[(ge, reg5, 4),],"Four.",
[(call_script, "script_kill_cattle_from_herd", "$g_encountered_party", 4),
(jump_to_menu, "mnu_cattle_herd_kill_end"),
(change_screen_loot, "trp_temp_troop"),
(play_sound, "snd_cow_slaughter"),
]
),
("cattle_kill_5",[(ge, reg5, 5),],"Five.",
[(call_script, "script_kill_cattle_from_herd", "$g_encountered_party", 5),
(jump_to_menu, "mnu_cattle_herd_kill_end"),
(change_screen_loot, "trp_temp_troop"),
(play_sound, "snd_cow_slaughter"),
]
),
("go_back_dot",[],"Go back.",
[(jump_to_menu, "mnu_cattle_herd"),
]
),
]
),
("cattle_herd_kill_end",0,
"{!}You shouldn't be reading this.",
"none",
[(change_screen_return)],
[
]
),
("arena_duel_fight",0,
"You and your opponent prepare to duel.",
"none",
[],
[
("continue",[],"Continue...",
[
(assign, "$g_leave_encounter", 0),
(try_begin),
(is_between, "$g_encountered_party", towns_begin, towns_end),
(party_get_slot, ":duel_scene", "$g_encountered_party", slot_town_arena),
(else_try),
(eq, "$g_start_arena_fight_at_nearest_town", 1),
(assign, ":closest_town", -1),
(assign, ":minimum_dist", 10000),
(try_for_range, ":cur_town", towns_begin, towns_end),
(store_distance_to_party_from_party, ":dist", ":cur_town", "$g_encountered_party"),
(lt, ":dist", ":minimum_dist"),
(assign, ":minimum_dist", ":dist"),
(assign, ":closest_town", ":cur_town"),
(try_end),
(try_begin),
(ge, ":closest_town", 0),
(party_get_slot, ":duel_scene", ":closest_town", slot_town_arena),
(try_end),
(assign, "$g_start_arena_fight_at_nearest_town", 0),
(else_try),
(party_get_current_terrain, ":terrain", "p_main_party"),
(eq, ":terrain", 4),
(assign, ":duel_scene", "scn_training_ground_ranged_melee_3"),
(else_try),
(eq, ":terrain", 5),
(assign, ":duel_scene", "scn_training_ground_ranged_melee_4"),
(else_try),
(assign, ":duel_scene", "scn_training_ground_ranged_melee_1"),
(try_end),
(modify_visitors_at_site, ":duel_scene"),
(reset_visitors),
(set_visitor, 0, "trp_player"),
(set_visitor, 1, "$g_duel_troop"),
(set_jump_mission, "mt_duel_with_lord"),
(jump_to_scene, ":duel_scene"),
(jump_to_menu, "mnu_arena_duel_conclusion"),
(change_screen_mission),
]),
]
),
("arena_duel_conclusion",0,
"{!}{s11}",
"none",
[
(try_begin),
(eq, "$g_leave_encounter", 1),
(change_screen_return),
(try_end),
(str_store_troop_name, s10, "$g_duel_troop"),
(try_begin),
(quest_slot_eq, "qst_duel_for_lady", slot_quest_target_troop, "$g_duel_troop"),
(check_quest_failed, "qst_duel_for_lady"),
(str_store_string, s11, "str_you_lie_stunned_for_several_minutes_then_stagger_to_your_feet_to_find_your_s10_standing_over_you_you_have_lost_the_duel"),
(else_try),
(quest_slot_eq, "qst_duel_for_lady", slot_quest_target_troop, "$g_duel_troop"),
(check_quest_succeeded, "qst_duel_for_lady"),
(str_store_string, s11, "str_s10_lies_in_the_arenas_dust_for_several_minutes_then_staggers_to_his_feet_you_have_won_the_duel"),
(else_try),
(quest_slot_eq, "qst_duel_courtship_rival", slot_quest_target_troop, "$g_duel_troop"),
(check_quest_failed, "qst_duel_courtship_rival"),
(str_store_string, s11, "str_you_lie_stunned_for_several_minutes_then_stagger_to_your_feet_to_find_your_s10_standing_over_you_you_have_lost_the_duel"),
(else_try),
(quest_slot_eq, "qst_duel_courtship_rival", slot_quest_target_troop, "$g_duel_troop"),
(check_quest_succeeded, "qst_duel_courtship_rival"),
(str_store_string, s11, "str_s10_lies_in_the_arenas_dust_for_several_minutes_then_staggers_to_his_feet_you_have_won_the_duel"),
(else_try),
(quest_slot_eq, "qst_duel_avenge_insult", slot_quest_target_troop, "$g_duel_troop"),
(check_quest_succeeded, "qst_duel_avenge_insult"),
(str_store_string, s11, "str_s10_lies_in_the_arenas_dust_for_several_minutes_then_staggers_to_his_feet_you_have_won_the_duel"),
(else_try),
(quest_slot_eq, "qst_duel_avenge_insult", slot_quest_target_troop, "$g_duel_troop"),
(check_quest_failed, "qst_duel_avenge_insult"),
(str_store_string, s11, "str_you_lie_stunned_for_several_minutes_then_stagger_to_your_feet_to_find_your_s10_standing_over_you_you_have_lost_the_duel"),
(else_try),
(quest_slot_eq, "qst_denounce_lord", slot_quest_target_troop, "$g_duel_troop"),
(check_quest_succeeded, "qst_denounce_lord"),
(str_store_string, s11, "str_s10_lies_in_the_arenas_dust_for_several_minutes_then_staggers_to_his_feet_you_have_won_the_duel"),
(else_try),
(quest_slot_eq, "qst_denounce_lord", slot_quest_target_troop, "$g_duel_troop"),
(check_quest_failed, "qst_denounce_lord"),
(str_store_string, s11, "str_you_lie_stunned_for_several_minutes_then_stagger_to_your_feet_to_find_your_s10_standing_over_you_you_have_lost_the_duel"),
(else_try),
(str_store_troop_name, s10, "$g_duel_troop"),
(try_end),
],
[
("continue",[],"Continue...",
[
(call_script, "script_get_meeting_scene"), (assign, ":meeting_scene", reg0),
(modify_visitors_at_site,":meeting_scene"),
(reset_visitors),
(set_visitor,0,"trp_player"),
(set_visitor,17,"$g_duel_troop"),
(set_jump_mission,"mt_conversation_encounter"),
(jump_to_scene,":meeting_scene"),
(assign, "$talk_context", tc_after_duel),
(change_screen_map_conversation, "$g_duel_troop"),
]),
]
),
(
"simple_encounter",mnf_enable_hot_keys|mnf_scale_picture,
"{s2} You have {reg10} troops fit for battle against their {reg11}.",
"none",
[
(assign, "$g_enemy_party", "$g_encountered_party"),
(assign, "$g_ally_party", -1),
(call_script, "script_encounter_calculate_fit"),
(try_begin),
(eq, "$new_encounter", 1),
(assign, "$new_encounter", 0),
(assign, "$g_encounter_is_in_village", 0),
(assign, "$g_encounter_type", 0),
(try_begin),
(party_slot_eq, "$g_enemy_party", slot_party_ai_state, spai_raiding_around_center),
(party_get_slot, ":village_no", "$g_enemy_party", slot_party_ai_object),
(store_distance_to_party_from_party, ":dist", ":village_no", "$g_enemy_party"),
(try_begin),
(lt, ":dist", raid_distance),
(assign, "$g_encounter_is_in_village", ":village_no"),
(assign, "$g_encounter_type", enctype_fighting_against_village_raid),
(try_end),
(try_end),
(try_begin),
(gt, "$g_player_raiding_village", 0),
(assign, "$g_encounter_is_in_village", "$g_player_raiding_village"),
(assign, "$g_encounter_type", enctype_catched_during_village_raid),
(party_quick_attach_to_current_battle, "$g_encounter_is_in_village", 1), #attach as enemy
(str_store_string, s1, "@Villagers"),
(display_message, "str_s1_joined_battle_enemy"),
(else_try),
(eq, "$g_encounter_type", enctype_fighting_against_village_raid),
(party_quick_attach_to_current_battle, "$g_encounter_is_in_village", 0), #attach as friend
(str_store_string, s1, "@Villagers"),
(display_message, "str_s1_joined_battle_friend"),
# Let village party join battle at your side
(try_end),
(call_script, "script_let_nearby_parties_join_current_battle", 0, 0),
(call_script, "script_encounter_init_variables"),
(assign, "$encountered_party_hostile", 0),
(assign, "$encountered_party_friendly", 0),
(try_begin),
(gt, "$g_encountered_party_relation", 0),
(assign, "$encountered_party_friendly", 1),
(try_end),
(try_begin),
(lt, "$g_encountered_party_relation", 0),
(assign, "$encountered_party_hostile", 1),
(try_begin),
(encountered_party_is_attacker),
(assign, "$cant_leave_encounter", 1),
(try_end),
(try_end),
(assign, "$talk_context", tc_party_encounter),
(call_script, "script_setup_party_meeting", "$g_encountered_party"),
(else_try), #second or more turn
# (try_begin),
# (call_script, "script_encounter_calculate_morale_change"),
# (try_end),
(try_begin),
# We can leave battle only after some troops have been killed.
(eq, "$cant_leave_encounter", 1),
(call_script, "script_party_count_members_with_full_health", "p_main_party_backup"),
(assign, ":org_total_party_counts", reg0),
(call_script, "script_party_count_members_with_full_health", "p_encountered_party_backup"),
(val_add, ":org_total_party_counts", reg0),
(call_script, "script_party_count_members_with_full_health", "p_main_party"),
(assign, ":cur_total_party_counts", reg0),
(call_script, "script_party_count_members_with_full_health", "p_collective_enemy"),
(val_add, ":cur_total_party_counts", reg0),
(store_sub, ":leave_encounter_limit", ":org_total_party_counts", 10),
(lt, ":cur_total_party_counts", ":leave_encounter_limit"),
(assign, "$cant_leave_encounter", 0),
(try_end),
(eq, "$g_leave_encounter",1),
(change_screen_return),
(try_end),
#setup s2
(try_begin),
(party_is_active, "$g_encountered_party"),
(str_store_party_name, s1,"$g_encountered_party"),
(try_begin),
(eq, "$g_encounter_type", 0),
(str_store_string, s2,"@You have encountered {s1}."),
(else_try),
(eq, "$g_encounter_type", enctype_fighting_against_village_raid),
(str_store_party_name, s3, "$g_encounter_is_in_village"),
(str_store_string, s2,"@You have engaged {s1} while they were raiding {s3}."),
(else_try),
(eq, "$g_encounter_type", enctype_catched_during_village_raid),
(str_store_party_name, s3, "$g_encounter_is_in_village"),
(str_store_string, s2,"@You were caught by {s1} while your forces were raiding {s3}."),
(try_end),
(try_end),
(try_begin),
(call_script, "script_party_count_members_with_full_health", "p_collective_enemy"),
(assign, ":num_enemy_regulars_remaining", reg0),
(assign, ":enemy_finished", 0),
(try_begin),
(eq, "$g_battle_result", 1), #battle won
(this_or_next|le, ":num_enemy_regulars_remaining", 0), #battle won
(le, ":num_enemy_regulars_remaining", "$num_routed_enemies"), #replaced for above line because we do not want routed agents to spawn again in next turn of battle.
(assign, ":enemy_finished",1),
(else_try),
(eq, "$g_engaged_enemy", 1),
(this_or_next|le, ":num_enemy_regulars_remaining", 0),
(le, "$g_enemy_fit_for_battle", "$num_routed_enemies"), #replaced for above line because we do not want routed agents to spawn again in next turn of battle.
(ge, "$g_friend_fit_for_battle",1),
(assign, ":enemy_finished",1),
(try_end),
(this_or_next|eq, ":enemy_finished",1),
(eq,"$g_enemy_surrenders",1),
(assign, "$g_next_menu", -1),
(jump_to_menu, "mnu_total_victory"),
(else_try),
(call_script, "script_party_count_members_with_full_health", "p_main_party"),
(assign, ":num_our_regulars_remaining", reg0),
(assign, ":friends_finished",0),
(try_begin),
(eq, "$g_battle_result", -1),
#(eq, ":num_our_regulars_remaining", 0), #battle lost
(le, ":num_our_regulars_remaining", "$num_routed_us"), #replaced for above line because we do not want routed agents to spawn again in next turn of battle.
(assign, ":friends_finished", 1),
(else_try),
(eq, "$g_engaged_enemy", 1),
(ge, "$g_enemy_fit_for_battle",1),
(le, "$g_friend_fit_for_battle",0),
(assign, ":friends_finished",1),
(try_end),
(this_or_next|eq, ":friends_finished",1),
(eq,"$g_player_surrenders",1),
(assign, "$g_next_menu", "mnu_captivity_start_wilderness"),
(jump_to_menu, "mnu_total_defeat"),
(try_end),
(try_begin),
(eq, "$g_encountered_party_template", "pt_looters"),
(set_background_mesh, "mesh_pic_bandits"),
(else_try),
(eq, "$g_encountered_party_template", "pt_mountain_bandits"),
(set_background_mesh, "mesh_pic_mountain_bandits"),
(else_try),
(eq, "$g_encountered_party_template", "pt_steppe_bandits"),
(set_background_mesh, "mesh_pic_steppe_bandits"),
(else_try),
(eq, "$g_encountered_party_template", "pt_taiga_bandits"),
(set_background_mesh, "mesh_pic_steppe_bandits"),
(else_try),
(eq, "$g_encountered_party_template", "pt_sea_raiders"),
(set_background_mesh, "mesh_pic_sea_raiders"),
(else_try),
(eq, "$g_encountered_party_template", "pt_forest_bandits"),
(set_background_mesh, "mesh_pic_forest_bandits"),
(else_try),
(eq, "$g_encountered_party_template", "pt_deserters"),
(set_background_mesh, "mesh_pic_deserters"),
(else_try),
(eq, "$g_encountered_party_template", "pt_kingdom_hero_party"),
(party_stack_get_troop_id, ":leader_troop", "$g_encountered_party", 0),
(ge, ":leader_troop", 1),
(troop_get_slot, ":leader_troop_faction", ":leader_troop", slot_troop_original_faction),
(try_begin),
(eq, ":leader_troop_faction", "fac_kingdom_7"),
(set_background_mesh, "mesh_pic_swad"),
(else_try),
(eq, ":leader_troop_faction", "fac_kingdom_7"),
(set_background_mesh, "mesh_pic_vaegir"),
(else_try),
(eq, ":leader_troop_faction", "fac_kingdom_7"),
(set_background_mesh, "mesh_pic_khergit"),
(else_try),
(eq, ":leader_troop_faction", "fac_kingdom_7"),
(set_background_mesh, "mesh_pic_nord"),
(else_try),
(eq, ":leader_troop_faction", "fac_kingdom_7"),
(set_background_mesh, "mesh_pic_rhodock"),
(else_try),
(eq, ":leader_troop_faction", "fac_kingdom_7"),
(set_background_mesh, "mesh_pic_sarranid_encounter"),
(try_end),
(try_end),
],
[
("encounter_attack",
[
(eq, "$encountered_party_friendly", 0),
(neg|troop_is_wounded, "trp_player"),
],
"Charge the enemy.",
[
(assign, "$g_battle_result", 0),
(assign, "$g_engaged_enemy", 1),
(party_get_template_id, ":encountered_party_template", "$g_encountered_party"),
(try_begin),
(eq, ":encountered_party_template", "pt_village_farmers"),
(unlock_achievement, ACHIEVEMENT_HELP_HELP_IM_BEING_REPRESSED),
(try_end),
(call_script, "script_calculate_renown_value"),
(call_script, "script_calculate_battle_advantage"),
(set_battle_advantage, reg0),
(set_party_battle_mode),
(try_begin),
(eq, "$g_encounter_type", enctype_fighting_against_village_raid),
(assign, "$g_village_raid_evil", 0),
(set_jump_mission,"mt_village_raid"),
(party_get_slot, ":scene_to_use", "$g_encounter_is_in_village", slot_castle_exterior),
(jump_to_scene, ":scene_to_use"),
(else_try),
(eq, "$g_encounter_type", enctype_catched_during_village_raid),
(assign, "$g_village_raid_evil", 0),
(set_jump_mission,"mt_village_raid"),
(party_get_slot, ":scene_to_use", "$g_encounter_is_in_village", slot_castle_exterior),
(jump_to_scene, ":scene_to_use"),
(else_try),
(set_jump_mission,"mt_lead_charge"),
(call_script, "script_setup_random_scene"),
(try_end),
(assign, "$g_next_menu", "mnu_simple_encounter"),
(jump_to_menu, "mnu_battle_debrief"),
(change_screen_mission),
]),
("encounter_order_attack",
[
(eq, "$encountered_party_friendly", 0),
(call_script, "script_party_count_members_with_full_health", "p_main_party"),(ge, reg0, 4),
],
"Order your troops to attack without you.",
[
(jump_to_menu, "mnu_order_attack_begin"),
#(simulate_battle,3),
]),
("encounter_leave",[
(eq,"$cant_leave_encounter", 0),
],"Leave.",[
###NPC companion changes begin
(try_begin),
(eq, "$encountered_party_friendly", 0),
(encountered_party_is_attacker),
(call_script, "script_objectionable_action", tmt_aristocratic, "str_flee_battle"),
(try_end),
###NPC companion changes end
#Troop commentary changes begin
(try_begin),
(eq, "$encountered_party_friendly", 0),
# (encountered_party_is_attacker),
(party_get_num_companion_stacks, ":num_stacks", "p_encountered_party_backup"),
(try_for_range, ":stack_no", 0, ":num_stacks"),
(party_stack_get_troop_id, ":stack_troop","p_encountered_party_backup",":stack_no"),
(is_between, ":stack_troop", active_npcs_begin, active_npcs_end),
(troop_slot_eq, ":stack_troop", slot_troop_occupation, slto_kingdom_hero),
(store_troop_faction, ":victorious_faction", ":stack_troop"),
# (store_relation, ":relation_with_stack_troop", ":victorious_faction", "fac_player_faction"),
# (lt, ":relation_with_stack_troop", 0),
(call_script, "script_add_log_entry", logent_player_retreated_from_lord, "trp_player", -1, ":stack_troop", ":victorious_faction"),
(try_end),
(try_end),
#Troop commentary changes end
(leave_encounter),(change_screen_return)]),
("encounter_retreat",[
(eq,"$cant_leave_encounter", 1),
(call_script, "script_get_max_skill_of_player_party", "skl_tactics"),
(assign, ":max_skill", reg0),
(val_add, ":max_skill", 4),
(call_script, "script_party_count_members_with_full_health", "p_collective_enemy", 0),
(assign, ":enemy_party_strength", reg0),
(val_div, ":enemy_party_strength", 2),
(val_div, ":enemy_party_strength", ":max_skill"),
(val_max, ":enemy_party_strength", 1),
(call_script, "script_party_count_fit_regulars", "p_main_party"),
(assign, ":player_count", reg0),
(ge, ":player_count", ":enemy_party_strength"),
],"Pull back, leaving some soldiers behind to cover your retreat.",[(jump_to_menu, "mnu_encounter_retreat_confirm"),]),
("encounter_surrender",[
(eq,"$cant_leave_encounter", 1),
],"Surrender.",[(assign,"$g_player_surrenders",1)]),
]
),
(
"encounter_retreat_confirm",0,
"As the party member with the highest tactics skill,\
({reg2}), {reg3?you devise:{s3} devises} a plan that will allow you and your men to escape with your lives,\
but you'll have to leave {reg4} soldiers behind to stop the enemy from giving chase.",
"none",
[(call_script, "script_get_max_skill_of_player_party", "skl_tactics"),
(assign, ":max_skill", reg0),
(assign, ":max_skill_owner", reg1),
(assign, reg2, ":max_skill"),
(val_add, ":max_skill", 4),
(call_script, "script_party_count_members_with_full_health", "p_collective_enemy", 0),
(assign, ":enemy_party_strength", reg0),
(val_div, ":enemy_party_strength", 2),
(store_div, reg4, ":enemy_party_strength", ":max_skill"),
(val_max, reg4, 1),
(try_begin),
(eq, ":max_skill_owner", "trp_player"),
(assign, reg3, 1),
(else_try),
(assign, reg3, 0),
(str_store_troop_name, s3, ":max_skill_owner"),
(try_end),
],
[
("leave_behind",[],"Go on. The sacrifice of these men will save the rest.",
[
(assign, ":num_casualties", reg4),
(try_for_range, ":unused", 0, ":num_casualties"),
(call_script, "script_cf_party_remove_random_regular_troop", "p_main_party"),
(assign, ":lost_troop", reg0),
(store_random_in_range, ":random_no", 0, 100),
(ge, ":random_no", 30),
(party_add_prisoners, "$g_encountered_party", ":lost_troop", 1),
(try_end),
(call_script, "script_change_player_party_morale", -20),
(jump_to_menu, "mnu_encounter_retreat"),
]),
("dont_leave_behind",[],"No. We leave no one behind.",[(jump_to_menu, "mnu_simple_encounter"),]),
]
),
(
"encounter_retreat",0,
"You tell {reg4} of your troops to hold the enemy while you retreat with the rest of your party.",
"none",
[
],
[
("continue",[],"Continue...",
[
###Troop commentary changes begin
(call_script, "script_objectionable_action", tmt_aristocratic, "str_flee_battle"),
(party_get_num_companion_stacks, ":num_stacks", "p_encountered_party_backup"),
(try_for_range, ":stack_no", 0, ":num_stacks"),
(party_stack_get_troop_id, ":stack_troop","p_encountered_party_backup",":stack_no"),
(is_between, ":stack_troop", active_npcs_begin, active_npcs_end),
(troop_slot_eq, ":stack_troop", slot_troop_occupation, slto_kingdom_hero),
(store_troop_faction, ":victorious_faction", ":stack_troop"),
(call_script, "script_add_log_entry", logent_player_retreated_from_lord_cowardly, "trp_player", -1, ":stack_troop", ":victorious_faction"),
(try_end),
###Troop commentary changes end
(party_ignore_player, "$g_encountered_party", 1),
(leave_encounter),
(change_screen_return)
]),
]
),
(
"order_attack_begin",0,
"Your troops prepare to attack the enemy.",
"none",
[],
[
("order_attack_begin",[],"Order the attack to begin.",
[
(party_get_template_id, ":encountered_party_template", "$g_encountered_party"),
(try_begin),
(eq, ":encountered_party_template", "pt_village_farmers"),
(unlock_achievement, ACHIEVEMENT_HELP_HELP_IM_BEING_REPRESSED),
(try_end),
(assign, "$g_engaged_enemy", 1),
(jump_to_menu,"mnu_order_attack_2"),
]),
("call_back",[],"Call them back.",[(jump_to_menu,"mnu_simple_encounter")]),
]
),
(
"order_attack_2",mnf_disable_all_keys,
"{s4}^^Your casualties: {s8}^^Enemy casualties: {s9}",
"none",
[
(set_background_mesh, "mesh_pic_charge"),
(call_script, "script_party_calculate_strength", "p_main_party", 1), #exclude player
(assign, ":player_party_strength", reg0),
(call_script, "script_party_calculate_strength", "p_collective_enemy", 0),
(assign, ":enemy_party_strength", reg0),
(party_collect_attachments_to_party, "p_main_party", "p_collective_ally"),
(call_script, "script_party_calculate_strength", "p_collective_ally", 1), #exclude player
(assign, ":total_player_and_followers_strength", reg0),
(try_begin),
(le, ":total_player_and_followers_strength", ":enemy_party_strength"),
(assign, ":minimum_power", ":total_player_and_followers_strength"),
(else_try),
(assign, ":minimum_power", ":enemy_party_strength"),
(try_end),
(try_begin),
(le, ":minimum_power", 25),
(assign, ":division_constant", 1),
(else_try),
(le, ":minimum_power", 50),
(assign, ":division_constant", 2),
(else_try),
(le, ":minimum_power", 75),
(assign, ":division_constant", 3),
(else_try),
(le, ":minimum_power", 125),
(assign, ":division_constant", 4),
(else_try),
(le, ":minimum_power", 200),
(assign, ":division_constant", 5),
(else_try),
(le, ":minimum_power", 400),
(assign, ":division_constant", 6),
(else_try),
(le, ":minimum_power", 800),
(assign, ":division_constant", 7),
(else_try),
(le, ":minimum_power", 1600),
(assign, ":division_constant", 8),
(else_try),
(le, ":minimum_power", 3200),
(assign, ":division_constant", 9),
(else_try),
(le, ":minimum_power", 6400),
(assign, ":division_constant", 10),
(else_try),
(le, ":minimum_power", 12800),
(assign, ":division_constant", 11),
(else_try),
(le, ":minimum_power", 25600),
(assign, ":division_constant", 12),
(else_try),
(le, ":minimum_power", 51200),
(assign, ":division_constant", 13),
(else_try),
(le, ":minimum_power", 102400),
(assign, ":division_constant", 14),
(else_try),
(assign, ":division_constant", 15),
(try_end),
(val_div, ":player_party_strength", ":division_constant"), #1.126, ":division_constant" was 5 before
(val_max, ":player_party_strength", 1), #1.126
(val_div, ":enemy_party_strength", ":division_constant"), #1.126, ":division_constant" was 5 before
(val_max, ":enemy_party_strength", 1), #1.126
(val_div, ":total_player_and_followers_strength", ":division_constant"), #1.126, ":division_constant" was 5 before
(val_max, ":total_player_and_followers_strength", 1), #1.126
(store_mul, "$g_strength_contribution_of_player", ":player_party_strength", 100),
(val_div, "$g_strength_contribution_of_player", ":total_player_and_followers_strength"),
(inflict_casualties_to_party_group, "p_main_party", ":enemy_party_strength", "p_temp_casualties"),
(call_script, "script_print_casualties_to_s0", "p_temp_casualties", 0),
(str_store_string_reg, s8, s0),
(try_begin),
(ge, "$g_ally_party", 0),
(inflict_casualties_to_party_group, "$g_ally_party", ":enemy_party_strength", "p_temp_casualties"),
(str_store_string_reg, s8, s0),
(try_end),
(inflict_casualties_to_party_group, "$g_encountered_party", ":total_player_and_followers_strength", "p_temp_casualties"),
#ozan begin
(party_get_num_companion_stacks, ":num_stacks", "p_temp_casualties"),
(try_for_range, ":stack_no", 0, ":num_stacks"),
(party_stack_get_troop_id, ":stack_troop", "p_temp_casualties", ":stack_no"),
(try_begin),
(party_stack_get_size, ":stack_size", "p_temp_casualties", ":stack_no"),
(gt, ":stack_size", 0),
(party_add_members, "p_total_enemy_casualties", ":stack_troop", ":stack_size"), #addition_to_p_total_enemy_casualties
(party_stack_get_num_wounded, ":stack_wounded_size", "p_temp_casualties", ":stack_no"),
(gt, ":stack_wounded_size", 0),
(party_wound_members, "p_total_enemy_casualties", ":stack_troop", ":stack_wounded_size"),
(try_end),
(try_end),
#ozan end
(call_script, "script_print_casualties_to_s0", "p_temp_casualties", 0),
(str_store_string_reg, s9, s0),
(party_collect_attachments_to_party, "$g_encountered_party", "p_collective_enemy"),
(assign, "$no_soldiers_left", 0),
(try_begin),
(call_script, "script_party_count_members_with_full_health", "p_main_party"),
(assign, ":num_our_regulars_remaining", reg0),
(store_add, ":num_routed_us_plus_one", "$num_routed_us", 1),
(le, ":num_our_regulars_remaining", ":num_routed_us_plus_one"), #replaced for above line because we do not want routed agents to spawn again in next turn of battle.
(assign, "$no_soldiers_left", 1),
(str_store_string, s4, "str_order_attack_failure"),
(else_try),
(call_script, "script_party_count_members_with_full_health", "p_collective_enemy"),
(assign, ":num_enemy_regulars_remaining", reg0),
(this_or_next|le, ":num_enemy_regulars_remaining", 0),
(le, ":num_enemy_regulars_remaining", "$num_routed_enemies"), #replaced for above line because we do not want routed agents to spawn again in next turn of battle.
(assign, ":continue", 0),
(party_get_num_companion_stacks, ":party_num_stacks", "p_collective_enemy"),
(try_begin),
(eq, ":party_num_stacks", 0),
(assign, ":continue", 1),
(else_try),
(party_stack_get_troop_id, ":party_leader", "p_collective_enemy", 0),
(try_begin),
(neg|troop_is_hero, ":party_leader"),
(assign, ":continue", 1),
(else_try),
(troop_is_wounded, ":party_leader"),
(assign, ":continue", 1),
(try_end),
(try_end),
(eq, ":continue", 1),
(assign, "$g_battle_result", 1),
(assign, "$no_soldiers_left", 1),
(str_store_string, s4, "str_order_attack_success"),
(else_try),
(str_store_string, s4, "str_order_attack_continue"),
(try_end),
],
[
("order_attack_continue",[(eq, "$no_soldiers_left", 0)],"Order your soldiers to continue the attack.",[
(jump_to_menu,"mnu_order_attack_2"),
]),
("order_retreat",[(eq, "$no_soldiers_left", 0)],"Call your soldiers back.",[
(jump_to_menu,"mnu_simple_encounter"),
]),
("continue",[(eq, "$no_soldiers_left", 1)],"Continue...",[
(jump_to_menu,"mnu_simple_encounter"),
]),
]
),
(
"battle_debrief",mnf_scale_picture|mnf_disable_all_keys,
"{s11}^^Your Casualties:{s8}{s10}^^Enemy Casualties:{s9}",
"none",
[
(try_begin),
(eq, "$g_battle_result", 1),
(call_script, "script_change_troop_renown", "trp_player", "$battle_renown_value"),
(try_begin),
(ge, "$g_encountered_party", 0),
(party_is_active, "$g_encountered_party"),
(party_get_template_id, ":encountered_party_template", "$g_encountered_party"),
(eq, ":encountered_party_template", "pt_kingdom_caravan_party"),
(get_achievement_stat, ":number_of_village_raids", ACHIEVEMENT_THE_BANDIT, 0),
(get_achievement_stat, ":number_of_caravan_raids", ACHIEVEMENT_THE_BANDIT, 1),
(val_add, ":number_of_caravan_raids", 1),
(set_achievement_stat, ACHIEVEMENT_THE_BANDIT, 1, ":number_of_caravan_raids"),
(try_begin),
(ge, ":number_of_village_raids", 3),
(ge, ":number_of_caravan_raids", 3),
(unlock_achievement, ACHIEVEMENT_THE_BANDIT),
(try_end),
(try_end),
(try_begin),
(party_get_current_terrain, ":cur_terrain", "p_main_party"),
(eq, ":cur_terrain", rt_snow),
(get_achievement_stat, ":number_of_victories_at_snowy_lands", ACHIEVEMENT_BEST_SERVED_COLD, 0),
(val_add, ":number_of_victories_at_snowy_lands", 1),
(set_achievement_stat, ACHIEVEMENT_BEST_SERVED_COLD, 0, ":number_of_victories_at_snowy_lands"),
(try_begin),
(eq, ":number_of_victories_at_snowy_lands", 10),
(unlock_achievement, ACHIEVEMENT_BEST_SERVED_COLD),
(try_end),
(try_end),
(try_begin),
(ge, "$g_enemy_party", 0),
(party_is_active, "$g_enemy_party"),
(party_stack_get_troop_id, ":stack_troop", "$g_enemy_party", 0),
(eq, ":stack_troop", "trp_mountain_bandit"),
(get_achievement_stat, ":number_of_victories_aganist_mountain_bandits", ACHIEVEMENT_MOUNTAIN_BLADE, 0),
(val_add, ":number_of_victories_aganist_mountain_bandits", 1),
(set_achievement_stat, ACHIEVEMENT_MOUNTAIN_BLADE, 0, ":number_of_victories_aganist_mountain_bandits"),
(try_begin),
(eq, ":number_of_victories_aganist_mountain_bandits", 10),
(unlock_achievement, ACHIEVEMENT_MOUNTAIN_BLADE),
(try_end),
(try_end),
(try_begin),
(is_between, "$g_ally_party", walled_centers_begin, walled_centers_end),
(unlock_achievement, ACHIEVEMENT_NONE_SHALL_PASS),
(try_end),
(try_begin),
(eq, "$g_joined_battle_to_help", 1),
(unlock_achievement, ACHIEVEMENT_GOOD_SAMARITAN),
(try_end),
(try_end),
(assign, "$g_joined_battle_to_help", 0),
(call_script, "script_count_casualties_and_adjust_morale"),#new
(call_script, "script_encounter_calculate_fit"),
(call_script, "script_party_count_fit_regulars", "p_main_party"),
(assign, "$playerparty_postbattle_regulars", reg0),
(try_begin),
(eq, "$g_battle_result", 1),
(eq, "$g_enemy_fit_for_battle", 0),
(str_store_string, s11, "@You were victorious!"),
# (play_track, "track_bogus"), #clear current track.
# (call_script, "script_music_set_situation_with_culture", mtf_sit_victorious),
(try_begin),
(gt, "$g_friend_fit_for_battle", 1),
(set_background_mesh, "mesh_pic_victory"),
(try_end),
(else_try),
(eq, "$g_battle_result", -1),
(ge, "$g_enemy_fit_for_battle",1),
(this_or_next|le, "$g_friend_fit_for_battle",0),
(le, "$playerparty_postbattle_regulars", 0),
(str_store_string, s11, "@Battle was lost. Your forces were utterly crushed."),
(set_background_mesh, "mesh_pic_defeat"),
(else_try),
(eq, "$g_battle_result", -1),
(str_store_string, s11, "@Your companions carry you away from the fighting."),
(troop_get_type, ":is_female", "trp_player"),
(try_begin),
(eq, ":is_female", 1),
(set_background_mesh, "mesh_pic_wounded_fem"),
(else_try),
(set_background_mesh, "mesh_pic_wounded"),
(try_end),
(else_try),
(eq, "$g_battle_result", 1),
(str_store_string, s11, "@You have defeated the enemy."),
(try_begin),
(gt, "$g_friend_fit_for_battle", 1),
(set_background_mesh, "mesh_pic_victory"),
(try_end),
(else_try),
(eq, "$g_battle_result", 0),
(str_store_string, s11, "@You have retreated from the fight."),
(try_end),
#NPC companion changes begin
##check for excessive casualties, more forgiving if battle result is good
(try_begin),
(gt, "$playerparty_prebattle_regulars", 9),
(store_add, ":divisor", 3, "$g_battle_result"),
(store_div, ":half_of_prebattle_regulars", "$playerparty_prebattle_regulars", ":divisor"),
(lt, "$playerparty_postbattle_regulars", ":half_of_prebattle_regulars"),
(call_script, "script_objectionable_action", tmt_egalitarian, "str_excessive_casualties"),
(try_end),
#NPC companion changes end
(call_script, "script_print_casualties_to_s0", "p_player_casualties", 0),
(str_store_string_reg, s8, s0),
(call_script, "script_print_casualties_to_s0", "p_enemy_casualties", 0),
(str_store_string_reg, s9, s0),
(str_clear, s10),
(try_begin),
(eq, "$any_allies_at_the_last_battle", 1),
(call_script, "script_print_casualties_to_s0", "p_ally_casualties", 0),
(str_store_string, s10, "@^^Ally Casualties:{s0}"),
(try_end),
],
[
("continue",[],"Continue...",[(jump_to_menu, "$g_next_menu"),]),
]
),
(
"total_victory", 0,
"You shouldn't be reading this... {s9}",
"none",
[
# We exploit the menu condition system below.
# The conditions should make sure that always another screen or menu is called.
(assign, ":break", 0),
(try_begin),
(eq, "$routed_party_added", 0), #new
(assign, "$routed_party_added", 1),
#add new party to map (routed_warriors)
(call_script, "script_add_routed_party"),
(end_try),
(try_begin),
(check_quest_active, "qst_track_down_bandits"),
(neg|check_quest_succeeded, "qst_track_down_bandits"),
(neg|check_quest_failed, "qst_track_down_bandits"),
(quest_get_slot, ":quest_party", "qst_track_down_bandits", slot_quest_target_party),
(party_is_active, ":quest_party"),
(party_get_attached_to, ":quest_party_attached"),
(this_or_next|eq, ":quest_party", "$g_enemy_party"),
(eq, ":quest_party_attached", "$g_enemy_party"),
(call_script, "script_succeed_quest", "qst_track_down_bandits"),
(try_end),
(try_begin),
(gt, "$g_private_battle_with_troop", 0),
(troop_slot_eq, "$g_private_battle_with_troop", slot_troop_leaded_party, "$g_encountered_party"),
(assign, "$g_private_battle_with_troop", 0),
(assign, "$g_disable_condescending_comments", 1),
(try_end),
#new - begin
(party_get_num_companion_stacks, ":num_stacks", "p_collective_enemy"),
(try_for_range, ":i_stack", 0, ":num_stacks"),
(party_stack_get_troop_id, ":stack_troop", "p_collective_enemy", ":i_stack"),
(is_between, ":stack_troop", lords_begin, lords_end),
(troop_is_wounded, ":stack_troop"),
(party_add_members, "p_total_enemy_casualties", ":stack_troop", 1),
(try_end),
#new - end
(try_begin),
# Talk to ally leader
(eq, "$thanked_by_ally_leader", 0),
(assign, "$thanked_by_ally_leader", 1),
(gt, "$g_ally_party", 0),
#(store_add, ":total_str_without_player", "$g_starting_strength_ally_party", "$g_starting_strength_enemy_party"),
(store_add, ":total_str_without_player", "$g_starting_strength_friends", "$g_starting_strength_enemy_party"),
(val_sub, ":total_str_without_player", "$g_starting_strength_main_party"),
(store_sub, ":ally_strength_without_player", "$g_starting_strength_friends", "$g_starting_strength_main_party"),
(store_mul, ":ally_advantage", ":ally_strength_without_player", 100),
(val_add, ":total_str_without_player", 1),
(val_div, ":ally_advantage", ":total_str_without_player"),
#Ally advantage=50 means battle was evenly matched
(store_sub, ":enemy_advantage", 100, ":ally_advantage"),
(store_mul, ":faction_reln_boost", ":enemy_advantage", "$g_starting_strength_enemy_party"),
(val_div, ":faction_reln_boost", 3000),
(val_min, ":faction_reln_boost", 4),
(store_mul, "$g_relation_boost", ":enemy_advantage", ":enemy_advantage"),
(val_div, "$g_relation_boost", 700),
(val_clamp, "$g_relation_boost", 0, 20),
(party_get_num_companion_stacks, ":num_ally_stacks", "$g_ally_party"),
(gt, ":num_ally_stacks", 0),
(store_faction_of_party, ":ally_faction","$g_ally_party"),
(call_script, "script_change_player_relation_with_faction", ":ally_faction", ":faction_reln_boost"),
(party_stack_get_troop_id, ":ally_leader", "$g_ally_party"),
(party_stack_get_troop_dna, ":ally_leader_dna", "$g_ally_party", 0),
(try_begin),
(troop_is_hero, ":ally_leader"),
(troop_get_slot, ":hero_relation", ":ally_leader", slot_troop_player_relation),
(assign, ":rel_boost", "$g_relation_boost"),
(try_begin),
(lt, ":hero_relation", -5),
(val_div, ":rel_boost", 3),
(try_end),
(call_script,"script_change_player_relation_with_troop", ":ally_leader", ":rel_boost"),
(try_end),
(assign, "$talk_context", tc_ally_thanks),
(call_script, "script_setup_troop_meeting", ":ally_leader", ":ally_leader_dna"),
(else_try),
# Talk to enemy leaders
(assign, ":break", 0),
(party_get_num_companion_stacks, ":num_stacks", "p_total_enemy_casualties"), #p_encountered changed to total_enemy_casualties
(try_for_range, ":stack_no", "$last_defeated_hero", ":num_stacks"), #May 31 bug note -- this now returns some heroes in victorious party as well as in the other party
(eq, ":break", 0),
(party_stack_get_troop_id, ":stack_troop", "p_total_enemy_casualties", ":stack_no"),
(party_stack_get_troop_dna, ":stack_troop_dna", "p_total_enemy_casualties", ":stack_no"),
(troop_is_hero, ":stack_troop"),
(store_troop_faction, ":defeated_faction", ":stack_troop"),
#steve post 0912 changes begin - removed, this is duplicated elsewhere in game menus
#(call_script, "script_add_log_entry", logent_lord_defeated_by_player, "trp_player", -1, ":stack_troop", ":defeated_faction"),
(try_begin),
(store_relation, ":relation", ":defeated_faction", "fac_player_faction"),
(ge, ":relation", 0),
(str_store_troop_name, s4, ":stack_troop"),
(try_begin),
(eq, "$cheat_mode", 1),
(display_message, "@{!}{s4} skipped in p_total_enemy_casualties capture queue because is friendly"),
(try_end),
(else_try),
(try_begin),
(party_stack_get_troop_id, ":party_leader", "$g_encountered_party", 0),
(is_between, ":party_leader", active_npcs_begin, active_npcs_end),
(troop_slot_eq, ":party_leader", slot_troop_occupation, slto_kingdom_hero),
(store_sub, ":kingdom_hero_id", ":party_leader", active_npcs_begin),
(get_achievement_stat, ":was_he_defeated_player_before", ACHIEVEMENT_BARON_GOT_BACK, ":kingdom_hero_id"),
(eq, ":was_he_defeated_player_before", 1),
(unlock_achievement, ACHIEVEMENT_BARON_GOT_BACK),
(try_end),
(store_add, "$last_defeated_hero", ":stack_no", 1),
(call_script, "script_remove_troop_from_prison", ":stack_troop"),
(troop_set_slot, ":stack_troop", slot_troop_leaded_party, -1),
(call_script, "script_cf_check_hero_can_escape_from_player", ":stack_troop"),
(str_store_troop_name, s1, ":stack_troop"),
(str_store_faction_name, s3, ":defeated_faction"),
(str_store_string, s17, "@{s1} of {s3} managed to escape."),
(display_log_message, "@{!}{s17}"),
(jump_to_menu, "mnu_enemy_slipped_away"),
(assign, ":break", 1),
(else_try),
(store_add, "$last_defeated_hero", ":stack_no", 1),
(call_script, "script_remove_troop_from_prison", ":stack_troop"),
(troop_set_slot, ":stack_troop", slot_troop_leaded_party, -1),
(assign, "$talk_context", tc_hero_defeated),
(call_script, "script_setup_troop_meeting", ":stack_troop", ":stack_troop_dna"),
(assign, ":break", 1),
(try_end),
(try_end),
(eq, ":break", 1),
(else_try),
# Talk to freed heroes
(assign, ":break", 0),
(party_get_num_prisoner_stacks, ":num_prisoner_stacks", "p_collective_enemy"),
(try_for_range, ":stack_no", "$last_freed_hero", ":num_prisoner_stacks"),
(eq, ":break", 0),
(party_prisoner_stack_get_troop_id, ":stack_troop", "p_collective_enemy", ":stack_no"),
(troop_is_hero, ":stack_troop"),
(party_prisoner_stack_get_troop_dna, ":stack_troop_dna", "p_collective_enemy", ":stack_no"),
(store_add, "$last_freed_hero", ":stack_no", 1),
(assign, "$talk_context", tc_hero_freed),
(call_script, "script_setup_troop_meeting", ":stack_troop", ":stack_troop_dna"),
(assign, ":break", 1),
(try_end),
(eq, ":break", 1),
(else_try),
(eq, "$capture_screen_shown", 0),
(assign, "$capture_screen_shown", 1),
(party_clear, "p_temp_party"),
(assign, "$g_move_heroes", 0),
#(call_script, "script_party_prisoners_add_party_companions", "p_temp_party", "p_collective_enemy"),
#p_total_enemy_casualties deki yarali askerler p_temp_party'e prisoner olarak eklenecek.
(call_script, "script_party_add_wounded_members_as_prisoners", "p_temp_party", "p_total_enemy_casualties"),
(call_script, "script_party_add_party_prisoners", "p_temp_party", "p_collective_enemy"),
(try_begin),
(call_script, "script_party_calculate_strength", "p_collective_friends_backup",0),
(assign,":total_initial_strength", reg(0)),
(gt, ":total_initial_strength", 0),
#(gt, "$g_ally_party", 0),
(call_script, "script_party_calculate_strength", "p_main_party_backup",0),
(assign,":player_party_initial_strength", reg(0)),
# move ally_party_initial_strength/(player_party_initial_strength + ally_party_initial_strength) prisoners to ally party.
# First we collect the share of prisoners of the ally party and distribute those among the allies.
(store_sub, ":ally_party_initial_strength", ":total_initial_strength", ":player_party_initial_strength"),
#(call_script, "script_party_calculate_strength", "p_ally_party_backup"),
#(assign,":ally_party_initial_strength", reg(0)),
#(store_add, ":total_initial_strength", ":player_party_initial_strength", ":ally_party_initial_strength"),
(store_mul, ":ally_share", ":ally_party_initial_strength", 1000),
(val_div, ":ally_share", ":total_initial_strength"),
(assign, "$pin_number", ":ally_share"), #we send this as a parameter to the script.
(party_clear, "p_temp_party_2"),
(call_script, "script_move_members_with_ratio", "p_temp_party", "p_temp_party_2"),
#TODO: This doesn't handle prisoners if our allies joined battle after us.
(try_begin),
(gt, "$g_ally_party", 0),
(distribute_party_among_party_group, "p_temp_party_2", "$g_ally_party"),
(try_end),
#next if there's anything left, we'll open up the party exchange screen and offer them to the player.
(try_end),
(party_get_num_companions, ":num_rescued_prisoners", "p_temp_party"),
(party_get_num_prisoners, ":num_captured_enemies", "p_temp_party"),
(store_add, ":total_capture_size", ":num_rescued_prisoners", ":num_captured_enemies"),
(gt, ":total_capture_size", 0),
(change_screen_exchange_with_party, "p_temp_party"),
(else_try),
(eq, "$loot_screen_shown", 0),
(assign, "$loot_screen_shown", 1),
# (try_begin),
# (gt, "$g_ally_party", 0),
# (call_script, "script_party_add_party", "$g_ally_party", "p_temp_party"), #Add remaining prisoners to ally TODO: FIX it.
# (else_try),
# (party_get_num_attached_parties, ":num_quick_attachments", "p_main_party"),
# (gt, ":num_quick_attachments", 0),
# (party_get_attached_party_with_rank, ":helper_party", "p_main_party", 0),
# (call_script, "script_party_add_party", ":helper_party", "p_temp_party"), #Add remaining prisoners to our reinforcements
# (try_end),
(troop_clear_inventory, "trp_temp_troop"),
(call_script, "script_party_calculate_loot", "p_total_enemy_casualties"), #p_encountered_party_backup changed to total_enemy_casualties
(gt, reg0, 0),
(troop_sort_inventory, "trp_temp_troop"),
(change_screen_loot, "trp_temp_troop"),
(else_try),
#finished all
(try_begin),
(le, "$g_ally_party", 0),
(end_current_battle),
(try_end),
(call_script, "script_party_give_xp_and_gold", "p_total_enemy_casualties"), #p_encountered_party_backup changed to total_enemy_casualties
(try_begin),
(eq, "$g_enemy_party", 0),
(display_message,"str_error_string"),
(try_end),
(try_begin),
(party_is_active, "$g_ally_party"),
(call_script, "script_battle_political_consequences", "$g_enemy_party", "$g_ally_party"),
(else_try),
(call_script, "script_battle_political_consequences", "$g_enemy_party", "p_main_party"),
(try_end),
(call_script, "script_event_player_defeated_enemy_party", "$g_enemy_party"),
(call_script, "script_clear_party_group", "$g_enemy_party"),
(try_begin),
(eq, "$g_next_menu", -1),
#NPC companion changes begin
(call_script, "script_post_battle_personality_clash_check"),
#NPC companion changes end
#Post 0907 changes begin
(party_stack_get_troop_id, ":enemy_leader", "p_encountered_party_backup",0),
(try_begin),
(is_between, ":enemy_leader", active_npcs_begin, active_npcs_end),
(neg|is_between, "$g_encountered_party", centers_begin, centers_end),
(store_troop_faction, ":enemy_leader_faction", ":enemy_leader"),
(try_begin),
(eq, "$g_ally_party", 0),
(call_script, "script_add_log_entry", logent_lord_defeated_by_player, "trp_player", -1, ":enemy_leader", ":enemy_leader_faction"),
(try_begin),
(eq, "$cheat_mode", 1),
(display_message, "@{!}Victory comment. Player was alone"),
(try_end),
(else_try),
(ge, "$g_strength_contribution_of_player", 40),
(call_script, "script_add_log_entry", logent_lord_defeated_by_player, "trp_player", -1, ":enemy_leader", ":enemy_leader_faction"),
(try_begin),
(eq, "$cheat_mode", 1),
(display_message, "@{!}Ordinary victory comment. The player provided at least 40 percent forces."),
(try_end),
(else_try),
(gt, "$g_starting_strength_enemy_party", 1000),
(call_script, "script_get_closest_center", "p_main_party"),
(assign, ":battle_of_where", reg0),
(call_script, "script_add_log_entry", logent_player_participated_in_major_battle, "trp_player", ":battle_of_where", -1, ":enemy_leader_faction"),
(try_begin),
(eq, "$cheat_mode", 1),
(display_message, "@{!}Player participation comment. The enemy had at least 1k starting strength."),
(try_end),
(else_try),
(eq, "$cheat_mode", 1),
(display_message, "@{!}No victory comment. The battle was small, and the player provided less than 40 percent of allied strength"),
(try_end),
(try_end),
#Post 0907 changes end
(val_add, "$g_total_victories", 1),
(leave_encounter),
(change_screen_return),
(else_try),
(try_begin), #my kingdom
#(change_screen_return),
(eq, "$g_next_menu", "mnu_castle_taken"),
(call_script, "script_add_log_entry", logent_castle_captured_by_player, "trp_player", "$g_encountered_party", -1, "$g_encountered_party_faction"),
(store_current_hours, ":hours"),
(faction_set_slot, "$players_kingdom", slot_faction_ai_last_decisive_event, ":hours"),
(try_begin), #player took a walled center while he is a vassal of npc kingdom.
(is_between, "$players_kingdom", npc_kingdoms_begin, npc_kingdoms_end),
(jump_to_menu, "$g_next_menu"),
(else_try), #player took a walled center while he is a vassal of rebels.
(eq, "$players_kingdom", "fac_player_supporters_faction"),
(assign, "$g_center_taken_by_player_faction", "$g_encountered_party"),
(neg|faction_slot_eq, "fac_player_supporters_faction", slot_faction_leader, "trp_player"),
(faction_get_slot, ":faction_leader", "fac_player_supporters_faction", slot_faction_leader),
(change_screen_return),
(start_map_conversation, ":faction_leader", -1),
(else_try), #player took a walled center for player's kingdom
(neg|is_between, "$players_kingdom", npc_kingdoms_begin, npc_kingdoms_end),
(assign, "$g_center_taken_by_player_faction", "$g_encountered_party"),
(assign, "$talk_context", tc_give_center_to_fief),
(change_screen_return),
(assign, ":best_troop", "trp_swadian_sharpshooter"),
(assign, ":maximum_troop_score", 0),
(party_get_num_companion_stacks, ":num_stacks", "p_main_party"),
(try_for_range, ":stack_no", 0, ":num_stacks"),
(party_stack_get_troop_id, ":stack_troop", "p_main_party", ":stack_no"),
(neq, ":stack_troop", "trp_player"),
(party_stack_get_size, ":stack_size", "p_main_party", ":stack_no"),
(party_stack_get_num_wounded, ":num_wounded", "p_main_party", ":stack_no"),
(troop_get_slot, ":num_routed", "p_main_party", slot_troop_player_routed_agents),
(assign, ":continue", 0),
(try_begin),
(neg|troop_is_hero, ":stack_troop"),
(store_add, ":agents_which_cannot_speak", ":num_wounded", ":num_routed"),
(gt, ":stack_size", ":agents_which_cannot_speak"),
(assign, ":continue", 1),
(else_try),
(troop_is_hero, ":stack_troop"),
(neg|troop_is_wounded, ":stack_troop"),
(assign, ":continue", 1),
(try_end),
(eq, ":continue", 1),
(try_begin),
(troop_is_hero, ":stack_troop"),
(troop_get_slot, ":troop_renown", ":stack_troop", slot_troop_renown),
(store_mul, ":troop_score", ":troop_renown", 100),
(val_add, ":troop_score", 1000),
(else_try),
(store_character_level, ":troop_level", ":stack_troop"),
(assign, ":troop_score", ":troop_level"),
(try_end),
(try_begin),
(gt, ":troop_score", ":maximum_troop_score"),
(assign, ":maximum_troop_score", ":troop_score"),
(assign, ":best_troop", ":stack_troop"),
(party_stack_get_troop_dna, ":best_troop_dna", "p_main_party", ":stack_no"),
(try_end),
(try_end),
(start_map_conversation, ":best_troop", ":best_troop_dna"),
(try_end),
(try_end),
(try_end),
(try_end),
],
[
("continue",[],"Continue...",[]),
]
),
(
"enemy_slipped_away",0,
"{s17}",
"none",
[],
[
("continue",[],"Continue...",[(jump_to_menu,"mnu_total_victory")]),
]
),
(
"total_defeat",0,
"{!}You shouldn't be reading this...",
"none",
[
(play_track, "track_captured", 1),
# Free prisoners
(party_get_num_prisoner_stacks, ":num_prisoner_stacks","p_main_party"),
(try_for_range, ":stack_no", 0, ":num_prisoner_stacks"),
(party_prisoner_stack_get_troop_id, ":stack_troop","p_main_party",":stack_no"),
(troop_is_hero, ":stack_troop"),
(call_script, "script_remove_troop_from_prison", ":stack_troop"),
(try_end),
(try_begin),
(party_is_active, "$g_ally_party"),
(call_script, "script_battle_political_consequences", "$g_ally_party", "$g_enemy_party"),
(else_try),
(call_script, "script_battle_political_consequences", "p_main_party", "$g_enemy_party"),
(try_end),
(call_script, "script_loot_player_items", "$g_enemy_party"),
(assign, "$g_move_heroes", 0),
(party_clear, "p_temp_party"),
(call_script, "script_party_add_party_prisoners", "p_temp_party", "p_main_party"),
(call_script, "script_party_prisoners_add_party_companions", "p_temp_party", "p_main_party"),
(distribute_party_among_party_group, "p_temp_party", "$g_enemy_party"),
(assign, "$g_prison_heroes", 1),
(call_script, "script_party_remove_all_companions", "p_main_party"),
(assign, "$g_prison_heroes", 0),
(assign, "$g_move_heroes", 1),
(call_script, "script_party_remove_all_prisoners", "p_main_party"),
(val_add, "$g_total_defeats", 1),
(try_begin),
(neq, "$g_player_surrenders", 1),
(store_random_in_range, ":random_no", 0, 100),
(ge, ":random_no", "$g_player_luck"),
(jump_to_menu, "mnu_permanent_damage"),
(else_try),
(try_begin),
(eq, "$g_next_menu", -1),
(leave_encounter),
(change_screen_return),
(else_try),
(jump_to_menu, "$g_next_menu"),
(try_end),
(try_end),
(try_begin),
(gt, "$g_ally_party", 0),
(call_script, "script_party_wound_all_members", "$g_ally_party"),
(try_end),
#Troop commentary changes begin
(party_get_num_companion_stacks, ":num_stacks", "p_encountered_party_backup"),
(try_for_range, ":stack_no", 0, ":num_stacks"),
(party_stack_get_troop_id, ":stack_troop","p_encountered_party_backup",":stack_no"),
(is_between, ":stack_troop", active_npcs_begin, active_npcs_end),
(troop_slot_eq, ":stack_troop", slot_troop_occupation, slto_kingdom_hero),
(store_troop_faction, ":victorious_faction", ":stack_troop"),
(call_script, "script_add_log_entry", logent_player_defeated_by_lord, "trp_player", -1, ":stack_troop", ":victorious_faction"),
(try_end),
#Troop commentary changes end
],
[]
),
(
"permanent_damage",mnf_disable_all_keys,
"{s0}",
"none",
[
(assign, ":end_cond", 1),
(try_for_range, ":unused", 0, ":end_cond"),
(store_random_in_range, ":random_attribute", 0, 4),
(store_attribute_level, ":attr_level", "trp_player", ":random_attribute"),
(try_begin),
(gt, ":attr_level", 3),
(neq, ":random_attribute", ca_charisma),
(try_begin),
(eq, ":random_attribute", ca_strength),
(str_store_string, s0, "@Some of your tendons have been damaged in the battle. You lose 1 strength."),
(else_try),
(eq, ":random_attribute", ca_agility),
(str_store_string, s0, "@You took a nasty wound which will cause you to limp slightly even after it heals. You lose 1 agility."),
## (else_try),
## (eq, ":random_attribute", ca_charisma),
## (str_store_string, s0, "@After the battle you are aghast to find that one of the terrible blows you suffered has left a deep, disfiguring scar on your face, horrifying those around you. Your charisma is reduced by 1."),
(else_try),
## (eq, ":random_attribute", ca_intelligence),
(str_store_string, s0, "@You have trouble thinking straight after the battle, perhaps from a particularly hard hit to your head, and frequent headaches now plague your existence. Your intelligence is reduced by 1."),
(try_end),
(else_try),
(lt, ":end_cond", 200),
(val_add, ":end_cond", 1),
(try_end),
(try_end),
(try_begin),
(eq, ":end_cond", 200),
(try_begin),
(eq, "$g_next_menu", -1),
(leave_encounter),
(change_screen_return),
(else_try),
(jump_to_menu, "$g_next_menu"),
(try_end),
(else_try),
(troop_raise_attribute, "trp_player", ":random_attribute", -1),
(try_end),
],
[
("s0",
[
(store_random_in_range, ":random_no", 0, 4),
(try_begin),
(eq, ":random_no", 0),
(str_store_string, s0, "@Perhaps I'm getting unlucky..."),
(else_try),
(eq, ":random_no", 1),
(str_store_string, s0, "@Retirement is starting to sound better and better."),
(else_try),
(eq, ":random_no", 2),
(str_store_string, s0, "@No matter! I will persevere!"),
(else_try),
(eq, ":random_no", 3),
(troop_get_type, ":is_female", "trp_player"),
(try_begin),
(eq, ":is_female", 1),
(str_store_string, s0, "@What did I do to deserve this?"),
(else_try),
(str_store_string, s0, "@I suppose it'll make for a good story, at least..."),
(try_end),
(try_end),
],
"{s0}",
[
(try_begin),
(eq, "$g_next_menu", -1),
(leave_encounter),
(change_screen_return),
(else_try),
(jump_to_menu, "$g_next_menu"),
(try_end),
]),
]
),
(
"pre_join",0,
"You come across a battle between {s2} and {s1}. You decide to...",
"none",
[
(str_store_party_name, 1,"$g_encountered_party"),
(str_store_party_name, 2,"$g_encountered_party_2"),
],
[
("pre_join_help_attackers",[
(store_faction_of_party, ":attacker_faction", "$g_encountered_party_2"),
(store_relation, ":attacker_relation", ":attacker_faction", "fac_player_supporters_faction"),
(store_faction_of_party, ":defender_faction", "$g_encountered_party"),
(store_relation, ":defender_relation", ":defender_faction", "fac_player_supporters_faction"),
(ge, ":attacker_relation", 0),
(lt, ":defender_relation", 0),
],
"Move in to help the {s2}.",[
(select_enemy,0),
(assign,"$g_enemy_party","$g_encountered_party"),
(assign,"$g_ally_party","$g_encountered_party_2"),
(jump_to_menu,"mnu_join_battle")]),
("pre_join_help_defenders",[
(store_faction_of_party, ":attacker_faction", "$g_encountered_party_2"),
(store_relation, ":attacker_relation", ":attacker_faction", "fac_player_supporters_faction"),
(store_faction_of_party, ":defender_faction", "$g_encountered_party"),
(store_relation, ":defender_relation", ":defender_faction", "fac_player_supporters_faction"),
(ge, ":defender_relation", 0),
(lt, ":attacker_relation", 0),
],
"Rush to the aid of the {s1}.",[
(select_enemy,1),
(assign,"$g_enemy_party","$g_encountered_party_2"),
(assign,"$g_ally_party","$g_encountered_party"),
(jump_to_menu,"mnu_join_battle")]),
("pre_join_leave",[],"Don't get involved.",[(leave_encounter),(change_screen_return)]),
]
),
(
"join_battle",0,
"You are helping the {s2} against the {s1}. You have {reg10} troops fit for battle against the enemy's {reg11}.",
"none",
[
(str_store_party_name, 1,"$g_enemy_party"),
(str_store_party_name, 2,"$g_ally_party"),
(call_script, "script_encounter_calculate_fit"),
(try_begin),
(eq, "$new_encounter", 1),
(assign, "$new_encounter", 0),
(call_script, "script_encounter_init_variables"),
(else_try), #second or more turn
(eq, "$g_leave_encounter",1),
(change_screen_return),
(try_end),
(try_begin),
(call_script, "script_party_count_members_with_full_health", "p_collective_enemy"),
(assign, ":num_enemy_regulars_remaining", reg0),
(assign, ":enemy_finished",0),
(try_begin),
(eq, "$g_battle_result", 1),
(this_or_next|le, ":num_enemy_regulars_remaining", 0), #battle won
(le, ":num_enemy_regulars_remaining", "$num_routed_enemies"), #replaced for above line because we do not want routed agents to spawn again in next turn of battle.
(assign, ":enemy_finished",1),
(else_try),
(eq, "$g_engaged_enemy", 1),
(le, "$g_enemy_fit_for_battle",0),
(ge, "$g_friend_fit_for_battle",1),
(assign, ":enemy_finished",1),
(try_end),
(this_or_next|eq, ":enemy_finished",1),
(eq,"$g_enemy_surrenders",1),
(assign, "$g_next_menu", -1),
(jump_to_menu, "mnu_total_victory"),
(else_try),
(call_script, "script_party_count_members_with_full_health", "p_collective_friends"),
(assign, ":num_ally_regulars_remaining", reg0),
(assign, ":battle_lost", 0),
(try_begin),
(eq, "$g_battle_result", -1),
#(eq, ":num_ally_regulars_remaining", 0), #battle lost
(le, ":num_ally_regulars_remaining", "$num_routed_allies"), #replaced for above line because we do not want routed agents to spawn again in next turn of battle.
(assign, ":battle_lost",1),
(try_end),
(this_or_next|eq, ":battle_lost",1),
(eq,"$g_player_surrenders",1),
(leave_encounter),
(change_screen_return),
(try_end),
],
[
("join_attack",
[
(neg|troop_is_wounded, "trp_player"),
],
"Charge the enemy.",
[
(assign, "$g_joined_battle_to_help", 1),
(party_set_next_battle_simulation_time, "$g_encountered_party", -1),
(assign, "$g_battle_result", 0),
(call_script, "script_calculate_renown_value"),
(call_script, "script_calculate_battle_advantage"),
(set_battle_advantage, reg0),
(set_party_battle_mode),
(set_jump_mission,"mt_lead_charge"),
(call_script, "script_setup_random_scene"),
(assign, "$g_next_menu", "mnu_join_battle"),
(jump_to_menu, "mnu_battle_debrief"),
(change_screen_mission),
]),
("join_order_attack",
[
(call_script, "script_party_count_members_with_full_health", "p_main_party"),
(ge, reg0, 3),
],
"Order your troops to attack with your allies while you stay back.",
[
(assign, "$g_joined_battle_to_help", 1),
(party_set_next_battle_simulation_time, "$g_encountered_party", -1),
(jump_to_menu,"mnu_join_order_attack"),
]),
("join_leave",[],"Leave.",
[
(try_begin),
(neg|troop_is_wounded, "trp_player"),
(call_script, "script_objectionable_action", tmt_aristocratic, "str_flee_battle"),
(party_stack_get_troop_id, ":enemy_leader","$g_enemy_party",0),
(is_between, ":enemy_leader", active_npcs_begin, active_npcs_end),
(call_script, "script_add_log_entry", logent_player_retreated_from_lord, "trp_player", -1, ":enemy_leader", -1),
(try_end),
(leave_encounter),(change_screen_return)]),
]),
(
"join_order_attack",mnf_disable_all_keys,
"{s4}^^Your casualties: {s8}^^Allies' casualties: {s9}^^Enemy casualties: {s10}",
"none",
[
(call_script, "script_party_calculate_strength", "p_main_party", 1), #skip player
(assign, ":player_party_strength", reg0),
(val_div, ":player_party_strength", 5),
(call_script, "script_party_calculate_strength", "p_collective_friends", 0),
(assign, ":friend_party_strength", reg0),
(val_div, ":friend_party_strength", 5),
(call_script, "script_party_calculate_strength", "p_collective_enemy", 0),
(assign, ":enemy_party_strength", reg0),
(val_div, ":enemy_party_strength", 5),
(try_begin),
(eq, ":friend_party_strength", 0),
(store_div, ":enemy_party_strength_for_p", ":enemy_party_strength", 2),
(else_try),
(assign, ":enemy_party_strength_for_p", ":enemy_party_strength"),
(val_mul, ":enemy_party_strength_for_p", ":player_party_strength"),
(val_div, ":enemy_party_strength_for_p", ":friend_party_strength"),
(try_end),
(val_sub, ":enemy_party_strength", ":enemy_party_strength_for_p"),
(inflict_casualties_to_party_group, "p_main_party", ":enemy_party_strength_for_p", "p_temp_casualties"),
(call_script, "script_print_casualties_to_s0", "p_temp_casualties", 0),
(str_store_string_reg, s8, s0),
(inflict_casualties_to_party_group, "$g_enemy_party", ":friend_party_strength", "p_temp_casualties"),
#ozan begin
(party_get_num_companion_stacks, ":num_stacks", "p_temp_casualties"),
(try_for_range, ":stack_no", 0, ":num_stacks"),
(party_stack_get_troop_id, ":stack_troop", "p_temp_casualties", ":stack_no"),
(try_begin),
(party_stack_get_size, ":stack_size", "p_temp_casualties", ":stack_no"),
(gt, ":stack_size", 0),
(party_add_members, "p_total_enemy_casualties", ":stack_troop", ":stack_size"), #addition_to_p_total_enemy_casualties
(party_stack_get_num_wounded, ":stack_wounded_size", "p_temp_casualties", ":stack_no"),
(gt, ":stack_wounded_size", 0),
(party_wound_members, "p_total_enemy_casualties", ":stack_troop", ":stack_wounded_size"),
(try_end),
(try_end),
#ozan end
(call_script, "script_print_casualties_to_s0", "p_temp_casualties", 0),
(str_store_string_reg, s10, s0),
(call_script, "script_collect_friendly_parties"),
#(party_collect_attachments_to_party, "$g_ally_party", "p_collective_ally"),
(inflict_casualties_to_party_group, "$g_ally_party", ":enemy_party_strength", "p_temp_casualties"),
(call_script, "script_print_casualties_to_s0", "p_temp_casualties", 0),
(str_store_string_reg, s9, s0),
(party_collect_attachments_to_party, "$g_enemy_party", "p_collective_enemy"),
#(assign, "$cant_leave_encounter", 0),
(assign, "$no_soldiers_left", 0),
(try_begin),
(call_script, "script_party_count_members_with_full_health","p_main_party"),
(assign, ":num_our_regulars_remaining", reg0),
#(le, ":num_our_regulars_remaining", 0),
(le, ":num_our_regulars_remaining", "$num_routed_us"), #replaced for above line because we do not want routed agents to spawn again in next turn of battle.
(assign, "$no_soldiers_left", 1),
(str_store_string, s4, "str_join_order_attack_failure"),
(else_try),
(call_script, "script_party_count_members_with_full_health","p_collective_enemy"),
(assign, ":num_enemy_regulars_remaining", reg0),
(this_or_next|le, ":num_enemy_regulars_remaining", 0),
(le, ":num_enemy_regulars_remaining", "$num_routed_enemies"), #replaced for above line because we do not want routed agents to spawn again in next turn of battle.
(assign, "$g_battle_result", 1),
(assign, "$no_soldiers_left", 1),
(str_store_string, s4, "str_join_order_attack_success"),
(else_try),
(str_store_string, s4, "str_join_order_attack_continue"),
(try_end),
],
[
("continue",[],"Continue...",
[
(jump_to_menu,"mnu_join_battle"),
]),
]
),
# Towns
(
"zendar",mnf_auto_enter,
"You enter the town of Zendar.",
"none",
[(reset_price_rates,0),(set_price_rate_for_item,"itm_tools",70),(set_price_rate_for_item,"itm_salt",140)],
[
("zendar_enter",[],"_",[(set_jump_mission,"mt_town_default"),(jump_to_scene,"scn_zendar_center"),(change_screen_mission)],"Door to the town center."),
("zendar_tavern",[],"_",[(set_jump_mission,"mt_town_default"),
(jump_to_scene,"scn_the_happy_boar"),
(change_screen_mission)],"Door to the tavern."),
("zendar_merchant",[],"_",[(set_jump_mission,"mt_town_default"),
(jump_to_scene,"scn_zendar_merchant"),
(change_screen_mission)],"Door to the merchant."),
("zendar_arena",[],"_",[(set_jump_mission,"mt_town_default"),
(jump_to_scene,"scn_zendar_arena"),
(change_screen_mission)],"Door to the arena."),
# ("zendar_leave",[],"Leave town.",[[leave_encounter],[change_screen_return]]),
("town_1_leave",[],"_",[(leave_encounter),(change_screen_return)]),
]
),
(
"salt_mine",mnf_auto_enter,
"You enter the salt mine.",
"none",
[(reset_price_rates,0),(set_price_rate_for_item,"itm_salt",55)],
[
("enter",[],"Enter.",[(set_jump_mission,"mt_town_center"),(jump_to_scene,"scn_salt_mine"),(change_screen_mission)]),
("leave",[],"Leave.",[(leave_encounter),(change_screen_return)]),
]
),
(
"four_ways_inn",mnf_auto_enter,
"You arrive at the Four Ways Inn.",
"none",
[],
[
# ("enter",[],"Enter.",[[set_jump_mission,"mt_town_default"],[jump_to_scene,"scn_conversation_scene"],[change_screen_mission]]),
("enter",[],"Enter.",[(set_jump_mission,"mt_ai_training"),(jump_to_scene,"scn_four_ways_inn"),(change_screen_mission)]),
("leave",[],"Leave.",[(leave_encounter),(change_screen_return)]),
]
),
(
"test_scene",0,
"You enter the test scene.",
"none",
[],
[
("enter",[],"Enter 1.",[[set_jump_mission,"mt_ai_training"],[jump_to_scene,"scn_multi_scene_1"],[change_screen_mission]]),
("enter",[],"Enter 2.",[[set_jump_mission,"mt_ai_training"],[jump_to_scene,"scn_multi_scene_2"],[change_screen_mission]]),
("enter",[],"Enter 3.",[[set_jump_mission,"mt_ai_training"],[jump_to_scene,"scn_multi_scene_3"],[change_screen_mission]]),
("enter",[],"Enter 4.",[[set_jump_mission,"mt_ai_training"],[jump_to_scene,"scn_multi_scene_4"],[change_screen_mission]]),
("enter",[],"Enter 5.",[[set_jump_mission,"mt_ai_training"],[jump_to_scene,"scn_multi_scene_5"],[change_screen_mission]]),
("enter",[],"Enter 6.",[[set_jump_mission,"mt_ai_training"],[jump_to_scene,"scn_multi_scene_6"],[change_screen_mission]]),
("enter",[],"Enter 7.",[[set_jump_mission,"mt_ai_training"],[jump_to_scene,"scn_test2"],[change_screen_mission]]),
("enter",[],"Enter 8.",[[set_jump_mission,"mt_ai_training"],[jump_to_scene,"scn_test3"],[change_screen_mission]]),
("enter",[],"Enter 9.",[[set_jump_mission,"mt_ai_training"],[jump_to_scene,"scn_multi_scene_13"],[change_screen_mission]]),
("leave",[],"Leave.",[(leave_encounter),(change_screen_return)]),
]
),
(
"battlefields",0,
"{!}Select a field...",
"none",
[],
[
("enter_f1",[],"{!}Field 1",[[set_jump_mission,"mt_ai_training"],[jump_to_scene,"scn_field_1"],[change_screen_mission]]),
("enter_f2",[],"{!}Field 2",[[set_jump_mission,"mt_ai_training"],[jump_to_scene,"scn_field_2"],[change_screen_mission]]),
("enter_f3",[],"{!}Field 3",[[set_jump_mission,"mt_ai_training"],[jump_to_scene,"scn_field_3"],[change_screen_mission]]),
("enter_f4",[],"{!}Field 4",[[set_jump_mission,"mt_ai_training"],[jump_to_scene,"scn_field_4"],[change_screen_mission]]),
("enter_f5",[],"{!}Field 5",[[set_jump_mission,"mt_ai_training"],[jump_to_scene,"scn_field_5"],[change_screen_mission]]),
("leave",[],"Leave.",[(leave_encounter),(change_screen_return)]),
]
),
(
"dhorak_keep",0,
# "Dhorak Keep, the stronghold of the bandits stands overlooking the barren wilderness.",
"You enter the Dhorak Keep",
"none",
[],
[
("enter",[],"Enter.",[(set_jump_mission,"mt_town_center"),(jump_to_scene,"scn_dhorak_keep"),(change_screen_mission)]),
("leave",[],"Leave.",[(leave_encounter),(change_screen_return)]),
]
),
## (
## "center_under_attack_while_resting",0,
## "{s1} has been besieged by {s2}, and the enemy seems to be preparing for an assault!\
## What will you do?",
## "none",
## [
## (party_get_battle_opponent, ":besieger_party", "$auto_enter_town"),
## (str_store_party_name, s1, "$auto_enter_town"),
## (str_store_party_name, s2, ":besieger_party"),
## ],
## [
## ("defend_against_siege", [],"Help the defenders of {s1}!",
## [
## (assign, "$g_last_player_do_nothing_against_siege_next_check", 0),
## (rest_for_hours, 0, 0, 0),
## (change_screen_return),
## (start_encounter, "$auto_enter_town"),
## ]),
## ("do_not_defend_against_siege",[],"Find a secure place and wait there.",
## [
## (change_screen_return),
## ]),
## ]
## ),
(
"join_siege_outside",mnf_scale_picture,
"{s1} has come under siege by {s2}.",
"none",
[
(str_store_party_name, s1, "$g_encountered_party"),
(str_store_party_name, s2, "$g_encountered_party_2"),
(troop_get_type, ":is_female", "trp_player"),
(try_begin),
(eq, ":is_female", 1),
(set_background_mesh, "mesh_pic_siege_sighted_fem"),
(else_try),
(set_background_mesh, "mesh_pic_siege_sighted"),
(try_end),
],
[
("approach_besiegers",[(store_faction_of_party, ":faction_no", "$g_encountered_party_2"),
(store_relation, ":relation", ":faction_no", "fac_player_supporters_faction"),
(ge, ":relation", 0),
(store_faction_of_party, ":faction_no", "$g_encountered_party"),
(store_relation, ":relation", ":faction_no", "fac_player_supporters_faction"),
(lt, ":relation", 0),
],"Approach the siege camp.",[
(jump_to_menu, "mnu_besiegers_camp_with_allies"),
]),
("pass_through_siege",[(store_faction_of_party, ":faction_no", "$g_encountered_party"),
(store_relation, ":relation", ":faction_no", "fac_player_supporters_faction"),
(ge, ":relation", 0),
],"Pass through the siege lines and enter {s1}.",
[
(jump_to_menu,"mnu_cut_siege_without_fight"),
]),
("leave",[],"Leave.",[(leave_encounter),
(change_screen_return)]),
]
),
(
"cut_siege_without_fight",0,
"The besiegers let you approach the gates without challenge.",
"none",
[],
[
("continue",[],"Continue...",[(try_begin),
(this_or_next|eq, "$g_encountered_party_faction", "fac_player_supporters_faction"),
(eq, "$g_encountered_party_faction", "$players_kingdom"),
(jump_to_menu, "mnu_town"),
(else_try),
(jump_to_menu, "mnu_castle_outside"),
(try_end)]),
]
),
(
"besiegers_camp_with_allies",0,
"{s1} remains under siege. The banners of {s2} fly above the camp of the besiegers,\
where you and your men are welcomed.",
"none",
[
(str_store_party_name, s1, "$g_encountered_party"),
(str_store_party_name, s2, "$g_encountered_party_2"),
(assign, "$g_enemy_party", "$g_encountered_party"),
(assign, "$g_ally_party", "$g_encountered_party_2"),
(select_enemy, 0),
(call_script, "script_encounter_calculate_fit"),
(try_begin),
(eq, "$new_encounter", 1),
(assign, "$new_encounter", 0),
(call_script, "script_encounter_init_variables"),
(try_end),
(try_begin),
(eq, "$g_leave_encounter",1),
(change_screen_return),
(else_try),
(assign, ":enemy_finished", 0),
(try_begin),
(eq, "$g_battle_result", 1),
(assign, ":enemy_finished", 1),
(else_try),
(le, "$g_enemy_fit_for_battle", 0),
(ge, "$g_friend_fit_for_battle", 1),
(assign, ":enemy_finished", 1),
(try_end),
(this_or_next|eq, ":enemy_finished", 1),
(eq, "$g_enemy_surrenders", 1),
## (assign, "$g_next_menu", -1),#"mnu_castle_taken_by_friends"),
## (jump_to_menu, "mnu_total_victory"),
(call_script, "script_party_wound_all_members", "$g_enemy_party"),
(leave_encounter),
(change_screen_return),
(else_try),
(call_script, "script_party_count_members_with_full_health", "p_collective_friends"),
(assign, ":ally_num_soldiers", reg0),
(eq, "$g_battle_result", -1),
(eq, ":ally_num_soldiers", 0), #battle lost (TODO : also compare this with routed allies too like in other parts)
(leave_encounter),
(change_screen_return),
(try_end),
],
[
("talk_to_siege_commander",[],"Request a meeting with the commander.",[
(call_script, "script_get_meeting_scene"), (assign, ":meeting_scene", reg0),
(modify_visitors_at_site,":meeting_scene"),(reset_visitors),
(set_visitor,0,"trp_player"),
(party_stack_get_troop_id, ":siege_leader_id","$g_encountered_party_2",0),
(party_stack_get_troop_dna,":siege_leader_dna","$g_encountered_party_2",0),
(set_visitor,17,":siege_leader_id",":siege_leader_dna"),
(set_jump_mission,"mt_conversation_encounter"),
(jump_to_scene,":meeting_scene"),
(assign, "$talk_context", tc_siege_commander),
(change_screen_map_conversation, ":siege_leader_id")]),
("join_siege_with_allies",[(neg|troop_is_wounded, "trp_player")], "Join the next assault.",
[
(assign, "$g_joined_battle_to_help", 1),
(party_set_next_battle_simulation_time, "$g_encountered_party", -1),
(try_begin),
(check_quest_active, "qst_join_siege_with_army"),
(quest_slot_eq, "qst_join_siege_with_army", slot_quest_target_center, "$g_encountered_party"),
(add_xp_as_reward, 250),
(call_script, "script_end_quest", "qst_join_siege_with_army"),
#Reactivating follow army quest
(faction_get_slot, ":faction_marshall", "$players_kingdom", slot_faction_marshall),
(str_store_troop_name_link, s9, ":faction_marshall"),
(setup_quest_text, "qst_follow_army"),
(str_store_string, s2, "@{s9} wants you to follow his army until further notice."),
(call_script, "script_start_quest", "qst_follow_army", ":faction_marshall"),
(assign, "$g_player_follow_army_warnings", 0),
(try_end),
(try_begin),
(party_slot_eq, "$g_encountered_party", slot_party_type, spt_town),
(party_get_slot, ":battle_scene", "$g_encountered_party", slot_town_walls),
(else_try),
(party_get_slot, ":battle_scene", "$g_encountered_party", slot_castle_exterior),
(try_end),
(call_script, "script_calculate_battle_advantage"),
(val_mul, reg0, 2),
(val_div, reg0, 3), #scale down the advantage a bit in sieges.
(set_battle_advantage, reg0),
(set_party_battle_mode),
(try_begin),
(party_slot_eq, "$g_encountered_party", slot_center_siege_with_belfry, 1),
(set_jump_mission,"mt_castle_attack_walls_belfry"),
(else_try),
(set_jump_mission,"mt_castle_attack_walls_ladder"),
(try_end),
(jump_to_scene,":battle_scene"),
(assign, "$g_siege_final_menu", "mnu_besiegers_camp_with_allies"),
(assign, "$g_siege_battle_state", 1),
(assign, "$g_next_menu", "mnu_castle_besiege_inner_battle"),
(jump_to_menu, "mnu_battle_debrief"),
(change_screen_mission),
]),
("join_siege_stay_back", [(call_script, "script_party_count_members_with_full_health", "p_main_party"),
(ge, reg0, 3),
],
"Order your soldiers to join the next assault without you.",
[
(assign, "$g_joined_battle_to_help", 1),
(party_set_next_battle_simulation_time, "$g_encountered_party", -1),
(try_begin),
(check_quest_active, "qst_join_siege_with_army"),
(quest_slot_eq, "qst_join_siege_with_army", slot_quest_target_center, "$g_encountered_party"),
(add_xp_as_reward, 100),
(call_script, "script_end_quest", "qst_join_siege_with_army"),
#Reactivating follow army quest
(faction_get_slot, ":faction_marshall", "$players_kingdom", slot_faction_marshall),
(str_store_troop_name_link, s9, ":faction_marshall"),
(setup_quest_text, "qst_follow_army"),
(str_store_string, s2, "@{s9} wants you to follow his army until further notice."),
(call_script, "script_start_quest", "qst_follow_army", ":faction_marshall"),
(assign, "$g_player_follow_army_warnings", 0),
(try_end),
(jump_to_menu,"mnu_castle_attack_walls_with_allies_simulate")]),
("leave",[],"Leave.",[(leave_encounter),(change_screen_return)]),
]
),
(
"castle_outside",mnf_scale_picture,
"You are outside {s2}.{s11} {s3} {s4}",
"none",
[
(assign, "$g_enemy_party", "$g_encountered_party"),
(assign, "$g_ally_party", -1),
(str_store_party_name, s2,"$g_encountered_party"),
(call_script, "script_encounter_calculate_fit"),
(assign,"$all_doors_locked",1),
(assign, "$current_town","$g_encountered_party"),
(try_begin),
(eq, "$new_encounter", 1),
(assign, "$new_encounter", 0),
(call_script, "script_let_nearby_parties_join_current_battle", 1, 0),
(call_script, "script_encounter_init_variables"),
(assign, "$entry_to_town_forbidden",0),
(assign, "$sneaked_into_town",0),
(assign, "$town_entered", 0),
# (assign, "$waiting_for_arena_fight_result", 0),
(assign, "$encountered_party_hostile", 0),
(assign, "$encountered_party_friendly", 0),
(try_begin),
(gt, "$g_player_besiege_town", 0),
(neq,"$g_player_besiege_town","$g_encountered_party"),
(party_slot_eq, "$g_player_besiege_town", slot_center_is_besieged_by, "p_main_party"),
(call_script, "script_lift_siege", "$g_player_besiege_town", 0),
(assign,"$g_player_besiege_town",-1),
(try_end),
(try_begin),
(lt, "$g_encountered_party_relation", 0),
(assign, "$encountered_party_hostile", 1),
(assign,"$entry_to_town_forbidden",1),
(try_end),
(assign,"$cant_sneak_into_town",0),
(try_begin),
(eq,"$current_town","$last_sneak_attempt_town"),
(store_current_hours,reg(2)),
(val_sub,reg(2),"$last_sneak_attempt_time"),
(lt,reg(2),12),
(assign,"$cant_sneak_into_town",1),
(try_end),
(else_try), #second or more turn
(eq, "$g_leave_encounter",1),
(change_screen_return),
(try_end),
(str_clear,s4),
(try_begin),
(eq,"$entry_to_town_forbidden",1),
(try_begin),
(eq,"$cant_sneak_into_town",1),
(str_store_string,s4,"str_sneaking_to_town_impossible"),
(else_try),
(str_store_string,s4,"str_entrance_to_town_forbidden"),
(try_end),
(try_end),
(party_get_slot, ":center_lord", "$current_town", slot_town_lord),
(store_faction_of_party, ":center_faction", "$current_town"),
(str_store_faction_name,s9,":center_faction"),
(try_begin),
(ge, ":center_lord", 0),
(str_store_troop_name,s8,":center_lord"),
(str_store_string,s7,"@{s8} of {s9}"),
(try_end),
(try_begin), # same mnu_town
(party_slot_eq,"$current_town",slot_party_type, spt_castle),
(try_begin),
(eq, ":center_lord", "trp_player"),
(str_store_string,s11,"@ Your own banner flies over the castle gate."),
(else_try),
(ge, ":center_lord", 0),
(str_store_string,s11,"@ You see the banner of {s7} over the castle gate."),
(else_try),
(is_between, ":center_faction", kingdoms_begin, kingdoms_end),
(str_store_string,s11,"str__this_castle_is_temporarily_under_royal_control"),
(else_try),
(str_store_string,s11,"str__this_castle_does_not_seem_to_be_under_anyones_control"),
(try_end),
(else_try),
(try_begin),
(eq, ":center_lord", "trp_player"),
(str_store_string,s11,"@ Your own banner flies over the town gates."),
(else_try),
(ge, ":center_lord", 0),
(str_store_string,s11,"@ You see the banner of {s7} over the town gates."),
(else_try),
(is_between, ":center_faction", kingdoms_begin, kingdoms_end),
(str_store_string,s11,"str__this_town_is_temporarily_under_royal_control"),
(else_try),
(str_store_string,s11,"str__the_townspeople_seem_to_have_declared_their_independence"),
(try_end),
(try_end),
(party_get_num_companions, reg(7),"p_collective_enemy"),
(assign,"$castle_undefended",0),
(str_clear, s3),
(try_begin),
(eq,reg(7),0),
(assign,"$castle_undefended",1),
# (party_set_faction,"$g_encountered_party","fac_neutral"),
# (party_set_slot, "$g_encountered_party", slot_town_lord, stl_unassigned),
(str_store_string, s3, "str_castle_is_abondened"),
(else_try),
(eq,"$g_encountered_party_faction","fac_player_supporters_faction"),
(str_store_string, s3, "str_place_is_occupied_by_player"),
(else_try),
(lt, "$g_encountered_party_relation", 0),
(str_store_string, s3, "str_place_is_occupied_by_enemy"),
(else_try),
# (str_store_string, s3, "str_place_is_occupied_by_friendly"),
(try_end),
(try_begin),
(eq, "$g_leave_town_outside",1),
(assign, "$g_leave_town_outside",0),
(assign, "$g_permitted_to_center", 0),
(change_screen_return),
(else_try),
(check_quest_active, "qst_escort_lady"),
(quest_slot_eq, "qst_escort_lady", slot_quest_target_center, "$g_encountered_party"),
(quest_get_slot, ":quest_object_troop", "qst_escort_lady", slot_quest_object_troop),
(call_script, "script_get_meeting_scene"), (assign, ":meeting_scene", reg0),
(modify_visitors_at_site,":meeting_scene"),
(reset_visitors),
(set_visitor,0, "trp_player"),
(set_visitor,17, ":quest_object_troop"),
(set_jump_mission, "mt_conversation_encounter"),
(jump_to_scene, ":meeting_scene"),
(assign, "$talk_context", tc_entering_center_quest_talk),
(change_screen_map_conversation, ":quest_object_troop"),
(else_try),
(check_quest_active, "qst_kidnapped_girl"),
(quest_slot_eq, "qst_kidnapped_girl", slot_quest_giver_center, "$g_encountered_party"),
(quest_slot_eq, "qst_kidnapped_girl", slot_quest_current_state, 3),
(call_script, "script_get_meeting_scene"), (assign, ":meeting_scene", reg0),
(modify_visitors_at_site,":meeting_scene"),
(reset_visitors),
(set_visitor,0, "trp_player"),
(set_visitor,17, "trp_kidnapped_girl"),
(set_jump_mission, "mt_conversation_encounter"),
(jump_to_scene, ":meeting_scene"),
(assign, "$talk_context", tc_entering_center_quest_talk),
(change_screen_map_conversation, "trp_kidnapped_girl"),
## (else_try),
## (gt, "$lord_requested_to_talk_to", 0),
## (store_current_hours, ":cur_hours"),
## (neq, ":cur_hours", "$quest_given_time"),
## (modify_visitors_at_site,"scn_conversation_scene"),
## (reset_visitors),
## (assign, ":cur_lord", "$lord_requested_to_talk_to"),
## (assign, "$lord_requested_to_talk_to", 0),
## (set_visitor,0,"trp_player"),
## (set_visitor,17,":cur_lord"),
## (set_jump_mission,"mt_conversation_encounter"),
## (jump_to_scene,"scn_conversation_scene"),
## (assign, "$talk_context", tc_castle_gate_lord),
## (change_screen_map_conversation, ":cur_lord"),
(else_try),
(eq, "$g_town_visit_after_rest", 1),
(assign, "$g_town_visit_after_rest", 0),
(jump_to_menu,"mnu_town"),
(else_try),
(party_slot_eq, "$g_encountered_party", slot_party_type, spt_castle),
(this_or_next|party_slot_eq, "$g_encountered_party", slot_town_lord, "trp_player"),
(faction_slot_eq, "$g_encountered_party_faction", slot_faction_leader, "trp_player"),
(jump_to_menu, "mnu_enter_your_own_castle"),
(else_try),
(party_slot_eq,"$g_encountered_party", slot_party_type,spt_castle),
(ge, "$g_encountered_party_relation", 0),
(this_or_next|eq,"$castle_undefended", 1),
(this_or_next|eq, "$g_permitted_to_center", 1),
(eq, "$g_encountered_party_faction", "$players_kingdom"),
(jump_to_menu, "mnu_town"),
(else_try),
(party_slot_eq,"$g_encountered_party", slot_party_type,spt_town),
(ge, "$g_encountered_party_relation", 0),
(jump_to_menu, "mnu_town"),
(else_try),
(eq, "$g_player_besiege_town", "$g_encountered_party"),
(jump_to_menu, "mnu_castle_besiege"),
(try_end),
(call_script, "script_set_town_picture"),
],
[
# ("talk_to_castle_commander",[
# (party_get_num_companions, ":no_companions", "$g_encountered_party"),
# (ge, ":no_companions", 1),
# (eq,"$ruler_meeting_denied",0), #this variable is removed
# ],
# "Request a meeting with the lord of the castle.",[
# (modify_visitors_at_site,"scn_conversation_scene"),(reset_visitors),
# (set_visitor,0,"trp_player"),
# (party_stack_get_troop_id, reg(6),"$g_encountered_party",0),
# (party_stack_get_troop_dna,reg(7),"$g_encountered_party",0),
# (set_visitor,17,reg(6),reg(7)),
# (set_jump_mission,"mt_conversation_encounter"),
# (jump_to_scene,"scn_conversation_scene"),
# (assign, "$talk_context", tc_castle_commander),
# (change_screen_map_conversation, reg(6))
# ]),
("approach_gates",[(this_or_next|eq,"$entry_to_town_forbidden",1),
(party_slot_eq,"$g_encountered_party", slot_party_type,spt_castle)],
"Approach the gates and hail the guard.",[
(jump_to_menu, "mnu_castle_guard"),
## (modify_visitors_at_site,"scn_conversation_scene"),(reset_visitors),
## (set_visitor,0,"trp_player"),
## (store_faction_of_party, ":cur_faction", "$g_encountered_party"),
## (faction_get_slot, ":cur_guard", ":cur_faction", slot_faction_guard_troop),
## (set_visitor,17,":cur_guard"),
## (set_jump_mission,"mt_conversation_encounter"),
## (jump_to_scene,"scn_conversation_scene"),
## (assign, "$talk_context", tc_castle_gate),
## (change_screen_map_conversation, ":cur_guard")
]),
("town_sneak",
[
(try_begin),
(party_slot_eq, "$g_encountered_party", slot_party_type,spt_town),
(str_store_string, s7, "str_town"),
(else_try),
(str_store_string, s7, "str_castle"),
(try_end),
(eq, "$entry_to_town_forbidden", 1),
(eq, "$cant_sneak_into_town", 0)
],
"Disguise yourself and try to sneak into the {s7}",
[
(faction_get_slot, ":player_alarm", "$g_encountered_party_faction", slot_faction_player_alarm),
(party_get_num_companions, ":num_men", "p_main_party"),
(party_get_num_prisoners, ":num_prisoners", "p_main_party"),
(val_add, ":num_men", ":num_prisoners"),
(val_mul, ":num_men", 2),
(val_div, ":num_men", 3),
(store_add, ":get_caught_chance", ":player_alarm", ":num_men"),
(store_random_in_range, ":random_chance", 0, 100),
(try_begin),
(this_or_next|ge, ":random_chance", ":get_caught_chance"),
(eq, "$g_last_defeated_bandits_town", "$g_encountered_party"),
(assign, "$g_last_defeated_bandits_town", 0),
(assign, "$sneaked_into_town",1),
(assign, "$town_entered", 1),
(jump_to_menu,"mnu_sneak_into_town_suceeded"),
(assign, "$g_mt_mode", tcm_disguised),
(else_try),
(jump_to_menu,"mnu_sneak_into_town_caught"),
(try_end)
]),
("castle_start_siege",
[
(this_or_next|party_slot_eq, "$g_encountered_party", slot_center_is_besieged_by, -1),
( party_slot_eq, "$g_encountered_party", slot_center_is_besieged_by, "p_main_party"),
(store_relation, ":reln", "$g_encountered_party_faction", "fac_player_supporters_faction"),
(lt, ":reln", 0),
(lt, "$g_encountered_party_2", 1),
(call_script, "script_party_count_fit_for_battle","p_main_party"),
(gt, reg(0), 5),
(try_begin),
(party_slot_eq, "$g_encountered_party", slot_party_type, spt_town),
(assign, reg6, 1),
(else_try),
(assign, reg6, 0),
(try_end),
],
"Besiege the {reg6?town:castle}.",
[
(assign,"$g_player_besiege_town","$g_encountered_party"),
(store_relation, ":relation", "fac_player_supporters_faction", "$g_encountered_party_faction"),
(val_min, ":relation", -40),
(call_script, "script_set_player_relation_with_faction", "$g_encountered_party_faction", ":relation"),
(call_script, "script_update_all_notes"),
(jump_to_menu, "mnu_castle_besiege"),
]),
("cheat_castle_start_siege",
[
(eq, "$cheat_mode", 1),
(this_or_next|party_slot_eq, "$g_encountered_party", slot_center_is_besieged_by, -1),
( party_slot_eq, "$g_encountered_party", slot_center_is_besieged_by, "p_main_party"),
(store_relation, ":reln", "$g_encountered_party_faction", "fac_player_supporters_faction"),
(ge, ":reln", 0),
(lt, "$g_encountered_party_2", 1),
(call_script, "script_party_count_fit_for_battle","p_main_party"),
(gt, reg(0), 1),
(try_begin),
(party_slot_eq, "$g_encountered_party", slot_party_type, spt_town),
(assign, reg6, 1),
(else_try),
(assign, reg6, 0),
(try_end),
],
"{!}CHEAT: Besiege the {reg6?town:castle}...",
[
(assign,"$g_player_besiege_town","$g_encountered_party"),
(jump_to_menu, "mnu_castle_besiege"),
]),
("castle_leave",[],"Leave.",[(change_screen_return,0)]),
("castle_cheat_interior",[(eq, "$cheat_mode", 1)], "{!}CHEAT! Interior.",[(set_jump_mission,"mt_ai_training"),
(party_get_slot, ":castle_scene", "$current_town", slot_town_castle),
(jump_to_scene,":castle_scene"),
(change_screen_mission)]),
("castle_cheat_exterior",[(eq, "$cheat_mode", 1)], "{!}CHEAT! Exterior.",[
# (set_jump_mission,"mt_town_default"),
(set_jump_mission,"mt_ai_training"),
(party_get_slot, ":castle_scene", "$current_town", slot_castle_exterior),
(jump_to_scene,":castle_scene"),
(change_screen_mission)]),
("castle_cheat_town_walls",[(eq, "$cheat_mode", 1),(party_slot_eq,"$current_town",slot_party_type, spt_town),], "{!}CHEAT! Town Walls.",
[
(party_get_slot, ":scene", "$current_town", slot_town_walls),
(set_jump_mission,"mt_ai_training"),
(jump_to_scene,":scene"),
(change_screen_mission)]),
]
),
(
"castle_guard",mnf_scale_picture,
"You approach the gate. The men on the walls watch you closely.",
"none",
[
(call_script, "script_set_town_picture"),
],
[
("request_shelter",[(party_slot_eq, "$g_encountered_party",slot_party_type, spt_castle),
(ge, "$g_encountered_party_relation", 0)],
"Request entry to the castle.",
[(party_get_slot, ":castle_lord", "$g_encountered_party", slot_town_lord),
(try_begin),
(lt, ":castle_lord", 0),
(jump_to_menu, "mnu_castle_entry_granted"),
(else_try),
(call_script, "script_troop_get_player_relation", ":castle_lord"),
(assign, ":castle_lord_relation", reg0),
#(troop_get_slot, ":castle_lord_relation", ":castle_lord", slot_troop_player_relation),
(try_begin),
(gt, ":castle_lord_relation", -15),
(jump_to_menu, "mnu_castle_entry_granted"),
(else_try),
(jump_to_menu, "mnu_castle_entry_denied"),
(try_end),
(try_end),
]),
("request_meeting_commander",[],
"Request a meeting with someone.",
[
(jump_to_menu, "mnu_castle_meeting"),
]),
("guard_leave",[],
"Leave.",
[(change_screen_return,0)]),
]
),
(
"castle_entry_granted",mnf_scale_picture,
"After a brief wait, the guards open the gates for you and allow your party inside.",
"none",
[
(call_script, "script_set_town_picture"),
],
[
("continue",[],
"Continue...",
[(jump_to_menu,"mnu_town")]),
]
),
(
"castle_entry_denied",mnf_scale_picture,
"The lord of this castle has forbidden you from coming inside these walls,\
and the guard sergeant informs you that his men will fire if you attempt to come any closer.",
"none",
[
(call_script, "script_set_town_picture"),
],
[
("continue",[],
"Continue...",
[(jump_to_menu,"mnu_castle_guard")]),
]
),
(
"castle_meeting",mnf_scale_picture,
"With whom do you want to meet?",
"none",
[
(assign, "$num_castle_meeting_troops", 0),
(try_for_range, ":troop_no", active_npcs_begin, active_npcs_end),
(troop_slot_eq, ":troop_no", slot_troop_occupation, slto_kingdom_hero),
(call_script, "script_get_troop_attached_party", ":troop_no"),
(eq, "$g_encountered_party", reg0),
(troop_set_slot, "trp_temp_array_a", "$num_castle_meeting_troops", ":troop_no"),
(val_add, "$num_castle_meeting_troops", 1),
(try_end),
(call_script, "script_set_town_picture"),
],
[
("guard_meet_s5",[(gt, "$num_castle_meeting_troops", 0),(troop_get_slot, ":troop_no", "trp_temp_array_a", 0),(str_store_troop_name, s5, ":troop_no")],
"{s5}.",[(troop_get_slot, "$castle_meeting_selected_troop", "trp_temp_array_a", 0),(jump_to_menu,"mnu_castle_meeting_selected")]),
("guard_meet_s5",[(gt, "$num_castle_meeting_troops", 1),(troop_get_slot, ":troop_no", "trp_temp_array_a", 1),(str_store_troop_name, s5, ":troop_no")],
"{s5}.",[(troop_get_slot, "$castle_meeting_selected_troop", "trp_temp_array_a", 1),(jump_to_menu,"mnu_castle_meeting_selected")]),
("guard_meet_s5",[(gt, "$num_castle_meeting_troops", 2),(troop_get_slot, ":troop_no", "trp_temp_array_a", 2),(str_store_troop_name, s5, ":troop_no")],
"{s5}.",[(troop_get_slot, "$castle_meeting_selected_troop", "trp_temp_array_a", 2),(jump_to_menu,"mnu_castle_meeting_selected")]),
("guard_meet_s5",[(gt, "$num_castle_meeting_troops", 3),(troop_get_slot, ":troop_no", "trp_temp_array_a", 3),(str_store_troop_name, s5, ":troop_no")],
"{s5}.",[(troop_get_slot, "$castle_meeting_selected_troop", "trp_temp_array_a", 3),(jump_to_menu,"mnu_castle_meeting_selected")]),
("guard_meet_s5",[(gt, "$num_castle_meeting_troops", 4),(troop_get_slot, ":troop_no", "trp_temp_array_a", 4),(str_store_troop_name, s5, ":troop_no")],
"{s5}.",[(troop_get_slot, "$castle_meeting_selected_troop", "trp_temp_array_a", 4),(jump_to_menu,"mnu_castle_meeting_selected")]),
("guard_meet_s5",[(gt, "$num_castle_meeting_troops", 5),(troop_get_slot, ":troop_no", "trp_temp_array_a", 5),(str_store_troop_name, s5, ":troop_no")],
"{s5}.",[(troop_get_slot, "$castle_meeting_selected_troop", "trp_temp_array_a", 5),(jump_to_menu,"mnu_castle_meeting_selected")]),
("guard_meet_s5",[(gt, "$num_castle_meeting_troops", 6),(troop_get_slot, ":troop_no", "trp_temp_array_a", 6),(str_store_troop_name, s5, ":troop_no")],
"{s5}.",[(troop_get_slot, "$castle_meeting_selected_troop", "trp_temp_array_a", 6),(jump_to_menu,"mnu_castle_meeting_selected")]),
("guard_meet_s5",[(gt, "$num_castle_meeting_troops", 7),(troop_get_slot, ":troop_no", "trp_temp_array_a", 7),(str_store_troop_name, s5, ":troop_no")],
"{s5}.",[(troop_get_slot, "$castle_meeting_selected_troop", "trp_temp_array_a", 7),(jump_to_menu,"mnu_castle_meeting_selected")]),
("guard_meet_s5",[(gt, "$num_castle_meeting_troops", 8),(troop_get_slot, ":troop_no", "trp_temp_array_a", 8),(str_store_troop_name, s5, ":troop_no")],
"{s5}.",[(troop_get_slot, "$castle_meeting_selected_troop", "trp_temp_array_a", 8),(jump_to_menu,"mnu_castle_meeting_selected")]),
("guard_meet_s5",[(gt, "$num_castle_meeting_troops", 9),(troop_get_slot, ":troop_no", "trp_temp_array_a", 9),(str_store_troop_name, s5, ":troop_no")],
"{s5}.",[(troop_get_slot, "$castle_meeting_selected_troop", "trp_temp_array_a", 9),(jump_to_menu,"mnu_castle_meeting_selected")]),
("forget_it",[],
"Forget it.",
[(jump_to_menu,"mnu_castle_guard")]),
]
),
(
"castle_meeting_selected",0,
"Your request for a meeting is relayed inside, and finally {s6} appears in the courtyard to speak with you.",
"none",
[(str_store_troop_name, s6, "$castle_meeting_selected_troop")],
[
("continue",[],
"Continue...",
[(jump_to_menu, "mnu_castle_outside"),
(modify_visitors_at_site,"scn_conversation_scene"),(reset_visitors),
(set_visitor,0,"trp_player"),
(set_visitor,17,"$castle_meeting_selected_troop"),
(set_jump_mission,"mt_conversation_encounter"),
(jump_to_scene,"scn_conversation_scene"),
(assign, "$talk_context", tc_castle_gate),
(change_screen_map_conversation, "$castle_meeting_selected_troop"),
]),
]
),
(
"castle_besiege",mnf_scale_picture,
"You are laying siege to {s1}. {s2} {s3}",
"none",
[
(troop_get_type, ":is_female", "trp_player"),
(try_begin),
(eq, ":is_female", 1),
(set_background_mesh, "mesh_pic_siege_sighted_fem"),
(else_try),
(set_background_mesh, "mesh_pic_siege_sighted"),
(try_end),
(assign, "$g_siege_force_wait", 0),
(try_begin),
(party_slot_eq, "$g_encountered_party", slot_center_is_besieged_by, -1),
(party_set_slot, "$g_encountered_party", slot_center_is_besieged_by, "p_main_party"),
(store_current_hours, ":cur_hours"),
(party_set_slot, "$g_encountered_party", slot_center_siege_begin_hours, ":cur_hours"),
(assign, "$g_siege_method", 0),
(assign, "$g_siege_sallied_out_once", 0),
(try_end),
(party_get_slot, ":town_food_store", "$g_encountered_party", slot_party_food_store),
(call_script, "script_center_get_food_consumption", "$g_encountered_party"),
(assign, ":food_consumption", reg0),
(assign, reg7, ":food_consumption"),
(assign, reg8, ":town_food_store"),
(store_div, reg3, ":town_food_store", ":food_consumption"),
(try_begin),
(party_slot_eq, "$g_encountered_party", slot_party_type, spt_town),
(assign, reg6, 1),
(else_try),
(assign, reg6, 0),
(try_end),
(try_begin),
(gt, reg3, 0),
(str_store_string, s2, "@The {reg6?town's:castle's} food stores should last for {reg3} more days."),
(else_try),
(str_store_string, s2, "@The {reg6?town's:castle's} food stores have run out and the defenders are starving."),
(try_end),
(str_store_string, s3, "str_empty_string"),
(try_begin),
(ge, "$g_siege_method", 1),
(store_current_hours, ":cur_hours"),
(try_begin),
(lt, ":cur_hours", "$g_siege_method_finish_hours"),
(store_sub, reg9, "$g_siege_method_finish_hours", ":cur_hours"),
(try_begin),
(eq, "$g_siege_method", 1),
(str_store_string, s3, "@You're preparing to attack the walls, the work should finish in {reg9} hours."),
(else_try),
(eq, "$g_siege_method", 2),
(str_store_string, s3, "@Your forces are building a siege tower. They estimate another {reg9} hours to complete the build."),
(try_end),
(else_try),
(try_begin),
(eq, "$g_siege_method", 1),
(str_store_string, s3, "@You are ready to attack the walls at any time."),
(else_try),
(eq, "$g_siege_method", 2),
(str_store_string, s3, "@The siege tower is built and ready to make an assault."),
(try_end),
(try_end),
(try_end),
#Check if enemy leaves the castle to us...
(try_begin),
(eq, "$g_castle_left_to_player",1), #we come here after dialog. Empty the castle and send parties away.
(assign, "$g_castle_left_to_player",0),
(store_faction_of_party, ":castle_faction", "$g_encountered_party"),
(party_set_faction,"$g_encountered_party","fac_neutral"), #temporarily erase faction so that it is not the closest town
(party_get_num_attached_parties, ":num_attached_parties_to_castle","$g_encountered_party"),
(try_for_range_backwards, ":iap", 0, ":num_attached_parties_to_castle"),
(party_get_attached_party_with_rank, ":attached_party", "$g_encountered_party", ":iap"),
(party_detach, ":attached_party"),
(party_get_slot, ":attached_party_type", ":attached_party", slot_party_type),
(eq, ":attached_party_type", spt_kingdom_hero_party),
(store_faction_of_party, ":attached_party_faction", ":attached_party"),
(call_script, "script_get_closest_walled_center_of_faction", ":attached_party", ":attached_party_faction"),
(try_begin),
(gt, reg0, 0),
(call_script, "script_party_set_ai_state", ":attached_party", spai_holding_center, reg0),
(else_try),
(call_script, "script_party_set_ai_state", ":attached_party", spai_patrolling_around_center, "$g_encountered_party"),
(try_end),
(try_end),
(call_script, "script_party_remove_all_companions", "$g_encountered_party"),
(change_screen_return),
(party_collect_attachments_to_party, "$g_encountered_party", "p_collective_enemy"), #recalculate so that
(call_script, "script_party_copy", "p_encountered_party_backup", "p_collective_enemy"), #leaving troops will not be considered as captured
(party_set_faction,"$g_encountered_party",":castle_faction"),
(try_end),
#Check for victory or defeat....
(assign, "$g_enemy_party", "$g_encountered_party"),
(assign, "$g_ally_party", -1),
(str_store_party_name, 1,"$g_encountered_party"),
(call_script, "script_encounter_calculate_fit"),
(assign, reg11, "$g_enemy_fit_for_battle"),
(assign, reg10, "$g_friend_fit_for_battle"),
(try_begin),
(eq, "$g_leave_encounter",1),
(change_screen_return),
(else_try),
(call_script, "script_party_count_fit_regulars","p_collective_enemy"),
(assign, ":enemy_finished", 0),
(try_begin),
(eq, "$g_battle_result", 1),
(assign, ":enemy_finished", 1),
(else_try),
(le, "$g_enemy_fit_for_battle", 0),
(ge, "$g_friend_fit_for_battle", 1),
(assign, ":enemy_finished", 1),
(try_end),
(this_or_next|eq, ":enemy_finished", 1),
(eq, "$g_enemy_surrenders", 1),
(assign, "$g_next_menu", "mnu_castle_taken"),
(jump_to_menu, "mnu_total_victory"),
(else_try),
(call_script, "script_party_count_members_with_full_health", "p_main_party"),
(assign, ":main_party_fit_regulars", reg0),
(eq, "$g_battle_result", -1),
(eq, ":main_party_fit_regulars", 0), #all lost (TODO : )
(assign, "$g_next_menu", "mnu_captivity_start_castle_defeat"),
(jump_to_menu, "mnu_total_defeat"),
(try_end),
],
[
("siege_request_meeting",[(eq, "$cant_talk_to_enemy", 0)],"Call for a meeting with the castle commander.", [
(assign, "$cant_talk_to_enemy", 1),
(assign, "$g_enemy_surrenders",0),
(assign, "$g_castle_left_to_player",0),
(assign, "$talk_context", tc_castle_commander),
(party_get_num_attached_parties, ":num_attached_parties_to_castle","$g_encountered_party"),
(try_begin),
(gt, ":num_attached_parties_to_castle", 0),
(party_get_attached_party_with_rank, ":leader_attached_party", "$g_encountered_party", 0),
(call_script, "script_setup_party_meeting", ":leader_attached_party"),
(else_try),
(call_script, "script_setup_party_meeting", "$g_encountered_party"),
(try_end),
]),
("wait_24_hours",[],"Wait until tomorrow.", [
(assign,"$auto_besiege_town","$g_encountered_party"),
(assign, "$g_siege_force_wait", 1),
(store_time_of_day,":cur_time_of_day"),
(val_add, ":cur_time_of_day", 1),
(assign, ":time_to_wait", 31),
(val_sub,":time_to_wait",":cur_time_of_day"),
(val_mod,":time_to_wait",24),
(val_add, ":time_to_wait", 1),
(rest_for_hours_interactive, ":time_to_wait", 5, 1), #rest while attackable
(assign, "$cant_talk_to_enemy", 0),
(change_screen_return),
]),
("castle_lead_attack",
[
(neg|troop_is_wounded, "trp_player"),
(ge, "$g_siege_method", 1),
(gt, "$g_friend_fit_for_battle", 3),
(store_current_hours, ":cur_hours"),
(ge, ":cur_hours", "$g_siege_method_finish_hours"),
],
"Lead your soldiers in an assault.",
[
(try_begin),
(party_slot_eq, "$g_encountered_party", slot_party_type, spt_town),
(party_get_slot, ":battle_scene", "$g_encountered_party", slot_town_walls),
(else_try),
(party_get_slot, ":battle_scene", "$g_encountered_party", slot_castle_exterior),
(try_end),
(call_script, "script_calculate_renown_value"),
(call_script, "script_calculate_battle_advantage"),
(assign, ":battle_advantage", reg0),
(val_mul, ":battle_advantage", 2),
(val_div, ":battle_advantage", 3), #scale down the advantage a bit in sieges.
(set_battle_advantage, ":battle_advantage"),
(set_party_battle_mode),
(assign, "$g_siege_battle_state", 1),
(assign, ":siege_sally", 0),
(try_begin),
(le, ":battle_advantage", -4), #we are outnumbered, defenders sally out
(eq, "$g_siege_sallied_out_once", 0),
(set_jump_mission,"mt_castle_attack_walls_defenders_sally"),
(assign, "$g_siege_battle_state", 0),
(assign, ":siege_sally", 1),
(else_try),
(party_slot_eq, "$current_town", slot_center_siege_with_belfry, 1),
(set_jump_mission,"mt_castle_attack_walls_belfry"),
(else_try),
(set_jump_mission,"mt_castle_attack_walls_ladder"),
(try_end),
(assign, "$cant_talk_to_enemy", 0),
(assign, "$g_siege_final_menu", "mnu_castle_besiege"),
(assign, "$g_next_menu", "mnu_castle_besiege_inner_battle"),
(assign, "$g_siege_method", 0), #reset siege timer
(jump_to_scene,":battle_scene"),
(try_begin),
(eq, ":siege_sally", 1),
(jump_to_menu, "mnu_siege_attack_meets_sally"),
(else_try),
(jump_to_menu, "mnu_battle_debrief"),
(change_screen_mission),
(try_end),
]),
("attack_stay_back",
[
(ge, "$g_siege_method", 1),
(gt, "$g_friend_fit_for_battle", 3),
(store_current_hours, ":cur_hours"),
(ge, ":cur_hours", "$g_siege_method_finish_hours"),
],
"Order your soldiers to attack while you stay back...", [(assign, "$cant_talk_to_enemy", 0),(jump_to_menu,"mnu_castle_attack_walls_simulate")]),
("build_ladders",[(party_slot_eq, "$current_town", slot_center_siege_with_belfry, 0),(eq, "$g_siege_method", 0)],
"Prepare ladders to attack the walls.", [(jump_to_menu,"mnu_construct_ladders")]),
("build_siege_tower",[(party_slot_eq, "$current_town", slot_center_siege_with_belfry, 1),(eq, "$g_siege_method", 0)],
"Build a siege tower.", [(jump_to_menu,"mnu_construct_siege_tower")]),
("cheat_castle_lead_attack",[(eq, "$cheat_mode", 1),
(eq, "$g_siege_method", 0)],
"{!}CHEAT: Instant build equipments.",
[
(assign, "$g_siege_method", 1),
(assign, "$g_siege_method_finish_hours", 0),
(jump_to_menu, "mnu_castle_besiege"),
]),
("cheat_conquer_castle",[(eq, "$cheat_mode", 1),
],
"{!}CHEAT: Instant conquer castle.",
[
(assign, "$g_next_menu", "mnu_castle_taken"),
(jump_to_menu, "mnu_total_victory"),
]),
("lift_siege",[],"Abandon the siege.",
[
(call_script, "script_lift_siege", "$g_player_besiege_town", 0),
(assign,"$g_player_besiege_town", -1),
(change_screen_return)]),
]
),
(
"siege_attack_meets_sally",mnf_scale_picture,
"The defenders sally out to meet your assault.",
"none",
[
(set_background_mesh, "mesh_pic_sally_out"),
],
[
("continue",[],
"Continue...",
[
(jump_to_menu, "mnu_battle_debrief"),
(change_screen_mission),
]),
]
),
(
"castle_besiege_inner_battle",mnf_scale_picture,
"{s1}",
"none",
[
(troop_get_type, ":is_female", "trp_player"),
(try_begin),
(eq, ":is_female", 1),
(set_background_mesh, "mesh_pic_siege_sighted_fem"),
(else_try),
(set_background_mesh, "mesh_pic_siege_sighted"),
(try_end),
(assign, ":result", "$g_battle_result"),#will be reset at script_encounter_calculate_fit
(call_script, "script_encounter_calculate_fit"),
# TODO: To use for the future:
(str_store_string, s1, "@As a last defensive effort, you retreat to the main hall of the keep.\
You and your remaining soldiers will put up a desperate fight here. If you are defeated, there's no other place to fall back to."),
(str_store_string, s1, "@You've been driven away from the walls.\
Now the attackers are pouring into the streets. IF you can defeat them, you can perhaps turn the tide and save the day."),
(try_begin),
(this_or_next|neq, ":result", 1),
(this_or_next|le, "$g_friend_fit_for_battle", 0),
(le, "$g_enemy_fit_for_battle", 0),
(jump_to_menu, "$g_siege_final_menu"),
(else_try),
(call_script, "script_encounter_calculate_fit"),
(party_slot_eq, "$g_encountered_party", slot_party_type, spt_town),
(try_begin),
(eq, "$g_siege_battle_state", 0),
(eq, ":result", 1),
(assign, "$g_battle_result", 0),
(jump_to_menu, "$g_siege_final_menu"),
(else_try),
(eq, "$g_siege_battle_state", 1),
(eq, ":result", 1),
(str_store_string, s1, "@You've breached the town walls,\
but the stubborn defenders continue to resist you in the streets!\
You'll have to deal with them before you can attack the keep at the heart of the town."),
(else_try),
(eq, "$g_siege_battle_state", 2),
(eq, ":result", 1),
(str_store_string, s1, "@The town centre is yours,\
but the remaining defenders have retreated to the castle.\
It must fall before you can complete your victory."),
(else_try),
(jump_to_menu, "$g_siege_final_menu"),
(try_end),
(else_try),
(try_begin),
(eq, "$g_siege_battle_state", 0),
(eq, ":result", 1),
(assign, "$g_battle_result", 0),
(jump_to_menu, "$g_siege_final_menu"),
(else_try),
(eq, "$g_siege_battle_state", 1),
(eq, ":result", 1),
(str_store_string, s1, "@The remaining defenders have retreated to the castle as a last defense. You must go in and crush any remaining resistance."),
(else_try),
(jump_to_menu, "$g_siege_final_menu"),
(try_end),
(try_end),
],
[
("continue",[],
"Continue...",
[
(try_begin),
(party_slot_eq, "$g_encountered_party", slot_party_type, spt_town),
(try_begin),
(eq, "$g_siege_battle_state", 1),
(party_get_slot, ":battle_scene", "$g_encountered_party", slot_town_center),
(set_jump_mission, "mt_besiege_inner_battle_town_center"),
(else_try),
(party_get_slot, ":battle_scene", "$g_encountered_party", slot_town_castle),
(set_jump_mission, "mt_besiege_inner_battle_castle"),
(try_end),
(else_try),
(party_get_slot, ":battle_scene", "$g_encountered_party", slot_town_castle),
(set_jump_mission, "mt_besiege_inner_battle_castle"),
(try_end),
## (call_script, "script_calculate_battle_advantage"),
## (set_battle_advantage, reg0),
(set_party_battle_mode),
(jump_to_scene, ":battle_scene"),
(val_add, "$g_siege_battle_state", 1),
(assign, "$g_next_menu", "mnu_castle_besiege_inner_battle"),
(jump_to_menu, "mnu_battle_debrief"),
(change_screen_mission),
]),
]
),
(
"construct_ladders",0,
"As the party member with the highest Engineer skill ({reg2}), {reg3?you estimate:{s3} estimates} that it will take\
{reg4} hours to build enough scaling ladders for the assault.",
"none",
[(call_script, "script_get_max_skill_of_player_party", "skl_engineer"),
(assign, ":max_skill", reg0),
(assign, ":max_skill_owner", reg1),
(assign, reg2, ":max_skill"),
(store_sub, reg4, 14, ":max_skill"),
(val_mul, reg4, 2),
(val_div, reg4, 3),
(try_begin),
(eq, ":max_skill_owner", "trp_player"),
(assign, reg3, 1),
(else_try),
(assign, reg3, 0),
(str_store_troop_name, s3, ":max_skill_owner"),
(try_end),
],
[
("build_ladders_cont",[],
"Do it.", [
(assign, "$g_siege_method", 1),
(store_current_hours, ":cur_hours"),
(call_script, "script_get_max_skill_of_player_party", "skl_engineer"),
(store_sub, ":hours_takes", 14, reg0),
(val_mul, ":hours_takes", 2),
(val_div, ":hours_takes", 3),
(store_add, "$g_siege_method_finish_hours",":cur_hours", ":hours_takes"),
(assign,"$auto_besiege_town","$current_town"),
(rest_for_hours_interactive, 96, 5, 1), #rest while attackable. A trigger will divert control when attack is ready.
(change_screen_return),
]),
("go_back",[],
"Go back.", [(jump_to_menu,"mnu_castle_besiege")]),
],
),
(
"construct_siege_tower",0,
"As the party member with the highest Engineer skill ({reg2}), {reg3?you estimate:{s3} estimates} that building a siege tower will take\
{reg4} hours.",
"none",
[(call_script, "script_get_max_skill_of_player_party", "skl_engineer"),
(assign, ":max_skill", reg0),
(assign, ":max_skill_owner", reg1),
(assign, reg2, ":max_skill"),
(store_sub, reg4, 15, ":max_skill"),
(val_mul, reg4, 6),
(try_begin),
(eq, ":max_skill_owner", "trp_player"),
(assign, reg3, 1),
(else_try),
(assign, reg3, 0),
(str_store_troop_name, s3, ":max_skill_owner"),
(try_end),
],
[
("build_siege_tower_cont",[],
"Start building.", [
(assign, "$g_siege_method", 2),
(store_current_hours, ":cur_hours"),
(call_script, "script_get_max_skill_of_player_party", "skl_engineer"),
(store_sub, ":hours_takes", 15, reg0),
(val_mul, ":hours_takes", 6),
(store_add, "$g_siege_method_finish_hours",":cur_hours", ":hours_takes"),
(assign,"$auto_besiege_town","$current_town"),
(rest_for_hours_interactive, 240, 5, 1), #rest while attackable. A trigger will divert control when attack is ready.
(change_screen_return),
]),
("go_back",[],
"Go back.", [(jump_to_menu,"mnu_castle_besiege")]),
],
),
(
"castle_attack_walls_simulate",mnf_scale_picture|mnf_disable_all_keys,
"{s4}^^Your casualties:{s8}^^Enemy casualties were: {s9}",
"none",
[
(try_begin),
(set_background_mesh, "mesh_pic_siege_attack"),
(try_end),
(call_script, "script_party_calculate_strength", "p_main_party", 1), #skip player
(assign, ":player_party_strength", reg0),
(val_div, ":player_party_strength", 10),
(call_script, "script_party_calculate_strength", "$g_encountered_party", 0),
(assign, ":enemy_party_strength", reg0),
(val_div, ":enemy_party_strength", 4),
(inflict_casualties_to_party_group, "p_main_party", ":enemy_party_strength", "p_temp_casualties"),
(call_script, "script_print_casualties_to_s0", "p_temp_casualties", 0),
(str_store_string_reg, s8, s0),
(inflict_casualties_to_party_group, "$g_encountered_party", ":player_party_strength", "p_temp_casualties"),
(call_script, "script_print_casualties_to_s0", "p_temp_casualties", 0),
(str_store_string_reg, s9, s0),
(assign, "$no_soldiers_left", 0),
(try_begin),
(call_script, "script_party_count_members_with_full_health","p_main_party"),
(le, reg0, 0), #(TODO : compare with num_routed_us)
(assign, "$no_soldiers_left", 1),
(str_store_string, s4, "str_attack_walls_failure"),
(else_try),
(call_script, "script_party_count_members_with_full_health","$g_encountered_party"),
(le, reg0, 0), #(TODO : compare with num_routed_enemies)
(assign, "$no_soldiers_left", 1),
(assign, "$g_battle_result", 1),
(str_store_string, s4, "str_attack_walls_success"),
(else_try),
(str_store_string, s4, "str_attack_walls_continue"),
(try_end),
],
[
## ("lead_next_wave",[(eq, "$no_soldiers_left", 0)],"Lead the next wave of attack personally.", [
## (party_get_slot, ":battle_scene", "$g_encountered_party", slot_castle_exterior),
## (set_party_battle_mode),
## (set_jump_mission,"mt_castle_attack_walls"),
## (jump_to_scene,":battle_scene"),
## (jump_to_menu,"mnu_castle_outside"),
## (change_screen_mission),
## ]),
## ("continue_attacking",[(eq, "$no_soldiers_left", 0)],"Order your soldiers to keep attacking...", [
## (jump_to_menu,"mnu_castle_attack_walls_3"),
## ]),
## ("call_soldiers_back",[(eq, "$no_soldiers_left", 0)],"Call your soldiers back.",[(jump_to_menu,"mnu_castle_outside")]),
("continue",[],"Continue...",[(jump_to_menu,"mnu_castle_besiege")]),
]
),
(
"castle_attack_walls_with_allies_simulate",mnf_scale_picture|mnf_disable_all_keys,
"{s4}^^Your casualties: {s8}^^Allies' casualties: {s9}^^Enemy casualties: {s10}",
"none",
[
(try_begin),
(set_background_mesh, "mesh_pic_siege_attack"),
(try_end),
(call_script, "script_party_calculate_strength", "p_main_party", 1), #skip player
(assign, ":player_party_strength", reg0),
(val_div, ":player_party_strength", 10),
(call_script, "script_party_calculate_strength", "p_collective_friends", 0),
(assign, ":friend_party_strength", reg0),
(val_div, ":friend_party_strength", 10),
(val_max, ":friend_party_strength", 1),
(call_script, "script_party_calculate_strength", "p_collective_enemy", 0),
(assign, ":enemy_party_strength", reg0),
(val_div, ":enemy_party_strength", 4),
## (assign, reg0, ":player_party_strength"),
## (assign, reg1, ":friend_party_strength"),
## (assign, reg2, ":enemy_party_strength"),
## (assign, reg3, "$g_enemy_party"),
## (assign, reg4, "$g_ally_party"),
## (display_message, "@{!}player_str={reg0} friend_str={reg1} enemy_str={reg2}"),
## (display_message, "@{!}enemy_party={reg3} ally_party={reg4}"),
(try_begin),
(eq, ":friend_party_strength", 0),
(store_div, ":enemy_party_strength_for_p", ":enemy_party_strength", 2),
(else_try),
(assign, ":enemy_party_strength_for_p", ":enemy_party_strength"),
(val_mul, ":enemy_party_strength_for_p", ":player_party_strength"),
(val_div, ":enemy_party_strength_for_p", ":friend_party_strength"),
(try_end),
(val_sub, ":enemy_party_strength", ":enemy_party_strength_for_p"),
(inflict_casualties_to_party_group, "p_main_party", ":enemy_party_strength_for_p", "p_temp_casualties"),
(call_script, "script_print_casualties_to_s0", "p_temp_casualties", 0),
(str_store_string_reg, s8, s0),
(inflict_casualties_to_party_group, "$g_enemy_party", ":friend_party_strength", "p_temp_casualties"),
(call_script, "script_print_casualties_to_s0", "p_temp_casualties", 0),
(str_store_string_reg, s10, s0),
(call_script, "script_collect_friendly_parties"),
(inflict_casualties_to_party_group, "$g_ally_party", ":enemy_party_strength", "p_temp_casualties"),
(call_script, "script_print_casualties_to_s0", "p_temp_casualties", 0),
(str_store_string_reg, s9, s0),
(party_collect_attachments_to_party, "$g_enemy_party", "p_collective_enemy"),
(assign, "$no_soldiers_left", 0),
(try_begin),
(call_script, "script_party_count_members_with_full_health", "p_main_party"),
(le, reg0, 0), #(TODO : compare with num_routed_us)
(assign, "$no_soldiers_left", 1),
(str_store_string, s4, "str_attack_walls_failure"),
(else_try),
(call_script, "script_party_count_members_with_full_health", "p_collective_enemy"),
(le, reg0, 0), #(TODO : compare with num_routed_enemies)
(assign, "$no_soldiers_left", 1),
(assign, "$g_battle_result", 1),
(str_store_string, s4, "str_attack_walls_success"),
(else_try),
(str_store_string, s4, "str_attack_walls_continue"),
(try_end),
],
[
("continue",[],"Continue...",[(jump_to_menu,"mnu_besiegers_camp_with_allies")]),
]
),
(
"castle_taken_by_friends",0,
"Nothing to see here.",
"none",
[
(party_clear, "$g_encountered_party"),
(party_stack_get_troop_id, ":leader", "$g_encountered_party_2", 0),
(party_set_slot, "$g_encountered_party", slot_center_last_taken_by_troop, ":leader"),
(store_troop_faction, ":faction_no", ":leader"),
#Reduce prosperity of the center by 5
(call_script, "script_change_center_prosperity", "$g_encountered_party", -5),
(try_begin),
(assign, ":damage", 20),
(is_between, "$g_encountered_party", towns_begin, towns_end),
(assign, ":damage", 40),
(try_end),
(try_begin),
(neq, ":faction_no", "$g_encountered_party_faction"),
(call_script, "script_faction_inflict_war_damage_on_faction", ":faction_no", "$g_encountered_party_faction", ":damage"),
(try_end),
(call_script, "script_give_center_to_faction", "$g_encountered_party", ":faction_no"),
(call_script, "script_add_log_entry", logent_player_participated_in_siege, "trp_player", "$g_encountered_party", 0, "$g_encountered_party_faction"),
## (call_script, "script_change_troop_renown", "trp_player", 1),
(change_screen_return),
],
[
],
),
(
"castle_taken",mnf_disable_all_keys,
"{s3} has fallen to your troops, and you now have full control of the {reg2?town:castle}.\
{reg1? You may station troops here to defend it against enemies who may try to recapture it. Also, you should select now whether you will hold the {reg2?town:castle} yourself or give it to a faithful vassal...:}",# Only visible when castle is taken without being a vassal of a kingdom.
"none",
[
(party_clear, "$g_encountered_party"),
(try_begin),
(eq, "$players_kingdom", "fac_player_supporters_faction"),
(party_get_slot, ":new_owner", "$g_encountered_party", slot_town_lord),
(neq, ":new_owner", "trp_player"),
(try_for_range, ":unused", 0, 4),
(call_script, "script_cf_reinforce_party", "$g_encountered_party"),
(try_end),
(try_end),
(call_script, "script_lift_siege", "$g_encountered_party", 0),
(assign, "$g_player_besiege_town", -1),
(party_set_slot, "$g_encountered_party", slot_center_last_taken_by_troop, "trp_player"),
#Reduce prosperity of the center by 5
(call_script, "script_change_center_prosperity", "$g_encountered_party", -5),
(call_script, "script_change_troop_renown", "trp_player", 5),
(assign, ":damage", 20),
(try_begin),
(is_between, "$g_encountered_party", towns_begin, towns_end),
(assign, ":damage", 40),
(try_end),
(call_script, "script_faction_inflict_war_damage_on_faction", "$players_kingdom", "$g_encountered_party_faction", ":damage"),
#removed, is it duplicate (useless)? See 20 lines above.
#(call_script, "script_add_log_entry", logent_castle_captured_by_player, "trp_player", "$g_encountered_party", -1, "$g_encountered_party_faction"),
(try_begin),
(is_between, "$players_kingdom", kingdoms_begin, kingdoms_end),
(neq, "$players_kingdom", "fac_player_supporters_faction"),
(call_script, "script_give_center_to_faction", "$g_encountered_party", "$players_kingdom"),
(call_script, "script_order_best_besieger_party_to_guard_center", "$g_encountered_party", "$players_kingdom"),
(jump_to_menu, "mnu_castle_taken_2"),
(else_try),
(call_script, "script_give_center_to_faction", "$g_encountered_party", "fac_player_supporters_faction"),
(call_script, "script_order_best_besieger_party_to_guard_center", "$g_encountered_party", "fac_player_supporters_faction"),
(str_store_party_name, s3, "$g_encountered_party"),
(assign, reg1, 0),
(try_begin),
(faction_slot_eq, "fac_player_supporters_faction", slot_faction_leader, "trp_player"),
(assign, reg1, 1),
(try_end),
#(party_set_slot, "$g_encountered_party", slot_town_lord, stl_unassigned),
(try_end),
(assign, reg2, 0),
(try_begin),
(is_between, "$g_encountered_party", towns_begin, towns_end),
(assign, reg2, 1),
(try_end),
],
[
("continue",[],"Continue...",
[
(assign, "$auto_enter_town", "$g_encountered_party"),
(change_screen_return),
]),
],
),
(
"castle_taken_2",mnf_disable_all_keys,
"{s3} has fallen to your troops, and you now have full control of the castle.\
It is time to send word to {s9} about your victory. {s5}",
"none",
[
(str_store_party_name, s3, "$g_encountered_party"),
(str_clear, s5),
(faction_get_slot, ":faction_leader", "$players_kingdom", slot_faction_leader),
(str_store_troop_name, s9, ":faction_leader"),
(try_begin),
(eq, "$player_has_homage", 0),
(assign, reg8, 0),
(try_begin),
(party_slot_eq, "$g_encountered_party", spt_town),
(assign, reg8, 1),
(try_end),
(str_store_string, s5, "@However, since you are not a sworn {man/follower} of {s9}, there is no chance he would recognize you as the {lord/lady} of this {reg8?town:castle}."),
(try_end),
],
[
("castle_taken_claim",[(eq, "$player_has_homage", 1)],
"Request that {s3} be awarded to you.",
[
(party_set_slot, "$g_encountered_party", slot_center_last_taken_by_troop, "trp_player"),
(assign, "$g_castle_requested_by_player", "$current_town"),
(assign, "$g_castle_requested_for_troop", "trp_player"),
(assign, "$auto_enter_town", "$g_encountered_party"),
(change_screen_return),
]),
("castle_taken_claim_2",[
(troop_get_slot, ":spouse", "trp_player", slot_troop_spouse),
(is_between, ":spouse", active_npcs_begin, active_npcs_end),
(troop_slot_eq, ":spouse", slot_troop_occupation, slto_kingdom_hero),
(store_faction_of_troop, ":spouse_faction", ":spouse"),
(eq, ":spouse_faction", "$players_kingdom"),
],
"Request that {s3} be awarded to your {wife/husband}.",
[
(party_set_slot, "$g_encountered_party", slot_center_last_taken_by_troop, "trp_player"),
(assign, "$g_castle_requested_by_player", "$current_town"),
(troop_get_slot, ":spouse", "trp_player", slot_troop_spouse),
(assign, "$g_castle_requested_for_troop", ":spouse"),
(assign, "$auto_enter_town", "$g_encountered_party"),
(change_screen_return),
]),
("castle_taken_no_claim",[],"Ask no rewards.",
[
(party_set_slot, "$g_encountered_party", slot_center_last_taken_by_troop, -1),
(assign, "$auto_enter_town", "$g_encountered_party"),
(change_screen_return),
# (jump_to_menu, "mnu_town"),
]),
],
),
(
"requested_castle_granted_to_player",mnf_scale_picture,
"You receive a message from your liege, {s3}.^^\
{reg4?She:He} has decided to grant {s2}{reg3? and the nearby village of {s4}:} to you, with all due incomes and titles, to hold in {reg4?her:his} name for as long as you maintain your oath of homage..",
"none",
[
(set_background_mesh, "mesh_pic_messenger"),
(faction_get_slot, ":faction_leader", "$players_kingdom", slot_faction_leader),
(str_store_troop_name, s3, ":faction_leader"),
(str_store_party_name, s2, "$g_center_to_give_to_player"),
(try_begin),
(party_slot_eq, "$g_center_to_give_to_player", slot_party_type, spt_castle),
(assign, reg3, 1),
(try_for_range, ":cur_village", villages_begin, villages_end),
(party_slot_eq, ":cur_village", slot_village_bound_center, "$g_center_to_give_to_player"),
(str_store_party_name, s4, ":cur_village"),
(try_end),
(else_try),
(assign, reg3, 0),
(try_end),
(troop_get_type, reg4, ":faction_leader"),
],
[
("continue",[],"Continue.",
[
(call_script, "script_give_center_to_lord", "$g_center_to_give_to_player", "trp_player", 0),
(jump_to_menu, "mnu_give_center_to_player_2"),
],
),
]
),
(
"requested_castle_granted_to_player_husband", mnf_scale_picture,
"You receive a message from your liege, {s3}.^^\
{reg4?She:He} has decided to grant {s2}{reg3? and the nearby village of {s4}:} to your husband, {s7}.",
"none",
[
(set_background_mesh, "mesh_pic_messenger"),
(faction_get_slot, ":faction_leader", "$players_kingdom", slot_faction_leader),
(str_store_troop_name, s3, ":faction_leader"),
(str_store_party_name, s2, "$g_center_to_give_to_player"),
(try_begin),
(party_slot_eq, "$g_center_to_give_to_player", slot_party_type, spt_castle),
(assign, reg3, 1),
(try_for_range, ":cur_village", villages_begin, villages_end),
(party_slot_eq, ":cur_village", slot_village_bound_center, "$g_center_to_give_to_player"),
(str_store_party_name, s4, ":cur_village"),
(try_end),
(else_try),
(assign, reg3, 0),
(try_end),
(troop_get_type, reg4, ":faction_leader"),
(troop_get_slot, ":spouse", "trp_player", slot_troop_spouse),
(str_store_troop_name, s11, ":spouse"),
(str_store_string, s7, "str_to_your_husband_s11"),
],
[
("continue",[],"Continue.",
[
(troop_get_slot, ":spouse", "trp_player", slot_troop_spouse),
(call_script, "script_give_center_to_lord", "$g_center_to_give_to_player", ":spouse", 0),
],
),
]
),
(
"requested_castle_granted_to_another",mnf_scale_picture,
"You receive a message from your monarch, {s3}.^^\
'I was most pleased to hear of your valiant efforts in the capture of {s2}. Your victory has gladdened all our hearts.\
You also requested me to give you ownership of the castle, but that is a favour which I fear I cannot grant,\
as you already hold significant estates in my realm.\
Instead I have sent you {reg6} denars to cover the expenses of your campaign, but {s2} I give to {s5}.'\
",
"none",
[(set_background_mesh, "mesh_pic_messenger"),
(faction_get_slot, ":faction_leader", "$players_kingdom", slot_faction_leader),
(str_store_troop_name, s3, ":faction_leader"),
(str_store_party_name, s2, "$g_center_to_give_to_player"),
(party_get_slot, ":new_owner", "$g_center_to_give_to_player", slot_town_lord),
(str_store_troop_name, s5, ":new_owner"),
(assign, reg6, 900),
(assign, "$g_castle_requested_by_player", -1),
(assign, "$g_castle_requested_for_troop", -1),
],
[
("accept_decision",[],"Accept the decision.",
[
(call_script, "script_troop_add_gold", "trp_player", reg6),
(change_screen_return),
]),
("leave_faction",[],"You have been wronged! Renounce your oath to your liege! ",
[
(jump_to_menu, "mnu_leave_faction"),
(call_script, "script_troop_add_gold", "trp_player", reg6),
]),
],
),
(
"requested_castle_granted_to_another_female",mnf_scale_picture,
"You receive a message from your monarch, {s3}.^^\
'I was most pleased to hear of your valiant efforts in the capture of {s2}. Your victory has gladdened all our hearts.\
You also requested me to give ownership of the castle to your husband, but that is a favour which I fear I cannot grant,\
as he already holds significant estates in my realm.\
Instead I have sent you {reg6} denars to cover the expenses of your campaign, but {s2} I give to {s5}.'\
",
"none",
[(set_background_mesh, "mesh_pic_messenger"),
(faction_get_slot, ":faction_leader", "$players_kingdom", slot_faction_leader),
(str_store_troop_name, s3, ":faction_leader"),
(str_store_party_name, s2, "$g_center_to_give_to_player"),
(party_get_slot, ":new_owner", "$g_center_to_give_to_player", slot_town_lord),
(str_store_troop_name, s5, ":new_owner"),
(assign, reg6, 900),
(assign, "$g_castle_requested_by_player", -1),
(assign, "$g_castle_requested_for_troop", -1),
],
[
("accept_decision",[],"Accept the decision.",
[
(call_script, "script_troop_add_gold", "trp_player", reg6),
(change_screen_return),
]),
],
),
(
"leave_faction",0,
"Renouncing your oath is a grave act. Your lord may condemn you and confiscate your lands and holdings.\
However, if you return them of your own free will, he may let the betrayal go without a fight.",
"none",
[
],
[
("leave_faction_give_back", [], "Renounce your oath and give up your holdings.",
[
#Troop commentary changes begin
# (call_script, "script_add_log_entry", logent_renounced_allegiance, "trp_player", -1, "$g_talk_troop", "$g_talk_troop_faction"),
#Troop commentary changes end
(call_script, "script_player_leave_faction", 1), #1 means give back fiefs
(change_screen_return),
]),
("leave_faction_hold", [
(str_store_party_name, s2, "$g_center_to_give_to_player"),
], "Renounce your oath and rule your lands, including {s2}, in your own name.",
[
(call_script, "script_give_center_to_lord", "$g_center_to_give_to_player", "trp_player", 0), #this should activate the player faction (it does not)
(call_script, "script_player_leave_faction", 0), #"1" would mean give back fiefs
(call_script, "script_activate_player_faction", "trp_player"), #Activating player faction should now work
(change_screen_return),
]),
("leave_faction_cancel", [], "Remain loyal and accept the decision.",
[
(change_screen_return),
]),
],
),
(
"give_center_to_player",mnf_scale_picture,
"Your lord offers to extend your fiefs!\
{s1} sends word that he is willing to grant {s2} to you in payment for your loyal service,\
adding it to your holdings. What is your answer?",
"none",
[(set_background_mesh, "mesh_pic_messenger"),
(store_faction_of_party, ":center_faction", "$g_center_to_give_to_player"),
(faction_get_slot, ":faction_leader", ":center_faction", slot_faction_leader),
(str_store_troop_name, s1, ":faction_leader"),
(str_store_party_name, s2, "$g_center_to_give_to_player"),
],
[
("give_center_to_player_accept",[],"Accept the offer.",
[(call_script, "script_give_center_to_lord", "$g_center_to_give_to_player", "trp_player", 0),
(jump_to_menu, "mnu_give_center_to_player_2"),
]),
("give_center_to_player_reject",[],"Reject. You have no interest in holding {s2}.",
[(party_set_slot, "$g_center_to_give_to_player", slot_town_lord, stl_rejected_by_player),
(change_screen_return),
]),
],
),
(
"give_center_to_player_2",0,
"With a brief ceremony, you are officially confirmed as the new lord of {s2}{reg3? and its bound village {s4}:}.\
{reg3?They:It} will make a fine part of your fiefdom.\
You can now claim the rents and revenues from your personal estates there, draft soldiers from the populace,\
and manage the lands as you see fit.\
However, you are also expected to defend your fief and your people from harm,\
as well as maintaining the rule of law and order.",
"none",
[
(str_store_party_name, s2, "$g_center_to_give_to_player"),
(assign, reg3, 0),
(try_begin),
(party_slot_eq, "$g_center_to_give_to_player", slot_party_type, spt_castle),
(try_for_range, ":cur_village", villages_begin, villages_end),
(party_slot_eq, ":cur_village", slot_village_bound_center, "$g_center_to_give_to_player"),
(str_store_party_name, s4, ":cur_village"),
(assign, reg3, 1),
(try_end),
(try_end),
],
[
("continue",[],"Continue...",
[(change_screen_return),
]),
],
),
(
"oath_fulfilled",0,
"You had a contract with {s1} to serve him for a certain duration.\
Your contract has now expired. What will you do?",
"none",
[
(faction_get_slot, ":faction_leader", "$players_kingdom", slot_faction_leader),
(str_store_troop_name, s1, ":faction_leader"),
],
[
("renew_oath",[(faction_get_slot, ":faction_leader", "$players_kingdom", slot_faction_leader),
(str_store_troop_name, s1, ":faction_leader")], "Renew your contract with {s1} for another month.",
[
(store_current_day, ":cur_day"),
(store_add, "$mercenary_service_next_renew_day", ":cur_day", 30),
(change_screen_return),
]),
("dont_renew_oath",[],"Become free of your bond.",
[
(call_script, "script_player_leave_faction", 1), #1 means give back fiefs
(change_screen_return),
]),
]
),
## (
## "castle_garrison_stationed",0,
### "The rest of the castle garrison recognizes that their situation is hopeless and surrenders. {s1} is at your mercy now. What do you want to do with this castle?",
## "_",
## "none",
## [
## (jump_to_menu, "mnu_town"),
## ],
## [],
## ),
## (
## "castle_choose_captain",0,
## "You will need to assign one of your companions as the castellan. Who will it be?",
## "none",
## [
## (try_for_range, ":slot_no", 0, 20),
## (troop_set_slot, "trp_temp_troop", ":slot_no", 0),
## (try_end),
## (assign, ":num_captains", 0),
## (party_clear, "p_temp_party"),
## (party_get_num_companion_stacks, ":num_stacks", "p_main_party"),
## (try_for_range, ":i_s", 1,":num_stacks"),
## (party_stack_get_troop_id, ":companion","p_main_party", ":i_s"),
## (troop_slot_eq, ":companion", slot_troop_occupation, slto_player_companion),
## (troop_set_slot, "trp_temp_troop", ":num_captains", ":companion"),
## (try_end),
## ],
## [
## ("castellan_candidate", [(troop_get_slot, ":captain", "trp_temp_troop", 0),(gt,":captain",0),(str_store_troop_name, s5,":captain")],
## "{s5}", [(troop_get_slot, "$selected_castellan", "trp_temp_troop", 0),(jump_to_menu,"mnu_castle_captain_chosen")]),
## ("castellan_candidate", [(troop_get_slot, ":captain", "trp_temp_troop", 1),(gt,":captain",0),(str_store_troop_name, s5,":captain")],
## "{s5}", [(troop_get_slot, "$selected_castellan", "trp_temp_troop", 1),(jump_to_menu,"mnu_castle_captain_chosen")]),
## ("castellan_candidate", [(troop_get_slot, ":captain", "trp_temp_troop", 2),(gt,":captain",0),(str_store_troop_name, s5,":captain")],
## "{s5}", [(troop_get_slot, "$selected_castellan", "trp_temp_troop", 2),(jump_to_menu,"mnu_castle_captain_chosen")]),
## ("castellan_candidate", [(troop_get_slot, ":captain", "trp_temp_troop", 3),(gt,":captain",0),(str_store_troop_name, s5,":captain")],
## "{s5}", [(troop_get_slot, "$selected_castellan", "trp_temp_troop", 3),(jump_to_menu,"mnu_castle_captain_chosen")]),
## ("castellan_candidate", [(troop_get_slot, ":captain", "trp_temp_troop", 4),(gt,":captain",0),(str_store_troop_name, s5,":captain")],
## "{s5}", [(troop_get_slot, "$selected_castellan", "trp_temp_troop", 4),(jump_to_menu,"mnu_castle_captain_chosen")]),
## ("castellan_candidate", [(troop_get_slot, ":captain", "trp_temp_troop", 5),(gt,":captain",0),(str_store_troop_name, s5,":captain")],
## "{s5}", [(troop_get_slot, "$selected_castellan", "trp_temp_troop", 5),(jump_to_menu,"mnu_castle_captain_chosen")]),
## ("castellan_candidate", [(troop_get_slot, ":captain", "trp_temp_troop", 6),(gt,":captain",0),(str_store_troop_name, s5,":captain")],
## "{s5}", [(troop_get_slot, "$selected_castellan", "trp_temp_troop", 6),(jump_to_menu,"mnu_castle_captain_chosen")]),
## ("castellan_candidate", [(troop_get_slot, ":captain", "trp_temp_troop", 7),(gt,":captain",0),(str_store_troop_name, s5,":captain")],
## "{s5}", [(troop_get_slot, "$selected_castellan", "trp_temp_troop", 7),(jump_to_menu,"mnu_castle_captain_chosen")]),
## ("castellan_candidate", [(troop_get_slot, ":captain", "trp_temp_troop", 8),(gt,":captain",0),(str_store_troop_name, s5,":captain")],
## "{s5}", [(troop_get_slot, "$selected_castellan", "trp_temp_troop", 8),(jump_to_menu,"mnu_castle_captain_chosen")]),
## ("castellan_candidate", [(troop_get_slot, ":captain", "trp_temp_troop", 9),(gt,":captain",0),(str_store_troop_name, s5,":captain")],
## "{s5}", [(troop_get_slot, "$selected_castellan", "trp_temp_troop", 9),(jump_to_menu,"mnu_castle_captain_chosen")]),
## ("castellan_candidate", [(troop_get_slot, ":captain", "trp_temp_troop", 10),(gt,":captain",0),(str_store_troop_name, s5,":captain")],
## "{s5}", [(troop_get_slot, "$selected_castellan", "trp_temp_troop", 10),(jump_to_menu,"mnu_castle_captain_chosen")]),
## ("castellan_candidate", [(troop_get_slot, ":captain", "trp_temp_troop", 11),(gt,":captain",0),(str_store_troop_name, s5,":captain")],
## "{s5}", [(troop_get_slot, "$selected_castellan", "trp_temp_troop", 11),(jump_to_menu,"mnu_castle_captain_chosen")]),
## ("castellan_candidate", [(troop_get_slot, ":captain", "trp_temp_troop", 12),(gt,":captain",0),(str_store_troop_name, s5,":captain")],
## "{s5}", [(troop_get_slot, "$selected_castellan", "trp_temp_troop", 12),(jump_to_menu,"mnu_castle_captain_chosen")]),
## ("castellan_candidate", [(troop_get_slot, ":captain", "trp_temp_troop", 13),(gt,":captain",0),(str_store_troop_name, s5,":captain")],
## "{s5}", [(troop_get_slot, "$selected_castellan", "trp_temp_troop", 13),(jump_to_menu,"mnu_castle_captain_chosen")]),
## ("castellan_candidate", [(troop_get_slot, ":captain", "trp_temp_troop", 14),(gt,":captain",0),(str_store_troop_name, s5,":captain")],
## "{s5}", [(troop_get_slot, "$selected_castellan", "trp_temp_troop", 14),(jump_to_menu,"mnu_castle_captain_chosen")]),
## ("castellan_candidate", [(troop_get_slot, ":captain", "trp_temp_troop", 15),(gt,":captain",0),(str_store_troop_name, s5,":captain")],
## "{s5}", [(troop_get_slot, "$selected_castellan", "trp_temp_troop", 15),(jump_to_menu,"mnu_castle_captain_chosen")]),
##
## ("cancel",[],
## "Cancel...",
## [(jump_to_menu, "mnu_town")]),
## ],
## ),
## (
## "castle_captain_chosen",0,
## "h this castle?",
## "none",
## [
## (party_add_leader, "$g_encountered_party", "$selected_castellan"),
## (party_remove_members, "p_main_party", "$selected_castellan",1),
## (party_set_slot, "$g_encountered_party", slot_town_lord, "trp_player"),
## (party_set_faction, "$g_encountered_party", "fac_player_supporters_faction"),
## (try_for_range, ":slot_no", 0, 20), #clear temp troop slots just in case
## (troop_set_slot, "trp_temp_troop", ":slot_no", 0),
## (try_end),
## (jump_to_menu, "mnu_town"),
## (change_screen_exchange_members,0),
## ],
## [],
## ),
## (
## "under_siege_attacked_continue",0,
## "Nothing to see here.",
## "none",
## [
## (assign, "$g_enemy_party", "$g_encountered_party_2"),
## (assign, "$g_ally_party", "$g_encountered_party"),
## (party_set_next_battle_simulation_time, "$g_encountered_party", 0),
## (call_script, "script_encounter_calculate_fit"),
## (try_begin),
## (call_script, "script_party_count_fit_regulars", "p_collective_enemy"),
## (assign, ":num_enemy_regulars_remaining", reg(0)),
## (assign, ":enemy_finished",0),
## (try_begin),
## (eq, "$g_battle_result", 1),
## (eq, ":num_enemy_regulars_remaining", 0), #battle won
## (assign, ":enemy_finished",1),
## (else_try),
## (eq, "$g_engaged_enemy", 1),
## (le, "$g_enemy_fit_for_battle",0),
## (ge, "$g_friend_fit_for_battle",1),
## (assign, ":enemy_finished",1),
## (try_end),
## (this_or_next|eq, ":enemy_finished",1),
## (eq,"$g_enemy_surrenders",1),
#### (assign, "$g_center_under_siege_battle", 0),
## (assign, "$g_next_menu", -1),
## (jump_to_menu, "mnu_total_victory"),
## (else_try),
## (assign, ":battle_lost", 0),
## (try_begin),
## (eq, "$g_battle_result", -1),
## (assign, ":battle_lost",1),
## (try_end),
## (this_or_next|eq, ":battle_lost",1),
## (eq,"$g_player_surrenders",1),
#### (assign, "$g_center_under_siege_battle", 0),
## (assign, "$g_next_menu", "mnu_captivity_start_under_siege_defeat"),
## (jump_to_menu, "mnu_total_defeat"),
## (else_try),
## # Ordinary victory.
## (try_begin),
## #check whether enemy retreats
## (eq, "$g_battle_result", 1),
## (store_mul, ":min_enemy_str", "$g_enemy_fit_for_battle", 2),
## (lt, ":min_enemy_str", "$g_friend_fit_for_battle"),
## (party_set_slot, "$g_enemy_party", slot_party_retreat_flag, 1),
##
## (try_for_range, ":troop_no", kingdom_heroes_begin, kingdom_heroes_end),
## (troop_slot_eq, ":troop_no", slot_troop_occupation, slto_kingdom_hero),
## (troop_slot_eq, ":troop_no", slot_troop_is_prisoner, 0),
## (troop_get_slot, ":party_no", ":troop_no", slot_troop_leaded_party),
## (gt, ":party_no", 0),
## (party_slot_eq, ":party_no", slot_party_ai_state, spai_besieging_center),
## (party_slot_eq, ":party_no", slot_party_ai_object, "$g_encountered_party"),
## (party_slot_eq, ":party_no", slot_party_ai_substate, 1),
## (call_script, "script_party_set_ai_state", ":party_no", spai_undefined, -1),
## (call_script, "script_party_set_ai_state", ":party_no", spai_besieging_center, ":center_no"),
## (try_end),
## (display_message, "@{!}TODO: Enemy retreated. The assault has ended, siege continues."),
## (change_screen_return),
## (try_end),
#### (assign, "$g_center_under_siege_battle", 0),
## (try_end),
## ],
## [
## ]
## ),
(
"siege_started_defender",0,
"{s1} is launching an assault against the walls of {s2}. You have {reg10} troops fit for battle against the enemy's {reg11}. You decide to...",
"none",
[
(select_enemy,1),
(assign, "$g_enemy_party", "$g_encountered_party_2"),
(assign, "$g_ally_party", "$g_encountered_party"),
(str_store_party_name, 1,"$g_enemy_party"),
(str_store_party_name, 2,"$g_ally_party"),
(call_script, "script_encounter_calculate_fit"),
(try_begin),
(eq, "$g_siege_first_encounter", 1),
(call_script, "script_let_nearby_parties_join_current_battle", 0, 1),
(call_script, "script_encounter_init_variables"),
(try_end),
(try_begin),
(eq, "$g_siege_first_encounter", 0),
(try_begin),
(call_script, "script_party_count_members_with_full_health", "p_collective_enemy"),
(assign, ":num_enemy_regulars_remaining", reg0),
(call_script, "script_party_count_members_with_full_health", "p_collective_friends"),
(assign, ":num_ally_regulars_remaining", reg0),
(assign, ":enemy_finished", 0),
(try_begin),
(eq, "$g_battle_result", 1),
(eq, ":num_enemy_regulars_remaining", 0), #battle won (TODO : compare with num_routed_us)
(assign, ":enemy_finished",1),
(else_try),
(eq, "$g_engaged_enemy", 1),
(le, "$g_enemy_fit_for_battle",0),
(ge, "$g_friend_fit_for_battle",1),
(assign, ":enemy_finished",1),
(try_end),
(this_or_next|eq, ":enemy_finished",1),
(eq,"$g_enemy_surrenders",1),
(assign, "$g_next_menu", -1),
(jump_to_menu, "mnu_total_victory"),
(else_try),
(assign, ":battle_lost", 0),
(try_begin),
(this_or_next|eq, "$g_battle_result", -1),
(troop_is_wounded, "trp_player"),
(eq, ":num_ally_regulars_remaining", 0), #(TODO : compare with num_routed_allies)
(assign, ":battle_lost",1),
(try_end),
(this_or_next|eq, ":battle_lost",1),
(eq,"$g_player_surrenders",1),
(assign, "$g_next_menu", "mnu_captivity_start_under_siege_defeat"),
(jump_to_menu, "mnu_total_defeat"),
(else_try),
# Ordinary victory/defeat.
(assign, ":attackers_retreat", 0),
(try_begin),
#check whether enemy retreats
(eq, "$g_battle_result", 1),
## (store_mul, ":min_enemy_str", "$g_enemy_fit_for_battle", 2),
## (lt, ":min_enemy_str", "$g_friend_fit_for_battle"),
(assign, ":attackers_retreat", 1),
(else_try),
(eq, "$g_battle_result", 0),
(store_div, ":min_enemy_str", "$g_enemy_fit_for_battle", 3),
(lt, ":min_enemy_str", "$g_friend_fit_for_battle"),
(assign, ":attackers_retreat", 1),
(else_try),
(store_random_in_range, ":random_no", 0, 100),
(store_mul, ":num_ally_regulars_remaining_multiplied", ":num_ally_regulars_remaining", 13),
(val_div, ":num_ally_regulars_remaining_multiplied", 10),
(ge, ":num_ally_regulars_remaining_multiplied", ":num_enemy_regulars_remaining"),
(lt, ":random_no", 10),
(neq, "$new_encounter", 1),
(assign, ":attackers_retreat", 1),
(try_end),
(try_begin),
(eq, ":attackers_retreat", 1),
(party_get_slot, ":siege_hardness", "$g_encountered_party", slot_center_siege_hardness),
(val_add, ":siege_hardness", 100),
(party_set_slot, "$g_encountered_party", slot_center_siege_hardness, ":siege_hardness"),
(party_set_slot, "$g_enemy_party", slot_party_retreat_flag, 1),
(try_for_range, ":troop_no", active_npcs_begin, active_npcs_end),
(troop_slot_eq, ":troop_no", slot_troop_occupation, slto_kingdom_hero),
#(troop_slot_eq, ":troop_no", slot_troop_is_prisoner, 0),
(neg|troop_slot_ge, ":troop_no", slot_troop_prisoner_of_party, 0),
(troop_get_slot, ":party_no", ":troop_no", slot_troop_leaded_party),
(gt, ":party_no", 0),
(party_slot_eq, ":party_no", slot_party_ai_state, spai_besieging_center),
(party_slot_eq, ":party_no", slot_party_ai_object, "$g_encountered_party"),
(party_slot_eq, ":party_no", slot_party_ai_substate, 1),
(call_script, "script_party_set_ai_state", ":party_no", spai_undefined, -1),
(call_script, "script_party_set_ai_state", ":party_no", spai_besieging_center, "$g_encountered_party"),
(try_end),
(display_message, "@The enemy has been forced to retreat. The assault is over, but the siege continues."),
(assign, "$g_battle_simulation_cancel_for_party", "$g_encountered_party"),
(leave_encounter),
(change_screen_return),
(assign, "$g_battle_simulation_auto_enter_town_after_battle", "$g_encountered_party"),
(try_end),
(try_end),
(try_end),
(assign, "$g_siege_first_encounter", 0),
(assign, "$new_encounter", 0),
],
[
("siege_defender_join_battle",
[
(neg|troop_is_wounded, "trp_player"),
],
"Join the battle.",[
(party_set_next_battle_simulation_time, "$g_encountered_party", -1),
(assign, "$g_battle_result", 0),
(try_begin),
(party_slot_eq, "$g_encountered_party", slot_party_type, spt_town),
(party_get_slot, ":battle_scene", "$g_encountered_party", slot_town_walls),
(else_try),
(party_get_slot, ":battle_scene", "$g_encountered_party", slot_castle_exterior),
(try_end),
(call_script, "script_calculate_battle_advantage"),
(val_mul, reg0, 2),
(val_div, reg0, 3), #scale down the advantage a bit.
(set_battle_advantage, reg0),
(set_party_battle_mode),
(try_begin),
(party_slot_eq, "$current_town", slot_center_siege_with_belfry, 1),
(set_jump_mission,"mt_castle_attack_walls_belfry"),
(else_try),
(set_jump_mission,"mt_castle_attack_walls_ladder"),
(try_end),
(jump_to_scene,":battle_scene"),
(assign, "$g_next_menu", "mnu_siege_started_defender"),
(jump_to_menu, "mnu_battle_debrief"),
(change_screen_mission)]),
("siege_defender_troops_join_battle",[(call_script, "script_party_count_members_with_full_health", "p_main_party"),
(this_or_next|troop_is_wounded, "trp_player"),
(ge, reg0, 3)],
"Order your men to join the battle without you.",[
(party_set_next_battle_simulation_time, "$g_encountered_party", -1),
(select_enemy,1),
(assign,"$g_enemy_party","$g_encountered_party_2"),
(assign,"$g_ally_party","$g_encountered_party"),
(assign,"$g_siege_join", 1),
(jump_to_menu,"mnu_siege_join_defense")]),
]
),
(
"siege_join_defense",mnf_disable_all_keys,
"{s4}^^Your casualties: {s8}^^Allies' casualties: {s9}^^Enemy casualties: {s10}",
"none",
[
(try_begin),
(eq, "$g_siege_join", 1),
(call_script, "script_party_calculate_strength", "p_main_party", 1), #skip player
(assign, ":player_party_strength", reg0),
(val_div, ":player_party_strength", 5),
(else_try),
(assign, ":player_party_strength", 0),
(try_end),
(call_script, "script_party_calculate_strength", "p_collective_ally", 0),
(assign, ":ally_party_strength", reg0),
(val_div, ":ally_party_strength", 5),
(call_script, "script_party_calculate_strength", "p_collective_enemy", 0),
(assign, ":enemy_party_strength", reg0),
(val_div, ":enemy_party_strength", 10),
(store_add, ":friend_party_strength", ":player_party_strength", ":ally_party_strength"),
(try_begin),
(eq, ":friend_party_strength", 0),
(store_div, ":enemy_party_strength_for_p", ":enemy_party_strength", 2),
(else_try),
(assign, ":enemy_party_strength_for_p", ":enemy_party_strength"),
(val_mul, ":enemy_party_strength_for_p", ":player_party_strength"),
(val_div, ":enemy_party_strength_for_p", ":friend_party_strength"),
(try_end),
(val_sub, ":enemy_party_strength", ":enemy_party_strength_for_p"),
(inflict_casualties_to_party_group, "p_main_party", ":enemy_party_strength_for_p", "p_temp_casualties"),
(call_script, "script_print_casualties_to_s0", "p_temp_casualties", 0),
(str_store_string_reg, s8, s0),
(inflict_casualties_to_party_group, "$g_ally_party", ":enemy_party_strength", "p_temp_casualties"),
(call_script, "script_print_casualties_to_s0", "p_temp_casualties", 0),
(str_store_string_reg, s9, s0),
(party_collect_attachments_to_party, "$g_ally_party", "p_collective_ally"),
(inflict_casualties_to_party_group, "$g_enemy_party", ":friend_party_strength", "p_temp_casualties"),
(call_script, "script_print_casualties_to_s0", "p_temp_casualties", 0),
(str_store_string_reg, s10, s0),
(party_collect_attachments_to_party, "$g_enemy_party", "p_collective_enemy"),
(try_begin),
(call_script, "script_party_count_members_with_full_health","p_main_party"),
(le, reg0, 0),
(str_store_string, s4, "str_siege_defender_order_attack_failure"),
(else_try),
(call_script, "script_party_count_members_with_full_health","p_collective_enemy"),
(le, reg0, 0),
(assign, "$g_battle_result", 1),
(str_store_string, s4, "str_siege_defender_order_attack_success"),
(else_try),
(str_store_string, s4, "str_siege_defender_order_attack_continue"),
(try_end),
],
[
("continue",[],"Continue...",[
(jump_to_menu,"mnu_siege_started_defender"),
]),
]
),
(
"enter_your_own_castle",0,
"{s10}",
"none",
[
(try_begin),
(neg|is_between, "$players_kingdom", npc_kingdoms_begin, npc_kingdoms_end),
(faction_get_slot, ":faction_leader", "fac_player_supporters_faction", slot_faction_leader),
(eq, ":faction_leader", "trp_player"),
(str_store_string, s10, "@As you approach, you are spotted by the castle guards, who welcome you and open the gates for their {king/queen}."),
(else_try),
(str_store_string, s10, "@As you approach, you are spotted by the castle guards, who welcome you and open the gates for their {lord/lady}."),
(try_end),
(str_store_party_name, s2, "$current_town"),
],
[
("continue",[],"Continue...",
[ (jump_to_menu,"mnu_town"),
]),
],
),
(
"village",mnf_enable_hot_keys,
"{s10} {s12}^{s11}^{s6}{s7}",
"none",
[
(assign, "$current_town", "$g_encountered_party"),
(call_script, "script_update_center_recon_notes", "$current_town"),
(assign, "$g_defending_against_siege", 0), #required for bandit check
(assign, "$g_battle_result", 0),
(assign, "$qst_collect_taxes_currently_collecting", 0),
(assign, "$qst_train_peasants_against_bandits_currently_training", 0),
(try_begin),
(gt, "$auto_enter_menu_in_center", 0),
(jump_to_menu, "$auto_enter_menu_in_center"),
(assign, "$auto_enter_menu_in_center", 0),
(try_end),
(try_begin),
(neq, "$g_player_raiding_village", "$current_town"),
(assign, "$g_player_raiding_village", 0),
(else_try),
(jump_to_menu, "mnu_village_loot_continue"),
(try_end),
(try_begin),#Fix for collecting taxes
(eq, "$g_town_visit_after_rest", 1),
(assign, "$g_town_visit_after_rest", 0),
(try_end),
(str_store_party_name,s2, "$current_town"),
(party_get_slot, ":center_lord", "$current_town", slot_town_lord),
(store_faction_of_party, ":center_faction", "$current_town"),
(str_store_faction_name,s9,":center_faction"),
(try_begin),
(ge, ":center_lord", 0),
(str_store_troop_name,s8,":center_lord"),
(str_store_string,s7,"@{s8} of {s9}"),
(try_end),
(str_clear, s10),
(str_clear, s12),
(try_begin),
(neg|party_slot_eq, "$current_town", slot_village_state, svs_looted),
(str_store_string, s60, s2),
(party_get_slot, ":prosperity", "$current_town", slot_town_prosperity),
(try_begin),
(eq, "$cheat_mode", 1),
(assign, reg4, ":prosperity",),
(display_message, "@{!}Prosperity: {reg4}"),
(try_end),
#(val_add, ":prosperity", 5),
(store_div, ":str_id", ":prosperity", 10),
(val_min, ":str_id", 9),
(val_add, ":str_id", "str_village_prosperity_0"),
(str_store_string, s10, ":str_id"),
(store_div, ":str_id", ":prosperity", 20),
(val_min, ":str_id", 4),
(try_begin),
(is_between, "$current_town", "p_village_91", villages_end),
(val_add, ":str_id", "str_oasis_village_alt_prosperity_0"),
(else_try),
(val_add, ":str_id", "str_village_alt_prosperity_0"),
(try_end),
(str_store_string, s12, ":str_id"),
(try_end),
(str_clear, s11),
(try_begin),
(party_slot_eq, "$current_town", slot_village_state, svs_looted),
(else_try),
(eq, ":center_lord", "trp_player"),
(str_store_string,s11,"@ This village and the surrounding lands belong to you."),
(else_try),
(ge, ":center_lord", 0),
(str_store_string,s11,"@ You remember that this village and the surrounding lands belong to {s7}."),
(else_try),
(str_store_string,s11,"@ These lands belong to no one."),
(try_end),
(str_clear, s7),
(try_begin),
(neg|party_slot_eq, "$current_town", slot_village_state, svs_looted),
(party_get_slot, ":center_relation", "$current_town", slot_center_player_relation),
(call_script, "script_describe_center_relation_to_s3", ":center_relation"),
(assign, reg9, ":center_relation"),
(str_store_string, s7, "@{!} {s3} ({reg9})."),
(try_end),
(str_clear, s6),
(try_begin),
(party_slot_ge, "$current_town", slot_village_infested_by_bandits, 1),
(party_get_slot, ":bandit_troop", "$current_town", slot_village_infested_by_bandits),
(store_character_level, ":player_level", "trp_player"),
(store_add, "$qst_eliminate_bandits_infesting_village_num_bandits", ":player_level", 10),
(val_mul, "$qst_eliminate_bandits_infesting_village_num_bandits", 12),
(val_div, "$qst_eliminate_bandits_infesting_village_num_bandits", 10),
(store_random_in_range, "$qst_eliminate_bandits_infesting_village_num_villagers", 25, 30),
(assign, reg8, "$qst_eliminate_bandits_infesting_village_num_bandits"),
(str_store_troop_name_by_count, s35, ":bandit_troop", "$qst_eliminate_bandits_infesting_village_num_bandits"),
(str_store_string, s6, "@ The village is infested by {reg8} {s35}."),
(assign, "$g_enemy_party", -1), #new, no known enemy party while saving village from bandits dfdf
(assign, "$g_ally_party", -1), #new, no known enemy party while saving village from bandits dfdf
(try_begin),
(eq, ":bandit_troop", "trp_forest_bandit"),
(set_background_mesh, "mesh_pic_forest_bandits"),
(else_try),
(eq, ":bandit_troop", "trp_steppe_bandit"),
(set_background_mesh, "mesh_pic_steppe_bandits"),
(else_try),
(eq, ":bandit_troop", "trp_taiga_bandit"),
(set_background_mesh, "mesh_pic_steppe_bandits"),
(else_try),
(eq, ":bandit_troop", "trp_mountain_bandit"),
(set_background_mesh, "mesh_pic_mountain_bandits"),
(else_try),
(eq, ":bandit_troop", "trp_sea_raider"),
(set_background_mesh, "mesh_pic_sea_raiders"),
(else_try),
(set_background_mesh, "mesh_pic_bandits"),
(try_end),
(else_try),
(party_slot_eq, "$current_town", slot_village_state, svs_looted),
(str_store_string, s6, "@ The village has been looted. A handful of souls scatter as you pass through the burnt out houses."),
(try_begin),
(neq, "$g_player_raid_complete", 1),
(play_track, "track_empty_village", 1),
(try_end),
(set_background_mesh, "mesh_pic_looted_village"),
(else_try),
(party_slot_eq, "$current_town", slot_village_state, svs_being_raided),
(str_store_string, s6, "@ The village is being raided."),
(else_try),
(party_get_current_terrain, ":cur_terrain", "$current_town"),
(try_begin),
(this_or_next|eq, ":cur_terrain", rt_steppe),
(this_or_next|eq, ":cur_terrain", rt_steppe_forest),
(this_or_next|eq, ":cur_terrain", rt_desert),
( eq, ":cur_terrain", rt_desert_forest),
(set_background_mesh, "mesh_pic_village_s"),
(else_try),
(this_or_next|eq, ":cur_terrain", rt_snow),
( eq, ":cur_terrain", rt_snow_forest),
(set_background_mesh, "mesh_pic_village_w"),
(else_try),
(set_background_mesh, "mesh_pic_village_p"),
(try_end),
(try_end),
(try_begin),
(eq, "$g_player_raid_complete", 1),
(assign, "$g_player_raid_complete", 0),
(jump_to_menu, "mnu_village_loot_complete"),
(else_try),
(party_get_slot, ":raider_party", "$current_town", slot_village_raided_by),
(gt, ":raider_party", 0),
# Process here...
(try_end),
(try_begin),
(eq,"$g_leave_town",1),
(assign,"$g_leave_town",0),
(change_screen_return),
(try_end),
(try_begin),
(store_time_of_day, ":cur_hour"),
(ge, ":cur_hour", 5),
(lt, ":cur_hour", 21),
(assign, "$town_nighttime", 0),
(else_try),
(assign, "$town_nighttime", 1),
(try_end),
],
[
("village_manage",
[
(neg|party_slot_eq, "$current_town", slot_village_state, svs_looted),
(neg|party_slot_eq, "$current_town", slot_village_state, svs_being_raided),
(neg|party_slot_ge, "$current_town", slot_village_infested_by_bandits, 1),
(party_slot_eq, "$current_town", slot_town_lord, "trp_player")
]
,"Manage this village.",
[
(assign, "$g_next_menu", "mnu_village"),
(jump_to_menu, "mnu_center_manage"),
]),
("recruit_volunteers",
[
(call_script, "script_cf_village_recruit_volunteers_cond"),
]
,"Recruit Volunteers.",
[
(try_begin),
(call_script, "script_cf_enter_center_location_bandit_check"),
(else_try),
(jump_to_menu, "mnu_recruit_volunteers"),
(try_end),
]),
("village_center",[(neg|party_slot_eq, "$current_town", slot_village_state, svs_looted),
(neg|party_slot_eq, "$current_town", slot_village_state, svs_being_raided),
(neg|party_slot_ge, "$current_town", slot_village_infested_by_bandits, 1),]
,"Go to the village center.",
[
(try_begin),
(call_script, "script_cf_enter_center_location_bandit_check"),
(else_try),
(party_get_slot, ":village_scene", "$current_town", slot_castle_exterior),
(modify_visitors_at_site,":village_scene"),
(reset_visitors),
(party_get_slot, ":village_elder_troop", "$current_town",slot_town_elder),
(set_visitor, 11, ":village_elder_troop"),
(call_script, "script_init_town_walkers"),
(try_begin),
(check_quest_active, "qst_hunt_down_fugitive"),
(neg|is_currently_night),
(quest_slot_eq, "qst_hunt_down_fugitive", slot_quest_target_center, "$current_town"),
(neg|check_quest_succeeded, "qst_hunt_down_fugitive"),
(neg|check_quest_failed, "qst_hunt_down_fugitive"),
(set_visitor, 45, "trp_fugitive"),
(try_end),
(set_jump_mission,"mt_village_center"),
(jump_to_scene,":village_scene"),
(change_screen_mission),
(try_end),
],"Door to the village center."),
("village_buy_food",[(party_slot_eq, "$current_town", slot_village_state, 0),
(neg|party_slot_ge, "$current_town", slot_village_infested_by_bandits, 1),
],"Buy supplies from the peasants.",
[
(try_begin),
(call_script, "script_cf_enter_center_location_bandit_check"),
(else_try),
(party_get_slot, ":merchant_troop", "$current_town", slot_town_elder),
#(try_for_range, ":cur_goods", trade_goods_begin, trade_goods_end),
#(store_sub, ":cur_good_price_slot", ":cur_goods", trade_goods_begin),
#(val_add, ":cur_good_price_slot", slot_town_trade_good_prices_begin),
#(party_get_slot, ":cur_price", "$current_town", ":cur_good_price_slot"),
#(call_script, "script_center_get_production", "$current_town", ":cur_goods"),
#(assign, reg13, reg0),
#(call_script, "script_center_get_consumption", "$current_town", ":cur_goods"),
#(str_store_party_name, s1, "$current_town"),
#(str_store_item_name, s2, ":cur_goods"),
#(assign, reg16, ":cur_price"),
#(display_log_message, "@DEBUG:{s1}-{s2}, prd: {reg13}, con: {reg0}, raw: {reg1}, cns: {reg2}, fee: {reg16}"),
#(try_end),
(change_screen_trade, ":merchant_troop"),
(try_end),
]),
("village_attack_bandits",[(party_slot_ge, "$current_town", slot_village_infested_by_bandits, 1),],
"Attack the bandits.",
[(party_get_slot, ":bandit_troop", "$current_town", slot_village_infested_by_bandits),
(party_get_slot, ":scene_to_use", "$current_town", slot_castle_exterior),
(modify_visitors_at_site,":scene_to_use"),
(reset_visitors),
(set_visitors, 0, ":bandit_troop", "$qst_eliminate_bandits_infesting_village_num_bandits"),
(set_visitors, 2, "trp_farmer", "$qst_eliminate_bandits_infesting_village_num_villagers"),
(set_party_battle_mode),
(set_battle_advantage, 0),
(assign, "$g_battle_result", 0),
(set_jump_mission,"mt_village_attack_bandits"),
(jump_to_scene, ":scene_to_use"),
(assign, "$g_next_menu", "mnu_village_infest_bandits_result"),
(jump_to_menu, "mnu_battle_debrief"),
(assign, "$g_mt_mode", vba_normal),
(change_screen_mission),
]),
("village_wait",
[(party_slot_eq, "$current_town", slot_center_has_manor, 1),
(party_slot_eq, "$current_town", slot_town_lord, "trp_player"),
],
"Wait here for some time.",
[
(assign,"$auto_enter_town","$current_town"),
(assign, "$g_last_rest_center", "$current_town"),
(try_begin),
(party_is_active, "p_main_party"),
(party_get_current_terrain, ":cur_terrain", "p_main_party"),
(try_begin),
(eq, ":cur_terrain", rt_desert),
(unlock_achievement, ACHIEVEMENT_SARRANIDIAN_NIGHTS),
(try_end),
(try_end),
(rest_for_hours_interactive, 24 * 7, 5, 1), #rest while attackable
(change_screen_return),
]),
("collect_taxes_qst",[(party_slot_eq, "$current_town", slot_village_state, 0),
(neg|party_slot_ge, "$current_town", slot_village_infested_by_bandits, 1),
(check_quest_active, "qst_collect_taxes"),
(quest_get_slot, ":quest_giver_troop", "qst_collect_taxes", slot_quest_giver_troop),
(quest_slot_eq, "qst_collect_taxes", slot_quest_target_center, "$current_town"),
(neg|quest_slot_eq, "qst_collect_taxes", slot_quest_current_state, 4),
(str_store_troop_name, s1, ":quest_giver_troop"),
(quest_get_slot, reg5, "qst_collect_taxes", slot_quest_current_state),
], "{reg5?Continue collecting taxes:Collect taxes} due to {s1}.",
[(jump_to_menu, "mnu_collect_taxes"),]),
("train_peasants_against_bandits_qst",
[
(party_slot_eq, "$current_town", slot_village_state, 0),
(check_quest_active, "qst_train_peasants_against_bandits"),
(neg|check_quest_concluded, "qst_train_peasants_against_bandits"),
(quest_slot_eq, "qst_train_peasants_against_bandits", slot_quest_target_center, "$current_town"),
], "Train the peasants.",
[(jump_to_menu, "mnu_train_peasants_against_bandits"),]),
("village_hostile_action",[(party_slot_eq, "$current_town", slot_village_state, 0),
(neg|party_slot_ge, "$current_town", slot_village_infested_by_bandits, 1),
(neq, "$players_kingdom", "$g_encountered_party_faction"),
], "Take a hostile action.",
[(jump_to_menu,"mnu_village_hostile_action"),
]),
("village_reports",[(eq, "$cheat_mode", 1),], "{!}CHEAT! Show reports.",
[(jump_to_menu,"mnu_center_reports"),
]),
("village_leave",[],"Leave...",[(change_screen_return,0)]),
],
),
(
"village_hostile_action",0,
"What action do you have in mind?",
"none",
[],
[
("village_take_food",[
(party_slot_eq, "$current_town", slot_village_state, 0),
(neg|party_slot_ge, "$current_town", slot_village_infested_by_bandits, 1),
(party_get_slot, ":merchant_troop", "$current_town", slot_town_elder),
(assign, ":town_stores_not_empty", 0),
(try_for_range, ":slot_no", num_equipment_kinds, max_inventory_items + num_equipment_kinds),
(troop_get_inventory_slot, ":slot_item", ":merchant_troop", ":slot_no"),
(ge, ":slot_item", 0),
(assign, ":town_stores_not_empty", 1),
(try_end),
(eq, ":town_stores_not_empty", 1),
],"Force the peasants to give you supplies.",
[
(jump_to_menu, "mnu_village_take_food_confirm")
]),
("village_steal_cattle",
[
(party_slot_eq, "$current_town", slot_village_state, 0),
(party_slot_eq, "$current_town", slot_village_player_can_not_steal_cattle, 0),
(neg|party_slot_ge, "$current_town", slot_village_infested_by_bandits, 1),
(party_get_slot, ":num_cattle", "$current_town", slot_village_number_of_cattle),
(neg|party_slot_eq, "$current_town", slot_town_lord, "trp_player"),
(gt, ":num_cattle", 0),
],"Steal cattle.",
[
(jump_to_menu, "mnu_village_steal_cattle_confirm")
]),
("village_loot",[(party_slot_eq, "$current_town", slot_village_state, 0),
(neg|party_slot_ge, "$current_town", slot_village_infested_by_bandits, 1),
(store_faction_of_party, ":center_faction", "$current_town"),
(store_relation, ":reln", "fac_player_supporters_faction", ":center_faction"),
(lt, ":reln", 0),
],
"Loot and burn this village.",
[
# (party_clear, "$current_town"),
# (party_add_template, "$current_town", "pt_villagers_in_raid"),
(jump_to_menu, "mnu_village_start_attack"),
]),
("forget_it",[],
"Forget it.",[(jump_to_menu,"mnu_village")]),
],
),
(
"recruit_volunteers",0,
"{s18}",
"none",
[(party_get_slot, ":volunteer_troop", "$current_town", slot_center_volunteer_troop_type),
(party_get_slot, ":volunteer_amount", "$current_town", slot_center_volunteer_troop_amount),
(party_get_free_companions_capacity, ":free_capacity", "p_main_party"),
(store_troop_gold, ":gold", "trp_player"),
(store_div, ":gold_capacity", ":gold", 10),#10 denars per man
(assign, ":party_capacity", ":free_capacity"),
(val_min, ":party_capacity", ":gold_capacity"),
(try_begin),
(gt, ":party_capacity", 0),
(val_min, ":volunteer_amount", ":party_capacity"),
(try_end),
(assign, reg5, ":volunteer_amount"),
(assign, reg7, 0),
(try_begin),
(gt, ":volunteer_amount", ":gold_capacity"),
(assign, reg7, 1), #not enough money
(try_end),
(try_begin),
(eq, ":volunteer_amount", 0),
(str_store_string, s18, "@No one here seems to be willing to join your party."),
(else_try),
(store_mul, reg6, ":volunteer_amount", 10),#10 denars per man
(str_store_troop_name_by_count, s3, ":volunteer_troop", ":volunteer_amount"),
(try_begin),
(eq, reg5, 1),
(str_store_string, s18, "@One {s3} volunteers to follow you."),
(else_try),
(str_store_string, s18, "@{reg5} {s3} volunteer to follow you."),
(try_end),
(set_background_mesh, "mesh_pic_recruits"),
(try_end),
],
[
("continue_not_enough_gold",
[
(eq, reg7, 1),
],
"I don't have enough money...",
[
(jump_to_menu,"mnu_village"),
]),
("continue",
[
(eq, reg7, 0),
(eq, reg5, 0),
], #noone willing to join
"Continue...",
[
(party_set_slot, "$current_town", slot_center_volunteer_troop_amount, -1),
(jump_to_menu,"mnu_village"),
]),
("recruit_them",
[
(eq, reg7, 0),
(gt, reg5, 0),
],
"Recruit them ({reg6} denars).",
[
(call_script, "script_village_recruit_volunteers_recruit"),
(jump_to_menu,"mnu_village"),
]),
("forget_it",
[
(eq, reg7, 0),
(gt, reg5, 0),
],
"Forget it.",
[
(jump_to_menu,"mnu_village"),
]),
],
),
(
"village_hunt_down_fugitive_defeated",0,
"A heavy blow from the fugitive sends you to the ground, and your vision spins and goes dark.\
Time passes. When you open your eyes again you find yourself battered and bloody,\
but luckily none of the wounds appear to be lethal.",
"none",
[],
[
("continue",[],"Continue...",[(jump_to_menu, "mnu_village"),]),
],
),
(
"village_infest_bandits_result",mnf_scale_picture,
"{s9}",
"none",
[(try_begin),
(eq, "$g_battle_result", 1),
(jump_to_menu, "mnu_village_infestation_removed"),
(else_try),
(str_store_string, s9, "@Try as you might, you could not defeat the bandits.\
Infuriated, they raze the village to the ground to punish the peasants,\
and then leave the burning wasteland behind to find greener pastures to plunder."),
(set_background_mesh, "mesh_pic_looted_village"),
(try_end),
],
[
("continue",[],"Continue...",
[(party_set_slot, "$g_encountered_party", slot_village_infested_by_bandits, 0),
(call_script, "script_village_set_state", "$current_town", svs_looted),
(party_set_slot, "$current_town", slot_village_raid_progress, 0),
(party_set_slot, "$current_town", slot_village_recover_progress, 0),
(try_begin),
(check_quest_active, "qst_eliminate_bandits_infesting_village"),
(quest_slot_eq, "qst_eliminate_bandits_infesting_village", slot_quest_target_center, "$g_encountered_party"),
(call_script, "script_change_player_relation_with_center", "$g_encountered_party", -5),
(call_script, "script_fail_quest", "qst_eliminate_bandits_infesting_village"),
(call_script, "script_end_quest", "qst_eliminate_bandits_infesting_village"),
(else_try),
(check_quest_active, "qst_deal_with_bandits_at_lords_village"),
(quest_slot_eq, "qst_deal_with_bandits_at_lords_village", slot_quest_target_center, "$g_encountered_party"),
(call_script, "script_change_player_relation_with_center", "$g_encountered_party", -4),
(call_script, "script_fail_quest", "qst_deal_with_bandits_at_lords_village"),
(call_script, "script_end_quest", "qst_deal_with_bandits_at_lords_village"),
(else_try),
(call_script, "script_change_player_relation_with_center", "$g_encountered_party", -3),
(try_end),
(jump_to_menu, "mnu_village"),]),
],
),
(
"village_infestation_removed",mnf_disable_all_keys,
"In a battle worthy of song, you and your men drive the bandits out of the village, making it safe once more.\
The villagers have little left in the way of wealth after their ordeal,\
but they offer you all they can find.",
"none",
[(party_get_slot, ":bandit_troop", "$g_encountered_party", slot_village_infested_by_bandits),
(party_set_slot, "$g_encountered_party", slot_village_infested_by_bandits, 0),
(party_clear, "p_temp_party"),
(party_add_members, "p_temp_party", ":bandit_troop", "$qst_eliminate_bandits_infesting_village_num_bandits"),
(assign, "$g_strength_contribution_of_player", 50),
(call_script, "script_party_give_xp_and_gold", "p_temp_party"),
(try_begin),
(check_quest_active, "qst_eliminate_bandits_infesting_village"),
(quest_slot_eq, "qst_eliminate_bandits_infesting_village", slot_quest_target_center, "$g_encountered_party"),
(call_script, "script_end_quest", "qst_eliminate_bandits_infesting_village"),
#Add quest reward
(call_script, "script_change_player_relation_with_center", "$g_encountered_party", 5),
(else_try),
(check_quest_active, "qst_deal_with_bandits_at_lords_village"),
(quest_slot_eq, "qst_deal_with_bandits_at_lords_village", slot_quest_target_center, "$g_encountered_party"),
(call_script, "script_succeed_quest", "qst_deal_with_bandits_at_lords_village"),
(call_script, "script_change_player_relation_with_center", "$g_encountered_party", 3),
(else_try),
#Add normal reward
(call_script, "script_change_player_relation_with_center", "$g_encountered_party", 4),
(try_end),
(party_get_slot, ":merchant_troop", "$current_town", slot_town_elder),
(try_for_range, ":slot_no", num_equipment_kinds ,max_inventory_items + num_equipment_kinds),
(store_random_in_range, ":rand", 0, 100),
(lt, ":rand", 70),
(troop_set_inventory_slot, ":merchant_troop", ":slot_no", -1),
(try_end),
],
[
("village_bandits_defeated_accept",[],"Take it as your just due.",[(jump_to_menu, "mnu_village"),
(party_get_slot, ":merchant_troop", "$current_town", slot_town_elder),
(troop_sort_inventory, ":merchant_troop"),
(change_screen_loot, ":merchant_troop"),
]),
("village_bandits_defeated_cont",[], "Refuse, stating that they need these items more than you do.",
[ (call_script, "script_change_player_relation_with_center", "$g_encountered_party", 3),
(call_script, "script_change_player_honor", 1),
(jump_to_menu, "mnu_village")]),
],
),
(
"center_manage",0,
"{s19}^{reg6?^^You are\
currently building {s7}. The building will be completed after {reg8} day{reg9?s:}.:}",
"none",
[(assign, ":num_improvements", 0),
(str_clear, s18),
(try_begin),
(party_slot_eq, "$g_encountered_party", slot_party_type, spt_village),
(assign, ":begin", village_improvements_begin),
(assign, ":end", village_improvements_end),
(str_store_string, s17, "@village"),
(else_try),
(assign, ":begin", walled_center_improvements_begin),
(assign, ":end", walled_center_improvements_end),
(party_slot_eq, "$g_encountered_party", slot_party_type, spt_town),
(str_store_string, s17, "@town"),
(else_try),
(str_store_string, s17, "@castle"),
(try_end),
(try_for_range, ":improvement_no", ":begin", ":end"),
(party_slot_ge, "$g_encountered_party", ":improvement_no", 1),
(val_add, ":num_improvements", 1),
(call_script, "script_get_improvement_details", ":improvement_no"),
(try_begin),
(eq, ":num_improvements", 1),
(str_store_string, s18, "@{!}{s0}"),
(else_try),
(str_store_string, s18, "@{!}{s18}, {s0}"),
(try_end),
(try_end),
(try_begin),
(eq, ":num_improvements", 0),
(str_store_string, s19, "@The {s17} has no improvements."),
(else_try),
(str_store_string, s19, "@The {s17} has the following improvements:{s18}."),
(try_end),
(assign, reg6, 0),
(try_begin),
(party_get_slot, ":cur_improvement", "$g_encountered_party", slot_center_current_improvement),
(gt, ":cur_improvement", 0),
(call_script, "script_get_improvement_details", ":cur_improvement"),
(str_store_string, s7, s0),
(assign, reg6, 1),
(store_current_hours, ":cur_hours"),
(party_get_slot, ":finish_time", "$g_encountered_party", slot_center_improvement_end_hour),
(val_sub, ":finish_time", ":cur_hours"),
(store_div, reg8, ":finish_time", 24),
(val_max, reg8, 1),
(store_sub, reg9, reg8, 1),
(try_end),
],
[
("center_build_manor",[(eq, reg6, 0),
(party_slot_eq, "$g_encountered_party", slot_party_type, spt_village),
(party_slot_eq, "$g_encountered_party", slot_center_has_manor, 0),
],
"Build a manor.",[(assign, "$g_improvement_type", slot_center_has_manor),
(jump_to_menu, "mnu_center_improve"),]),
("center_build_fish_pond",[(eq, reg6, 0),
(party_slot_eq, "$g_encountered_party", slot_party_type, spt_village),
(party_slot_eq, "$g_encountered_party", slot_center_has_fish_pond, 0),
],
"Build a mill.",[(assign, "$g_improvement_type", slot_center_has_fish_pond),
(jump_to_menu, "mnu_center_improve"),]),
("center_build_watch_tower",[(eq, reg6, 0),
(party_slot_eq, "$g_encountered_party", slot_party_type, spt_village),
(party_slot_eq, "$g_encountered_party", slot_center_has_watch_tower, 0),
],
"Build a watch tower.",[(assign, "$g_improvement_type", slot_center_has_watch_tower),
(jump_to_menu, "mnu_center_improve"),]),
("center_build_school",[(eq, reg6, 0),
(party_slot_eq, "$g_encountered_party", slot_party_type, spt_village),
(party_slot_eq, "$g_encountered_party", slot_center_has_school, 0),
],
"Build a school.",[(assign, "$g_improvement_type", slot_center_has_school),
(jump_to_menu, "mnu_center_improve"),]),
("center_build_messenger_post",[(eq, reg6, 0),
(party_slot_eq, "$g_encountered_party", slot_center_has_messenger_post, 0),
],
"Build a messenger post.",[(assign, "$g_improvement_type", slot_center_has_messenger_post),
(jump_to_menu, "mnu_center_improve"),]),
("center_build_prisoner_tower",[(eq, reg6, 0),
(this_or_next|party_slot_eq, "$g_encountered_party", slot_party_type, spt_town),
(party_slot_eq, "$g_encountered_party", slot_party_type, spt_castle),
(party_slot_eq, "$g_encountered_party", slot_center_has_prisoner_tower, 0),
],
"Build a prisoner tower.",[(assign, "$g_improvement_type", slot_center_has_prisoner_tower),
(jump_to_menu, "mnu_center_improve"),]),
("go_back_dot",[],"Go back.",[(jump_to_menu, "$g_next_menu")]),
],
),
(
"center_improve",0,
"{s19} As the party member with the highest engineer skill ({reg2}), {reg3?you reckon:{s3} reckons} that building the {s4} will cost you\
{reg5} denars and will take {reg6} days.",
"none",
[(call_script, "script_get_improvement_details", "$g_improvement_type"),
(assign, ":improvement_cost", reg0),
(str_store_string, s4, s0),
(str_store_string, s19, s1),
(call_script, "script_get_max_skill_of_player_party", "skl_engineer"),
(assign, ":max_skill", reg0),
(assign, ":max_skill_owner", reg1),
(assign, reg2, ":max_skill"),
(store_sub, ":multiplier", 20, ":max_skill"),
(val_mul, ":improvement_cost", ":multiplier"),
(val_div, ":improvement_cost", 20),
(store_div, ":improvement_time", ":improvement_cost", 100),
(val_add, ":improvement_time", 3),
(assign, reg5, ":improvement_cost"),
(assign, reg6, ":improvement_time"),
(try_begin),
(eq, ":max_skill_owner", "trp_player"),
(assign, reg3, 1),
(else_try),
(assign, reg3, 0),
(str_store_troop_name, s3, ":max_skill_owner"),
(try_end),
],
[
("improve_cont",[(store_troop_gold, ":cur_gold", "trp_player"),
(ge, ":cur_gold", reg5)],
"Go on.", [(troop_remove_gold, "trp_player", reg5),
(party_set_slot, "$g_encountered_party", slot_center_current_improvement, "$g_improvement_type"),
(store_current_hours, ":cur_hours"),
(store_mul, ":hours_takes", reg6, 24),
(val_add, ":hours_takes", ":cur_hours"),
(party_set_slot, "$g_encountered_party", slot_center_improvement_end_hour, ":hours_takes"),
(jump_to_menu,"mnu_center_manage"),
]),
("forget_it",[(store_troop_gold, ":cur_gold", "trp_player"),
(ge, ":cur_gold", reg5)],
"Forget it.", [(jump_to_menu,"mnu_center_manage")]),
("improve_not_enough_gold",[(store_troop_gold, ":cur_gold", "trp_player"),
(lt, ":cur_gold", reg5)],
"I don't have enough money for that.", [(jump_to_menu, "mnu_center_manage"),]),
],
),
(
"town_bandits_failed",mnf_disable_all_keys,
"{s4} {s5}",
"none",
[
# (call_script, "script_loot_player_items", 0),
(store_troop_gold, ":total_gold", "trp_player"),
(store_div, ":gold_loss", ":total_gold", 30),
(store_random_in_range, ":random_loss", 40, 100),
(val_add, ":gold_loss", ":random_loss"),
(val_min, ":gold_loss", ":total_gold"),
(troop_remove_gold, "trp_player",":gold_loss"),
(party_set_slot, "$current_town", slot_center_has_bandits, 0),
(party_get_num_companions, ":num_companions", "p_main_party"),
(str_store_string, s4, "@The assasins beat you down and leave you for dead. ."),
(str_store_string, s4, "@You have fallen. The bandits quickly search your body for every coin they can find,\
then vanish into the night. They have left you alive, if only barely."),
(try_begin),
(gt, ":num_companions", 2),
(str_store_string, s5, "@Luckily some of your companions come to search for you when you do not return, and find you lying by the side of the road. They hurry you to safety and dress your wounds."),
(else_try),
(str_store_string, s5, "@Luckily some passing townspeople find you lying by the side of the road, and recognise you as something other than a simple beggar. They carry you to the nearest inn and dress your wounds."),
(try_end),
],
[
("continue",[],"Continue...",[(change_screen_return)]),
],
),
(
"town_bandits_succeeded",mnf_disable_all_keys,
"The bandits fall before you as wheat to a scythe! Soon you stand alone in the streets\
while most of your attackers lie unconscious, dead or dying.\
Searching the bodies, you find a purse which must have belonged to a previous victim of these brutes.\
Or perhaps, it was given to them by someone who wanted to arrange a suitable ending to your life.",
"none",
[
(party_set_slot, "$current_town", slot_center_has_bandits, 0),
(assign, "$g_last_defeated_bandits_town", "$g_encountered_party"),
(try_begin),
(check_quest_active, "qst_deal_with_night_bandits"),
(neg|check_quest_succeeded, "qst_deal_with_night_bandits"),
(quest_slot_eq, "qst_deal_with_night_bandits", slot_quest_target_center, "$g_encountered_party"),
(call_script, "script_succeed_quest", "qst_deal_with_night_bandits"),
(try_end),
(store_mul, ":xp_reward", "$num_center_bandits", 117),
(add_xp_to_troop, ":xp_reward", "trp_player"),
(store_mul, ":gold_reward", "$num_center_bandits", 50),
(call_script, "script_troop_add_gold","trp_player",":gold_reward"),
],
[
("continue",[],"Continue...",[(change_screen_return)]),
],
),
(
"village_steal_cattle_confirm",0,
"As the party member with the highest looting skill ({reg2}), {reg3?you reckon:{s1} reckons} that you can steal as many as {reg4} heads of village's cattle.",
"none",
[
(call_script, "script_get_max_skill_of_player_party", "skl_looting"),
(assign, reg2, reg0),
(assign, ":max_skill_owner", reg1),
(try_begin),
(eq, ":max_skill_owner", "trp_player"),
(assign, reg3, 1),
(else_try),
(assign, reg3, 0),
(str_store_troop_name, s1, ":max_skill_owner"),
(try_end),
(call_script, "script_calculate_amount_of_cattle_can_be_stolen", "$current_town"),
(assign, reg4, reg0),
],
[
("village_steal_cattle_confirm",[],"Go on.",
[
(rest_for_hours_interactive, 3, 5, 1), #rest while attackable
(assign, "$auto_menu", "mnu_village_steal_cattle"),
(change_screen_return),
]),
("forget_it",[],"Forget it.",[(change_screen_return)]),
],
),
(
"village_steal_cattle",mnf_disable_all_keys,
"{s1}",
"none",
[
(call_script, "script_calculate_amount_of_cattle_can_be_stolen", "$current_town"),
(assign, ":max_value", reg0),
(val_add, ":max_value", 1),
(store_random_in_range, ":random_value", 0, ":max_value"),
(party_set_slot, "$current_town", slot_village_player_can_not_steal_cattle, 1),
(party_get_slot, ":lord", "$current_town", slot_town_lord),
(try_begin),
(le, ":random_value", 0),
(call_script, "script_change_player_relation_with_center", "$current_town", -3),
(str_store_string, s1, "@You fail to steal any cattle."),
(else_try),
(assign, reg17, ":random_value"),
(store_sub, reg12, ":random_value", 1),
(try_begin),
(gt, ":lord", 0),
(call_script, "script_change_player_relation_with_troop", ":lord", -3),
(call_script, "script_add_log_entry", logent_player_stole_cattles_from_village, "trp_player", "$current_town", ":lord", "$g_encountered_party_faction"),
(try_end),
(call_script, "script_change_player_relation_with_center", "$current_town", -5),
(str_store_string, s1, "@You drive away {reg17} {reg12?heads:head} of cattle from the village's herd."),
(try_begin),
(eq, ":random_value", 3),
(unlock_achievement, ACHIEVEMENT_GOT_MILK),
(try_end),
(call_script, "script_create_cattle_herd", "$current_town", ":random_value"),
(party_get_slot, ":num_cattle", "$current_town", slot_village_number_of_cattle),
(val_sub, ":num_cattle", ":random_value"),
(party_set_slot, "$current_town", slot_village_number_of_cattle, ":num_cattle"),
(try_end),
],
[
("continue",[],"Continue...",
[
(change_screen_return),
]),
],
),
(
"village_take_food_confirm",0,
"It will be difficult to force and threaten the peasants into giving their precious supplies. You think you will need at least one hour.",
#TODO: mention looting skill?
"none",
[],
[
("village_take_food_confirm",[],"Go ahead.",
[
(rest_for_hours_interactive, 1, 5, 0), #rest while not attackable
(assign, "$auto_enter_town", "$current_town"),
(assign, "$g_town_visit_after_rest", 1),
(assign, "$auto_enter_menu_in_center", "mnu_village_take_food"),
(change_screen_return),
]),
("forget_it",[],"Forget it.",[(jump_to_menu, "mnu_village_hostile_action")]),
],
),
(
"village_take_food",0,
"The villagers grudgingly bring out what they have for you.",
"none",
[
(call_script, "script_party_count_members_with_full_health","p_main_party"),
(assign, ":player_party_size", reg0),
(call_script, "script_party_count_members_with_full_health","$current_town"),
(assign, ":villagers_party_size", reg0),
(try_begin),
(lt, ":player_party_size", 6),
(ge, ":villagers_party_size", 40),
(neg|party_slot_eq, "$current_town", slot_town_lord, "trp_player"),
(jump_to_menu, "mnu_village_start_attack"),
(try_end),
],
[
("take_supplies",[],"Take the supplies.",
[
(try_begin),
(party_slot_ge, "$current_town", slot_center_player_relation, -55),
(try_begin),
(party_slot_eq, "$current_town", slot_town_lord, "trp_player"),
(call_script, "script_change_player_relation_with_center", "$current_town", -1),
(else_try),
(call_script, "script_change_player_relation_with_center", "$current_town", -3),
(try_end),
(try_end),
(party_get_slot, ":village_lord", "$current_town", slot_town_lord),
(try_begin),
(gt, ":village_lord", 1),
(call_script, "script_change_player_relation_with_troop", ":village_lord", -1),
(try_end),
(party_get_slot, ":merchant_troop", "$current_town", slot_town_elder),
(party_get_skill_level, ":player_party_looting", "p_main_party", "skl_looting"),
(val_mul, ":player_party_looting", 3),
(store_sub, ":random_chance", 70, ":player_party_looting"), #Increases the chance of looting by 3% per skill level
(try_for_range, ":slot_no", num_equipment_kinds ,max_inventory_items + num_equipment_kinds),
(store_random_in_range, ":rand", 0, 100),
(lt, ":rand", ":random_chance"),
(troop_set_inventory_slot, ":merchant_troop", ":slot_no", -1),
(try_end),
###NPC companion changes begin
(call_script, "script_objectionable_action", tmt_humanitarian, "str_steal_from_villagers"),
#NPC companion changes end
#Troop commentary changes begin
(call_script, "script_add_log_entry", logent_village_extorted, "trp_player", "$current_town", -1, -1),
(store_faction_of_party,":village_faction", "$current_town"),
(call_script, "script_faction_inflict_war_damage_on_faction", "$players_kingdom", ":village_faction", 5),
#Troop commentary changes end
(jump_to_menu, "mnu_village"),
(troop_sort_inventory, ":merchant_troop"),
(change_screen_loot, ":merchant_troop"),
]),
("let_them_keep_it",[],"Let them keep it.",[(jump_to_menu, "mnu_village")]),
],
),
(
"village_start_attack",mnf_disable_all_keys|mnf_scale_picture,
"Some of the angry villagers grab their tools and prepare to resist you.\
It looks like you'll have a fight on your hands if you continue.",
"none",
[
(set_background_mesh, "mesh_pic_villageriot"),
(call_script, "script_party_count_members_with_full_health","p_main_party"),
(assign, ":player_party_size", reg0),
(call_script, "script_party_count_members_with_full_health","$current_town"),
(assign, ":villagers_party_size", reg0),
(try_begin),
(gt, ":player_party_size", 25),
(jump_to_menu, "mnu_village_loot_no_resist"),
(else_try),
(this_or_next|eq, ":villagers_party_size", 0),
(eq, "$g_battle_result", 1),
(try_begin),
(eq, "$g_battle_result", 1),
(store_random_in_range, ":enmity", -30, -15),
(call_script, "script_change_player_relation_with_center", "$current_town", ":enmity"),
(party_get_slot, ":town_lord", "$current_town", slot_town_lord),
(gt, ":town_lord", 0),
(call_script, "script_change_player_relation_with_troop", ":town_lord", -3),
(try_end),
(jump_to_menu, "mnu_village_loot_no_resist"),
(else_try),
(eq, "$g_battle_result", -1),
(jump_to_menu, "mnu_village_loot_defeat"),
(try_end),
],
[
("village_raid_attack",[],"Charge them.",[
(store_random_in_range, ":enmity", -10, -5),
(call_script, "script_change_player_relation_with_center", "$current_town", ":enmity"),
(try_begin),
(party_get_slot, ":town_lord", "$current_town", slot_town_lord),
(gt, ":town_lord", 0),
(call_script, "script_change_player_relation_with_troop", ":town_lord", -3),
(try_end),
(call_script, "script_calculate_battle_advantage"),
(set_battle_advantage, reg0),
(set_party_battle_mode),
(assign, "$g_battle_result", 0),
(assign, "$g_village_raid_evil", 1),
(set_jump_mission,"mt_village_raid"),
(party_get_slot, ":scene_to_use", "$current_town", slot_castle_exterior),
(jump_to_scene, ":scene_to_use"),
(assign, "$g_next_menu", "mnu_village_start_attack"),
(call_script, "script_diplomacy_party_attacks_neutral", "p_main_party", "$g_encountered_party"),
###NPC companion changes begin
(call_script, "script_objectionable_action", tmt_humanitarian, "str_loot_village"),
#NPC companion changes end
(jump_to_menu, "mnu_battle_debrief"),
(change_screen_mission),
]),
("village_raid_leave",[],"Leave this village alone.",[(change_screen_return)]),
],
),
(
"village_loot_no_resist",0,
"The villagers here are few and frightened, and they quickly scatter and run before you.\
The village is at your mercy.",
"none",
[],
[
("village_loot",[], "Plunder the village, then raze it.",
[
(call_script, "script_village_set_state", "$current_town", svs_being_raided),
(party_set_slot, "$current_town", slot_village_raided_by, "p_main_party"),
(assign,"$g_player_raiding_village","$current_town"),
(try_begin),
(store_faction_of_party, ":village_faction", "$current_town"),
(store_relation, ":relation", "$players_kingdom", ":village_faction"),
(ge, ":relation", 0),
(call_script, "script_diplomacy_party_attacks_neutral", "p_main_party", "$current_town"),
(try_end),
(rest_for_hours, 3, 5, 1), #rest while attackable (3 hours will be extended by the trigger)
(change_screen_return),
]),
("village_raid_leave",[],"Leave this village alone.",[(change_screen_return)]),
],
),
(
"village_loot_complete",mnf_disable_all_keys,
"On your orders your troops sack the village, pillaging everything of any value,\
and then put the buildings to the torch. From the coins and valuables that are found, you get your share of {reg1} denars.",
"none",
[
(get_achievement_stat, ":number_of_village_raids", ACHIEVEMENT_THE_BANDIT, 0),
(get_achievement_stat, ":number_of_caravan_raids", ACHIEVEMENT_THE_BANDIT, 1),
(val_add, ":number_of_village_raids", 1),
(set_achievement_stat, ACHIEVEMENT_THE_BANDIT, 0, ":number_of_village_raids"),
(try_begin),
(ge, ":number_of_village_raids", 3),
(ge, ":number_of_caravan_raids", 3),
(unlock_achievement, ACHIEVEMENT_THE_BANDIT),
(try_end),
(party_get_slot, ":village_lord", "$current_town", slot_town_lord),
(try_begin),
(gt, ":village_lord", 0),
(call_script, "script_change_player_relation_with_troop", ":village_lord", -5),
(try_end),
(store_random_in_range, ":enmity", -35, -25),
(call_script, "script_change_player_relation_with_center", "$current_town", ":enmity"),
(store_faction_of_party, ":village_faction", "$current_town"),
(store_relation, ":relation", ":village_faction", "fac_player_supporters_faction"),
(try_begin),
(lt, ":relation", 0),
(call_script, "script_change_player_relation_with_faction", ":village_faction", -3),
(try_end),
(assign, ":money_gained", 50),
(party_get_slot, ":prosperity", "$current_town", slot_town_prosperity),
(store_mul, ":prosperity_of_village_mul_5", ":prosperity", 5),
(val_add, ":money_gained", ":prosperity_of_village_mul_5"),
(call_script, "script_troop_add_gold", "trp_player", ":money_gained"),
(assign, ":morale_increase", 3),
(store_div, ":money_gained_div_100", ":money_gained", 100),
(val_add, ":morale_increase", ":money_gained_div_100"),
(call_script, "script_change_player_party_morale", ":morale_increase"),
(faction_get_slot, ":faction_morale", ":village_faction", slot_faction_morale_of_player_troops),
(store_mul, ":morale_increase_mul_2", ":morale_increase", 200),
(val_sub, ":faction_morale", ":morale_increase_mul_2"),
(faction_set_slot, ":village_faction", slot_faction_morale_of_player_troops, ":faction_morale"),
#NPC companion changes begin
(call_script, "script_objectionable_action", tmt_humanitarian, "str_loot_village"),
#NPC companion changes end
(assign, reg1, ":money_gained"),
],
[
("continue",[], "Continue...",
[
(jump_to_menu, "mnu_close"),
(call_script, "script_calculate_amount_of_cattle_can_be_stolen", "$current_town"),
(assign, ":max_cattle", reg0),
(val_mul, ":max_cattle", 3),
(val_div, ":max_cattle", 2),
(party_get_slot, ":num_cattle", "$current_town", slot_village_number_of_cattle),
(val_min, ":max_cattle", ":num_cattle"),
(val_add, ":max_cattle", 1),
(store_random_in_range, ":random_value", 0, ":max_cattle"),
(try_begin),
(gt, ":random_value", 0),
(call_script, "script_create_cattle_herd", "$current_town", ":random_value"),
(val_sub, ":num_cattle", ":random_value"),
(party_set_slot, "$current_town", slot_village_number_of_cattle, ":num_cattle"),
(try_end),
(troop_clear_inventory, "trp_temp_troop"),
#below line changed with below lines to make plunder result more realistic. Now only items produced in bound town can be stolen after raid.
#(reset_item_probabilities,100),
#begin of changes
(party_get_slot, ":bound_town", slot_village_bound_center, "$current_town"),
(store_sub, ":item_to_price_slot", slot_town_trade_good_prices_begin, trade_goods_begin),
(reset_item_probabilities,100),
(assign, ":total_probability", 0),
(try_for_range, ":cur_goods", trade_goods_begin, trade_goods_end),
(store_add, ":cur_price_slot", ":cur_goods", ":item_to_price_slot"),
(party_get_slot, ":cur_price", ":bound_town", ":cur_price_slot"),
(call_script, "script_center_get_production", ":bound_town", ":cur_goods"),
(assign, ":cur_probability", reg0),
(call_script, "script_center_get_consumption", ":bound_town", ":cur_goods"),
(val_div, reg0, 3),
(val_add, ":cur_probability", reg0),
(val_mul, ":cur_probability", 4),
(val_mul, ":cur_probability", average_price_factor),
(val_div, ":cur_probability", ":cur_price"),
#first only simulation
#(set_item_probability_in_merchandise,":cur_goods",":cur_probability"),
(val_add, ":total_probability", ":cur_probability"),
(try_end),
(try_for_range, ":cur_goods", trade_goods_begin, trade_goods_end),
(store_add, ":cur_price_slot", ":cur_goods", ":item_to_price_slot"),
(party_get_slot, ":cur_price", ":bound_town", ":cur_price_slot"),
(call_script, "script_center_get_production", ":bound_town", ":cur_goods"),
(assign, ":cur_probability", reg0),
(call_script, "script_center_get_consumption", ":bound_town", ":cur_goods"),
(val_div, reg0, 3),
(val_add, ":cur_probability", reg0),
(val_mul, ":cur_probability", 4),
(val_mul, ":cur_probability", average_price_factor),
(val_div, ":cur_probability", ":cur_price"),
(val_mul, ":cur_probability", num_merchandise_goods),
(val_mul, ":cur_probability", 100),
(val_div, ":cur_probability", ":total_probability"),
(set_item_probability_in_merchandise,":cur_goods",":cur_probability"),
(try_end),
#end of changes
(troop_add_merchandise,"trp_temp_troop",itp_type_goods,30),
(troop_sort_inventory, "trp_temp_troop"),
(change_screen_loot, "trp_temp_troop"),
]),
],
),
(
"village_loot_defeat",mnf_scale_picture,
"Fighting with courage and determination, the villagers manage to hold together and drive off your forces.",
"none",
[
(set_background_mesh, "mesh_pic_villageriot"),
],
[
("continue",[],"Continue...",[(change_screen_return)]),
],
),
(
"village_loot_continue",0,
"Do you wish to continue looting this village?",
"none",
[],
[
("disembark_yes",[],"Yes.",[ (rest_for_hours, 3, 5, 1), #rest while attackable (3 hours will be extended by the trigger)
(change_screen_return),
]),
("disembark_no",[],"No.",[(call_script, "script_village_set_state", "$current_town", 0),
(party_set_slot, "$current_town", slot_village_raided_by, -1),
(assign, "$g_player_raiding_village", 0),
(change_screen_return)]),
],
),
(
"close",0,
"Nothing.",
"none",
[
(change_screen_return),
],
[],
),
(
"town",mnf_enable_hot_keys|mnf_scale_picture,
"{s10} {s14}^{s11}{s12}{s13}",
"none",
[
(try_begin),
(eq, "$sneaked_into_town", 1),
(call_script, "script_music_set_situation_with_culture", mtf_sit_town_infiltrate),
(else_try),
(call_script, "script_music_set_situation_with_culture", mtf_sit_travel),
(try_end),
(store_encountered_party, "$current_town"),
(call_script, "script_update_center_recon_notes", "$current_town"),
(assign, "$g_defending_against_siege", 0),
(str_clear, s3),
(party_get_battle_opponent, ":besieger_party", "$current_town"),
(store_faction_of_party, ":encountered_faction", "$g_encountered_party"),
(store_relation, ":faction_relation", ":encountered_faction", "fac_player_supporters_faction"),
(try_begin),
(gt, ":besieger_party", 0),
(ge, ":faction_relation", 0),
(store_faction_of_party, ":besieger_party_faction", ":besieger_party"),
(store_relation, ":besieger_party_relation", ":besieger_party_faction", "fac_player_supporters_faction"),
(lt, ":besieger_party_relation", 0),
(assign, "$g_defending_against_siege", 1),
(assign, "$g_siege_first_encounter", 1),
(jump_to_menu, "mnu_siege_started_defender"),
(try_end),
(try_begin),
(is_between, "$g_encountered_party", towns_begin, towns_end),
(store_sub, ":encountered_town_no", "$g_encountered_party", towns_begin),
(set_achievement_stat, ACHIEVEMENT_MIGRATING_COCONUTS, ":encountered_town_no", 1),
(assign, ":there_are_villages_not_visited", 0),
(try_for_range, ":cur_town", towns_begin, towns_end),
(store_sub, ":encountered_town_no", ":cur_town", towns_begin),
(get_achievement_stat, ":town_is_visited", ACHIEVEMENT_MIGRATING_COCONUTS, ":encountered_town_no"),
(eq, ":town_is_visited", 0),
(assign, ":there_are_villages_not_visited", 1),
(try_end),
(try_begin),
(eq, ":there_are_villages_not_visited", 0),
(unlock_achievement, ACHIEVEMENT_MIGRATING_COCONUTS),
(try_end),
(try_end),
#Quest menus
(assign, "$qst_collect_taxes_currently_collecting", 0),
(try_begin),
(gt, "$quest_auto_menu", 0),
(jump_to_menu, "$quest_auto_menu"),
(assign, "$quest_auto_menu", 0),
(try_end),
(try_begin),
## (eq, "$g_center_under_siege_battle", 1),
## (jump_to_menu,"mnu_siege_started_defender"),
## (else_try),
(eq, "$g_town_assess_trade_goods_after_rest", 1),
(assign, "$g_town_assess_trade_goods_after_rest", 0),
(jump_to_menu,"mnu_town_trade_assessment"),
(try_end),
(assign, "$talk_context", 0),
(assign,"$all_doors_locked",0),
(try_begin),
(eq, "$g_town_visit_after_rest", 1),
(assign, "$g_town_visit_after_rest", 0),
(assign, "$town_entered", 1),
(try_end),
(try_begin),
(eq,"$g_leave_town",1),
(assign,"$g_leave_town",0),
(assign,"$g_permitted_to_center",0),
(leave_encounter),
(change_screen_return),
(try_end),
(str_store_party_name, s2, "$current_town"),
(party_get_slot, ":center_lord", "$current_town", slot_town_lord),
(store_faction_of_party, ":center_faction", "$current_town"),
(str_store_faction_name, s9, ":center_faction"),
(try_begin),
(ge, ":center_lord", 0),
(str_store_troop_name,s8,":center_lord"),
(str_store_string,s7,"@{s8} of {s9}"),
(try_end),
(try_begin),
(party_slot_eq,"$current_town",slot_party_type, spt_town),
(str_store_string, s60, s2),
(party_get_slot, ":prosperity", "$current_town", slot_town_prosperity),
(try_begin),
(ge, "$cheat_mode", 1),
(assign, reg4, ":prosperity",),
(display_message, "@{!}DEBUG -- Prosperity: {reg4}"),
(try_end),
# (val_add, ":prosperity", 5),
(store_div, ":str_id", ":prosperity", 10),
(val_min, ":str_id", 9),
(val_add, ":str_id", "str_town_prosperity_0"),
(str_store_string, s10, ":str_id"),
(store_div, ":str_id", ":prosperity", 20),
(val_min, ":str_id", 4),
(val_add, ":str_id", "str_town_alt_prosperity_0"),
(str_store_string, s14, ":str_id"),
(else_try),
(str_clear, s14),
(str_store_string,s10,"@You are at {s2}."),
(try_end),
(try_begin),
(party_slot_eq,"$current_town",slot_party_type, spt_castle),
(try_begin),
(eq, ":center_lord", "trp_player"),
(str_store_string,s11,"@ Your own banner flies over the castle gate."),
(else_try),
(gt, ":center_lord", -1),
(troop_slot_eq, ":center_lord", slot_troop_spouse, "trp_player"),
(str_store_string,s11,"str__you_see_the_banner_of_your_wifehusband_s7_over_the_castle_gate"),
(else_try),
(ge, ":center_lord", 0),
(str_store_string,s11,"@ You see the banner of {s7} over the castle gate."),
(else_try),
## (str_store_string,s11,"@ This castle seems to belong to no one."),
(str_store_string,s11,"@ This castle has no garrison."),
(try_end),
(else_try),
(try_begin),
(eq, ":center_lord", "trp_player"),
(str_store_string,s11,"@ Your own banner flies over the town gates."),
(else_try),
(gt, ":center_lord", -1),
(troop_slot_eq, ":center_lord", slot_troop_spouse, "trp_player"),
(str_store_string,s11,"str__the_banner_of_your_wifehusband_s7_flies_over_the_town_gates"),
(else_try),
(ge, ":center_lord", 0),
(str_store_string,s11,"@ You see the banner of {s7} over the town gates."),
(else_try),
## (str_store_string,s11,"@ The townsfolk here have declared their independence."),
(str_store_string,s11,"@ This town has no garrison."),
(try_end),
(try_end),
(str_clear, s12),
(try_begin),
(party_slot_eq,"$current_town",slot_party_type, spt_town),
(party_get_slot, ":center_relation", "$current_town", slot_center_player_relation),
(call_script, "script_describe_center_relation_to_s3", ":center_relation"),
(assign, reg9, ":center_relation"),
(str_store_string, s12, "@{!} {s3} ({reg9})."),
(try_end),
(str_clear, s13),
(try_begin),
(gt,"$entry_to_town_forbidden",0),
(str_store_string, s13, "@ You have successfully sneaked in."),
(else_try),
(faction_slot_eq, ":center_faction", slot_faction_ai_state, sfai_feast),
(faction_slot_eq, ":center_faction", slot_faction_ai_object, "$current_town"),
(str_store_string, s13, "str__the_lord_is_currently_holding_a_feast_in_his_hall"),
(try_end),
#forbidden to enter?
(try_begin),
(store_time_of_day,reg(12)),
(ge,reg(12),5),
(lt,reg(12),21),
(assign,"$town_nighttime",0),
(else_try),
(assign,"$town_nighttime",1),
(party_slot_eq,"$current_town",slot_party_type, spt_town),
(str_store_string, s13, "str_town_nighttime"),
(try_end),
(try_begin),
(party_slot_ge, "$current_town", slot_town_has_tournament, 1),
(neg|is_currently_night),
(party_set_slot, "$current_town", slot_town_has_tournament, 1),
(str_store_string, s13, "@{s13} A tournament will be held here soon."),
(try_end),
(assign,"$castle_undefended",0),
(party_get_num_companions, ":castle_garrison_size", "p_collective_enemy"),
(try_begin),
(eq,":castle_garrison_size",0),
(assign,"$castle_undefended",1),
(try_end),
(call_script, "script_set_town_picture"),
# (str_clear, s5), #alert player that there are new rumors
# (try_begin),
# (eq, 1, 0),
# (neg|is_currently_night),
# (str_store_string, s5, "@^The buzz of excited voices as you come near the gate suggests to you that news of some import is circulating among the townsfolk."),
# (lt, "$last_town_log_entry_checked", "$num_log_entries"),
# (assign, "$g_town_rumor_log_entry", 0),
# (try_for_range, ":log_entry", "$last_town_log_entry_checked", "$num_log_entries"),
# (eq, ":log_entry", 4123), #placeholder to avoid having unused variable error message
# (try_end),
# (assign, "$last_town_log_entry_checked", "$num_log_entries"),
# (try_end),
],
[
("castle_castle",
[
(party_slot_eq,"$current_town",slot_party_type, spt_castle),
(eq, "$sneaked_into_town", 0),
(str_clear, s1),
(try_begin),
(store_faction_of_party, ":center_faction", "$current_town"),
(faction_slot_eq, ":center_faction", slot_faction_ai_state, sfai_feast),
(faction_slot_eq, ":center_faction", slot_faction_ai_object, "$current_town"),
(str_store_string, s1, "str__join_the_feast"),
(try_end),
],"Go to the Lord's hall{s1}.",
[
(try_begin),
(this_or_next|eq, "$all_doors_locked", 1),
(eq, "$sneaked_into_town", 1),
(display_message,"str_door_locked",0xFFFFAAAA),
(else_try),
(this_or_next|neq, "$players_kingdom", "$g_encountered_party_faction"),
(neg|troop_slot_ge, "trp_player", slot_troop_renown, 50),
(neg|troop_slot_ge, "trp_player", slot_troop_renown, 125),
(neq, "$g_player_eligible_feast_center_no", "$current_town"),
(faction_slot_eq, "$g_encountered_party_faction", slot_faction_ai_state, sfai_feast),
(faction_slot_eq, "$g_encountered_party_faction", slot_faction_ai_object, "$g_encountered_party"),
(neg|check_quest_active, "qst_wed_betrothed"),
(neg|check_quest_active, "qst_wed_betrothed_female"),
(neg|troop_slot_ge, "trp_player", slot_troop_spouse, active_npcs_begin), #Married players always make the cut
(jump_to_menu, "mnu_cannot_enter_court"),
(else_try),
(assign, "$town_entered", 1),
(call_script, "script_enter_court", "$current_town"),
(try_end),
], "Door to the castle."),
("join_tournament", [(neg|is_currently_night),(party_slot_ge, "$current_town", slot_town_has_tournament, 1),]
,"Join the tournament.",
[
(call_script, "script_fill_tournament_participants_troop", "$current_town", 1),
(assign, "$g_tournament_cur_tier", 0),
(assign, "$g_tournament_player_team_won", -1),
(assign, "$g_tournament_bet_placed", 0),
(assign, "$g_tournament_bet_win_amount", 0),
(assign, "$g_tournament_last_bet_tier", -1),
(assign, "$g_tournament_next_num_teams", 0),
(assign, "$g_tournament_next_team_size", 0),
(jump_to_menu, "mnu_town_tournament"),
]),
("town_castle",[
(party_slot_eq,"$current_town",slot_party_type, spt_town),
(eq,"$entry_to_town_forbidden",0),
(str_clear, s1),
(try_begin),
(store_faction_of_party, ":center_faction", "$current_town"),
(faction_slot_eq, ":center_faction", slot_faction_ai_state, sfai_feast),
(faction_slot_eq, ":center_faction", slot_faction_ai_object, "$current_town"),
(str_store_string, s1, "str__join_the_feast"),
(try_end),
],"Go to the castle{s1}.",
[
(try_begin),
(this_or_next|eq, "$all_doors_locked", 1),
(eq, "$sneaked_into_town", 1),
(display_message,"str_door_locked",0xFFFFAAAA),
(else_try),
(this_or_next|neq, "$players_kingdom", "$g_encountered_party_faction"),
(neg|troop_slot_ge, "trp_player", slot_troop_renown, 50),
(neg|troop_slot_ge, "trp_player", slot_troop_renown, 125),
(neq, "$g_player_eligible_feast_center_no", "$current_town"),
(faction_slot_eq, "$g_encountered_party_faction", slot_faction_ai_state, sfai_feast),
(faction_slot_eq, "$g_encountered_party_faction", slot_faction_ai_object, "$g_encountered_party"),
(neg|check_quest_active, "qst_wed_betrothed"),
(neg|check_quest_active, "qst_wed_betrothed_female"),
(neg|troop_slot_ge, "trp_player", slot_troop_spouse, active_npcs_begin), #Married players always make the cut
(jump_to_menu, "mnu_cannot_enter_court"),
(else_try),
(assign, "$town_entered", 1),
(call_script, "script_enter_court", "$current_town"),
(try_end),
], "Door to the castle."),
("town_center",
[
(party_slot_eq, "$current_town", slot_party_type, spt_town),
(this_or_next|eq,"$entry_to_town_forbidden",0),
(eq, "$sneaked_into_town",1)
],
"Take a walk around the streets.",
[
#If the player is fighting his or her way out
(try_begin),
(eq, "$talk_context", tc_prison_break),
(assign, "$talk_context", tc_escape),
(assign, "$g_mt_mode", tcm_escape),
(store_faction_of_party, ":town_faction", "$current_town"),
(faction_get_slot, ":tier_2_troop", ":town_faction", slot_faction_tier_3_troop),
(faction_get_slot, ":tier_3_troop", ":town_faction", slot_faction_tier_3_troop),
(faction_get_slot, ":tier_4_troop", ":town_faction", slot_faction_tier_4_troop),
(party_get_slot, ":town_scene", "$current_town", slot_town_center),
(modify_visitors_at_site, ":town_scene"),
(reset_visitors),
#ideally we could alarm troops at locations
(try_begin),
#if guards have not gone to some other important happening at nearby villages, then spawn 4 guards. (example : fire)
(party_get_slot, ":last_nearby_fire_time", "$current_town", slot_town_last_nearby_fire_time),
(store_current_hours, ":cur_time"),
(store_add, ":fire_finish_time", ":last_nearby_fire_time", fire_duration),
(neg|is_between, ":cur_time", ":last_nearby_fire_time", ":fire_finish_time"),
(store_time_of_day, ":cur_day_hour"),
(try_begin), #there are 6 guards at day time (no fire ext)
(ge, ":cur_day_hour", 6),
(lt, ":cur_day_hour", 22),
(set_visitors, 25, ":tier_2_troop", 2),
(set_visitors, 26, ":tier_2_troop", 1),
(set_visitors, 27, ":tier_3_troop", 2),
(set_visitors, 28, ":tier_4_troop", 1),
(else_try), #only 4 guards because of night
(set_visitors, 25, ":tier_2_troop", 1),
(set_visitors, 26, ":tier_2_troop", 1),
(set_visitors, 27, ":tier_3_troop", 1),
(set_visitors, 28, ":tier_4_troop", 1),
(try_end),
(else_try),
#if guards have gone to some other important happening at nearby villages, then spawn only 1 guard. (example : fire)
(store_time_of_day, ":cur_day_hour"),
(try_begin), #only 2 guard because there is a fire at one owned village
(ge, ":cur_day_hour", 6),
(lt, ":cur_day_hour", 22),
(set_visitors, 25, ":tier_2_troop", 1),
(set_visitors, 26, ":tier_2_troop", 0),
(set_visitors, 27, ":tier_3_troop", 1),
(set_visitors, 28, ":tier_4_troop", 0),
(else_try), #only 1 guard because both night and there is a fire at one owned village
(set_visitors, 25, ":tier_2_troop", 1),
(set_visitors, 26, ":tier_2_troop", 0),
(set_visitors, 27, ":tier_3_troop", 0),
(set_visitors, 28, ":tier_4_troop", 0),
(try_end),
(try_end),
(set_jump_mission,"mt_town_center"),
(jump_to_scene, ":town_scene"),
(change_screen_mission),
#If you're already at escape, then talk context will reset
(else_try),
(assign, "$talk_context", 0),
(call_script, "script_cf_enter_center_location_bandit_check"),
#All other circumstances...
(else_try),
(party_get_slot, ":town_scene", "$current_town", slot_town_center),
(modify_visitors_at_site, ":town_scene"),
(reset_visitors),
(assign, "$g_mt_mode", tcm_default),
(store_faction_of_party, ":town_faction","$current_town"),
(try_begin),
(neq, ":town_faction", "fac_player_supporters_faction"),
(faction_get_slot, ":troop_prison_guard", "$g_encountered_party_faction", slot_faction_prison_guard_troop),
(faction_get_slot, ":troop_castle_guard", "$g_encountered_party_faction", slot_faction_castle_guard_troop),
(faction_get_slot, ":tier_2_troop", ":town_faction", slot_faction_tier_2_troop),
(faction_get_slot, ":tier_3_troop", ":town_faction", slot_faction_tier_3_troop),
(else_try),
(party_get_slot, ":town_original_faction", "$current_town", slot_center_original_faction),
(faction_get_slot, ":troop_prison_guard", ":town_original_faction", slot_faction_prison_guard_troop),
(faction_get_slot, ":troop_castle_guard", ":town_original_faction", slot_faction_castle_guard_troop),
(faction_get_slot, ":tier_2_troop", ":town_original_faction", slot_faction_tier_2_troop),
(faction_get_slot, ":tier_3_troop", ":town_original_faction", slot_faction_tier_3_troop),
(try_end),
(try_begin), #think about this, should castle guard have to go nearby fire too? If he do not go, killing 2 armored guard is too hard for player. For now he goes too.
#if guards have not gone to some other important happening at nearby villages, then spawn 4 guards. (example : fire)
(party_get_slot, ":last_nearby_fire_time", "$current_town", slot_town_last_nearby_fire_time),
(store_current_hours, ":cur_time"),
(store_add, ":fire_finish_time", ":last_nearby_fire_time", fire_duration),
(neg|is_between, ":cur_time", ":last_nearby_fire_time", ":fire_finish_time"),
(set_visitor, 23, ":troop_castle_guard"),
(try_end),
(set_visitor, 24, ":troop_prison_guard"),
(try_begin),
(gt,":tier_2_troop", 0),
(assign,reg0,":tier_3_troop"),
(assign,reg1,":tier_3_troop"),
(assign,reg2,":tier_2_troop"),
(assign,reg3,":tier_2_troop"),
(else_try),
(assign,reg0,"trp_vaegir_infantry"),
(assign,reg1,"trp_vaegir_infantry"),
(assign,reg2,"trp_vaegir_archer"),
(assign,reg3,"trp_vaegir_footman"),
(try_end),
(shuffle_range,0,4),
(try_begin),
#if guards have not gone to some other important happening at nearby villages, then spawn 4 guards. (example : fire)
(party_get_slot, ":last_nearby_fire_time", "$current_town", slot_town_last_nearby_fire_time),
(store_current_hours, ":cur_time"),
(store_add, ":fire_finish_time", ":last_nearby_fire_time", fire_duration),
(neg|is_between, ":cur_time", ":last_nearby_fire_time", ":fire_finish_time"),
(set_visitor,25,reg0),
(set_visitor,26,reg1),
(set_visitor,27,reg2),
(set_visitor,28,reg3),
(try_end),
(party_get_slot, ":spawned_troop", "$current_town", slot_town_armorer),
(set_visitor, 9, ":spawned_troop"),
(party_get_slot, ":spawned_troop", "$current_town", slot_town_weaponsmith),
(set_visitor, 10, ":spawned_troop"),
(party_get_slot, ":spawned_troop", "$current_town", slot_town_elder),
(set_visitor, 11, ":spawned_troop"),
(party_get_slot, ":spawned_troop", "$current_town", slot_town_horse_merchant),
(set_visitor, 12, ":spawned_troop"),
(call_script, "script_init_town_walkers"),
(set_jump_mission,"mt_town_center"),
(assign, ":override_state", af_override_horse),
(try_begin),
(eq, "$sneaked_into_town", 1), #setup disguise
(assign, ":override_state", af_override_all),
(try_end),
(mission_tpl_entry_set_override_flags, "mt_town_center", 0, ":override_state"),
(mission_tpl_entry_set_override_flags, "mt_town_center", 2, ":override_state"),
(mission_tpl_entry_set_override_flags, "mt_town_center", 3, ":override_state"),
(mission_tpl_entry_set_override_flags, "mt_town_center", 4, ":override_state"),
(mission_tpl_entry_set_override_flags, "mt_town_center", 5, ":override_state"),
(mission_tpl_entry_set_override_flags, "mt_town_center", 6, ":override_state"),
(mission_tpl_entry_set_override_flags, "mt_town_center", 7, ":override_state"),
(try_begin),
(eq, "$town_entered", 0),
(assign, "$town_entered", 1),
(eq, "$town_nighttime", 0),
(set_jump_entry, 1),
(try_end),
(jump_to_scene, ":town_scene"),
(change_screen_mission),
(try_end),
],"Door to the town center."),
("town_tavern",[
(party_slot_eq,"$current_town",slot_party_type, spt_town),
(this_or_next|eq,"$entry_to_town_forbidden",0),
(eq, "$sneaked_into_town",1),
# (party_get_slot, ":scene", "$current_town", slot_town_tavern),
# (scene_slot_eq, ":scene", slot_scene_visited, 1), #check if scene has been visited before to allow entry from menu. Otherwise scene will only be accessible from the town center.
]
,"Visit the tavern.",
[
(try_begin),
(eq,"$all_doors_locked",1),
(display_message,"str_door_locked",0xFFFFAAAA),
(else_try),
(call_script, "script_cf_enter_center_location_bandit_check"),
(else_try),
(assign, "$town_entered", 1),
(set_jump_mission, "mt_town_default"),
(mission_tpl_entry_set_override_flags, "mt_town_default", 0, af_override_horse),
(try_begin),
(eq, "$sneaked_into_town",1),
(mission_tpl_entry_set_override_flags, "mt_town_default", 0, af_override_all),
(try_end),
(party_get_slot, ":cur_scene", "$current_town", slot_town_tavern),
(jump_to_scene, ":cur_scene"),
(scene_set_slot, ":cur_scene", slot_scene_visited, 1),
(assign, "$talk_context", tc_tavern_talk),
(call_script, "script_initialize_tavern_variables"),
(store_random_in_range, ":randomize_attacker_placement", 0, 4),
(modify_visitors_at_site, ":cur_scene"),
(reset_visitors),
(assign, ":cur_entry", 17),
#this is just a cheat right now
#(troop_set_slot, "trp_belligerent_drunk", slot_troop_cur_center, "$g_encountered_party"),
(try_begin),
(eq, "$cheat_mode", 1),
(troop_get_slot, ":drunk_location", "trp_belligerent_drunk", slot_troop_cur_center),
(try_begin),
(eq, "$cheat_mode", 0),
(else_try),
(is_between, ":drunk_location", centers_begin, centers_end),
(str_store_party_name, s4, ":drunk_location"),
(display_message, "str_belligerent_drunk_in_s4"),
(else_try),
(display_message, "str_belligerent_drunk_not_found"),
(try_end),
(troop_get_slot, ":promoter_location", "trp_fight_promoter", slot_troop_cur_center),
(try_begin),
(eq, "$cheat_mode", 0),
(else_try),
(is_between, ":promoter_location", centers_begin, centers_end),
(str_store_party_name, s4, ":promoter_location"),
(display_message, "str_roughlooking_character_in_s4"),
(else_try),
(display_message, "str_roughlooking_character_not_found"),
(try_end),
(try_end),
#this determines whether or not a lord who dislikes you will commission an assassin
(try_begin),
(store_current_hours, ":hours"),
(store_sub, ":hours_since_last_attempt", ":hours", "$g_last_assassination_attempt_time"),
(gt, ":hours_since_last_attempt", 168),
(try_for_range, ":lord", active_npcs_begin, active_npcs_end),
(troop_slot_eq, ":lord", slot_lord_reputation_type, lrep_debauched),
(troop_get_slot, ":led_party", ":lord", slot_troop_leaded_party),
(party_is_active, ":led_party"),
(party_get_attached_to, ":led_party_attached", ":led_party"),
(eq, ":led_party_attached", "$g_encountered_party"),
(call_script, "script_troop_get_relation_with_troop", "trp_player", ":lord"),
(lt, reg0, -20),
(assign, "$g_last_assassination_attempt_time", ":hours"),
# (assign, "$g_last_assassination_attempt_location", "$g_encountered_party"),
# (assign, "$g_last_assassination_attempt_perpetrator", ":lord"),
(troop_set_slot, "trp_hired_assassin", slot_troop_cur_center, "$g_encountered_party"),
(try_end),
(try_end),
(try_begin),
(eq, ":randomize_attacker_placement", 0),
(call_script, "script_setup_tavern_attacker", ":cur_entry"),
(val_add, ":cur_entry", 1),
(try_end),
(try_begin),
(eq, 1, 0),
(troop_slot_eq, "trp_fight_promoter", slot_troop_cur_center, "$current_town"),
(set_visitor, ":cur_entry", "trp_fight_promoter"),
(val_add, ":cur_entry", 1),
(try_end),
(party_get_slot, ":mercenary_troop", "$current_town", slot_center_mercenary_troop_type),
(party_get_slot, ":mercenary_amount", "$current_town", slot_center_mercenary_troop_amount),
(try_begin),
(gt, ":mercenary_troop", 0),
(gt, ":mercenary_amount", 0),
(set_visitor, ":cur_entry", ":mercenary_troop"),
(val_add, ":cur_entry", 1),
(try_end),
(try_begin),
(eq, ":randomize_attacker_placement", 1),
(call_script, "script_setup_tavern_attacker", ":cur_entry"),
(val_add, ":cur_entry", 1),
(try_end),
(try_for_range, ":companion_candidate", companions_begin, companions_end),
(troop_slot_eq, ":companion_candidate", slot_troop_occupation, 0),
(troop_slot_eq, ":companion_candidate", slot_troop_cur_center, "$current_town"),
(neg|troop_slot_ge, ":companion_candidate", slot_troop_prisoner_of_party, centers_begin),
(set_visitor, ":cur_entry", ":companion_candidate"),
(val_add, ":cur_entry", 1),
(try_end),
(try_begin),
(eq, ":randomize_attacker_placement", 2),
(call_script, "script_setup_tavern_attacker", ":cur_entry"),
(val_add, ":cur_entry", 1),
(try_end),
(try_begin), #this doubles the incidence of ransom brokers and (below) minstrels
(party_get_slot, ":ransom_broker", "$current_town", slot_center_ransom_broker),
(gt, ":ransom_broker", 0),
(assign, reg0, ":ransom_broker"),
(assign, reg1, "$current_town"),
(set_visitor, ":cur_entry", ":ransom_broker"),
(val_add, ":cur_entry", 1),
(else_try),
(is_between, "$g_talk_troop", ransom_brokers_begin, ransom_brokers_end),
(store_add, ":alternative_town", "$current_town", 9),
(try_begin),
(ge, ":alternative_town", towns_end),
(val_sub, ":alternative_town", 22),
(try_end),
(try_begin),
(eq, "$cheat_mode", 1),
(str_store_party_name, s3, "$current_town"),
(str_store_party_name, s4, ":alternative_town"),
(display_message, "@{!}DEBUG - Current town is {s3}, but also checking {s4}"),
(try_end),
(party_get_slot, ":ransom_broker", ":alternative_town", slot_center_ransom_broker),
(gt, ":ransom_broker", 0),
(set_visitor, ":cur_entry", ":ransom_broker"),
(val_add, ":cur_entry", 1),
(try_end),
(try_begin),
(party_get_slot, ":tavern_traveler", "$current_town", slot_center_tavern_traveler),
(gt, ":tavern_traveler", 0),
(set_visitor, ":cur_entry", ":tavern_traveler"),
(val_add, ":cur_entry", 1),
(try_end),
(try_begin),
(party_get_slot, ":tavern_minstrel", "$current_town", slot_center_tavern_minstrel),
(gt, ":tavern_minstrel", 0),
(set_visitor, ":cur_entry", ":tavern_minstrel"),
(val_add, ":cur_entry", 1),
(else_try),
(store_add, ":alternative_town", "$current_town", 9),
(try_begin),
(ge, ":alternative_town", towns_end),
(val_sub, ":alternative_town", 22),
(try_end),
(party_get_slot, ":tavern_minstrel", ":alternative_town", slot_center_tavern_minstrel),
(gt, ":tavern_minstrel", 0),
(set_visitor, ":cur_entry", ":tavern_minstrel"),
(val_add, ":cur_entry", 1),
(try_end),
(try_begin),
(party_get_slot, ":tavern_bookseller", "$current_town", slot_center_tavern_bookseller),
(gt, ":tavern_bookseller", 0),
(set_visitor, ":cur_entry", ":tavern_bookseller"),
(val_add, ":cur_entry", 1),
(try_end),
(try_begin),
(eq, ":randomize_attacker_placement", 3),
(call_script, "script_setup_tavern_attacker", ":cur_entry"),
(val_add, ":cur_entry", 1),
(try_end),
(try_begin),
(neg|check_quest_active, "qst_eliminate_bandits_infesting_village"),
(neg|check_quest_active, "qst_deal_with_bandits_at_lords_village"),
(assign, ":end_cond", villages_end),
(try_for_range, ":cur_village", villages_begin, ":end_cond"),
(party_slot_eq, ":cur_village", slot_village_bound_center, "$current_town"),
(party_slot_ge, ":cur_village", slot_village_infested_by_bandits, 1),
(neg|party_slot_eq, ":cur_village", slot_town_lord, "trp_player"),
(set_visitor, ":cur_entry", "trp_farmer_from_bandit_village"),
(val_add, ":cur_entry", 1),
(assign, ":end_cond", 0),
(try_end),
(try_end),
(try_begin),
(eq, "$g_starting_town", "$current_town"),
(this_or_next|neg|check_quest_finished, "qst_collect_men"),
(this_or_next|neg|check_quest_finished, "qst_learn_where_merchant_brother_is"),
(this_or_next|neg|check_quest_finished, "qst_save_relative_of_merchant"),
(this_or_next|neg|check_quest_finished, "qst_save_town_from_bandits"),
(eq, "$g_do_one_more_meeting_with_merchant", 1),
(assign, ":troop_of_merchant", 0),
(try_begin),
(eq, "$g_encountered_party_faction", "fac_kingdom_7"),
(assign, ":troop_of_merchant", "trp_swadian_merchant"),
(else_try),
(eq, "$g_encountered_party_faction", "fac_kingdom_7"),
(assign, ":troop_of_merchant", "trp_vaegir_merchant"),
(else_try),
(eq, "$g_encountered_party_faction", "fac_kingdom_7"),
(assign, ":troop_of_merchant", "trp_khergit_merchant"),
(else_try),
(eq, "$g_encountered_party_faction", "fac_kingdom_7"),
(assign, ":troop_of_merchant", "trp_nord_merchant"),
(else_try),
(eq, "$g_encountered_party_faction", "fac_kingdom_7"),
(assign, ":troop_of_merchant", "trp_rhodok_merchant"),
(else_try),
(eq, "$g_encountered_party_faction", "fac_kingdom_7"),
(assign, ":troop_of_merchant", "trp_sarranid_merchant"),
(try_end),
(gt, ":troop_of_merchant", 0),
(set_visitor, ":cur_entry", ":troop_of_merchant"),
(val_add, ":cur_entry", 1),
(try_end),
(change_screen_mission),
(try_end),
],"Door to the tavern."),
# ("town_smithy",[
# (eq,"$entry_to_town_forbidden",0),
# (eq,"$town_nighttime",0),
# ],
# "Visit the smithy.",
# [
# (set_jump_mission,"mt_town_default"),
# (jump_to_scene,"$pout_scn_smithy"),
# (change_screen_mission,0),
# ]),
("town_merchant",
[(party_slot_eq,"$current_town",slot_party_type, spt_town),
(eq, 1, 0),
(eq,"$town_nighttime",0),
(this_or_next|eq,"$entry_to_town_forbidden",0),
(eq, "$sneaked_into_town",1),
# (party_get_slot, ":scene", "$current_town", slot_town_store),
# (scene_slot_eq, ":scene", slot_scene_visited, 1), #check if scene has been visited before to allow entry from menu. Otherwise scene will only be accessible from the town center.
],
"Speak with the merchant.",
[
(try_begin),
(this_or_next|eq,"$all_doors_locked",1),
(eq,"$town_nighttime",1),
(display_message,"str_door_locked",0xFFFFAAAA),
(else_try),
(assign, "$town_entered", 1),
(set_jump_mission, "mt_town_default"),
(mission_tpl_entry_set_override_flags, "mt_town_default", 0, af_override_horse),
(try_begin),
(eq, "$sneaked_into_town",1),
(mission_tpl_entry_set_override_flags, "mt_town_default", 0, af_override_all),
(try_end),
(party_get_slot, ":cur_scene", "$current_town", slot_town_store),
(jump_to_scene, ":cur_scene"),
(scene_set_slot, ":cur_scene", slot_scene_visited, 1),
(change_screen_mission),
(try_end),
],"Door to the shop."),
("town_arena",
[(party_slot_eq,"$current_town",slot_party_type, spt_town),
(eq, "$sneaked_into_town", 0),
# (party_get_slot, ":scene", "$current_town", slot_town_arena),
# (scene_slot_eq, ":scene", slot_scene_visited, 1), #check if scene has been visited before to allow entry from menu. Otherwise scene will only be accessible from the town center.
],
"Enter the arena.",
[
(try_begin),
(this_or_next|eq,"$all_doors_locked",1),
(eq,"$town_nighttime",1),
(display_message,"str_door_locked",0xFFFFAAAA),
(else_try),
(assign, "$g_mt_mode", abm_visit),
(assign, "$town_entered", 1),
(set_jump_mission, "mt_arena_melee_fight"),
(party_get_slot, ":arena_scene", "$current_town", slot_town_arena),
(modify_visitors_at_site, ":arena_scene"),
(reset_visitors),
(set_visitor, 43, "trp_veteran_fighter"),
(set_visitor, 44, "trp_hired_blade"),
(set_jump_entry, 50),
(jump_to_scene, ":arena_scene"),
(scene_set_slot, ":arena_scene", slot_scene_visited, 1),
(change_screen_mission),
(try_end),
],"Door to the arena."),
("town_dungeon",
[(eq, 1, 0)],
"Never: Enter the prison.",
[
(try_begin),
(eq, "$talk_context", tc_prison_break),
(gt, "$g_main_attacker_agent", 0),
(neg|agent_is_alive, "$g_main_attacker_agent"),
(agent_get_troop_id, ":agent_type", "$g_main_attacker_agent"),
(try_begin),
(eq, "$g_encountered_party_faction", "fac_player_supporters_faction"),
(party_get_slot, ":prison_guard_faction", "$current_town", slot_center_original_faction),
(else_try),
(assign, ":prison_guard_faction", "$g_encountered_party_faction"),
(try_end),
(faction_slot_eq, ":prison_guard_faction", slot_faction_prison_guard_troop, ":agent_type"),
(call_script, "script_deduct_casualties_from_garrison"),
(call_script, "script_enter_dungeon", "$current_town", "mt_visit_town_castle"),
(else_try),
(eq,"$all_doors_locked",1),
(display_message,"str_door_locked",0xFFFFAAAA),
(else_try),
(this_or_next|party_slot_eq, "$current_town", slot_town_lord, "trp_player"),
(eq, "$g_encountered_party_faction", "$players_kingdom"),
(assign, "$town_entered", 1),
(call_script, "script_enter_dungeon", "$current_town", "mt_visit_town_castle"),
(else_try),
(display_message,"str_door_locked",0xFFFFAAAA),
(try_end),
],"Door to the dungeon."),
("castle_inspect",
[
(party_slot_eq,"$current_town",slot_party_type, spt_castle),
],
"Take a walk around the courtyard.",
[
(try_begin),
(eq, "$talk_context", tc_prison_break),
(assign, "$talk_context", tc_escape),
(party_get_slot, ":cur_castle_exterior", "$current_town", slot_castle_exterior),
(modify_visitors_at_site, ":cur_castle_exterior"),
(reset_visitors),
(assign, ":guard_no", 40),
(party_get_num_companion_stacks, ":num_stacks", "$g_encountered_party"),
(try_for_range, ":troop_iterator", 0, ":num_stacks"),
#nearby fire condition start
(party_get_slot, ":last_nearby_fire_time", "$current_town", slot_town_last_nearby_fire_time),
(store_current_hours, ":cur_time"),
(store_add, ":fire_finish_time", ":last_nearby_fire_time", fire_duration),
(this_or_next|eq, ":guard_no", 40),
(neg|is_between, ":cur_time", ":last_nearby_fire_time", ":fire_finish_time"),
#nearby fire condition end
(lt, ":guard_no", 47),
(party_stack_get_troop_id, ":cur_troop_id", "$g_encountered_party", ":troop_iterator"),
(neg|troop_is_hero, ":cur_troop_id"),
(party_stack_get_size, ":stack_size","$g_encountered_party",":troop_iterator"),
(party_stack_get_num_wounded, ":num_wounded","$g_encountered_party",":troop_iterator"),
(val_sub, ":stack_size", ":num_wounded"),
(gt, ":stack_size", 0),
(party_stack_get_troop_dna,":troop_dna", "$g_encountered_party", ":troop_iterator"),
(set_visitor, ":guard_no", ":cur_troop_id", ":troop_dna"),
(val_add, ":guard_no", 1),
(try_end),
#(set_jump_entry, 1),
(set_visitor, 7, "$g_player_troop"),
(set_jump_mission,"mt_castle_visit"),
(jump_to_scene, ":cur_castle_exterior"),
(change_screen_mission),
#If you're already at escape, then talk context will reset
(else_try),
(assign, "$talk_context", tc_town_talk),
(assign, "$g_mt_mode", tcm_default),
(party_get_slot, ":cur_castle_exterior", "$current_town", slot_castle_exterior),
(modify_visitors_at_site,":cur_castle_exterior"),
(reset_visitors),
(try_begin),
(neq, "$g_encountered_party_faction", "fac_player_supporters_faction"),
(faction_get_slot, ":troop_prison_guard", "$g_encountered_party_faction", slot_faction_prison_guard_troop),
(else_try),
(party_get_slot, ":town_original_faction", "$current_town", slot_center_original_faction),
(faction_get_slot, ":troop_prison_guard", ":town_original_faction", slot_faction_prison_guard_troop),
(try_end),
(set_visitor, 24, ":troop_prison_guard"),
(assign, ":guard_no", 40),
(party_get_num_companion_stacks, ":num_stacks", "$g_encountered_party"),
(try_for_range, ":troop_iterator", 0, ":num_stacks"),
#nearby fire condition start
(party_get_slot, ":last_nearby_fire_time", "$current_town", slot_town_last_nearby_fire_time),
(store_current_hours, ":cur_time"),
(store_add, ":fire_finish_time", ":last_nearby_fire_time", fire_duration),
(neg|is_between, ":cur_time", ":fire_finish_time", ":last_nearby_fire_time"),
(lt, ":guard_no", 47),
(party_stack_get_troop_id, ":cur_troop_id", "$g_encountered_party", ":troop_iterator"),
(neg|troop_is_hero, ":cur_troop_id"),
(party_stack_get_size, ":stack_size","$g_encountered_party",":troop_iterator"),
(party_stack_get_num_wounded, ":num_wounded","$g_encountered_party",":troop_iterator"),
(val_sub, ":stack_size", ":num_wounded"),
(gt, ":stack_size", 0),
(party_stack_get_troop_dna,":troop_dna","$g_encountered_party",":troop_iterator"),
(set_visitor, ":guard_no", ":cur_troop_id", ":troop_dna"),
(val_add, ":guard_no", 1),
(try_end),
(try_begin),
(eq, "$town_entered", 0),
(assign, "$town_entered", 1),
(try_end),
(set_jump_entry, 1),
(assign, ":override_state", af_override_horse),
(try_begin),
(eq, "$sneaked_into_town", 1), #setup disguise
(assign, ":override_state", af_override_all),
(try_end),
(set_jump_mission, "mt_castle_visit"),
(mission_tpl_entry_set_override_flags, "mt_castle_visit", 0, ":override_state"),
(mission_tpl_entry_set_override_flags, "mt_castle_visit", 1, ":override_state"),
(mission_tpl_entry_set_override_flags, "mt_castle_visit", 2, ":override_state"),
(mission_tpl_entry_set_override_flags, "mt_castle_visit", 3, ":override_state"),
(mission_tpl_entry_set_override_flags, "mt_castle_visit", 4, ":override_state"),
(mission_tpl_entry_set_override_flags, "mt_castle_visit", 5, ":override_state"),
(mission_tpl_entry_set_override_flags, "mt_castle_visit", 6, ":override_state"),
(mission_tpl_entry_set_override_flags, "mt_castle_visit", 7, ":override_state"),
(jump_to_scene, ":cur_castle_exterior"),
(change_screen_mission),
(try_end),
], "To the castle courtyard."),
("town_enterprise",
[
(party_slot_eq,"$current_town",slot_party_type, spt_town),
(party_get_slot, ":item_produced", "$current_town", slot_center_player_enterprise),
(gt, ":item_produced", 1),
(eq,"$entry_to_town_forbidden",0),
(call_script, "script_get_enterprise_name", ":item_produced"),
(str_store_string, s3, reg0),
],
"Visit your {s3}.",
[
(store_sub, ":town_order", "$current_town", towns_begin),
(store_add, ":master_craftsman", "trp_town_1_master_craftsman", ":town_order"),
(party_get_slot, ":item_produced", "$current_town", slot_center_player_enterprise),
(assign, ":enterprise_scene", "scn_enterprise_mill"),
(try_begin),
(eq, ":item_produced", "itm_bread"),
(assign, ":enterprise_scene", "scn_enterprise_mill"),
(else_try),
(eq, ":item_produced", "itm_ale"),
(assign, ":enterprise_scene", "scn_enterprise_brewery"),
(else_try),
(eq, ":item_produced", "itm_oil"),
(assign, ":enterprise_scene", "scn_enterprise_oil_press"),
(else_try),
(eq, ":item_produced", "itm_wine"),
(assign, ":enterprise_scene", "scn_enterprise_winery"),
(else_try),
(eq, ":item_produced", "itm_leatherwork"),
(assign, ":enterprise_scene", "scn_enterprise_tannery"),
(else_try),
(eq, ":item_produced", "itm_wool_cloth"),
(assign, ":enterprise_scene", "scn_enterprise_wool_weavery"),
(else_try),
(eq, ":item_produced", "itm_linen"),
(assign, ":enterprise_scene", "scn_enterprise_linen_weavery"),
(else_try),
(eq, ":item_produced", "itm_velvet"),
(assign, ":enterprise_scene", "scn_enterprise_dyeworks"),
(else_try),
(eq, ":item_produced", "itm_tools"),
(assign, ":enterprise_scene", "scn_enterprise_smithy"),
(try_end),
(modify_visitors_at_site,":enterprise_scene"),
(reset_visitors),
(set_visitor,0,"trp_player"),
(set_visitor,17,":master_craftsman"),
(set_jump_mission,"mt_town_default"),
(jump_to_scene,":enterprise_scene"),
(change_screen_mission),
],"Door to your enterprise."),
("visit_lady",
[
(neg|troop_slot_ge, "trp_player", slot_troop_spouse, kingdom_ladies_begin),
(assign, "$love_interest_in_town", 0),
(assign, "$love_interest_in_town_2", 0),
(assign, "$love_interest_in_town_3", 0),
(assign, "$love_interest_in_town_4", 0),
(assign, "$love_interest_in_town_5", 0),
(assign, "$love_interest_in_town_6", 0),
(assign, "$love_interest_in_town_7", 0),
(assign, "$love_interest_in_town_8", 0),
(try_for_range, ":lady_no", kingdom_ladies_begin, kingdom_ladies_end),
(troop_slot_eq, ":lady_no", slot_troop_cur_center, "$current_town"),
(call_script, "script_get_kingdom_lady_social_determinants", ":lady_no"),
(assign, ":lady_guardian", reg0),
(troop_slot_eq, ":lady_no", slot_troop_spouse, -1),
(ge, ":lady_guardian", 0), #not sure when this would not be the case
#must have spoken to either father or lady
(this_or_next|troop_slot_ge, ":lady_no", slot_troop_met, 2),
(troop_slot_eq, ":lady_guardian", slot_lord_granted_courtship_permission, 1),
(neg|troop_slot_eq, ":lady_no", slot_troop_met, 4),
#must have approached father
# (this_or_next|troop_slot_eq, ":lady_guardian", slot_lord_granted_courtship_permission, 1),
# (troop_slot_eq, ":lady_guardian", slot_lord_granted_courtship_permission, -1),
(try_begin),
(eq, "$love_interest_in_town", 0),
(assign, "$love_interest_in_town", ":lady_no"),
(else_try),
(eq, "$love_interest_in_town_2", 0),
(assign, "$love_interest_in_town_2", ":lady_no"),
(else_try),
(eq, "$love_interest_in_town_3", 0),
(assign, "$love_interest_in_town_3", ":lady_no"),
(else_try),
(eq, "$love_interest_in_town_4", 0),
(assign, "$love_interest_in_town_4", ":lady_no"),
(else_try),
(eq, "$love_interest_in_town_5", 0),
(assign, "$love_interest_in_town_5", ":lady_no"),
(else_try),
(eq, "$love_interest_in_town_6", 0),
(assign, "$love_interest_in_town_6", ":lady_no"),
(else_try),
(eq, "$love_interest_in_town_7", 0),
(assign, "$love_interest_in_town_7", ":lady_no"),
(else_try),
(eq, "$love_interest_in_town_8", 0),
(assign, "$love_interest_in_town_8", ":lady_no"),
(try_end),
(try_end),
(gt, "$love_interest_in_town", 0),
],
"Attempt to visit a lady",
[
(jump_to_menu, "mnu_lady_visit"),
], "Door to the garden."),
("trade_with_merchants",
[
(party_slot_eq,"$current_town",slot_party_type, spt_town)
],
"Go to the marketplace.",
[
(try_begin),
(call_script, "script_cf_enter_center_location_bandit_check"),
(else_try),
(jump_to_menu,"mnu_town_trade"),
(try_end),
]),
("walled_center_manage",
[
(neg|party_slot_eq, "$current_town", slot_village_state, svs_under_siege),
(party_slot_eq, "$current_town", slot_town_lord, "trp_player"),
(assign, reg0, 1),
(try_begin),
(party_slot_eq, "$current_town", slot_party_type, spt_castle),
(assign, reg0, 0),
(try_end),
],
"Manage this {reg0?town:castle}.",
[
(assign, "$g_next_menu", "mnu_town"),
(jump_to_menu, "mnu_center_manage"),
]),
("walled_center_move_court",
[
(neg|party_slot_eq, "$current_town", slot_village_state, svs_under_siege),
(faction_slot_eq, "fac_player_supporters_faction", slot_faction_leader, "trp_player"),
(party_slot_eq, "$current_town", slot_town_lord, "trp_player"),
(eq, "$g_encountered_party_faction", "fac_player_supporters_faction"),
(neq, "$g_player_court", "$current_town"),
],
"Move your court here.",
[
(jump_to_menu, "mnu_establish_court"),
]),
("castle_station_troops",
[
(party_get_slot, ":town_lord", "$current_town", slot_town_lord),
(str_clear, s10),
(assign, ":player_can_draw_from_garrison", 0),
(try_begin), #option 1 - player is town lord
(eq, ":town_lord", "trp_player"),
(assign, ":player_can_draw_from_garrison", 1),
(else_try), #option 2 - town is unassigned and part of the player faction
(store_faction_of_party, ":faction", "$g_encountered_party"),
(eq, ":faction", "fac_player_supporters_faction"),
(neg|party_slot_ge, "$g_encountered_party", slot_town_lord, active_npcs_begin), #ie, zero or -1
(assign, ":player_can_draw_from_garrison", 1),
(else_try), #option 3 - town was captured by player
(lt, ":town_lord", 0), #ie, unassigned
(store_faction_of_party, ":castle_faction", "$g_encountered_party"),
(eq, "$players_kingdom", ":castle_faction"),
(eq, "$g_encountered_party", "$g_castle_requested_by_player"),
(str_store_string, s10, "str_retrieve_garrison_warning"),
(assign, ":player_can_draw_from_garrison", 1),
(else_try),
(lt, ":town_lord", 0), #ie, unassigned
(store_faction_of_party, ":castle_faction", "$g_encountered_party"),
(eq, "$players_kingdom", ":castle_faction"),
(store_party_size_wo_prisoners, ":party_size", "$g_encountered_party"),
(eq, ":party_size", 0),
(str_store_string, s10, "str_retrieve_garrison_warning"),
(assign, ":player_can_draw_from_garrison", 1),
(else_try),
(party_slot_ge, "$g_encountered_party", slot_town_lord, active_npcs_begin),
(store_faction_of_party, ":castle_faction", "$g_encountered_party"),
(eq, "$players_kingdom", ":castle_faction"),
(troop_slot_eq, "trp_player", slot_troop_spouse, ":town_lord"),
(assign, ":player_can_draw_from_garrison", 1),
(try_end),
(eq, ":player_can_draw_from_garrison", 1),
],
"Manage the garrison {s10}",
[
(change_screen_exchange_members,1),
]),
("castle_wait",
[
#(party_slot_eq,"$current_town",slot_party_type, spt_castle),
(this_or_next|ge, "$g_encountered_party_relation", 0),
(eq,"$castle_undefended",1),
(assign, ":can_rest", 1),
(str_clear, s1),
(try_begin),
(neg|party_slot_eq, "$current_town", slot_town_lord, "trp_player"),
(troop_get_slot, ":player_spouse", "trp_player", slot_troop_spouse),
(neg|party_slot_eq, "$current_town", slot_town_lord, ":player_spouse"),
(party_slot_ge, "$current_town", slot_town_lord, "trp_player"), #can rest for free in castles and towns with unassigned lords
(store_faction_of_party, ":current_town_faction", "$current_town"),
(neq, ":current_town_faction", "fac_player_supporters_faction"),
(party_get_num_companions, ":num_men", "p_main_party"),
(store_div, reg1, ":num_men", 4),
(val_add, reg1, 1),
(str_store_string, s1, "@ ({reg1} denars per night)"),
(store_troop_gold, ":gold", "trp_player"),
(lt, ":gold", reg1),
(assign, ":can_rest", 0),
(try_end),
(eq, ":can_rest", 1),
],
"Wait here for some time{s1}.",
[
(assign, "$auto_enter_town", "$current_town"),
(assign, "$g_town_visit_after_rest", 1),
(assign, "$g_last_rest_center", "$current_town"),
(assign, "$g_last_rest_payment_until", -1),
(try_begin),
(party_is_active, "p_main_party"),
(party_get_current_terrain, ":cur_terrain", "p_main_party"),
(try_begin),
(eq, ":cur_terrain", rt_desert),
(unlock_achievement, ACHIEVEMENT_SARRANIDIAN_NIGHTS),
(try_end),
(try_end),
(rest_for_hours_interactive, 24 * 7, 5, 0), #rest while not attackable
(change_screen_return),
]),
## ("rest_until_morning",
## [
## (this_or_next|ge, "$g_encountered_party_relation", 0),
## (eq,"$castle_undefended",1),
## (store_time_of_day,reg(1)),(neg|is_between,reg(1), 5, 18),
## (eq, "$g_defending_against_siege", 0),
## ],
## "Rest until morning.",
## [
## (store_time_of_day,reg(1)),
## (assign, reg(2), 30),
## (val_sub,reg(2),reg(1)),
## (val_mod,reg(2),24),
## (assign,"$auto_enter_town","$current_town"),
## (assign, "$g_town_visit_after_rest", 1),
## (rest_for_hours_interactive, reg(2)),
## (change_screen_return),
## ]),
##
## ("rest_until_evening",
## [
## (this_or_next|ge, "$g_encountered_party_relation", 0),
## (eq,"$castle_undefended",1),
## (store_time_of_day,reg(1)), (is_between,reg(1), 5, 18),
## (eq, "$g_defending_against_siege", 0),
## ],
## "Rest until evening.",
## [
## (store_time_of_day,reg(1)),
## (assign, reg(2), 20),
## (val_sub,reg(2),reg(1)),
## (assign,"$auto_enter_town","$current_town"),
## (assign, "$g_town_visit_after_rest", 1),
## (rest_for_hours_interactive, reg(2)),
## (change_screen_return),
## ]),
("town_alley",
[
(party_slot_eq,"$current_town",slot_party_type, spt_town),
(eq, "$cheat_mode", 1),
],
"{!}CHEAT: Go to the alley.",
[
(party_get_slot, reg11, "$current_town", slot_town_alley),
(set_jump_mission, "mt_ai_training"),
(jump_to_scene, reg11),
(change_screen_mission),
]),
("collect_taxes_qst",
[
(check_quest_active, "qst_collect_taxes"),
(quest_slot_eq, "qst_collect_taxes", slot_quest_target_center, "$current_town"),
(neg|quest_slot_eq, "qst_collect_taxes", slot_quest_current_state, 4),
(quest_get_slot, ":quest_giver_troop", "qst_collect_taxes", slot_quest_giver_troop),
(str_store_troop_name, s1, ":quest_giver_troop"),
(quest_get_slot, reg5, "qst_collect_taxes", slot_quest_current_state),
],
"{reg5?Continue collecting taxes:Collect taxes} due to {s1}.",
[
(jump_to_menu, "mnu_collect_taxes"),
]),
("town_leave",[],"Leave...",
[
(assign, "$g_permitted_to_center",0),
(change_screen_return,0),
],"Leave Area."),
("castle_cheat_interior",
[
(eq, "$cheat_mode", 1),
],
"{!}CHEAT! Interior.",
[
(set_jump_mission,"mt_ai_training"),
(party_get_slot, ":castle_scene", "$current_town", slot_town_castle),
(jump_to_scene,":castle_scene"),
(change_screen_mission),
]),
("castle_cheat_town_exterior",
[
(eq, "$cheat_mode", 1),
],
"{!}CHEAT! Exterior.",
[
(try_begin),
(party_slot_eq, "$current_town",slot_party_type, spt_castle),
(party_get_slot, ":scene", "$current_town", slot_castle_exterior),
(else_try),
(party_get_slot, ":scene", "$current_town", slot_town_center),
(try_end),
(set_jump_mission,"mt_ai_training"),
(jump_to_scene,":scene"),
(change_screen_mission),
]),
("castle_cheat_dungeon",
[
(eq, "$cheat_mode", 1),
],
"{!}CHEAT! Prison.",
[
(set_jump_mission,"mt_ai_training"),
(party_get_slot, ":castle_scene", "$current_town", slot_town_prison),
(jump_to_scene,":castle_scene"),
(change_screen_mission),
]),
("castle_cheat_town_walls",
[
(eq, "$cheat_mode", 1),
(party_slot_eq,"$current_town",slot_party_type, spt_town),
],
"{!}CHEAT! Town Walls.",
[
(party_get_slot, ":scene", "$current_town", slot_town_walls),
(set_jump_mission,"mt_ai_training"),
(jump_to_scene,":scene"),
(change_screen_mission),
]),
("cheat_town_start_siege",
[
(eq, "$cheat_mode", 1),
(party_slot_eq, "$g_encountered_party", slot_center_is_besieged_by, -1),
(lt, "$g_encountered_party_2", 1),
(call_script, "script_party_count_fit_for_battle","p_main_party"),
(gt, reg(0), 1),
(try_begin),
(party_slot_eq, "$g_encountered_party", slot_party_type, spt_town),
(assign, reg6, 1),
(else_try),
(assign, reg6, 0),
(try_end),
],
"{!}CHEAT: Besiege the {reg6?town:castle}...",
[
(assign,"$g_player_besiege_town","$g_encountered_party"),
(jump_to_menu, "mnu_castle_besiege"),
]),
("center_reports",
[
(eq, "$cheat_mode", 1),
],
"{!}CHEAT! Show reports.",
[
(jump_to_menu,"mnu_center_reports"),
]),
("sail_from_port",
[
(party_slot_eq,"$current_town",slot_party_type, spt_town),
(eq, "$cheat_mode", 1),
#(party_slot_eq,"$current_town",slot_town_near_shore, 1),
],
"{!}CHEAT: Sail from port.",
[
(assign, "$g_player_icon_state", pis_ship),
(party_set_flags, "p_main_party", pf_is_ship, 1),
(party_get_position, pos1, "p_main_party"),
(map_get_water_position_around_position, pos2, pos1, 6),
(party_set_position, "p_main_party", pos2),
(assign, "$g_main_ship_party", -1),
(change_screen_return),
]),
]
),
(
"cannot_enter_court",0,
"There is a feast in progress in the lord's hall, but you are not of sufficient status to be invited inside. Perhaps increasing your renown would win you admittance -- or you might also try distinguishing yourself at a tournament while the feast is in progress...",
"none",
[],
[
("continue", [],"Continue",
[
(jump_to_menu, "mnu_town"),
]),
]),
(
"lady_visit",0,
"Whom do you wish to visit?",
"none",
[],
[
("visit_lady_1", [
(gt, "$love_interest_in_town", 0),
(str_store_troop_name, s12, "$love_interest_in_town"),
],
"Visit {s12}",
[
(assign, "$love_interest_in_town", "$love_interest_in_town"),
(jump_to_menu, "mnu_garden"),
]),
("visit_lady_2", [
(gt, "$love_interest_in_town_2", 0),
(str_store_troop_name, s12, "$love_interest_in_town_2"),
],
"Visit {s12}",
[
(assign, "$love_interest_in_town", "$love_interest_in_town_2"),
(jump_to_menu, "mnu_garden"),
]),
("visit_lady_3", [
(gt, "$love_interest_in_town_3", 0),
(str_store_troop_name, s12, "$love_interest_in_town_3"),
],
"Visit {s12}",
[
(assign, "$love_interest_in_town", "$love_interest_in_town_3"),
(jump_to_menu, "mnu_garden")], "Door to the garden."),
("visit_lady_4", [(gt, "$love_interest_in_town_4", 0),(str_store_troop_name, s12, "$love_interest_in_town_4"),],
"Visit {s12}",[(assign, "$love_interest_in_town", "$love_interest_in_town_4"),(jump_to_menu, "mnu_garden"),]),
("visit_lady_5", [(gt, "$love_interest_in_town_5", 0),(str_store_troop_name, s12, "$love_interest_in_town_5"),],
"Visit {s12}",[(assign, "$love_interest_in_town", "$love_interest_in_town_5"),(jump_to_menu, "mnu_garden"),]),
("visit_lady_6",[(gt, "$love_interest_in_town_6", 0),(str_store_troop_name, s12, "$love_interest_in_town_6"),],
"Visit {s12}",[(assign, "$love_interest_in_town", "$love_interest_in_town_6"),(jump_to_menu, "mnu_garden"),]),
("visit_lady_7",[(gt, "$love_interest_in_town_7", 0),(str_store_troop_name, s12, "$love_interest_in_town_7"),],
"Visit {s12}",[(assign, "$love_interest_in_town", "$love_interest_in_town_7"),(jump_to_menu, "mnu_garden"),]),
("visit_lady_8",[(gt, "$love_interest_in_town_8", 0),(str_store_troop_name, s12, "$love_interest_in_town_8"),],
"Visit {s12}",[(assign, "$love_interest_in_town", "$love_interest_in_town_8"),(jump_to_menu, "mnu_garden"),]),
("leave",[], "Leave",[(jump_to_menu, "mnu_town")]),
]
),
(
"town_tournament_lost",0,
"You have been eliminated from the tournament.{s8}",
"none",
[
(str_clear, s8),
(try_begin),
(this_or_next|neq, "$players_kingdom", "$g_encountered_party_faction"),
(neg|troop_slot_ge, "trp_player", slot_troop_renown, 50),
(neg|troop_slot_ge, "trp_player", slot_troop_renown, 125),
(gt, "$g_player_tournament_placement", 4),
(faction_slot_eq, "$g_encountered_party_faction", slot_faction_ai_state, sfai_feast),
(faction_slot_eq, "$g_encountered_party_faction", slot_faction_ai_object, "$g_encountered_party"),
(str_store_string, s8, "str__however_you_have_sufficiently_distinguished_yourself_to_be_invited_to_attend_the_ongoing_feast_in_the_lords_castle"),
(try_end),
],
[
("continue", [], "Continue...",
[(jump_to_menu, "mnu_town_tournament_won_by_another"),
]),
]
),
(
"town_tournament_won",mnf_disable_all_keys,
"You have won the tournament of {s3}! You are filled with pride as the crowd cheers your name.\
In addition to honour, fame and glory, you earn a prize of {reg9} denars. {s8}",
"none",
[
(str_store_party_name, s3, "$current_town"),
(call_script, "script_change_troop_renown", "trp_player", 20),
(call_script, "script_change_player_relation_with_center", "$current_town", 1),
(assign, reg9, 200),
(add_xp_to_troop, 250, "trp_player"),
(troop_add_gold, "trp_player", reg9),
(str_clear, s8),
(store_add, ":total_win", "$g_tournament_bet_placed", "$g_tournament_bet_win_amount"),
(try_begin),
(gt, "$g_tournament_bet_win_amount", 0),
(assign, reg8, ":total_win"),
(str_store_string, s8, "@Moreover, you earn {reg8} denars from the clever bets you placed on yourself..."),
(try_end),
(try_begin),
(this_or_next|neq, "$players_kingdom", "$g_encountered_party_faction"),
(neg|troop_slot_ge, "trp_player", slot_troop_renown, 70),
(neg|troop_slot_ge, "trp_player", slot_troop_renown, 145),
(faction_slot_eq, "$g_encountered_party_faction", slot_faction_ai_state, sfai_feast),
(faction_slot_eq, "$g_encountered_party_faction", slot_faction_ai_object, "$g_encountered_party"),
(str_store_string, s8, "str_s8_you_are_also_invited_to_attend_the_ongoing_feast_in_the_castle"),
(try_end),
(troop_add_gold, "trp_player", ":total_win"),
(assign, ":player_odds_sub", 0),
(store_div, ":player_odds_sub", "$g_tournament_bet_win_amount", 5),
(party_get_slot, ":player_odds", "$current_town", slot_town_player_odds),
(val_sub, ":player_odds", ":player_odds_sub"),
(val_max, ":player_odds", 250),
(party_set_slot, "$current_town", slot_town_player_odds, ":player_odds"),
(call_script, "script_play_victorious_sound"),
(unlock_achievement, ACHIEVEMENT_MEDIEVAL_TIMES),
],
[
("continue", [], "Continue...",
[(jump_to_menu, "mnu_town"),
]),
]
),
(
"town_tournament_won_by_another",mnf_disable_all_keys,
"As the only {reg3?fighter:man} to remain undefeated this day, {s1} wins the lists and the glory of this tournament.",
"none",
[
(call_script, "script_get_num_tournament_participants"),
(store_sub, ":needed_to_remove_randomly", reg0, 1),
(try_begin),
(troop_slot_eq, "trp_tournament_participants", 0, 0), #delete player from the participants
(troop_set_slot, "trp_tournament_participants", 0, -1),
(val_sub, ":needed_to_remove_randomly", 1),
(try_end),
(call_script, "script_remove_tournament_participants_randomly", ":needed_to_remove_randomly"),
(call_script, "script_sort_tournament_participant_troops"),
(troop_get_slot, ":winner_troop", "trp_tournament_participants", 0),
(str_store_troop_name, s1, ":winner_troop"),
(try_begin),
(troop_is_hero, ":winner_troop"),
(call_script, "script_change_troop_renown", ":winner_troop", 20),
(try_end),
(troop_get_type, reg3, ":winner_troop"),
],
[
("continue", [], "Continue...",
[(jump_to_menu, "mnu_town"),
]),
]
),
(
"town_tournament",mnf_disable_all_keys,
"{s1}You are at tier {reg0} of the tournament, with {reg1} participants remaining. In the next round, there will be {reg2} teams with {reg3} {reg4?fighters:fighter} each.",
"none",
[
(party_set_slot, "$current_town", slot_town_has_tournament, 0), #No way to return back if this menu is left
(call_script, "script_sort_tournament_participant_troops"),#Moving trp_player to the top of the list
(call_script, "script_get_num_tournament_participants"),
(assign, ":num_participants", reg0),
(try_begin),
(neg|troop_slot_eq, "trp_tournament_participants", 0, 0),#Player is defeated
(assign, ":player_odds_add", 0),
(store_div, ":player_odds_add", "$g_tournament_bet_placed", 5),
(party_get_slot, ":player_odds", "$current_town", slot_town_player_odds),
(val_add, ":player_odds", ":player_odds_add"),
(val_min, ":player_odds", 4000),
(party_set_slot, "$current_town", slot_town_player_odds, ":player_odds"),
(jump_to_menu, "mnu_town_tournament_lost"),
(else_try),
(eq, ":num_participants", 1),#Tournament won
(jump_to_menu, "mnu_town_tournament_won"),
(else_try),
(try_begin),
(le, "$g_tournament_next_num_teams", 0),
(call_script, "script_get_random_tournament_team_amount_and_size"),
(assign, "$g_tournament_next_num_teams", reg0),
(assign, "$g_tournament_next_team_size", reg1),
(try_end),
(assign, reg2, "$g_tournament_next_num_teams"),
(assign, reg3, "$g_tournament_next_team_size"),
(store_sub, reg4, reg3, 1),
(str_clear, s1),
(try_begin),
(eq, "$g_tournament_player_team_won", 1),
(str_store_string, s1, "@Victory is yours! You have won this melee, but now you must prepare yourself for the next round. "),
(else_try),
(eq, "$g_tournament_player_team_won", 0),
(str_store_string, s1, "@You have been bested in this melee, but the master of ceremonies declares a recognition of your skill and bravery, allowing you to take part in the next round. "),
(try_end),
(assign, reg1, ":num_participants"),
(store_add, reg0, "$g_tournament_cur_tier", 1),
(try_end),
],
[
("tournament_view_participants", [], "View participants.",
[(jump_to_menu, "mnu_tournament_participants"),
]),
("tournament_bet", [(neq, "$g_tournament_cur_tier", "$g_tournament_last_bet_tier")], "Place a bet on yourself.",
[(jump_to_menu, "mnu_tournament_bet"),
]),
("tournament_join_next_fight", [], "Fight in the next round.",
[
(party_get_slot, ":arena_scene", "$current_town", slot_town_arena),
(modify_visitors_at_site, ":arena_scene"),
(reset_visitors),
#Assuming that there are enough participants for the teams
(assign, "$g_player_tournament_placement", "$g_tournament_cur_tier"),
(try_begin),
(gt, "$g_player_tournament_placement", 4),
(assign, "$g_player_eligible_feast_center_no", "$current_town"),
(try_end),
(val_add, "$g_tournament_cur_tier", 1),
(store_mul, "$g_tournament_num_participants_for_fight", "$g_tournament_next_num_teams", "$g_tournament_next_team_size"),
(troop_set_slot, "trp_tournament_participants", 0, -1),#Removing trp_player from the list
(troop_set_slot, "trp_temp_array_a", 0, "trp_player"),
(try_for_range, ":slot_no", 1, "$g_tournament_num_participants_for_fight"),
(call_script, "script_get_random_tournament_participant"),
(troop_set_slot, "trp_temp_array_a", ":slot_no", reg0),
(try_end),
(call_script, "script_shuffle_troop_slots", "trp_temp_array_a", 0, "$g_tournament_num_participants_for_fight"),
(try_for_range, ":slot_no", 0, 4),#shuffle teams
(troop_set_slot, "trp_temp_array_b", ":slot_no", ":slot_no"),
(try_end),
(call_script, "script_shuffle_troop_slots", "trp_temp_array_b", 0, 4),
(assign, ":cur_slot", 0),
(try_for_range, ":cur_team_offset", 0, "$g_tournament_next_num_teams"),
(troop_get_slot, ":cur_team", "trp_temp_array_b", ":cur_team_offset"),
(try_for_range, ":slot_no", 0, 8),#shuffle entry_points
(troop_set_slot, "trp_temp_array_c", ":slot_no", ":slot_no"),
(try_end),
(call_script, "script_shuffle_troop_slots", "trp_temp_array_c", 0, 8),
(try_for_range, ":cur_index", 0, "$g_tournament_next_team_size"),
(store_mul, ":cur_entry_point", ":cur_team", 8),
(troop_get_slot, ":entry_offset", "trp_temp_array_c", ":cur_index"),
(val_add, ":cur_entry_point", ":entry_offset"),
(troop_get_slot, ":troop_no", "trp_temp_array_a", ":cur_slot"),
(set_visitor, ":cur_entry_point", ":troop_no"),
(val_add, ":cur_slot", 1),
(try_end),
(try_end),
(assign, "$g_tournament_next_num_teams", 0),
(assign, "$g_tournament_next_team_size", 0),
(assign, "$g_mt_mode", abm_tournament),
(party_get_slot, ":town_original_faction", "$current_town", slot_center_original_faction),
(assign, ":town_index_within_faction", 0),
(assign, ":end_cond", towns_end),
(try_for_range, ":cur_town", towns_begin, ":end_cond"),
(try_begin),
(eq, ":cur_town", "$current_town"),
(assign, ":end_cond", 0), #break
(else_try),
(party_slot_eq, ":cur_town", slot_center_original_faction, ":town_original_faction"),
(val_add, ":town_index_within_faction", 1),
(try_end),
(try_end),
(set_jump_mission, "mt_arena_melee_fight"),
(try_begin),
(eq, ":town_original_faction", "fac_kingdom_7"),
#Swadia
(store_mod, ":mod", ":town_index_within_faction", 4),
(try_begin),
(eq, ":mod", 0),
(call_script, "script_set_items_for_tournament", 40, 80, 50, 20, 0, 0, 0, 0, "itm_arena_armor_red", "itm_tourney_helm_red"),
(else_try),
(eq, ":mod", 1),
(call_script, "script_set_items_for_tournament", 100, 100, 0, 0, 0, 0, 0, 0, "itm_arena_armor_red", "itm_tourney_helm_red"),
(else_try),
(eq, ":mod", 2),
(call_script, "script_set_items_for_tournament", 100, 0, 100, 0, 0, 0, 0, 0, "itm_arena_armor_red", "itm_tourney_helm_red"),
(else_try),
(eq, ":mod", 3),
(call_script, "script_set_items_for_tournament", 40, 80, 50, 20, 40, 0, 0, 0, "itm_arena_armor_red", "itm_tourney_helm_red"),
(try_end),
(else_try),
(eq, ":town_original_faction", "fac_kingdom_7"),
#Vaegirs
(store_mod, ":mod", ":town_index_within_faction", 4),
(try_begin),
(eq, ":mod", 0),
(call_script, "script_set_items_for_tournament", 40, 80, 50, 20, 0, 0, 0, 0, "itm_arena_armor_red", "itm_steppe_helmet_red"),
(else_try),
(eq, ":mod", 1),
(call_script, "script_set_items_for_tournament", 100, 50, 0, 0, 0, 20, 30, 0, "itm_arena_armor_red", "itm_steppe_helmet_red"),
(else_try),
(eq, ":mod", 2),
(call_script, "script_set_items_for_tournament", 100, 0, 50, 0, 0, 20, 30, 0, "itm_arena_armor_red", "itm_steppe_helmet_red"),
(else_try),
(eq, ":mod", 3),
(call_script, "script_set_items_for_tournament", 40, 80, 50, 20, 30, 0, 60, 0, "itm_arena_armor_red", "itm_steppe_helmet_red"),
(try_end),
(else_try),
(eq, ":town_original_faction", "fac_kingdom_7"),
#Khergit
(store_mod, ":mod", ":town_index_within_faction", 2),
(try_begin),
(eq, ":mod", 0),
(call_script, "script_set_items_for_tournament", 100, 0, 0, 0, 0, 40, 60, 0, "itm_arena_tunic_red", "itm_steppe_helmet_red"),
(else_try),
(eq, ":mod", 1),
(call_script, "script_set_items_for_tournament", 100, 50, 25, 0, 0, 30, 50, 0, "itm_arena_tunic_red", "itm_steppe_helmet_red"),
(try_end),
(else_try),
(eq, ":town_original_faction", "fac_kingdom_7"),
#Nords
(store_mod, ":mod", ":town_index_within_faction", 3),
(try_begin),
(eq, ":mod", 0),
(call_script, "script_set_items_for_tournament", 0, 0, 50, 80, 0, 0, 0, 0, "itm_arena_armor_red", -1),
(else_try),
(eq, ":mod", 1),
(call_script, "script_set_items_for_tournament", 0, 0, 50, 80, 50, 0, 0, 0, "itm_arena_armor_red", -1),
(else_try),
(eq, ":mod", 2),
(call_script, "script_set_items_for_tournament", 40, 0, 0, 100, 0, 0, 0, 0, "itm_arena_armor_red", -1),
(try_end),
(else_try),
#Rhodoks
(eq, ":town_original_faction", "fac_kingdom_7"),
(call_script, "script_set_items_for_tournament", 25, 100, 60, 0, 30, 0, 30, 50, "itm_arena_tunic_red", "itm_arena_helmet_red"),
(else_try),
#Sarranids
(store_mod, ":mod", ":town_index_within_faction", 2),
(try_begin),
(eq, ":mod", 0),
(call_script, "script_set_items_for_tournament", 100, 40, 60, 0, 30, 30, 0, 0, "itm_arena_tunic_red", "itm_arena_turban_red"),
(else_try),
(call_script, "script_set_items_for_tournament", 50, 0, 60, 0, 30, 30, 0, 0, "itm_arena_tunic_red", "itm_arena_turban_red"),
(try_end),
(try_end),
(jump_to_scene, ":arena_scene"),
(change_screen_mission),
]),
("leave_tournament",[],"Withdraw from the tournament.",
[
(jump_to_menu, "mnu_tournament_withdraw_verify"),
]),
]
),
(
"tournament_withdraw_verify",0,
"Are you sure you want to withdraw from the tournament?",
"none",
[],
[
("tournament_withdraw_yes", [], "Yes. This is a pointless affectation.",
[(jump_to_menu, "mnu_town_tournament_won_by_another"),
]),
("tournament_withdraw_no", [], "No, not as long as there is a chance of victory!",
[(jump_to_menu, "mnu_town_tournament"),
]),
]
),
(
"tournament_bet",0,
"The odds against you are {reg5} to {reg6}.{reg1? You have already bet {reg1} denars on yourself, and if you win, you will earn {reg2} denars.:} How much do you want to bet?",
"none",
[
(assign, reg1, "$g_tournament_bet_placed"),
(store_add, reg2, "$g_tournament_bet_win_amount", "$g_tournament_bet_placed"),
(call_script, "script_get_win_amount_for_tournament_bet"),
(assign, ":player_odds", reg0),
(assign, ":min_dif", 100000),
(assign, ":min_dif_divisor", 1),
(assign, ":min_dif_multiplier", 1),
(try_for_range, ":cur_multiplier", 1, 50),
(try_for_range, ":cur_divisor", 1, 50),
(store_mul, ":result", 100, ":cur_multiplier"),
(val_div, ":result", ":cur_divisor"),
(store_sub, ":difference", ":player_odds", ":result"),
(val_abs, ":difference"),
(lt, ":difference", ":min_dif"),
(assign, ":min_dif", ":difference"),
(assign, ":min_dif_divisor", ":cur_divisor"),
(assign, ":min_dif_multiplier", ":cur_multiplier"),
(try_end),
(try_end),
(assign, reg5, ":min_dif_multiplier"),
(assign, reg6, ":min_dif_divisor"),
],
[
("bet_100_denars", [(store_troop_gold, ":gold", "trp_player"),
(ge, ":gold", 100)
],
"100 denars.",
[
(assign, "$temp", 100),
(jump_to_menu, "mnu_tournament_bet_confirm"),
]),
("bet_50_denars", [(store_troop_gold, ":gold", "trp_player"),
(ge, ":gold", 50)
],
"50 denars.",
[
(assign, "$temp", 50),
(jump_to_menu, "mnu_tournament_bet_confirm"),
]),
("bet_20_denars", [(store_troop_gold, ":gold", "trp_player"),
(ge, ":gold", 20)
],
"20 denars.",
[
(assign, "$temp", 20),
(jump_to_menu, "mnu_tournament_bet_confirm"),
]),
("bet_10_denars", [(store_troop_gold, ":gold", "trp_player"),
(ge, ":gold", 10)
],
"10 denars.",
[
(assign, "$temp", 10),
(jump_to_menu, "mnu_tournament_bet_confirm"),
]),
("bet_5_denars", [(store_troop_gold, ":gold", "trp_player"),
(ge, ":gold", 5)
],
"5 denars.",
[
(assign, "$temp", 5),
(jump_to_menu, "mnu_tournament_bet_confirm"),
]),
("go_back_dot", [], "Go back.",
[
(jump_to_menu, "mnu_town_tournament"),
]),
]
),
(
"tournament_bet_confirm",0,
"If you bet {reg1} denars, you will earn {reg2} denars if you win the tournament. Is that all right?",
"none",
[
(call_script, "script_get_win_amount_for_tournament_bet"),
(assign, ":win_amount", reg0),
(val_mul, ":win_amount", "$temp"),
(val_div, ":win_amount", 100),
(assign, reg1, "$temp"),
(assign, reg2, ":win_amount"),
],
[
("tournament_bet_accept", [],
"Go ahead.",
[
(call_script, "script_tournament_place_bet", "$temp"),
(jump_to_menu, "mnu_town_tournament"),
]),
("tournament_bet_cancel", [],
"Forget it.",
[
(jump_to_menu, "mnu_tournament_bet"),
]),
]
),
(
"tournament_participants",0,
"You ask one of the criers for the names of the tournament participants. They are:^{s11}",
"none",
[
(str_clear, s11),
(call_script, "script_sort_tournament_participant_troops"),
(call_script, "script_get_num_tournament_participants"),
(assign, ":num_participants", reg0),
(try_for_range, ":cur_slot", 0, ":num_participants"),
(troop_get_slot, ":troop_no", "trp_tournament_participants", ":cur_slot"),
(str_store_troop_name, s12, ":troop_no"),
(str_store_string, s11, "@{!}{s11}^{s12}"),
(try_end),
],
[
("go_back_dot", [], "Go back.",
[(jump_to_menu, "mnu_town_tournament"),
]),
]
),
(
"collect_taxes",mnf_disable_all_keys,
"As the party member with the highest trade skill ({reg2}), {reg3?you expect:{s1} expects} that collecting taxes from here will take {reg4} days...",
"none",
[(call_script, "script_get_max_skill_of_player_party", "skl_trade"),
(assign, ":max_skill", reg0),
(assign, reg2, reg0),
(assign, ":max_skill_owner", reg1),
(try_begin),
(eq, ":max_skill_owner", "trp_player"),
(assign, reg3, 1),
(else_try),
(assign, reg3, 0),
(str_store_troop_name, s1, ":max_skill_owner"),
(try_end),
(assign, ":tax_quest_expected_revenue", 3000),
(try_begin),
(party_slot_eq, "$current_town", slot_party_type, spt_town),
(assign, ":tax_quest_expected_revenue", 6000),
(try_end),
(try_begin),
(quest_slot_eq, "qst_collect_taxes", slot_quest_current_state, 0),
(store_add, ":max_skill_plus_thirty", ":max_skill", 30),
(try_begin),
(party_slot_eq, "$current_town", slot_party_type, spt_town),
(store_div, "$qst_collect_taxes_total_hours", 24* 7 * 30, ":max_skill_plus_thirty"),
(else_try),
#Village
(store_div, "$qst_collect_taxes_total_hours", 24 * 3 * 30, ":max_skill_plus_thirty"),
(try_end),
(call_script, "script_party_count_fit_for_battle", "p_main_party"),
(val_add, reg0, 20),
(val_mul, "$qst_collect_taxes_total_hours", 20),
(val_div, "$qst_collect_taxes_total_hours", reg0),
(quest_set_slot, "qst_collect_taxes", slot_quest_target_amount, "$qst_collect_taxes_total_hours"),
(store_div, ":menu_begin_time", "$qst_collect_taxes_total_hours", 20),#between %5-%25
(store_div, ":menu_end_time", "$qst_collect_taxes_total_hours", 4),
(assign, ":unrest_begin_time", ":menu_end_time"),#between %25-%75
(store_mul, ":unrest_end_time", "$qst_collect_taxes_total_hours", 3),
(val_div, ":unrest_end_time", 4),
(val_mul, ":tax_quest_expected_revenue", 2),
(store_div, "$qst_collect_taxes_hourly_income", ":tax_quest_expected_revenue", "$qst_collect_taxes_total_hours"),
(store_random_in_range, "$qst_collect_taxes_menu_counter", ":menu_begin_time", ":menu_end_time"),
(store_random_in_range, "$qst_collect_taxes_unrest_counter", ":unrest_begin_time", ":unrest_end_time"),
(assign, "$qst_collect_taxes_halve_taxes", 0),
(try_end),
(quest_get_slot, ":target_hours", "qst_collect_taxes", slot_quest_target_amount),
(store_div, ":target_days", ":target_hours", 24),
(val_mul, ":target_days", 24),
(try_begin),
(lt, ":target_days", ":target_hours"),
(val_add, ":target_days", 24),
(try_end),
(val_div, ":target_days", 24),
(assign, reg4, ":target_days"),
],
[
("start_collecting", [], "Start collecting.",
[(assign, "$qst_collect_taxes_currently_collecting", 1),
(try_begin),
(quest_slot_eq, "qst_collect_taxes", slot_quest_current_state, 0),
(quest_set_slot, "qst_collect_taxes", slot_quest_current_state, 1),
(try_end),
(rest_for_hours_interactive, 1000, 5, 0), #rest while not attackable
(assign,"$auto_enter_town","$current_town"),
(assign, "$g_town_visit_after_rest", 1),
(change_screen_return),
]),
("collect_later", [], "Put it off until later.",
[(try_begin),
(party_slot_eq, "$current_town", slot_party_type, spt_town),
(jump_to_menu, "mnu_town"),
(else_try),
(jump_to_menu, "mnu_village"),
(try_end),
]),
]
),
(
"collect_taxes_complete",mnf_disable_all_keys,
"You've collected {reg3} denars in taxes from {s3}. {s19} will be expecting you to take the money to him.",
"none",
[(str_store_party_name, s3, "$current_town"),
(quest_get_slot, ":quest_giver", "qst_collect_taxes", slot_quest_giver_troop),
(str_store_troop_name, s19, ":quest_giver"),
(quest_get_slot, reg3, "qst_collect_taxes", slot_quest_gold_reward),
(try_begin),
(eq, "$qst_collect_taxes_halve_taxes", 0),
(call_script, "script_change_player_relation_with_center", "$current_town", -2),
(try_end),
(call_script, "script_succeed_quest", "qst_collect_taxes"),
],
[
("continue", [], "Continue...",
[(change_screen_return),
]),
]
),
(
"collect_taxes_rebels_killed",0,
"Your quick action and strong arm have successfully put down the revolt.\
Surely, anyone with a mind to rebel against you will think better of it after this.",
"none",
[
],
[
("continue", [], "Continue...",
[(change_screen_map),
]),
]
),
(
"collect_taxes_failed",mnf_disable_all_keys,
"You could collect only {reg3} denars as tax from {s3} before the revolt broke out.\
{s1} won't be happy, but some silver will placate him better than nothing at all...",
"none",
[(str_store_party_name, s3, "$current_town"),
(quest_get_slot, ":quest_giver", "qst_collect_taxes", slot_quest_giver_troop),
(str_store_troop_name, s1, ":quest_giver"),
(quest_get_slot, reg3, "qst_collect_taxes", slot_quest_gold_reward),
(call_script, "script_fail_quest", "qst_collect_taxes"),
(quest_set_slot, "qst_collect_taxes", slot_quest_current_state, 4),
(rest_for_hours, 0, 0, 0), #stop resting
],
[
("continue", [], "Continue...",
[(change_screen_map),
]),
]
),
(
"collect_taxes_revolt_warning",0,
"The people of {s3} are outraged at your demands and decry it as nothing more than extortion.\
They're getting very restless, and they may react badly if you keep pressing them.",
"none",
[(str_store_party_name, s3, "$current_town"),
],
[
("continue_collecting_taxes", [], "Ignore them and continue.",
[(change_screen_return),]),
("halve_taxes", [(quest_get_slot, ":quest_giver_troop", "qst_collect_taxes", slot_quest_giver_troop),
(str_store_troop_name, s1, ":quest_giver_troop"),],
"Agree to reduce your collection by half. ({s1} may be upset)",
[(assign, "$qst_collect_taxes_halve_taxes", 1),
(change_screen_return),
]),
]
),
(
"collect_taxes_revolt",0,
"You are interrupted while collecting the taxes at {s3}. A large band of angry {reg9?peasants:townsmen} is marching nearer,\
shouting about the exorbitant taxes and waving torches and weapons. It looks like they aim to fight you!",
"none",
[(str_store_party_name, s3, "$current_town"),
(assign, reg9, 0),
(try_begin),
(party_slot_eq, "$current_town", slot_party_type, spt_village),
(assign, reg9, 1),
(try_end),
],
[
("continue", [], "Continue...",
[(set_jump_mission,"mt_back_alley_revolt"),
(quest_get_slot, ":target_center", "qst_collect_taxes", slot_quest_target_center),
(try_begin),
(party_slot_eq, ":target_center", slot_party_type, spt_town),
(party_get_slot, ":town_alley", ":target_center", slot_town_alley),
(else_try),
(party_get_slot, ":town_alley", ":target_center", slot_castle_exterior),
(try_end),
(modify_visitors_at_site,":town_alley"),
(reset_visitors),
(assign, ":num_rebels", 6),
(store_character_level, ":level", "trp_player"),
(val_div, ":level", 5),
(val_add, ":num_rebels", ":level"),
(set_visitors, 1, "trp_tax_rebel", ":num_rebels"),
(jump_to_scene,":town_alley"),
(change_screen_mission),
]),
]
),
# They must learn field discipline and the steadiness to follow orders in combat before they can be thought to use arms.",
(
"train_peasants_against_bandits",0,
"As the party member with the highest training skill ({reg2}), {reg3?you expect:{s1} expects} that getting some peasants ready for practice will take {reg4} hours.",
"none",
[(call_script, "script_get_max_skill_of_player_party", "skl_trainer"),
(assign, ":max_skill", reg0),
(assign, reg2, reg0),
(assign, ":max_skill_owner", reg1),
(try_begin),
(eq, ":max_skill_owner", "trp_player"),
(assign, reg3, 1),
(else_try),
(assign, reg3, 0),
(str_store_troop_name, s1, ":max_skill_owner"),
(try_end),
(store_sub, ":needed_hours", 20, ":max_skill"),
(val_mul, ":needed_hours", 3),
(val_div, ":needed_hours", 5),
(store_sub, reg4, ":needed_hours", "$qst_train_peasants_against_bandits_num_hours_trained"),
],
[
("make_preparation", [], "Train them.",
[
(assign, "$qst_train_peasants_against_bandits_currently_training", 1),
(rest_for_hours_interactive, 1000, 5, 0), #rest while not attackable
(assign, "$auto_enter_town", "$current_town"),
(assign, "$g_town_visit_after_rest", 1),
(change_screen_return),
]),
("train_later", [], "Put it off until later.",
[
(jump_to_menu, "mnu_village"),
]),
]
),
(
"train_peasants_against_bandits_ready",0,
"You put the peasants through the basics of soldiering, discipline and obedience.\
You think {reg0} of them {reg1?have:has} fully grasped the training and {reg1?are:is} ready for some practice.",
"none",
[
(store_character_level, ":level", "trp_player"),
(val_div, ":level", 10),
(val_add, ":level", 1),
(quest_get_slot, ":quest_target_amount", "qst_train_peasants_against_bandits", slot_quest_target_amount),
(quest_get_slot, ":quest_current_state", "qst_train_peasants_against_bandits", slot_quest_current_state),
(val_sub, ":quest_target_amount", ":quest_current_state"),
(assign, ":max_random", ":level"),
(val_min, ":max_random", ":quest_target_amount"),
(val_add, ":max_random", 1),
(store_random_in_range, ":random_number", 1, ":max_random"),
(assign, "$g_train_peasants_against_bandits_num_peasants", ":random_number"),
(assign, reg0, ":random_number"),
(store_sub, reg1, ":random_number", 1),
(str_store_troop_name_by_count, s0, "trp_trainee_peasant", ":random_number"),
],
[
("peasant_start_practice", [], "Start the practice fight.",
[
(set_jump_mission,"mt_village_training"),
(quest_get_slot, ":target_center", "qst_train_peasants_against_bandits", slot_quest_target_center),
(party_get_slot, ":village_scene", ":target_center", slot_castle_exterior),
(modify_visitors_at_site, ":village_scene"),
(reset_visitors),
(set_visitor, 0, "trp_player"),
(set_visitors, 1, "trp_trainee_peasant", "$g_train_peasants_against_bandits_num_peasants"),
(set_jump_entry, 11),
(jump_to_scene, ":village_scene"),
(jump_to_menu, "mnu_train_peasants_against_bandits_training_result"),
(music_set_situation, 0),
(change_screen_mission),
]),
]
),
(
"train_peasants_against_bandits_training_result",mnf_disable_all_keys,
"{s0}",
"none",
[
(assign, reg5, "$g_train_peasants_against_bandits_num_peasants"),
(str_store_troop_name_by_count, s0, "trp_trainee_peasant", "$g_train_peasants_against_bandits_num_peasants"),
(try_begin),
(eq, "$g_train_peasants_against_bandits_training_succeeded", 0),
(str_store_string, s0, "@You were beaten. The peasants are heartened by their success, but the lesson you wanted to teach them probably didn't get through..."),
(else_try),
(str_store_string, s0, "@After beating your last opponent, you explain to the peasants how to better defend themselves against such an attack. Hopefully they'll take the experience on board and will be prepared next time."),
(quest_get_slot, ":quest_current_state", "qst_train_peasants_against_bandits", slot_quest_current_state),
(val_add, ":quest_current_state", "$g_train_peasants_against_bandits_num_peasants"),
(quest_set_slot, "qst_train_peasants_against_bandits", slot_quest_current_state, ":quest_current_state"),
(try_end),
],
[
("continue", [], "Continue...",
[
(try_begin),
(quest_get_slot, ":quest_current_state", "qst_train_peasants_against_bandits", slot_quest_current_state),
(quest_slot_eq, "qst_train_peasants_against_bandits", slot_quest_target_amount, ":quest_current_state"),
(jump_to_menu, "mnu_train_peasants_against_bandits_attack"),
(else_try),
(change_screen_map),
(try_end),
]),
]
),
(
"train_peasants_against_bandits_attack",0,
"As you get ready to continue the training, a sentry from the village runs up to you, shouting alarums.\
The bandits have been spotted on the horizon, riding hard for {s3}.\
The elder begs that you organize your newly-trained militia and face them.",
"none",
[
(str_store_party_name, s3, "$current_town"),
],
[
("peasants_against_bandits_attack_resist", [], "Prepare for a fight!",
[
(store_random_in_range, ":random_no", 0, 3),
(try_begin),
(eq, ":random_no", 0),
(assign, ":bandit_troop", "trp_bandit"),
(else_try),
(eq, ":random_no", 1),
(assign, ":bandit_troop", "trp_mountain_bandit"),
(else_try),
(assign, ":bandit_troop", "trp_forest_bandit"),
(try_end),
(party_get_slot, ":scene_to_use", "$g_encountered_party", slot_castle_exterior),
(modify_visitors_at_site, ":scene_to_use"),
(reset_visitors),
(store_character_level, ":level", "trp_player"),
(val_div, ":level", 2),
(store_add, ":min_bandits", ":level", 16),
(store_add, ":max_bandits", ":min_bandits", 6),
(store_random_in_range, ":random_no", ":min_bandits", ":max_bandits"),
(set_visitors, 0, ":bandit_troop", ":random_no"),
(assign, ":num_villagers", ":max_bandits"),
(set_visitors, 2, "trp_trainee_peasant", ":num_villagers"),
(set_party_battle_mode),
(set_battle_advantage, 0),
(assign, "$g_battle_result", 0),
(set_jump_mission,"mt_village_attack_bandits"),
(jump_to_scene, ":scene_to_use"),
(assign, "$g_next_menu", "mnu_train_peasants_against_bandits_attack_result"),
(jump_to_menu, "mnu_battle_debrief"),
(assign, "$g_mt_mode", vba_after_training),
(change_screen_mission),
]),
]
),
(
"train_peasants_against_bandits_attack_result",mnf_scale_picture|mnf_disable_all_keys,
"{s9}",
"none",
[
(try_begin),
(eq, "$g_battle_result", 1),
(str_store_string, s9, "@The bandits are broken!\
Those few who remain alive and conscious run off with their tails between their legs,\
terrified of the peasants and their new champion."),
(call_script, "script_succeed_quest", "qst_train_peasants_against_bandits"),
(jump_to_menu, "mnu_train_peasants_against_bandits_success"),
(else_try),
(call_script, "script_fail_quest", "qst_train_peasants_against_bandits"),
(str_store_string, s9, "@Try as you might, you could not defeat the bandits.\
Infuriated, they raze the village to the ground to punish the peasants,\
and then leave the burning wasteland behind to find greener pastures to plunder."),
(set_background_mesh, "mesh_pic_looted_village"),
(try_end),
],
[
("continue", [], "Continue...",
[(try_begin),
(call_script, "script_village_set_state", "$current_town", svs_looted),
(party_set_slot, "$current_town", slot_village_raid_progress, 0),
(party_set_slot, "$current_town", slot_village_recover_progress, 0),
(call_script, "script_change_player_relation_with_center", "$g_encountered_party", -3),
(call_script, "script_end_quest", "qst_train_peasants_against_bandits"),
(try_end),
(change_screen_map),
]),
]
),
(
"train_peasants_against_bandits_success",mnf_disable_all_keys,
"The bandits are broken!\
Those few who remain run off with their tails between their legs,\
terrified of the peasants and their new champion.\
The villagers have little left in the way of wealth after their ordeal,\
but they offer you all they can find to show their gratitude.",
"none",
[(party_clear, "p_temp_party"),
(call_script, "script_end_quest", "qst_train_peasants_against_bandits"),
(call_script, "script_change_player_relation_with_center", "$g_encountered_party", 4),
(party_get_slot, ":merchant_troop", "$current_town", slot_town_elder),
(try_for_range, ":slot_no", num_equipment_kinds ,max_inventory_items + num_equipment_kinds),
(store_random_in_range, ":rand", 0, 100),
(lt, ":rand", 50),
(troop_set_inventory_slot, ":merchant_troop", ":slot_no", -1),
(try_end),
(call_script, "script_add_log_entry", logent_helped_peasants, "trp_player", "$current_town", -1, -1),
],
[
("village_bandits_defeated_accept",[],"Take it as your just due.",[(jump_to_menu, "mnu_auto_return_to_map"),
(party_get_slot, ":merchant_troop", "$current_town", slot_town_elder),
(troop_sort_inventory, ":merchant_troop"),
(change_screen_loot, ":merchant_troop"),
]),
("village_bandits_defeated_cont",[], "Refuse, stating that they need these items more than you do.",[
(call_script, "script_change_player_relation_with_center", "$g_encountered_party", 3),
(call_script, "script_change_player_honor", 1),
(change_screen_map)]),
],
),
(
"disembark",0,
"Do you wish to disembark?",
"none",
[],
[
("disembark_yes", [], "Yes.",
[(assign, "$g_player_icon_state", pis_normal),
(party_set_flags, "p_main_party", pf_is_ship, 0),
(party_get_position, pos1, "p_main_party"),
(party_set_position, "p_main_party", pos0),
(try_begin),
(le, "$g_main_ship_party", 0),
(set_spawn_radius, 0),
(spawn_around_party, "p_main_party", "pt_none"),
(assign, "$g_main_ship_party", reg0),
(party_set_flags, "$g_main_ship_party", pf_is_static|pf_always_visible|pf_hide_defenders|pf_is_ship, 1),
(str_store_troop_name, s1, "trp_player"),
(party_set_name, "$g_main_ship_party", "@{s1}'s Ship"),
(party_set_icon, "$g_main_ship_party", "icon_ship"),
(party_set_slot, "$g_main_ship_party", slot_party_type, spt_ship),
(try_end),
(enable_party, "$g_main_ship_party"),
(party_set_position, "$g_main_ship_party", pos0),
(party_set_icon, "$g_main_ship_party", "icon_ship_on_land"),
(assign, "$g_main_ship_party", -1),
(change_screen_return),
]),
("disembark_no", [], "No.",
[(change_screen_return),
]),
]
),
(
"ship_reembark",0,
"Do you wish to embark?",
"none",
[],
[
("reembark_yes", [], "Yes.",
[(assign, "$g_player_icon_state", pis_ship),
(party_set_flags, "p_main_party", pf_is_ship, 1),
(party_get_position, pos1, "p_main_party"),
(map_get_water_position_around_position, pos2, pos1, 6),
(party_set_position, "p_main_party", pos2),
(assign, "$g_main_ship_party", "$g_encountered_party"),
(disable_party, "$g_encountered_party"),
(change_screen_return),
]),
("reembark_no", [], "No.",
[(change_screen_return),
]),
]
),
(
"center_reports",0,
"Town Name: {s1}^Rent Income: {reg1} denars^Tariff Income: {reg2} denars^Food Stock: for {reg3} days",
"none",
[(party_get_slot, ":town_food_store", "$g_encountered_party", slot_party_food_store),
(call_script, "script_center_get_food_consumption", "$g_encountered_party"),
(assign, ":food_consumption", reg0),
(try_begin),
(gt, ":food_consumption", 0),
(store_div, reg3, ":town_food_store", ":food_consumption"),
(else_try),
(assign, reg3, 9999),
(try_end),
(str_store_party_name, s1, "$g_encountered_party"),
(party_get_slot, reg1, "$g_encountered_party", slot_center_accumulated_rents),
(party_get_slot, reg2, "$g_encountered_party", slot_center_accumulated_tariffs),
],
[
("to_price_and_productions", [], "Show prices and productions.",
[(jump_to_menu, "mnu_price_and_production"),
]),
("go_back_dot",[],"Go back.",
[(try_begin),
(party_slot_eq, "$g_encountered_party", slot_party_type, spt_village),
(jump_to_menu, "mnu_village"),
(else_try),
(jump_to_menu, "mnu_town"),
(try_end),
]),
]
),
(
"price_and_production",0,
"Productions are:^(Note: base/modified by raw materials/modified by materials plus prosperity)^{s1}^^Price factors are:^{s2}",
"none",
[
(assign, ":calradian_average_urban_hardship", 0),
(assign, ":calradian_average_rural_hardship", 0),
(try_for_range, ":center", towns_begin, towns_end),
(call_script, "script_center_get_goods_availability", ":center"),
(val_add, ":calradian_average_urban_hardship", reg0),
(try_end),
(try_for_range, ":center", villages_begin, villages_end),
(call_script, "script_center_get_goods_availability", ":center"),
(val_add, ":calradian_average_rural_hardship", reg0),
(try_end),
(val_div, ":calradian_average_rural_hardship", 110),
(val_div, ":calradian_average_urban_hardship", 22),
(call_script, "script_center_get_goods_availability", "$g_encountered_party"),
(assign, reg1, ":calradian_average_urban_hardship"),
(assign, reg2, ":calradian_average_rural_hardship"),
(try_begin),
(ge, "$cheat_mode", 1),
(str_store_string, s1, "str___hardship_index_reg0_avg_towns_reg1_avg_villages_reg2__"),
(display_message, "@{!}DEBUG - {s1}"),
(try_end),
(try_for_range, ":cur_good", trade_goods_begin, trade_goods_end),
(neq, ":cur_good", "itm_pork"), #tied to price of grain
(neq, ":cur_good", "itm_chicken"), #tied to price of grain
(neq, ":cur_good", "itm_butter"), #tied to price of cheese
(neq, ":cur_good", "itm_cattle_meat"),
(neq, ":cur_good", "itm_cabbages"), #possibly include later
(call_script, "script_center_get_production", "$g_encountered_party", ":cur_good"),
(assign, ":production", reg0),
(assign, ":base_production", reg2),
(assign, ":base_production_modded_by_raw_materials", reg1),
(call_script, "script_center_get_consumption", "$g_encountered_party", ":cur_good"),
(assign, ":consumer_consumption", reg2),
(assign, ":raw_material_consumption", reg1),
(assign, ":consumption", reg0),
(store_sub, ":cur_good_price_slot", ":cur_good", trade_goods_begin),
(val_add, ":cur_good_price_slot", slot_town_trade_good_prices_begin),
(party_get_slot, ":price", "$g_encountered_party", ":cur_good_price_slot"),
(assign, ":total_centers", 0),
(assign, ":calradian_average_price", 0),
(assign, ":calradian_average_production", 0),
(assign, ":calradian_average_consumption", 0),
(try_for_range, ":center", centers_begin, centers_end),
(neg|is_between, ":center", castles_begin, castles_end),
(val_add, ":total_centers", 1),
(call_script, "script_center_get_production", ":center", ":cur_good"),
(assign, ":center_production", reg2),
(call_script, "script_center_get_consumption", ":center", ":cur_good"),
(store_add, ":center_consumption", reg1, reg2),
(party_get_slot, ":center_price", ":center", ":cur_good_price_slot"),
(val_add, ":calradian_average_price", ":center_price"),
(val_add, ":calradian_average_production", ":center_production"),
(val_add, ":calradian_average_consumption", ":center_consumption"),
(try_end),
(assign, ":calradian_total_production", ":calradian_average_production"),
(assign, ":calradian_total_consumption", ":calradian_average_consumption"),
(val_div, ":calradian_average_price", ":total_centers"),
(val_div, ":calradian_average_production", ":total_centers"),
(val_div, ":calradian_average_consumption", ":total_centers"),
(str_store_item_name, s3, ":cur_good"),
(assign, reg1, ":base_production"),
(assign, reg2, ":base_production_modded_by_raw_materials"),
(assign, reg3, ":production"),
(assign, reg4, ":price"),
(assign, reg5, ":calradian_average_production"),
(assign, reg6, ":calradian_average_price"),
(assign, reg7, ":consumer_consumption"),
(assign, reg8, ":raw_material_consumption"),
(assign, reg9, ":consumption"),
(assign, reg10, ":calradian_average_consumption"),
(item_get_slot, ":production_slot", ":cur_good", slot_item_production_slot),
(party_get_slot, ":production_number", "$g_encountered_party", ":production_slot"),
(assign, reg11, ":production_number"),
(assign, reg12, ":calradian_total_production"),
(assign, reg13, ":calradian_total_consumption"),
(item_get_slot, ":production_string", ":cur_good", slot_item_production_string),
(str_store_string, s4, ":production_string"),
(str_store_string, s1, "str___s3_price_=_reg4_calradian_average_reg6_capital_reg11_s4_base_reg1modified_by_raw_material_reg2modified_by_prosperity_reg3_calradian_average_production_base_reg5_total_reg12_consumed_reg7used_as_raw_material_reg8modified_total_reg9_calradian_consumption_base_reg10_total_reg13s1_"),
(try_end),
],
[
("go_back_dot",[],"Go back.",
[(try_begin),
(party_slot_eq, "$g_encountered_party", slot_party_type, spt_village),
(jump_to_menu, "mnu_village"),
(else_try),
(jump_to_menu, "mnu_town"),
(try_end),
]),
]
),
(
"town_trade",0,
"You head towards the marketplace.",
"none",
[],
[
("assess_prices",
[
(store_faction_of_party, ":current_town_faction", "$current_town"),
(store_relation, ":reln", ":current_town_faction", "fac_player_supporters_faction"),
(ge, ":reln", 0),
],
"Assess the local prices.",
[
(jump_to_menu,"mnu_town_trade_assessment_begin"),
]),
("trade_with_arms_merchant",[(party_slot_ge, "$current_town", slot_town_weaponsmith, 1)],
"Trade with the arms merchant.",
[
(party_get_slot, ":merchant_troop", "$current_town", slot_town_weaponsmith),
(change_screen_trade, ":merchant_troop"),
]),
("trade_with_armor_merchant",[(party_slot_ge, "$current_town", slot_town_armorer, 1)],
"Trade with the armor merchant.",
[
(party_get_slot, ":merchant_troop", "$current_town", slot_town_armorer),
(change_screen_trade, ":merchant_troop"),
]),
("trade_with_horse_merchant",[(party_slot_ge, "$current_town", slot_town_horse_merchant, 1)],
"Trade with the horse merchant.",
[
(party_get_slot, ":merchant_troop", "$current_town", slot_town_horse_merchant),
(change_screen_trade, ":merchant_troop"),
]),
("trade_with_goods_merchant",[(party_slot_ge, "$current_town", slot_town_merchant, 1)],
"Trade with the goods merchant.",
[
(party_get_slot, ":merchant_troop", "$current_town", slot_town_merchant),
(change_screen_trade, ":merchant_troop"),
]),
("back_to_town_menu",[],"Head back.",
[
(jump_to_menu,"mnu_town"),
]),
]
),
(
"town_trade_assessment_begin",0,
#"You overhear the following details about the roads out of town :^(experimental feature -- this may go into dialogs)^{s42}^You also overhear several discussions about the price of trade goods across the local area.^You listen closely, trying to work out the best deals around.",
"You overhear several discussions about the price of trade goods across the local area.^You listen closely, trying to work out the best deals around.",
"none",
[
(str_clear, s42),
## (call_script, "script_merchant_road_info_to_s42", "$g_encountered_party"),
],
[
("continue",[],"Continue...",
[
(assign,"$auto_enter_town", "$current_town"),
(assign, "$g_town_assess_trade_goods_after_rest", 1),
(call_script, "script_get_max_skill_of_player_party", "skl_trade"),
(val_div, reg0, 2),
(store_sub, ":num_hours", 6, reg0),
(assign, "$g_last_rest_center", "$current_town"),
(assign, "$g_last_rest_payment_until", -1),
(rest_for_hours, ":num_hours", 5, 0), #rest while not attackable
(change_screen_return),
]),
("go_back_dot",[],"Go back.",
[
(jump_to_menu,"mnu_town_trade"),
]),
]
),
(
"town_trade_assessment",mnf_disable_all_keys,
"As the party member with the highest trade skill ({reg2}), {reg3?you try to figure out:{s1} tries to figure out} the best goods to trade in. {s2}",
"none",
[
(call_script, "script_get_max_skill_of_player_party", "skl_trade"),
(assign, ":max_skill", reg0),
(assign, ":max_skill_owner", reg1),
(assign, ":num_best_results", 0),
(assign, ":best_result_1_item", -1),
(assign, ":best_result_1_town", -1),
(assign, ":best_result_1_profit", 0),
(assign, ":best_result_2_item", -1),
(assign, ":best_result_2_town", -1),
(assign, ":best_result_2_profit", 0),
(assign, ":best_result_3_item", -1),
(assign, ":best_result_3_town", -1),
(assign, ":best_result_3_profit", 0),
(assign, ":best_result_4_item", -1),
(assign, ":best_result_4_town", -1),
(assign, ":best_result_4_profit", 0),
(assign, ":best_result_5_item", -1),
(assign, ":best_result_5_town", -1),
(assign, ":best_result_5_profit", 0),
(store_sub, ":num_towns", walled_centers_end, walled_centers_begin),
(store_sub, ":num_goods", trade_goods_end, trade_goods_begin),
(store_mul, ":max_iteration", ":num_towns", ":num_goods"),
(val_mul, ":max_iteration", ":max_skill"),
(val_div, ":max_iteration", 20),
(assign, ":org_encountered_party", "$g_encountered_party"),
(try_for_range, ":unused", 0, ":max_iteration"),
(store_random_in_range, ":random_trade_good", trade_goods_begin, trade_goods_end),
(store_random_in_range, ":random_town", towns_begin, towns_end),
(party_get_slot, ":cur_merchant", ":org_encountered_party", slot_town_merchant),
(assign, ":num_items_in_town_inventory", 0),
(try_for_range, ":i_slot", num_equipment_kinds, max_inventory_items + num_equipment_kinds),
(troop_get_inventory_slot, ":slot_item", ":cur_merchant", ":i_slot"),
(try_begin),
(eq, ":slot_item", ":random_trade_good"),
(val_add, ":num_items_in_town_inventory", 1),
(try_end),
(try_end),
(ge, ":num_items_in_town_inventory", 1),
(assign, ":already_best", 0),
(try_begin),
(eq, ":random_trade_good", ":best_result_1_item"),
(eq, ":random_town", ":best_result_1_town"),
(val_add, ":already_best", 1),
(try_end),
(try_begin),
(eq, ":random_trade_good", ":best_result_2_item"),
(eq, ":random_town", ":best_result_2_town"),
(val_add, ":already_best", 1),
(try_end),
(try_begin),
(eq, ":random_trade_good", ":best_result_3_item"),
(eq, ":random_town", ":best_result_3_town"),
(val_add, ":already_best", 1),
(try_end),
(try_begin),
(eq, ":random_trade_good", ":best_result_4_item"),
(eq, ":random_town", ":best_result_4_town"),
(val_add, ":already_best", 1),
(try_end),
(try_begin),
(eq, ":random_trade_good", ":best_result_5_item"),
(eq, ":random_town", ":best_result_5_town"),
(val_add, ":already_best", 1),
(try_end),
(le, ":already_best", 1),
(store_item_value, ":random_trade_good_price", ":random_trade_good"),
(assign, "$g_encountered_party", ":org_encountered_party"),
(call_script, "script_game_get_item_buy_price_factor", ":random_trade_good"),
(store_mul, ":random_trade_good_buy_price", ":random_trade_good_price", reg0),
(val_div, ":random_trade_good_buy_price", 100),
(val_max, ":random_trade_good_buy_price", 1),
(assign, "$g_encountered_party", ":random_town"),
(call_script, "script_game_get_item_sell_price_factor", ":random_trade_good"),
(store_mul, ":random_trade_good_sell_price", ":random_trade_good_price", reg0),
(val_div, ":random_trade_good_sell_price", 100),
(val_max, ":random_trade_good_sell_price", 1),
(store_sub, ":difference", ":random_trade_good_sell_price", ":random_trade_good_buy_price"),
(try_begin),
(this_or_next|eq, ":best_result_1_item", ":random_trade_good"),
(this_or_next|eq, ":best_result_2_item", ":random_trade_good"),
(this_or_next|eq, ":best_result_3_item", ":random_trade_good"),
(this_or_next|eq, ":best_result_4_item", ":random_trade_good"),
(eq, ":best_result_5_item", ":random_trade_good"),
(try_begin),
(eq, ":best_result_1_item", ":random_trade_good"),
(gt, ":difference", ":best_result_1_profit"),
(assign, ":best_result_1_item", ":random_trade_good"),
(assign, ":best_result_1_town", ":random_town"),
(assign, ":best_result_1_profit", ":difference"),
(else_try),
(eq, ":best_result_2_item", ":random_trade_good"),
(gt, ":difference", ":best_result_2_profit"),
(assign, ":best_result_2_item", ":random_trade_good"),
(assign, ":best_result_2_town", ":random_town"),
(assign, ":best_result_2_profit", ":difference"),
(else_try),
(eq, ":best_result_3_item", ":random_trade_good"),
(gt, ":difference", ":best_result_3_profit"),
(assign, ":best_result_3_item", ":random_trade_good"),
(assign, ":best_result_3_town", ":random_town"),
(assign, ":best_result_3_profit", ":difference"),
(else_try),
(eq, ":best_result_4_item", ":random_trade_good"),
(gt, ":difference", ":best_result_4_profit"),
(assign, ":best_result_4_item", ":random_trade_good"),
(assign, ":best_result_4_town", ":random_town"),
(assign, ":best_result_4_profit", ":difference"),
(else_try),
(eq, ":best_result_5_item", ":random_trade_good"),
(gt, ":difference", ":best_result_5_profit"),
(assign, ":best_result_5_item", ":random_trade_good"),
(assign, ":best_result_5_town", ":random_town"),
(assign, ":best_result_5_profit", ":difference"),
(try_end),
(else_try),
(try_begin),
(gt, ":difference", ":best_result_1_profit"),
(val_add, ":num_best_results", 1),
(val_min, ":num_best_results", 5),
(assign, ":best_result_5_item", ":best_result_4_item"),
(assign, ":best_result_5_town", ":best_result_4_town"),
(assign, ":best_result_5_profit", ":best_result_4_profit"),
(assign, ":best_result_4_item", ":best_result_3_item"),
(assign, ":best_result_4_town", ":best_result_3_town"),
(assign, ":best_result_4_profit", ":best_result_3_profit"),
(assign, ":best_result_3_item", ":best_result_2_item"),
(assign, ":best_result_3_town", ":best_result_2_town"),
(assign, ":best_result_3_profit", ":best_result_2_profit"),
(assign, ":best_result_2_item", ":best_result_1_item"),
(assign, ":best_result_2_town", ":best_result_1_town"),
(assign, ":best_result_2_profit", ":best_result_1_profit"),
(assign, ":best_result_1_item", ":random_trade_good"),
(assign, ":best_result_1_town", ":random_town"),
(assign, ":best_result_1_profit", ":difference"),
(else_try),
(gt, ":difference", ":best_result_2_profit"),
(val_add, ":num_best_results", 1),
(val_min, ":num_best_results", 5),
(assign, ":best_result_5_item", ":best_result_4_item"),
(assign, ":best_result_5_town", ":best_result_4_town"),
(assign, ":best_result_5_profit", ":best_result_4_profit"),
(assign, ":best_result_4_item", ":best_result_3_item"),
(assign, ":best_result_4_town", ":best_result_3_town"),
(assign, ":best_result_4_profit", ":best_result_3_profit"),
(assign, ":best_result_3_item", ":best_result_2_item"),
(assign, ":best_result_3_town", ":best_result_2_town"),
(assign, ":best_result_3_profit", ":best_result_2_profit"),
(assign, ":best_result_2_item", ":random_trade_good"),
(assign, ":best_result_2_town", ":random_town"),
(assign, ":best_result_2_profit", ":difference"),
(else_try),
(gt, ":difference", ":best_result_3_profit"),
(val_add, ":num_best_results", 1),
(val_min, ":num_best_results", 5),
(assign, ":best_result_5_item", ":best_result_4_item"),
(assign, ":best_result_5_town", ":best_result_4_town"),
(assign, ":best_result_5_profit", ":best_result_4_profit"),
(assign, ":best_result_4_item", ":best_result_3_item"),
(assign, ":best_result_4_town", ":best_result_3_town"),
(assign, ":best_result_4_profit", ":best_result_3_profit"),
(assign, ":best_result_3_item", ":random_trade_good"),
(assign, ":best_result_3_town", ":random_town"),
(assign, ":best_result_3_profit", ":difference"),
(else_try),
(gt, ":difference", ":best_result_4_profit"),
(val_add, ":num_best_results", 1),
(val_min, ":num_best_results", 5),
(assign, ":best_result_5_item", ":best_result_4_item"),
(assign, ":best_result_5_town", ":best_result_4_town"),
(assign, ":best_result_5_profit", ":best_result_4_profit"),
(assign, ":best_result_4_item", ":random_trade_good"),
(assign, ":best_result_4_town", ":random_town"),
(assign, ":best_result_4_profit", ":difference"),
(else_try),
(gt, ":difference", ":best_result_5_profit"),
(val_add, ":num_best_results", 1),
(val_min, ":num_best_results", 5),
(assign, ":best_result_5_item", ":best_result_4_item"),
(assign, ":best_result_5_town", ":best_result_4_town"),
(assign, ":best_result_5_profit", ":best_result_4_profit"),
(try_end),
(try_end),
(try_end),
(assign, "$g_encountered_party", ":org_encountered_party"),
(str_clear, s3),
(assign, reg2, ":max_skill"),
(try_begin),
(eq, ":max_skill_owner", "trp_player"),
(assign, reg3, 1),
(else_try),
(assign, reg3, 0),
(str_store_troop_name, s1, ":max_skill_owner"),
(try_end),
(try_begin),
(le, ":num_best_results", 0),
(str_store_string, s2, "@However, {reg3?You are:{s1} is} unable to find any trade goods that would bring a profit."),
(else_try),
(try_begin),
(ge, ":best_result_5_item", 0),
(assign, reg6, ":best_result_5_profit"),
(str_store_item_name, s4, ":best_result_5_item"),
(str_store_party_name, s5, ":best_result_5_town"),
(str_store_string, s3, "@^Buying {s4} here and selling it at {s5} would bring a profit of {reg6} denars per item.{s3}"),
(try_end),
(try_begin),
(ge, ":best_result_4_item", 0),
(assign, reg6, ":best_result_4_profit"),
(str_store_item_name, s4, ":best_result_4_item"),
(str_store_party_name, s5, ":best_result_4_town"),
(str_store_string, s3, "@^Buying {s4} here and selling it at {s5} would bring a profit of {reg6} denars per item.{s3}"),
(try_end),
(try_begin),
(ge, ":best_result_3_item", 0),
(assign, reg6, ":best_result_3_profit"),
(str_store_item_name, s4, ":best_result_3_item"),
(str_store_party_name, s5, ":best_result_3_town"),
(str_store_string, s3, "@^Buying {s4} here and selling it at {s5} would bring a profit of {reg6} denars per item.{s3}"),
(try_end),
(try_begin),
(ge, ":best_result_2_item", 0),
(assign, reg6, ":best_result_2_profit"),
(str_store_item_name, s4, ":best_result_2_item"),
(str_store_party_name, s5, ":best_result_2_town"),
(str_store_string, s3, "@^Buying {s4} here and selling it at {s5} would bring a profit of {reg6} denars per item.{s3}"),
(try_end),
(try_begin),
(ge, ":best_result_1_item", 0),
(assign, reg6, ":best_result_1_profit"),
(str_store_item_name, s4, ":best_result_1_item"),
(str_store_party_name, s5, ":best_result_1_town"),
(str_store_string, s3, "@^Buying {s4} here and selling it at {s5} would bring a profit of {reg6} denars per item.{s3}"),
(try_end),
(str_store_string, s2, "@{reg3?You find:{s1} finds} out the following:^{s3}"),
(try_end),
],
[
("continue",[],"Continue...",
[
(jump_to_menu,"mnu_town_trade"),
]),
]
),
(
"sneak_into_town_suceeded",0,
"Disguised in the garments of a poor pilgrim, you fool the guards and make your way into the town.",
"none",
[],
[
("continue",[],"Continue...",
[
(assign, "$sneaked_into_town",1),
(jump_to_menu,"mnu_town"),
]),
]
),
(
"sneak_into_town_caught",0,
"As you try to sneak in, one of the guards recognizes you and raises the alarm!\
You must flee back through the gates before all the guards in the town come down on you!",
"none",
[
(assign,"$auto_menu","mnu_captivity_start_castle_surrender"),
],
[
("sneak_caught_fight",[],"Try to fight your way out!",
[
(assign,"$all_doors_locked",1),
(party_get_slot, ":sneak_scene", "$current_town", slot_town_center), # slot_town_gate),
(modify_visitors_at_site,":sneak_scene"),
(reset_visitors),
(try_begin),
(this_or_next|eq, "$talk_context", tc_escape),
(eq, "$talk_context", tc_prison_break),
(set_jump_entry, 7),
(else_try),
(party_slot_eq, "$current_town", slot_party_type, spt_town),
#(set_visitor,0,"trp_player"),
(set_jump_entry, 0),
(else_try),
#(set_visitor,1,"trp_player"),
(set_jump_entry, 1),
(try_end),
#(store_faction_of_party, ":town_faction","$current_town"),
#(faction_get_slot, ":tier_2_troop", ":town_faction", slot_faction_tier_2_troop),
#(faction_get_slot, ":tier_3_troop", ":town_faction", slot_faction_tier_3_troop),
#(try_begin),
# (gt, ":tier_2_troop", 0),
# (gt, ":tier_3_troop", 0),
# (assign,reg0,":tier_3_troop"),
# (assign,reg1,":tier_3_troop"),
# (assign,reg2,":tier_2_troop"),
# (assign,reg3,":tier_2_troop"),
#(else_try),
# (assign,reg0,"trp_swadian_skirmisher"),
# (assign,reg1,"trp_swadian_crossbowman"),
# (assign,reg2,"trp_swadian_infantry"),
# (assign,reg3,"trp_swadian_crossbowman"),
#(try_end),
#(assign,reg4,-1),
#(shuffle_range,0,5),
#(set_visitor,2,reg0),
#(set_visitor,3,reg1),
#(set_visitor,4,reg2),
#(set_visitor,5,reg3),
(set_jump_mission,"mt_sneak_caught_fight"),
(set_passage_menu,"mnu_town"),
(jump_to_scene,":sneak_scene"),
(change_screen_mission),
]),
("sneak_caught_surrender",[],"Surrender.",
[
(jump_to_menu,"mnu_captivity_start_castle_surrender"),
]),
]
),
(
"sneak_into_town_caught_dispersed_guards",0,
"You drive off the guards and cover your trail before running off, easily losing your pursuers in the maze of streets.",
"none",
[],
[
("continue",[],"Continue...",
[
(assign, "$sneaked_into_town",1),
(assign, "$town_entered", 1),
(jump_to_menu,"mnu_town"),
]),
]
),
(
"sneak_into_town_caught_ran_away",0,
"You make your way back through the gates and quickly retreat to the safety of the countryside.{s11}",
"none",
[
(str_clear, s11),
(assign, ":at_least_one_escaper_caught", 0),
(assign, ":end_cond", kingdom_ladies_end),
(try_for_range, ":prisoner", active_npcs_begin, ":end_cond"),
(try_begin),
(troop_slot_eq, ":prisoner", slot_troop_mission_participation, mp_prison_break_escaped),
(assign, "$talk_context", tc_hero_freed),
(assign, reg14, ":prisoner"),
(call_script, "script_setup_troop_meeting", ":prisoner", -1),
(troop_set_slot, ":prisoner", slot_troop_mission_participation, -1),
(troop_get_slot, ":prison_center", ":prisoner", slot_troop_prisoner_of_party),
(party_remove_prisoners, ":prison_center", ":prisoner", 1),
(troop_set_slot, ":prisoner", slot_troop_prisoner_of_party, -1),
(assign, ":end_cond", -1),
(else_try),
(troop_slot_eq, ":prisoner", slot_troop_mission_participation, mp_prison_break_caught),
(str_store_troop_name, s12, ":prisoner"),
(try_begin),
(eq, ":at_least_one_escaper_caught", 0),
(str_store_string, s11, "str_s11_unfortunately_s12_was_wounded_and_had_to_be_left_behind"),
(else_try),
(str_store_string, s11, "str_s11_also_s12_was_wounded_and_had_to_be_left_behind"),
(try_end),
(assign, ":at_least_one_escaper_caught", 1),
(try_end),
(troop_set_slot, ":prisoner", slot_troop_mission_participation, 0), #new
(try_end),
],
[
("continue",[],"Continue...",
[
(assign,"$auto_menu",-1),
(store_encountered_party,"$last_sneak_attempt_town"),
(store_current_hours,"$last_sneak_attempt_time"),
(change_screen_return),
]),
]
),
(
"enemy_offer_ransom_for_prisoner",0,
"{s2} offers you a sum of {reg12} denars in silver if you are willing to sell him {s1}.",
"none",
[(call_script, "script_calculate_ransom_amount_for_troop", "$g_ransom_offer_troop"),
(assign, reg12, reg0),
(str_store_troop_name, s1, "$g_ransom_offer_troop"),
(store_troop_faction, ":faction_no", "$g_ransom_offer_troop"),
(str_store_faction_name, s2, ":faction_no"),
],
[
("ransom_accept",[],"Accept the offer.",
[(troop_add_gold, "trp_player", reg12),
(party_remove_prisoners, "$g_ransom_offer_party", "$g_ransom_offer_troop", 1),
(call_script, "script_remove_troop_from_prison", "$g_ransom_offer_troop"),
(try_begin),
(troop_get_type, ":is_female", "trp_player"),
(eq, ":is_female", 1),
(get_achievement_stat, ":number_of_lords_sold", ACHIEVEMENT_MAN_HANDLER, 0),
(val_add, ":number_of_lords_sold", 1),
(set_achievement_stat, ACHIEVEMENT_MAN_HANDLER, 0, ":number_of_lords_sold"),
(eq, ":number_of_lords_sold", 3),
(unlock_achievement, ACHIEVEMENT_MAN_HANDLER),
(try_end),
(change_screen_return),
]),
("ransom_reject",[],"Reject the offer.",
[
(call_script, "script_change_player_relation_with_troop", "$g_ransom_offer_troop", -4),
(call_script, "script_change_player_honor", -1),
(assign, "$g_ransom_offer_rejected", 1),
(change_screen_return),
]),
]
),
(
"training_ground",0,
"You approach a training field where you can practice your martial skills. What kind of training do you want to do?",
"none",
[
(store_add, "$g_training_ground_melee_training_scene", "scn_training_ground_ranged_melee_1", "$g_encountered_party"),
(val_sub, "$g_training_ground_melee_training_scene", training_grounds_begin),
(try_begin),
(ge, "$g_training_ground_training_count", 3),
(assign, "$g_training_ground_training_count", 0),
(rest_for_hours, 1, 5, 1), #rest while attackable
(assign, "$auto_enter_town", "$g_encountered_party"),
(change_screen_return),
(try_end),
],
[
("camp_trainer",
[], "Speak with the trainer.",
[
(set_jump_mission, "mt_training_ground_trainer_talk"),
(modify_visitors_at_site, "$g_training_ground_melee_training_scene"),
(reset_visitors),
(set_jump_entry, 5),
(jump_to_scene, "$g_training_ground_melee_training_scene"),
(change_screen_mission),
(music_set_situation, 0),
]),
("camp_train_melee",
[
(neg|troop_is_wounded, "trp_player"),
(call_script, "script_party_count_fit_for_battle", "p_main_party"),
(gt, reg0, 1),
], "Sparring practice.",
[
(assign, "$g_mt_mode", ctm_melee),
(jump_to_menu, "mnu_training_ground_selection_details_melee_1"),
(music_set_situation, 0),
]),
("camp_train_archery",[], "Ranged weapon practice.",
[
(jump_to_menu, "mnu_training_ground_selection_details_ranged_1"),
(music_set_situation, 0),
]),
("camp_train_mounted",[], "Horseback practice.",
[
(assign, "$g_mt_mode", ctm_mounted),
(jump_to_menu, "mnu_training_ground_selection_details_mounted"),
(music_set_situation, 0),
]),
("go_to_track",[(eq, "$cheat_mode", 1)],"{!}Cheat: Go to track.",
[
(set_jump_mission, "mt_ai_training"),
(store_add, ":scene_no", "scn_training_ground_horse_track_1", "$g_encountered_party"),
(val_sub, ":scene_no", training_grounds_begin),
(jump_to_scene, ":scene_no"),
(change_screen_mission),
]
),
("go_to_range",[(eq, "$cheat_mode", 1)],"{!}Cheat: Go to range.",
[
(set_jump_mission, "mt_ai_training"),
(jump_to_scene, "$g_training_ground_melee_training_scene"),
(change_screen_mission),
]
),
("leave",[],"Leave.",
[(change_screen_return),
]),
]
),
("training_ground_selection_details_melee_1",0,
"How many opponents will you go against?",
"none",
[
(call_script, "script_write_fit_party_members_to_stack_selection", "p_main_party", 1),
(troop_get_slot, "$temp", "trp_stack_selection_amounts", 1), #number of men fit
(assign, "$temp_2", 1),
],
[
("camp_train_melee_num_men_1",[(ge, "$temp", 1)], "One.",
[
(assign, "$temp", 1),
(jump_to_menu, "mnu_training_ground_selection_details_melee_2"),
]),
("camp_train_melee_num_men_2",[(ge, "$temp", 2)], "Two.",
[
(assign, "$temp", 2),
(jump_to_menu, "mnu_training_ground_selection_details_melee_2"),
]),
("camp_train_melee_num_men_3",[(ge, "$temp", 3)], "Three.",
[
(assign, "$temp", 3),
(jump_to_menu, "mnu_training_ground_selection_details_melee_2"),
]),
("camp_train_melee_num_men_4",[(ge, "$temp", 4)], "Four.",
[
(assign, "$temp", 4),
(jump_to_menu, "mnu_training_ground_selection_details_melee_2"),
]),
("go_back_dot",[],"Cancel.",
[
(jump_to_menu, "mnu_training_ground"),
]),
]
),
("training_ground_selection_details_melee_2",0,
"Choose your opponent #{reg1}:",
"none",
[
(assign, reg1, "$temp_2"),
(troop_get_slot, "$temp_3", "trp_stack_selection_amounts", 0), #number of slots
],
[
("s0", [(call_script, "script_cf_training_ground_sub_routine_1_for_melee_details", 1),], "{s0}",
[(call_script, "script_training_ground_sub_routine_2_for_melee_details", 1),]),
("s0", [(call_script, "script_cf_training_ground_sub_routine_1_for_melee_details", 2),], "{s0}",
[(call_script, "script_training_ground_sub_routine_2_for_melee_details", 2),]),
("s0", [(call_script, "script_cf_training_ground_sub_routine_1_for_melee_details", 3),], "{s0}",
[(call_script, "script_training_ground_sub_routine_2_for_melee_details", 3),]),
("s0", [(call_script, "script_cf_training_ground_sub_routine_1_for_melee_details", 4),], "{s0}",
[(call_script, "script_training_ground_sub_routine_2_for_melee_details", 4),]),
("s0", [(call_script, "script_cf_training_ground_sub_routine_1_for_melee_details", 5),], "{s0}",
[(call_script, "script_training_ground_sub_routine_2_for_melee_details", 5),]),
("s0", [(call_script, "script_cf_training_ground_sub_routine_1_for_melee_details", 6),], "{s0}",
[(call_script, "script_training_ground_sub_routine_2_for_melee_details", 6),]),
("s0", [(call_script, "script_cf_training_ground_sub_routine_1_for_melee_details", 7),], "{s0}",
[(call_script, "script_training_ground_sub_routine_2_for_melee_details", 7),]),
("s0", [(call_script, "script_cf_training_ground_sub_routine_1_for_melee_details", 8),], "{s0}",
[(call_script, "script_training_ground_sub_routine_2_for_melee_details", 8),]),
("s0", [(call_script, "script_cf_training_ground_sub_routine_1_for_melee_details", 9),], "{s0}",
[(call_script, "script_training_ground_sub_routine_2_for_melee_details", 9),]),
("s0", [(call_script, "script_cf_training_ground_sub_routine_1_for_melee_details", 10),], "{s0}",
[(call_script, "script_training_ground_sub_routine_2_for_melee_details", 10),]),
("s0", [(call_script, "script_cf_training_ground_sub_routine_1_for_melee_details", 11),], "{s0}",
[(call_script, "script_training_ground_sub_routine_2_for_melee_details", 11),]),
("s0", [(call_script, "script_cf_training_ground_sub_routine_1_for_melee_details", 12),], "{s0}",
[(call_script, "script_training_ground_sub_routine_2_for_melee_details", 12),]),
("s0", [(call_script, "script_cf_training_ground_sub_routine_1_for_melee_details", 13),], "{s0}",
[(call_script, "script_training_ground_sub_routine_2_for_melee_details", 13),]),
("s0", [(call_script, "script_cf_training_ground_sub_routine_1_for_melee_details", 14),], "{s0}",
[(call_script, "script_training_ground_sub_routine_2_for_melee_details", 14),]),
("s0", [(call_script, "script_cf_training_ground_sub_routine_1_for_melee_details", 15),], "{s0}",
[(call_script, "script_training_ground_sub_routine_2_for_melee_details", 15),]),
("s0", [(call_script, "script_cf_training_ground_sub_routine_1_for_melee_details", 16),], "{s0}",
[(call_script, "script_training_ground_sub_routine_2_for_melee_details", 16),]),
("s0", [(call_script, "script_cf_training_ground_sub_routine_1_for_melee_details", 17),], "{s0}",
[(call_script, "script_training_ground_sub_routine_2_for_melee_details", 17),]),
("s0", [(call_script, "script_cf_training_ground_sub_routine_1_for_melee_details", 18),], "{s0}",
[(call_script, "script_training_ground_sub_routine_2_for_melee_details", 18),]),
("s0", [(call_script, "script_cf_training_ground_sub_routine_1_for_melee_details", 19),], "{s0}",
[(call_script, "script_training_ground_sub_routine_2_for_melee_details", 19),]),
("s0", [(call_script, "script_cf_training_ground_sub_routine_1_for_melee_details", 20),], "{s0}",
[(call_script, "script_training_ground_sub_routine_2_for_melee_details", 20),]),
("training_ground_selection_details_melee_random", [], "Choose randomly.",
[(call_script, "script_training_ground_sub_routine_2_for_melee_details", -1),]),
("go_back_dot",[],"Go back.",
[(jump_to_menu, "mnu_training_ground"),
]
),
]
),
("training_ground_selection_details_mounted",0,
"What kind of weapon do you want to train with?",
"none",
[],
[
("camp_train_mounted_details_1",[], "One handed weapon.",
[
(call_script, "script_start_training_at_training_ground", itp_type_one_handed_wpn, 0),
]),
("camp_train_mounted_details_2",[], "Polearm.",
[
(call_script, "script_start_training_at_training_ground", itp_type_polearm, 0),
]),
("camp_train_mounted_details_3",[], "Bow.",
[
(call_script, "script_start_training_at_training_ground", itp_type_bow, 0),
]),
("camp_train_mounted_details_4",[], "Thrown weapon.",
[
(call_script, "script_start_training_at_training_ground", itp_type_thrown, 0),
]),
("go_back_dot",[],"Go back.",
[(jump_to_menu, "mnu_training_ground"),
]
),
]
),
("training_ground_selection_details_ranged_1",0,
"What kind of ranged weapon do you want to train with?",
"none",
[],
[
("camp_train_ranged_weapon_bow",[], "Bow and arrows.",
[
(assign, "$g_mt_mode", ctm_ranged),
(assign, "$temp", itp_type_bow),
(jump_to_menu, "mnu_training_ground_selection_details_ranged_2"),
]),
("camp_train_ranged_weapon_crossbow",[], "Crossbow.",
[
(assign, "$g_mt_mode", ctm_ranged),
(assign, "$temp", itp_type_crossbow),
(jump_to_menu, "mnu_training_ground_selection_details_ranged_2"),
]),
("camp_train_ranged_weapon_thrown",[], "Throwing Knives.",
[
(assign, "$g_mt_mode", ctm_ranged),
(assign, "$temp", itp_type_thrown),
(jump_to_menu, "mnu_training_ground_selection_details_ranged_2"),
]),
("go_back_dot",[],"Go back.",
[(jump_to_menu, "mnu_training_ground"),
]
),
]
),
("training_ground_selection_details_ranged_2",0,
"What range do you want to practice at?",
"none",
[],
[
("camp_train_ranged_details_1",[], "10 yards.",
[
(call_script, "script_start_training_at_training_ground", "$temp", 10),
]),
("camp_train_ranged_details_2",[], "20 yards.",
[
(call_script, "script_start_training_at_training_ground", "$temp", 20),
]),
("camp_train_ranged_details_3",[], "30 yards.",
[
(call_script, "script_start_training_at_training_ground", "$temp", 30),
]),
("camp_train_ranged_details_4",[], "40 yards.",
[
(call_script, "script_start_training_at_training_ground", "$temp", 40),
]),
("camp_train_ranged_details_5",[(eq, "$g_mt_mode", ctm_ranged),], "50 yards.",
[
(call_script, "script_start_training_at_training_ground", "$temp", 50),
]),
("camp_train_ranged_details_6",[(eq, "$g_mt_mode", ctm_ranged),], "60 yards.",
[
(call_script, "script_start_training_at_training_ground", "$temp", 60),
]),
("camp_train_ranged_details_7",[(eq, "$g_mt_mode", ctm_ranged),], "70 yards.",
[
(call_script, "script_start_training_at_training_ground", "$temp", 70),
]),
("go_back_dot",[],"Go back.",
[(jump_to_menu, "mnu_training_ground"),
]
),
]
),
("training_ground_description",0,
"{s0}",
"none",
[],
[
("continue", [], "Continue...",
[
(jump_to_scene, "$g_training_ground_training_scene"),
(change_screen_mission),
]
),
]
),
("training_ground_training_result",mnf_disable_all_keys,
"{s7}{s2}",
"none",
[
(store_skill_level, ":trainer_skill", "skl_trainer", "trp_player"),
(store_add, ":trainer_skill_multiplier", 5, ":trainer_skill"),
(call_script, "script_write_fit_party_members_to_stack_selection", "p_main_party", 1),
(str_clear, s2),
(troop_get_slot, ":num_fit", "trp_stack_selection_amounts", 1),
(troop_get_slot, ":num_slots", "trp_stack_selection_amounts", 0),
(try_begin),
(gt, "$g_training_ground_training_success_ratio", 0),
(store_mul, ":xp_ratio_to_add", "$g_training_ground_training_success_ratio", "$g_training_ground_training_success_ratio"),
(try_begin),
(eq, "$g_training_ground_training_success_ratio", 100),
(val_mul, ":xp_ratio_to_add", 2), #2x when perfect
(try_end),
(try_begin),
(eq, "$g_mt_mode", ctm_melee),
(val_div, ":xp_ratio_to_add", 2),
(try_end),
(val_div, ":xp_ratio_to_add", 10), # value over 1000
(try_begin),
(gt, ":num_fit", 8),
(val_mul, ":xp_ratio_to_add", 3),
(assign, ":divisor", ":num_fit"),
(convert_to_fixed_point, ":divisor"),
(store_sqrt, ":divisor", ":divisor"),
(convert_to_fixed_point, ":xp_ratio_to_add"),
(val_div, ":xp_ratio_to_add", ":divisor"),
(try_end),
## (assign, reg0, ":xp_ratio_to_add"),
## (display_message, "@xp earn ratio: {reg0}/1000"),
(store_mul, ":xp_ratio_to_add_with_trainer_skill", ":xp_ratio_to_add", ":trainer_skill_multiplier"),
(val_div, ":xp_ratio_to_add_with_trainer_skill", 10),
(party_get_num_companion_stacks, ":num_stacks", "p_main_party"),
(store_add, ":end_cond", ":num_slots", 2),
(try_for_range, ":i_slot", 2, ":end_cond"),
(troop_get_slot, ":amount", "trp_stack_selection_amounts", ":i_slot"),
(troop_get_slot, ":troop_id", "trp_stack_selection_ids", ":i_slot"),
(assign, ":end_cond_2", ":num_stacks"),
(try_for_range, ":stack_no", 0, ":end_cond_2"),
(party_stack_get_troop_id, ":stack_troop", "p_main_party", ":stack_no"),
(eq, ":stack_troop", ":troop_id"),
(assign, ":end_cond_2", 0), #break
(call_script, "script_cf_training_ground_sub_routine_for_training_result", ":troop_id", ":stack_no", ":amount", ":xp_ratio_to_add_with_trainer_skill"),
(str_store_troop_name_by_count, s1, ":troop_id", ":amount"),
(assign, reg1, ":amount"),
(str_store_string, s2, "@{s2}^{reg1} {s1} earned {reg0} experience."),
(try_end),
(try_end),
(try_begin),
(eq, "$g_mt_mode", ctm_melee),
(store_mul, ":special_xp_ratio_to_add", ":xp_ratio_to_add", 3),
(val_div, ":special_xp_ratio_to_add", 2),
(try_for_range, ":enemy_index", 0, "$g_training_ground_training_num_enemies"),
(troop_get_slot, ":troop_id", "trp_temp_array_a", ":enemy_index"),
(assign, ":end_cond_2", ":num_stacks"),
(try_for_range, ":stack_no", 0, ":end_cond_2"),
(party_stack_get_troop_id, ":stack_troop", "p_main_party", ":stack_no"),
(eq, ":stack_troop", ":troop_id"),
(assign, ":end_cond_2", 0), #break
(call_script, "script_cf_training_ground_sub_routine_for_training_result", ":troop_id", ":stack_no", 1, ":special_xp_ratio_to_add"),
(str_store_troop_name, s1, ":troop_id"),
(str_store_string, s2, "@{s2}^{s1} earned an additional {reg0} experience."),
(try_end),
(try_end),
(try_end),
(try_begin),
(call_script, "script_cf_training_ground_sub_routine_for_training_result", "trp_player", -1, 1, ":xp_ratio_to_add"),
(str_store_string, s2, "@^You earned {reg0} experience.{s2}"),
(try_end),
(try_end),
(try_begin),
(eq, "$g_training_ground_training_success_ratio", 0),
(str_store_string, s7, "@The training didn't go well at all."),
(else_try),
(lt, "$g_training_ground_training_success_ratio", 25),
(str_store_string, s7, "@The training didn't go well at all."),
(else_try),
(lt, "$g_training_ground_training_success_ratio", 50),
(str_store_string, s7, "@The training didn't go very well."),
(else_try),
(lt, "$g_training_ground_training_success_ratio", 75),
(str_store_string, s7, "@The training went quite well."),
(else_try),
(lt, "$g_training_ground_training_success_ratio", 99),
(str_store_string, s7, "@The training went very well."),
(else_try),
(str_store_string, s7, "@The training went perfectly."),
(try_end),
],
[
("continue",[],"Continue...",
[(jump_to_menu, "mnu_training_ground"),
]
),
]
),
("marshall_selection_candidate_ask",0,
"{s15} will soon select a new marshall for {s23}. Some of the lords have suggested your name as a likely candidate.",
"none",
[
(try_begin),
(eq, "$g_presentation_marshall_selection_ended", 1),
(change_screen_return),
(try_end),
(faction_get_slot, ":king", "$players_kingdom", slot_faction_leader),
(str_store_troop_name, s15, ":king"),
(str_store_faction_name, s23, "$players_kingdom"),
],
[
("marshall_candidate_accept", [], "Let {s15} learn that you are willing to serve as marshall.",
[
(start_presentation, "prsnt_marshall_selection"),
]
),
("marshall_candidate_reject", [], "Tell everyone that you are too busy these days.",
[
(try_begin),
(eq, "$g_presentation_marshall_selection_max_renown_2_troop", "trp_player"),
(assign, "$g_presentation_marshall_selection_max_renown_2", "$g_presentation_marshall_selection_max_renown_3"),
(assign, "$g_presentation_marshall_selection_max_renown_2_troop", "$g_presentation_marshall_selection_max_renown_3_troop"),
(else_try),
(assign, "$g_presentation_marshall_selection_max_renown_1", "$g_presentation_marshall_selection_max_renown_2"),
(assign, "$g_presentation_marshall_selection_max_renown_1_troop", "$g_presentation_marshall_selection_max_renown_2_troop"),
(assign, "$g_presentation_marshall_selection_max_renown_2", "$g_presentation_marshall_selection_max_renown_3"),
(assign, "$g_presentation_marshall_selection_max_renown_2_troop", "$g_presentation_marshall_selection_max_renown_3_troop"),
(try_end),
(start_presentation, "prsnt_marshall_selection"),
]
),
]
),
## [
## ("renew_oath",[],"Renew your oath to {s1} for another month.",[
## (store_current_day, ":cur_day"),
## (store_add, "$g_oath_end_day", ":cur_day", 30),
## (change_screen_return)]),
## ("dont_renew_oath",[],"Become free of your bond.",[
## (assign, "$players_kingdom",0),
## (assign, "$g_player_permitted_castles", 0),
## (change_screen_return)]),
## ]
## ),
#####################################################################
## Captivity....
#####################################################################
#####################################################################
#####################################################################
#####################################################################
(
"captivity_avoid_wilderness",0,
"Suddenly all the world goes black around you.\
Many hours later you regain your conciousness and find yourself at the spot you fell.\
Your enemies must have taken you up for dead and left you there.\
However, it seems that none of your wound were lethal,\
and altough you feel awful, you find out that can still walk.\
You get up and try to look for any other survivors from your party.",
"none",
[
],
[]
),
(
"captivity_start_wilderness",0,
"Stub",
"none",
[
(assign, "$g_player_is_captive", 1),
(try_begin),
(eq,"$g_player_surrenders",1),
(jump_to_menu, "mnu_captivity_start_wilderness_surrender"),
(else_try),
(jump_to_menu, "mnu_captivity_start_wilderness_defeat"),
(try_end),
],
[]
),
(
"captivity_start_wilderness_surrender",0,
"Stub",
"none",
[
(assign, "$g_player_is_captive", 1),
(assign,"$auto_menu",-1), #We need this since we may come here by something other than auto_menu
(assign, "$capturer_party", "$g_encountered_party"),
(jump_to_menu, "mnu_captivity_wilderness_taken_prisoner"),
],
[]
),
(
"captivity_start_wilderness_defeat",0,
"Your enemies take you prisoner.",
"none",
[
(assign, "$g_player_is_captive", 1),
(assign,"$auto_menu",-1),
(assign, "$capturer_party", "$g_encountered_party"),
(try_begin),
(party_stack_get_troop_id, ":party_leader", "$g_encountered_party", 0),
(is_between, ":party_leader", active_npcs_begin, active_npcs_end),
(troop_slot_eq, ":party_leader", slot_troop_occupation, slto_kingdom_hero),
(store_sub, ":kingdom_hero_id", ":party_leader", active_npcs_begin),
(set_achievement_stat, ACHIEVEMENT_BARON_GOT_BACK, ":kingdom_hero_id", 1),
(try_end),
(jump_to_menu, "mnu_captivity_wilderness_taken_prisoner"),
],
[]
),
(
"captivity_start_castle_surrender",0,
"Stub",
"none",
[
(assign, "$g_player_is_captive", 1),
(assign,"$auto_menu",-1),
(assign, "$capturer_party", "$g_encountered_party"),
(jump_to_menu, "mnu_captivity_castle_taken_prisoner"),
],
[]
),
(
"captivity_start_castle_defeat",0,
"Stub",
"none",
[
(assign, "$g_player_is_captive", 1),
(assign,"$auto_menu",-1),
(assign, "$capturer_party", "$g_encountered_party"),
(jump_to_menu, "mnu_captivity_castle_taken_prisoner"),
],
[]
),
(
"captivity_start_under_siege_defeat",0,
"Your enemies take you prisoner.",
"none",
[
(assign, "$g_player_is_captive", 1),
(assign,"$auto_menu",-1),
(assign, "$capturer_party", "$g_encountered_party"),
(jump_to_menu, "mnu_captivity_castle_taken_prisoner"),
],
[]
),
(
"captivity_wilderness_taken_prisoner",mnf_scale_picture,
"Your enemies take you prisoner.",
"none",
[
(set_background_mesh, "mesh_pic_prisoner_wilderness"),
],
[
("continue",[],"Continue...",
[
# Explanation of removing below code : heros are already being removed with 50% (was 75%, I decreased it) probability in mnu_total_defeat, why here there is additionally 30% removing of heros?
# See codes linked to "mnu_captivity_start_wilderness_surrender" and "mnu_captivity_start_wilderness_defeat" which is connected with here they all also enter
# "mnu_total_defeat" and inside the "mnu_total_defeat" there is script_party_remove_all_companions which removes 50% (was 75%, I decreased it) of compainons from player party.
#(try_for_range, ":npc", companions_begin, companions_end),
# (main_party_has_troop, ":npc"),
# (store_random_in_range, ":rand", 0, 100),
# (lt, ":rand", 30),
# (remove_member_from_party, ":npc", "p_main_party"),
# (troop_set_slot, ":npc", slot_troop_occupation, 0),
# (troop_set_slot, ":npc", slot_troop_playerparty_history, pp_history_scattered),
# (assign, "$last_lost_companion", ":npc"),
# (store_faction_of_party, ":victorious_faction", "$g_encountered_party"),
# (troop_set_slot, ":npc", slot_troop_playerparty_history_string, ":victorious_faction"),
# (troop_set_health, ":npc", 100),
# (store_random_in_range, ":rand_town", towns_begin, towns_end),
# (troop_set_slot, ":npc", slot_troop_cur_center, ":rand_town"),
# (assign, ":nearest_town_dist", 1000),
# (try_for_range, ":town_no", towns_begin, towns_end),
# (store_faction_of_party, ":town_fac", ":town_no"),
# (store_relation, ":reln", ":town_fac", "fac_player_faction"),
# (ge, ":reln", 0),
# (store_distance_to_party_from_party, ":dist", ":town_no", "p_main_party"),
# (lt, ":dist", ":nearest_town_dist"),
# (assign, ":nearest_town_dist", ":dist"),
# (troop_set_slot, ":npc", slot_troop_cur_center, ":town_no"),
# (try_end),
#(try_end),
(set_camera_follow_party, "$capturer_party"),
(assign, "$g_player_is_captive", 1),
(store_random_in_range, ":random_hours", 18, 30),
(call_script, "script_event_player_captured_as_prisoner"),
(call_script, "script_stay_captive_for_hours", ":random_hours"),
(assign,"$auto_menu","mnu_captivity_wilderness_check"),
(change_screen_return),
]),
]
),
(
"captivity_wilderness_check",0,
"stub",
"none",
[(jump_to_menu,"mnu_captivity_end_wilderness_escape")],
[]
),
(
"captivity_end_wilderness_escape", mnf_scale_picture,
"After painful days of being dragged about as a prisoner, you find a chance and escape from your captors!",
"none",
[
(play_cue_track, "track_escape"),
(troop_get_type, ":is_female", "trp_player"),
(try_begin),
(eq, ":is_female", 1),
(set_background_mesh, "mesh_pic_escape_1_fem"),
(else_try),
(set_background_mesh, "mesh_pic_escape_1"),
(try_end),
],
[
("continue",[],"Continue...",
[
(assign, "$g_player_is_captive", 0),
(try_begin),
(party_is_active, "$capturer_party"),
(party_relocate_near_party, "p_main_party", "$capturer_party", 2),
(try_end),
(call_script, "script_set_parties_around_player_ignore_player", 8, 12), #it was radius:2 and hours:4, but players make lots of complains about consequent battle losses after releases from captivity then I changed this.
(assign, "$g_player_icon_state", pis_normal),
(set_camera_follow_party, "p_main_party"),
(rest_for_hours, 0, 0, 0), #stop resting
(change_screen_return),
]),
]
),
(
"captivity_castle_taken_prisoner",0,
"You are quickly surrounded by guards who take away your weapons. With curses and insults, they throw you into the dungeon where you must while away the miserable days of your captivity.",
"none",
[
(troop_get_type, ":is_female", "trp_player"),
(try_begin),
(eq, ":is_female", 1),
(set_background_mesh, "mesh_pic_prisoner_fem"),
(else_try),
(set_background_mesh, "mesh_pic_prisoner_man"),
(try_end),
],
[
("continue",[],"Continue...",
[
(assign, "$g_player_is_captive", 1),
(store_random_in_range, ":random_hours", 16, 22),
(call_script, "script_event_player_captured_as_prisoner"),
(call_script, "script_stay_captive_for_hours", ":random_hours"),
(assign,"$auto_menu", "mnu_captivity_castle_check"),
(change_screen_return)
]),
]
),
(
"captivity_rescue_lord_taken_prisoner",0,
"You remain in disguise for as long as possible before revealing yourself.\
The guards are outraged and beat you savagely before throwing you back into the cell for God knows how long...",
"none",
[
(troop_get_type, ":is_female", "trp_player"),
(try_begin),
(eq, ":is_female", 1),
(set_background_mesh, "mesh_pic_prisoner_fem"),
(else_try),
(set_background_mesh, "mesh_pic_prisoner_man"),
(try_end),
],
[
("continue",[],"Continue...",
[
(assign, "$g_player_is_captive", 1),
(store_random_in_range, ":random_hours", 16, 22),
(call_script, "script_event_player_captured_as_prisoner"),
(call_script, "script_stay_captive_for_hours", ":random_hours"),
(assign,"$auto_menu", "mnu_captivity_castle_check"),
(change_screen_return),
]),
]
),
(
"captivity_castle_check",0,
"stub",
"none",
[
(store_random_in_range, reg(7), 0, 10),
(try_begin),
(party_is_active, "$capturer_party"),
(store_faction_of_party, ":capturer_faction", "$capturer_party"),
(is_between, ":capturer_faction", kingdoms_begin, kingdoms_end),
(store_relation, ":relation_w_player_faction", ":capturer_faction", "fac_player_faction"),
(ge, ":relation_w_player_faction", 0),
(jump_to_menu,"mnu_captivity_end_exchanged_with_prisoner"),
(else_try),
(lt, reg(7), 4),
(store_character_level, ":player_level", "trp_player"),
(store_mul, "$player_ransom_amount", ":player_level", 50),
(val_add, "$player_ransom_amount", 100),
(store_troop_gold, reg3, "trp_player"),
(store_div, ":player_gold_div_20", reg3, 20),
(val_add, "$player_ransom_amount", ":player_gold_div_20"),
(gt, reg3, "$player_ransom_amount"),
(jump_to_menu,"mnu_captivity_end_propose_ransom"),
(else_try),
(lt, reg7, 7),
(jump_to_menu,"mnu_captivity_end_exchanged_with_prisoner"),
(else_try),
(jump_to_menu,"mnu_captivity_castle_remain"),
(try_end),
],
[]
),
(
"captivity_end_exchanged_with_prisoner",0,
"After days of imprisonment, you are finally set free when your captors exchange you with another prisoner.",
"none",
[
(play_cue_track, "track_escape"),
],
[
("continue",[],"Continue...",
[
(assign, "$g_player_is_captive", 0),
(try_begin),
(party_is_active, "$capturer_party"),
(party_relocate_near_party, "p_main_party", "$capturer_party", 2),
(try_end),
(call_script, "script_set_parties_around_player_ignore_player", 8, 12), #it was radius:2 and hours:12, but players make lots of complains about consequent battle losses after releases from captivity then I changed this.
(assign, "$g_player_icon_state", pis_normal),
(set_camera_follow_party, "p_main_party"),
(rest_for_hours, 0, 0, 0), #stop resting
(change_screen_return),
]),
]
),
(
"captivity_end_propose_ransom",0,
"You spend long hours in the sunless dank of the dungeon, more than you can count.\
Suddenly one of your captors enters your cell with an offer;\
he proposes to free you in return for {reg5} denars of your hidden wealth. You decide to...",
"none",
[
(assign, reg5, "$player_ransom_amount"),
],
[
("captivity_end_ransom_accept",
[
(store_troop_gold,":player_gold", "trp_player"),
(ge, ":player_gold","$player_ransom_amount")
],"Accept the offer.",
[
(play_cue_track, "track_escape"),
(assign, "$g_player_is_captive", 0),
(troop_remove_gold, "trp_player", "$player_ransom_amount"),
(try_begin),
(party_is_active, "$capturer_party"),
(party_relocate_near_party, "p_main_party", "$capturer_party", 1),
(try_end),
(call_script, "script_set_parties_around_player_ignore_player", 8, 12), #it was radius:2 and hours:6, but players make lots of complains about consequent battle losses after releases from captivity then I changed this.
(assign, "$g_player_icon_state", pis_normal),
(set_camera_follow_party, "p_main_party"),
(rest_for_hours, 0, 0, 0), #stop resting
(change_screen_return),
]),
("captivity_end_ransom_deny",
[
],"Refuse him, wait for something better.",
[
(assign, "$g_player_is_captive", 1),
(store_random_in_range, reg(8), 16, 22),
(call_script, "script_stay_captive_for_hours", reg8),
(assign,"$auto_menu", "mnu_captivity_castle_check"),
(change_screen_return),
]),
]
),
(
"captivity_castle_remain",mnf_scale_picture|mnf_disable_all_keys,
"More days pass in the darkness of your cell. You get through them as best you can,\
enduring the kicks and curses of the guards, watching your underfed body waste away more and more...",
"none",
[
(troop_get_type, ":is_female", "trp_player"),
(try_begin),
(eq, ":is_female", 1),
(set_background_mesh, "mesh_pic_prisoner_fem"),
(else_try),
(set_background_mesh, "mesh_pic_prisoner_man"),
(try_end),
(store_random_in_range, ":random_hours", 16, 22),
(call_script, "script_stay_captive_for_hours", ":random_hours"),
(assign,"$auto_menu", "mnu_captivity_castle_check"),
],
[
("continue",[],"Continue...",
[
(assign, "$g_player_is_captive", 1),
(change_screen_return),
]),
]
),
(
"kingdom_army_quest_report_to_army",mnf_scale_picture,
"{s8} sends word that he wishes you to join {reg4?her:his} new military campaign.\
You need to bring at least {reg13} troops to the army,\
and are instructed to raise more men with all due haste if you do not have enough.",
"none",
[
(set_background_mesh, "mesh_pic_messenger"),
(quest_get_slot, ":quest_target_troop", "qst_report_to_army", slot_quest_target_troop),
(quest_get_slot, ":quest_target_amount", "qst_report_to_army", slot_quest_target_amount),
(call_script, "script_get_information_about_troops_position", ":quest_target_troop", 0),
(str_clear, s9),
(try_begin),
(eq, reg0, 1), #troop is found and text is correct
(str_store_string, s9, s1),
(try_end),
(str_store_troop_name, s8, ":quest_target_troop"),
(assign, reg13, ":quest_target_amount"),
(troop_get_type, reg4, ":quest_target_troop"),
],
[
("continue",[],"Continue...",
[
(quest_get_slot, ":quest_target_troop", "qst_report_to_army", slot_quest_target_troop),
(quest_get_slot, ":quest_target_amount", "qst_report_to_army", slot_quest_target_amount),
(str_store_troop_name_link, s13, ":quest_target_troop"),
(assign, reg13, ":quest_target_amount"),
(setup_quest_text, "qst_report_to_army"),
(str_store_string, s2, "@{s13} asked you to report to him with at least {reg13} troops."),
(call_script, "script_start_quest", "qst_report_to_army", ":quest_target_troop"),
(call_script, "script_report_quest_troop_positions", "qst_report_to_army", ":quest_target_troop", 3),
(change_screen_return),
]),
]
),
(
"kingdom_army_quest_messenger",mnf_scale_picture,
"{s8} sends word that he wishes to speak with you about a task he needs performed.\
He requests you to come and see him as soon as possible.",
"none",
[
(set_background_mesh, "mesh_pic_messenger"),
(faction_get_slot, ":faction_marshall", "$players_kingdom", slot_faction_marshall),
(str_store_troop_name, s8, ":faction_marshall"),
],
[
("continue",[],"Continue...",
[(change_screen_return),
]),
]
),
(
"kingdom_army_quest_join_siege_order",mnf_scale_picture,
"{s8} sends word that you are to join the siege of {s9} in preparation for a full assault.\
Your troops are to take {s9} at all costs.",
"none",
[
(set_background_mesh, "mesh_pic_messenger"),
(faction_get_slot, ":faction_marshall", "$players_kingdom", slot_faction_marshall),
(quest_get_slot, ":quest_target_center", "qst_join_siege_with_army", slot_quest_target_center),
(str_store_troop_name, s8, ":faction_marshall"),
(str_store_party_name, s9, ":quest_target_center"),
],
[
("continue",[],"Continue...",
[
(call_script, "script_end_quest", "qst_follow_army"),
(quest_get_slot, ":quest_target_center", "qst_join_siege_with_army", slot_quest_target_center),
(faction_get_slot, ":faction_marshall", "$players_kingdom", slot_faction_marshall),
(str_store_troop_name_link, s13, ":faction_marshall"),
(str_store_party_name_link, s14, ":quest_target_center"),
(setup_quest_text, "qst_join_siege_with_army"),
(str_store_string, s2, "@{s13} ordered you to join the assault against {s14}."),
(call_script, "script_start_quest", "qst_join_siege_with_army", ":faction_marshall"),
(change_screen_return),
]),
]
),
(
"kingdom_army_follow_failed",mnf_scale_picture,
"You have failed to follow {s8}. The marshal assumes that you were otherwise engaged, but would have appreciated your support.",
"none",
[
(set_background_mesh, "mesh_pic_messenger"),
(faction_get_slot, ":faction_marshall", "$players_kingdom", slot_faction_marshall),
(str_store_troop_name, s8, ":faction_marshall"),
(call_script, "script_abort_quest", "qst_follow_army", 1),
# (call_script, "script_change_player_relation_with_troop", ":faction_marshall", -3),
],
[
("continue",[],"Continue...",
[(change_screen_return),
]),
]
),
(
"invite_player_to_faction_without_center",mnf_scale_picture,
"You receive an offer of vassalage!^^\
{s8} of {s9} has sent a royal herald to bring you an invititation in his own hand.\
You would be granted the honour of becoming a vassal {lord/lady} of {s9},\
and in return {s8} asks you to swear an oath of homage to him and fight in his military campaigns,\
although he offers you no lands or titles.\
He will surely be offended if you do not take the offer...",
"none",
[
(set_background_mesh, "mesh_pic_messenger"),
(faction_get_slot, "$g_invite_faction_lord", "$g_invite_faction", slot_faction_leader),
(str_store_troop_name, s8, "$g_invite_faction_lord"),
(str_store_faction_name, s9, "$g_invite_faction"),
],
[
("faction_accept",[],"Accept!",
[(str_store_troop_name,s1,"$g_invite_faction_lord"),
(setup_quest_text,"qst_join_faction"),
(str_store_troop_name_link, s3, "$g_invite_faction_lord"),
(str_store_faction_name_link, s4, "$g_invite_faction"),
(quest_set_slot, "qst_join_faction", slot_quest_giver_troop, "$g_invite_faction_lord"),
(quest_set_slot, "qst_join_faction", slot_quest_expiration_days, 30),
(quest_set_slot, "qst_join_faction", slot_quest_failure_consequence, 0),
(str_store_string, s2, "@Find and speak with {s3} of {s4} to give him your oath of homage."),
(call_script, "script_start_quest", "qst_join_faction", "$g_invite_faction_lord"),
(call_script, "script_report_quest_troop_positions", "qst_join_faction", "$g_invite_faction_lord", 3),
(jump_to_menu, "mnu_invite_player_to_faction_accepted"),
]),
("faction_reject",[],"Decline the invitation.",
[(call_script, "script_change_player_relation_with_troop", "$g_invite_faction_lord", -3),
(call_script, "script_change_player_relation_with_faction", "$g_invite_faction", -10),
(assign, "$g_invite_faction", 0),
(assign, "$g_invite_faction_lord", 0),
(assign, "$g_invite_offered_center", 0),
(change_screen_return),
]),
]
),
(
"invite_player_to_faction",mnf_scale_picture,
"You receive an offer of vassalage!^^\
{s8} of {s9} has sent a royal herald to bring you an invititation in his own hand.\
You would be granted the honour of becoming a vassal {lord/lady} of {s9},\
and in return {s8} asks you to swear an oath of homage to him and fight in his military campaigns,\
offering you the fief of {s2} for your loyal service.\
He will surely be offended if you do not take the offer...",
"none",
[
(set_background_mesh, "mesh_pic_messenger"),
(faction_get_slot, "$g_invite_faction_lord", "$g_invite_faction", slot_faction_leader),
(str_store_troop_name, s8, "$g_invite_faction_lord"),
(str_store_faction_name, s9, "$g_invite_faction"),
(str_store_party_name, s2, "$g_invite_offered_center"),
],
[
("faction_accept",[],"Accept!",
[(str_store_troop_name,s1,"$g_invite_faction_lord"),
(setup_quest_text,"qst_join_faction"),
(str_store_troop_name_link, s3, "$g_invite_faction_lord"),
(str_store_faction_name_link, s4, "$g_invite_faction"),
(quest_set_slot, "qst_join_faction", slot_quest_giver_troop, "$g_invite_faction_lord"),
(quest_set_slot, "qst_join_faction", slot_quest_expiration_days, 30),
(str_store_string, s2, "@Find and speak with {s3} of {s4} to give him your oath of homage."),
(call_script, "script_start_quest", "qst_join_faction", "$g_invite_faction_lord"),
(call_script, "script_report_quest_troop_positions", "qst_join_faction", "$g_invite_faction_lord", 3),
(jump_to_menu, "mnu_invite_player_to_faction_accepted"),
]),
("faction_reject",[],"Decline the invitation.",
[(call_script, "script_change_player_relation_with_troop", "$g_invite_faction_lord", -3),
(assign, "$g_invite_faction", 0),
(assign, "$g_invite_faction_lord", 0),
(assign, "$g_invite_offered_center", 0),
(change_screen_return),
]),
]
),
(
"invite_player_to_faction_accepted",0,
"In order to become a vassal, you must swear an oath of homage to {s3}.\
You shall have to find him and give him your oath in person. {s5}",
"none",
[
(call_script, "script_get_information_about_troops_position", "$g_invite_faction_lord", 0),
(str_store_troop_name, s3, "$g_invite_faction_lord"),
(str_store_string, s5, "@{!}{s1}"),
],
[
("continue",[],"Continue...",
[(change_screen_return),
]),
]
),
(
"question_peace_offer",0,
"You Receive a Peace Offer^^The {s1} offers you a peace agreement. What is your answer?",
"none",
[
(str_store_faction_name, s1, "$g_notification_menu_var1"),
(set_fixed_point_multiplier, 100),
(position_set_x, pos0, 65),
(position_set_y, pos0, 30),
(position_set_z, pos0, 170),
(set_game_menu_tableau_mesh, "tableau_faction_note_mesh_banner", "$g_notification_menu_var1", pos0),
],
[
("peace_offer_accept",[],"Accept",
[
(call_script, "script_diplomacy_start_peace_between_kingdoms", "fac_player_supporters_faction", "$g_notification_menu_var1", 1),
(change_screen_return),
]),
("peace_offer_reject",[],"Reject",
[
(call_script, "script_change_player_relation_with_faction", "$g_notification_menu_var1", -5),
(change_screen_return),
]),
]
),
(
"notification_truce_expired",0,
"Truce Has Expired^^The truce between {s1} and {s2} has expired.",
"none",
[
(str_store_faction_name, s1, "$g_notification_menu_var1"),
(str_store_faction_name, s2, "$g_notification_menu_var2"),
(set_fixed_point_multiplier, 100),
(position_set_x, pos0, 65),
(position_set_y, pos0, 30),
(position_set_z, pos0, 170),
(set_game_menu_tableau_mesh, "tableau_faction_note_mesh_banner", "$g_notification_menu_var1", pos0),
],
[
("continue",[],"Continue",
[
(change_screen_return),
]),
]
),
(
"notification_feast_quest_expired",0,
"{s10}",
"none",
[
(str_store_string, s10, "str_feast_quest_expired"),
],
[
("continue",[],"Continue",
[
(change_screen_return),
]),
]
),
(
"notification_sortie_possible",0,
"Enemy Sighted: Enemies have been sighted outside the walls of {s4}, and {s5} and others are preparing for a sortie. You may join them if you wish.",
"none",
[
(str_store_party_name, s4, "$g_notification_menu_var1"),
(party_stack_get_troop_id, ":leader", "$g_notification_menu_var2", 0),
(str_store_troop_name, s5, ":leader"),
],
[
("continue",[],"Continue",
[
#stop auto-clock
(change_screen_return),
]),
]
),
(
"notification_casus_belli_expired",0,
"Kingdom Fails to Respond^^The {s1} has not responded to the {s2}'s provocations, and {s3} suffers a loss of face among {reg4?her:his} more bellicose subjects...^",
"none",
[
(str_store_faction_name, s1, "$g_notification_menu_var1"),
(str_store_faction_name, s2, "$g_notification_menu_var2"),
(faction_get_slot, ":faction_leader", "$g_notification_menu_var1", slot_faction_leader),
(str_store_troop_name, s3, ":faction_leader"),
(troop_get_type, reg4, ":faction_leader"),
(set_fixed_point_multiplier, 100),
(position_set_x, pos0, 65),
(position_set_y, pos0, 30),
(position_set_z, pos0, 170),
(set_game_menu_tableau_mesh, "tableau_faction_note_mesh_banner", "$g_notification_menu_var1", pos0),
],
[
("continue",[],"Continue",
[
(call_script, "script_faction_follows_controversial_policy", "$g_notification_menu_var1", logent_policy_ruler_ignores_provocation),
(change_screen_return),
]),
]
),
(
"notification_lord_defects",0,
"Defection: {s4} has abandoned the {s5} and joined the {s7}, taking {reg4?her:his} his fiefs with him",
"none",
[
(assign, ":defecting_lord", "$g_notification_menu_var1"),
(assign, ":old_faction", "$g_notification_menu_var2"),
(str_store_troop_name, s4, ":defecting_lord"),
(str_store_faction_name, s5, ":old_faction"),
(store_faction_of_troop, ":new_faction", ":defecting_lord"),
(str_store_faction_name, s7, ":new_faction"),
(troop_get_type, reg4, ":defecting_lord"),
],
[
("continue",[],"Continue",
[
(change_screen_return),
]),
]
),
(
"notification_treason_indictment",0,
"Treason Indictment^^{s9}",
"none",
[
(assign, ":indicted_lord", "$g_notification_menu_var1"),
(assign, ":former_faction", "$g_notification_menu_var2"),
(faction_get_slot, ":former_faction_leader", ":former_faction", slot_faction_leader),
#Set up string
(try_begin),
(eq, ":indicted_lord", "trp_player"),
(str_store_troop_name, s7, ":former_faction_leader"),
(str_store_string, s9, "str_you_have_been_indicted_for_treason_to_s7_your_properties_have_been_confiscated_and_you_would_be_well_advised_to_flee_for_your_life"),
(else_try),
(str_store_troop_name, s4, ":indicted_lord"),
(str_store_faction_name, s5, ":former_faction"),
(str_store_troop_name, s6, ":former_faction_leader"),
(troop_get_type, reg4, ":indicted_lord"),
(store_faction_of_troop, ":new_faction", ":indicted_lord"),
(try_begin),
(is_between, ":new_faction", kingdoms_begin, kingdoms_end),
(str_store_faction_name, s10, ":new_faction"),
(str_store_string, s11, "str_with_the_s10"),
(else_try),
(str_store_string, s11, "str_outside_calradia"),
(try_end),
(str_store_string, s9, "str_by_order_of_s6_s4_of_the_s5_has_been_indicted_for_treason_the_lord_has_been_stripped_of_all_reg4herhis_properties_and_has_fled_for_reg4herhis_life_he_is_rumored_to_have_gone_into_exile_s11"),
(try_end),
],
[
("continue",[],"Continue",
[
(change_screen_return),
]),
]
),
(
"notification_border_incident",0,
"Border incident^^Word reaches you that {s9}. Though you don't know whether or not the rumors are true, you do know one thing -- this seemingly minor incident has raised passions among the {s4}, making it easier for them to go to war against the {s3}, if they want it...",
"none",
[
(assign, ":acting_village", "$g_notification_menu_var1"),
(assign, ":target_village", "$g_notification_menu_var2"),
(store_faction_of_party, ":acting_faction", ":acting_village"),
(try_begin),
(eq, ":target_village", -1),
(party_get_slot, ":target_faction", ":acting_village", slot_center_original_faction),
(try_begin),
(this_or_next|eq, ":target_faction", ":acting_faction"),
(neg|faction_slot_eq, ":target_faction", slot_faction_state, sfs_active),
(party_get_slot, ":target_faction", ":acting_village", slot_center_ex_faction),
(try_end),
(str_store_party_name, s1, ":acting_village"),
(str_store_faction_name, s3, ":acting_faction"),
(str_store_faction_name, s4, ":target_faction"),
(faction_get_slot, ":target_leader", ":target_faction", slot_faction_leader),
(str_store_troop_name, s5, ":target_leader"),
(str_store_string, s9, "str_local_notables_from_s1_a_village_claimed_by_the_s4_have_been_mistreated_by_their_overlords_from_the_s3_and_petition_s5_for_protection"),
(display_log_message, "@There has been an alleged border incident: {s9}"),
(call_script, "script_add_log_entry", logent_border_incident_subjects_mistreated, ":acting_village", -1, -1, ":acting_faction"),
(else_try),
(store_faction_of_party, ":target_faction", ":target_village"),
(str_store_party_name, s1, ":acting_village"),
(str_store_party_name, s2, ":target_village"),
(store_random_in_range, ":random", 0, 3),
(try_begin),
(eq, ":random", 0),
(str_store_string, s9, "str_villagers_from_s1_stole_some_cattle_from_s2"),
(display_log_message, "@There has been an alleged border incident: {s9}"),
(call_script, "script_add_log_entry", logent_border_incident_cattle_stolen, ":acting_village", ":target_village", -1,":acting_faction"),
(else_try),
(eq, ":random", 1),
(str_store_string, s9, "str_villagers_from_s1_abducted_a_woman_from_a_prominent_family_in_s2_to_marry_one_of_their_boys"),
(display_log_message, "@There has been an alleged border incident: {s9}"),
(call_script, "script_add_log_entry", logent_border_incident_bride_abducted, ":acting_village", ":target_village", -1, ":acting_faction"),
(else_try),
(eq, ":random", 2),
(str_store_string, s9, "str_villagers_from_s1_killed_some_farmers_from_s2_in_a_fight_over_the_diversion_of_a_stream"),
(display_log_message, "@There has been an alleged border incident: {s9}"),
(call_script, "script_add_log_entry", logent_border_incident_villagers_killed, ":acting_village", ":target_village", -1,":acting_faction"),
(try_end),
(try_end),
(str_store_faction_name, s3, ":acting_faction"),
(str_store_faction_name, s4, ":target_faction"),
(store_add, ":slot_provocation_days", ":acting_faction", slot_faction_provocation_days_with_factions_begin),
(val_sub, ":slot_provocation_days", kingdoms_begin),
(faction_set_slot, ":target_faction", ":slot_provocation_days", 30),
],
[
("continue",[],"Continue",
[
(change_screen_return),
]),
]
),
(
"notification_player_faction_active",0,
"You now possess land in your name, without being tied to any kingdom. This makes you a monarch in your own right, with your court temporarily located at {s12}. However, the other kings in Calradia will at first consider you a threat, for if any upstart warlord can grab a throne, then their own legitimacy is called into question.^^You may find it desirable at this time to pledge yourself to an existing kingdom. If you want to continue as a sovereign monarch, then your first priority should be to establish an independent right to rule. You can establish your right to rule through several means -- marrying into a high-born family, recruiting new lords, governing your lands, treating with other kings, or dispatching your companions on missions.^^At any rate, your first step should be to appoint a chief minister from among your companions, to handle affairs of state. Different companions have different capabilities.^You may appoint new ministers from time to time. You may also change the location of your court, by speaking to the minister.",
"none",
[
(set_fixed_point_multiplier, 100),
(position_set_x, pos0, 65),
(position_set_y, pos0, 30),
(position_set_z, pos0, 170),
(set_game_menu_tableau_mesh, "tableau_faction_note_mesh_banner", "fac_player_supporters_faction", pos0),
(unlock_achievement, ACHIEVEMENT_CALRADIAN_TEA_PARTY),
(play_track, "track_coronation"),
(try_for_range, ":walled_center", walled_centers_begin, walled_centers_end),
(lt, "$g_player_court", walled_centers_begin),
(store_faction_of_party, ":walled_center_faction", ":walled_center"),
(eq, ":walled_center_faction", "fac_player_supporters_faction"),
(assign, "$g_player_court", ":walled_center"),
(try_begin),
(troop_get_slot, ":spouse", "trp_player", slot_troop_spouse),
(is_between, ":spouse", kingdom_ladies_begin, kingdom_ladies_end),
(troop_set_slot, ":spouse", slot_troop_cur_center, "$g_player_court"),
(try_end),
(str_store_party_name, s12, "$g_player_court"),
(try_end),
],
[
("appoint_spouse",[
(troop_slot_ge, "trp_player", slot_troop_spouse, 1),
(troop_get_slot, ":player_spouse", "trp_player", slot_troop_spouse),
(neg|troop_slot_eq, ":player_spouse", slot_troop_occupation, slto_kingdom_hero),
(str_store_troop_name, s10, ":player_spouse"),
],"Appoint your wife, {s10}...",
[
(troop_get_slot, ":player_spouse", "trp_player", slot_troop_spouse),
(assign, "$g_player_minister", ":player_spouse"),
(jump_to_menu, "mnu_minister_confirm"),
]),
("appoint_npc1",[
(main_party_has_troop, "trp_npc1"),
(str_store_troop_name, s10, "trp_npc1"),
],"Appoint {s10}",
[
(assign, "$g_player_minister", "trp_npc1"),
(jump_to_menu, "mnu_minister_confirm"),
]),
("appoint_npc2",[
(main_party_has_troop, "trp_npc2"),
(str_store_troop_name, s10, "trp_npc2"),],"Appoint {s10}",
[
(assign, "$g_player_minister", "trp_npc2"),
(jump_to_menu, "mnu_minister_confirm"),]),
("appoint_npc3",[
(main_party_has_troop, "trp_npc3"),
(str_store_troop_name, s10, "trp_npc3"),
],"Appoint {s10}",
[
(assign, "$g_player_minister", "trp_npc3"),
(jump_to_menu, "mnu_minister_confirm"), ]),
("appoint_npc4",[
(main_party_has_troop, "trp_npc4"),
(str_store_troop_name, s10, "trp_npc4"),
],"Appoint {s10}",
[
(assign, "$g_player_minister", "trp_npc4"),
(jump_to_menu, "mnu_minister_confirm"), ]),
("appoint_npc5",[
(main_party_has_troop, "trp_npc5"),
(str_store_troop_name, s10, "trp_npc5"),
],"Appoint {s10}",
[
(assign, "$g_player_minister", "trp_npc5"),
(jump_to_menu, "mnu_minister_confirm"), ]),
("appoint_npc6",[
(main_party_has_troop, "trp_npc6"),
(str_store_troop_name, s10, "trp_npc6"),
],"Appoint {s10}",
[
(assign, "$g_player_minister", "trp_npc6"),
(jump_to_menu, "mnu_minister_confirm"), ]),
("appoint_npc7",[
(main_party_has_troop, "trp_npc7"),
(str_store_troop_name, s10, "trp_npc7"),
],"Appoint {s10}",
[
(assign, "$g_player_minister", "trp_npc7"),
(jump_to_menu, "mnu_minister_confirm"), ]),
("appoint_npc8",[
(main_party_has_troop, "trp_npc8"),
(str_store_troop_name, s10, "trp_npc8"),
],"Appoint {s10}",
[
(assign, "$g_player_minister", "trp_npc8"),
(jump_to_menu, "mnu_minister_confirm"), ]),
("appoint_npc9",[
(main_party_has_troop, "trp_npc9"),
(str_store_troop_name, s10, "trp_npc9"),
],"Appoint {s10}",
[
(assign, "$g_player_minister", "trp_npc9"),
(jump_to_menu, "mnu_minister_confirm"), ]),
("appoint_npc10",[ #was npc9
(main_party_has_troop, "trp_npc10"),
(str_store_troop_name, s10, "trp_npc10"),
],"Appoint {s10}",
[
(assign, "$g_player_minister", "trp_npc10"),
(jump_to_menu, "mnu_minister_confirm"), ]),
("appoint_npc11",[
(main_party_has_troop, "trp_npc11"),
(str_store_troop_name, s10, "trp_npc11"),
],"Appoint {s10}",
[
(assign, "$g_player_minister", "trp_npc11"),
(jump_to_menu, "mnu_minister_confirm"), ]),
("appoint_npc12",[
(main_party_has_troop, "trp_npc12"),
(str_store_troop_name, s10, "trp_npc12"),
],"Appoint {s10}",
[
(assign, "$g_player_minister", "trp_npc12"),
(jump_to_menu, "mnu_minister_confirm"), ]),
("appoint_npc13",[
(main_party_has_troop, "trp_npc13"),
(str_store_troop_name, s10, "trp_npc13"),
],"Appoint {s10}",
[
(assign, "$g_player_minister", "trp_npc13"),
(jump_to_menu, "mnu_minister_confirm"), ]),
("appoint_npc14",[
(main_party_has_troop, "trp_npc14"),
(str_store_troop_name, s10, "trp_npc14"),
],"Appoint {s10}",
[
(assign, "$g_player_minister", "trp_npc14"),
(jump_to_menu, "mnu_minister_confirm"), ]),
("appoint_npc15",[
(main_party_has_troop, "trp_npc15"),
(str_store_troop_name, s10, "trp_npc15"),
],"Appoint {s10}",
[
(assign, "$g_player_minister", "trp_npc15"),
(jump_to_menu, "mnu_minister_confirm"), ]),
("appoint_npc16",[
(main_party_has_troop, "trp_npc16"),
(str_store_troop_name, s10, "trp_npc16"),
],"Appoint {s10}",
[
(assign, "$g_player_minister", "trp_npc16"),
(jump_to_menu, "mnu_minister_confirm"), ]),
("appoint_default",[],"Appoint a prominent citizen from the area...",
[
(assign, "$g_player_minister", "trp_temporary_minister"),
(troop_set_faction, "trp_temporary_minister", "fac_player_supporters_faction"),
(jump_to_menu, "mnu_minister_confirm"),
]),
]
),
(
"minister_confirm",0,
"{s9}can be found at your court in {s12}. You should consult periodically, to avoid the accumulation of unresolved issues that may sap your authority...",
"none",
[
(try_begin),
(eq, "$players_kingdom_name_set", 1),
(change_screen_return),
(try_end),
(try_begin),
(eq, "$g_player_minister", "trp_temporary_minister"),
(str_store_string, s9, "str_your_new_minister_"),
(else_try),
(str_store_troop_name, s10, "$g_player_minister"),
(str_store_string, s9, "str_s10_is_your_new_minister_and_"),
(try_end),
(try_begin),
(main_party_has_troop, "$g_player_minister"),
(remove_member_from_party, "$g_player_minister", "p_main_party"),
(try_end),
],
[
("continue",[],"Continue...",
[
(start_presentation, "prsnt_name_kingdom"),
]),
]
),
(
"notification_court_lost",0,
"{s12}",
"none",
[
(try_begin),
(is_between, "$g_player_court", centers_begin, centers_end),
(str_store_party_name, s10, "$g_player_court"),
(str_store_party_name, s11, "$g_player_court"),
(else_try),
(str_store_string, s10, "str_your_previous_court_some_time_ago"),
(str_store_string, s11, "str_your_previous_court_some_time_ago"),
(try_end),
(assign, "$g_player_court", -1),
(str_store_string, s14, "str_after_to_the_fall_of_s11_your_court_has_nowhere_to_go"),
(try_begin),
(faction_slot_eq, "fac_player_supporters_faction", slot_faction_state, sfs_inactive),
(str_store_string, s14, "str_as_you_no_longer_maintain_an_independent_kingdom_you_no_longer_maintain_a_court"),
(try_end),
(try_for_range, ":walled_center", walled_centers_begin, walled_centers_end),
(eq, "$g_player_court", -1),
(store_faction_of_party, ":walled_center_faction", ":walled_center"),
(eq, ":walled_center_faction", "fac_player_supporters_faction"),
(neg|party_slot_ge, ":walled_center", slot_town_lord, active_npcs_begin),
(assign, "$g_player_court", ":walled_center"),
(try_begin),
(troop_get_slot, ":spouse", "trp_player", slot_troop_spouse),
(is_between, ":spouse", kingdom_ladies_begin, kingdom_ladies_end),
(troop_set_slot, ":spouse", slot_troop_cur_center, "$g_player_court"),
(str_store_party_name, s11, "$g_player_court"),
(try_end),
(str_store_string, s14, "str_due_to_the_fall_of_s10_your_court_has_been_relocated_to_s12"),
(try_end),
(try_for_range, ":walled_center", walled_centers_begin, walled_centers_end),
(eq, "$g_player_court", -1),
(store_faction_of_party, ":walled_center_faction", ":walled_center"),
(eq, ":walled_center_faction", "fac_player_supporters_faction"),
(assign, "$g_player_court", ":walled_center"),
(try_begin),
(troop_get_slot, ":spouse", "trp_player", slot_troop_spouse),
(is_between, ":spouse", kingdom_ladies_begin, kingdom_ladies_end),
(troop_set_slot, ":spouse", slot_troop_cur_center, "$g_player_court"),
(try_end),
(party_get_slot, ":town_lord", ":walled_center", slot_town_lord),
(str_store_party_name, s11, "$g_player_court"),
(str_store_troop_name, s9, ":town_lord"),
(str_store_string, s14, "str_after_to_the_fall_of_s10_your_faithful_vassal_s9_has_invited_your_court_to_s11_"),
(try_end),
(try_begin),
(faction_slot_eq, "fac_player_supporters_faction", slot_faction_state, sfs_inactive),
(str_store_string, s14, "str_as_you_no_longer_maintain_an_independent_kingdom_you_no_longer_maintain_a_court"),
(try_end),
(str_store_string, s12, s14),
],
[
("continue",[],"Continue...",[
(change_screen_return),
]),
],
),
(
"notification_player_faction_deactive",0,
"Your kingdom no longer holds any land.",
"none",
[
(set_fixed_point_multiplier, 100),
(position_set_x, pos0, 65),
(position_set_y, pos0, 30),
(position_set_z, pos0, 170),
(set_game_menu_tableau_mesh, "tableau_faction_note_mesh_banner", "fac_player_supporters_faction", pos0),
],
[
("continue",[],"Continue...",
[
(try_begin),
(try_end),
(assign, "$g_player_minister", -1),
(change_screen_return),
]),
]
),
(
"notification_player_wedding_day",mnf_scale_picture,
"{s8} wishes to inform you that preparations for your wedding at {s10} have been complete, and that your presence is expected imminently .",
"none",
[
(set_background_mesh, "mesh_pic_messenger"),
(str_store_troop_name, s8, "$g_notification_menu_var1"),
(str_store_party_name, s10, "$g_notification_menu_var2"),
],
[
("continue",[],"Continue...",
[(change_screen_return),
]),
]
),
(
"notification_player_kingdom_holds_feast",mnf_scale_picture,
"{s11}",
"none",
[
(set_background_mesh, "mesh_pic_messenger"),
(str_store_troop_name, s8, "$g_notification_menu_var1"),
(store_faction_of_troop, ":host_faction", "$g_notification_menu_var1"),
(str_store_faction_name, s9, ":host_faction"),
# (str_store_faction_name, s9, "$players_kingdom"),
(str_store_party_name, s10, "$g_notification_menu_var2"),
(str_clear, s12),
(try_begin),
(check_quest_active, "qst_wed_betrothed"),
(quest_get_slot, ":giver_troop", "qst_wed_betrothed", slot_quest_giver_troop),
(store_faction_of_troop, ":giver_troop_faction", ":giver_troop"),
(eq, ":giver_troop_faction", "$players_kingdom"),
(str_store_string, s12, "str_feast_wedding_opportunity"),
(try_end),
(str_store_string, s11, "str_s8_wishes_to_inform_you_that_the_lords_of_s9_will_be_gathering_for_a_feast_at_his_great_hall_in_s10_and_invites_you_to_be_part_of_this_august_assembly"),
(try_begin),
(eq, "$g_notification_menu_var1", 0),
(str_store_string, s11, "str_the_great_lords_of_your_kingdom_plan_to_gather_at_your_hall_in_s10_for_a_feast"),
(try_end),
(str_store_string, s11, "@{!}{s11}{s12}"),
(try_begin),
(ge, "$cheat_mode", 1),
(store_current_hours, ":hours_since_last_feast"),
(faction_get_slot, ":last_feast_start_time", "$players_kingdom", slot_faction_last_feast_start_time),
(val_sub, ":hours_since_last_feast", ":last_feast_start_time"),
(assign, reg4, ":hours_since_last_feast"),
(display_message, "@{!}DEBUG -- Hours since last feast started: {reg4}"),
(try_end),
],
[
("continue",[],"Continue...",
[(change_screen_return),
]),
]
),
(
"notification_center_under_siege",0,
"{s1} has been besieged by {s2} of {s3}!",
"none",
[
(str_store_party_name, s1, "$g_notification_menu_var1"),
(str_store_troop_name, s2, "$g_notification_menu_var2"),
(store_troop_faction, ":troop_faction", "$g_notification_menu_var2"),
(str_store_faction_name, s3, ":troop_faction"),
(set_fixed_point_multiplier, 100),
(position_set_x, pos0, 62),
(position_set_y, pos0, 30),
(position_set_z, pos0, 170),
(set_game_menu_tableau_mesh, "tableau_center_note_mesh", "$g_notification_menu_var1", pos0),
],
[
("continue",[],"Continue...",
[(change_screen_return),
]),
]
),
(
"notification_village_raided",0,
"Enemies have Laid Waste to a Fief^^{s1} has been raided by {s2} of {s3}!",
"none",
[
(str_store_party_name, s1, "$g_notification_menu_var1"),
(str_store_troop_name, s2, "$g_notification_menu_var2"),
(store_troop_faction, ":troop_faction", "$g_notification_menu_var2"),
(str_store_faction_name, s3, ":troop_faction"),
(set_fixed_point_multiplier, 100),
(position_set_x, pos0, 62),
(position_set_y, pos0, 30),
(position_set_z, pos0, 170),
(set_game_menu_tableau_mesh, "tableau_center_note_mesh", "$g_notification_menu_var1", pos0),
],
[
("continue",[],"Continue...",
[(change_screen_return),
]),
]
),
(
"notification_village_raid_started",0,
"Your Village is under Attack!^^{s2} of {s3} is laying waste to {s1}.",
"none",
[
(str_store_party_name, s1, "$g_notification_menu_var1"),
(str_store_troop_name, s2, "$g_notification_menu_var2"),
(store_troop_faction, ":troop_faction", "$g_notification_menu_var2"),
(str_store_faction_name, s3, ":troop_faction"),
(set_fixed_point_multiplier, 100),
(position_set_x, pos0, 62),
(position_set_y, pos0, 30),
(position_set_z, pos0, 170),
(set_game_menu_tableau_mesh, "tableau_center_note_mesh", "$g_notification_menu_var1", pos0),
],
[
("continue",[],"Continue...",
[(change_screen_return),
]),
]
),
(
"notification_one_faction_left",0,
"Calradia Conquered by One Kingdom^^{s1} has defeated all rivals and stands as the sole kingdom.",
"none",
[
(str_store_faction_name, s1, "$g_notification_menu_var1"),
(set_fixed_point_multiplier, 100),
(position_set_x, pos0, 65),
(position_set_y, pos0, 30),
(position_set_z, pos0, 170),
(try_begin),
(is_between, "$g_notification_menu_var1", "fac_kingdom_7", kingdoms_end), #Excluding player kingdom
(set_game_menu_tableau_mesh, "tableau_faction_note_mesh_for_menu", "$g_notification_menu_var1", pos0),
(else_try),
(set_game_menu_tableau_mesh, "tableau_faction_note_mesh_banner", "$g_notification_menu_var1", pos0),
(try_end),
(try_begin),
(faction_slot_eq, "$g_notification_menu_var1", slot_faction_leader, "trp_player"),
(unlock_achievement, ACHIEVEMENT_THE_GOLDEN_THRONE),
(else_try),
(unlock_achievement, ACHIEVEMENT_MANIFEST_DESTINY),
(try_end),
(try_begin),
(troop_get_type, ":is_female", "trp_player"),
(eq, ":is_female", 1),
(unlock_achievement, ACHIEVEMENT_EMPRESS),
(try_end),
],
[
("continue",[],"Continue...",
[(change_screen_return),
]),
]
),
(
"notification_oath_renounced_faction_defeated",0,
"Your Old Faction was Defeated^^You won the battle against {s1}! This ends your struggle which started after you renounced your oath to them.",
"none",
[
(str_store_faction_name, s1, "$g_notification_menu_var1"),
(set_fixed_point_multiplier, 100),
(position_set_x, pos0, 65),
(position_set_y, pos0, 30),
(position_set_z, pos0, 170),
(try_begin),
(is_between, "$g_notification_menu_var1", "fac_kingdom_7", kingdoms_end), #Excluding player kingdom
(set_game_menu_tableau_mesh, "tableau_faction_note_mesh_for_menu", "$g_notification_menu_var1", pos0),
(else_try),
(set_game_menu_tableau_mesh, "tableau_faction_note_mesh_banner", "$g_notification_menu_var1", pos0),
(try_end),
],
[
("continue",[],"Continue...",
[(change_screen_return),
]),
]
),
(
"notification_center_lost",0,
"An Estate was Lost^^You have lost {s1} to {s2}.",
"none",
[
(str_store_party_name, s1, "$g_notification_menu_var1"),
(str_store_faction_name, s2, "$g_notification_menu_var2"),
(set_fixed_point_multiplier, 100),
(position_set_x, pos0, 62),
(position_set_y, pos0, 30),
(position_set_z, pos0, 170),
(set_game_menu_tableau_mesh, "tableau_center_note_mesh", "$g_notification_menu_var1", pos0),
],
[
("continue",[],"Continue...",
[(change_screen_return),
]),
]
),
(
"notification_troop_left_players_faction",0,
"Betrayal!^^{s1} has left {s2} and joined {s3}.",
"none",
[
(str_store_troop_name, s1, "$g_notification_menu_var1"),
(str_store_faction_name, s2, "$players_kingdom"),
(str_store_faction_name, s3, "$g_notification_menu_var2"),
(set_fixed_point_multiplier, 100),
(position_set_x, pos0, 55),
(position_set_y, pos0, 20),
(position_set_z, pos0, 100),
(set_game_menu_tableau_mesh, "tableau_troop_note_mesh", "$g_notification_menu_var1", pos0),
],
[
("continue",[],"Continue...",
[(change_screen_return),
]),
]
),
(
"notification_troop_joined_players_faction",0,
"Good news!^^ {s1} has left {s2} and joined {s3}.",
"none",
[
(str_store_troop_name, s1, "$g_notification_menu_var1"),
(str_store_faction_name, s2, "$g_notification_menu_var2"),
(str_store_faction_name, s3, "$players_kingdom"),
(set_fixed_point_multiplier, 100),
(position_set_x, pos0, 55),
(position_set_y, pos0, 20),
(position_set_z, pos0, 100),
(set_game_menu_tableau_mesh, "tableau_troop_note_mesh", "$g_notification_menu_var1", pos0),
],
[
("continue",[],"Continue...",
[(change_screen_return),
]),
]
),
(
"notification_war_declared",0,
"Declaration of War^^{s1} has declared war against {s2}!",
"none",
[
# (try_begin),
# (eq, "$g_include_diplo_explanation", "$g_notification_menu_var1"),
# (assign, "$g_include_diplo_explanation", 0),
# (str_store_string, s57, "$g_notification_menu_var1"),
# (else_try),
# (str_clear, s57),
# (try_end),
#to do the reason, have war_damage = 0 yield pre-war reasons
(try_begin),
# (eq, "$g_notification_menu_var1", "fac_player_supporters_faction"),
# (str_store_faction_name, s1, "$g_notification_menu_var2"),
# (str_store_string, s2, "@you"),
# (else_try),
# (eq, "$g_notification_menu_var2", "fac_player_supporters_faction"),
# (str_store_faction_name, s1, "$g_notification_menu_var1"),
# (str_store_string, s2, "@you"),
# (else_try),
(str_store_faction_name, s1, "$g_notification_menu_var1"),
(str_store_faction_name, s2, "$g_notification_menu_var2"),
(try_end),
(set_fixed_point_multiplier, 100),
(position_set_x, pos0, 65),
(position_set_y, pos0, 30),
(position_set_z, pos0, 170),
(store_sub, ":faction_1", "$g_notification_menu_var1", kingdoms_begin),
(store_sub, ":faction_2", "$g_notification_menu_var2", kingdoms_begin),
(val_mul, ":faction_1", 128),
(val_add, ":faction_1", ":faction_2"),
(set_game_menu_tableau_mesh, "tableau_2_factions_mesh", ":faction_1", pos0),
],
[
("continue",[],"Continue...",
[(change_screen_return),
]),
]
),
(
"notification_peace_declared",0,
"Peace Agreement^^{s1} and {s2} have made peace!^{s57}",
"none",
[
(try_begin),
(eq, 1, 0), #Alas, this does not seem to work
(eq, "$g_include_diplo_explanation", "$g_notification_menu_var1"),
(assign, "$g_include_diplo_explanation", 0),
(else_try),
(str_clear, s57),
(try_end),
(str_store_faction_name, s1, "$g_notification_menu_var1"),
(str_store_faction_name, s2, "$g_notification_menu_var2"),
(set_fixed_point_multiplier, 100),
(position_set_x, pos0, 65),
(position_set_y, pos0, 30),
(position_set_z, pos0, 170),
(store_sub, ":faction_1", "$g_notification_menu_var1", kingdoms_begin),
(store_sub, ":faction_2", "$g_notification_menu_var2", kingdoms_begin),
(val_mul, ":faction_1", 128),
(val_add, ":faction_1", ":faction_2"),
(set_game_menu_tableau_mesh, "tableau_2_factions_mesh", ":faction_1", pos0),
],
[
("continue",[],"Continue...",
[(change_screen_return),
]),
]
),
(
"notification_faction_defeated",0,
"Faction Eliminated^^{s1} is no more!",
"none",
[
(str_store_faction_name, s1, "$g_notification_menu_var1"),
(set_fixed_point_multiplier, 100),
(position_set_x, pos0, 65),
(position_set_y, pos0, 30),
(position_set_z, pos0, 170),
(try_begin),
(is_between, "$g_notification_menu_var1", "fac_kingdom_7", kingdoms_end), #Excluding player kingdom
(set_game_menu_tableau_mesh, "tableau_faction_note_mesh_for_menu", "$g_notification_menu_var1", pos0),
(else_try),
(set_game_menu_tableau_mesh, "tableau_faction_note_mesh_banner", "$g_notification_menu_var1", pos0),
(try_end),
],
[
("continue",[],"Continue...",
[
(try_begin),
(is_between, "$supported_pretender", pretenders_begin, pretenders_end),
(troop_slot_eq, "$supported_pretender", slot_troop_original_faction, "$g_notification_menu_var1"),
#All rebels switch to kingdom
(try_for_range, ":cur_troop", active_npcs_begin, active_npcs_end),
(troop_slot_eq, ":cur_troop", slot_troop_occupation, slto_kingdom_hero),
(store_troop_faction, ":cur_faction", ":cur_troop"),
(eq, ":cur_faction", "fac_player_supporters_faction"),
(troop_set_faction, ":cur_troop", "$g_notification_menu_var1"),
(call_script, "script_troop_set_title_according_to_faction", ":cur_troop", "$g_notification_menu_var1"),
(try_begin),
(this_or_next|eq, "$g_notification_menu_var1", "$players_kingdom"),
(eq, "$g_notification_menu_var1", "fac_player_supporters_faction"),
(call_script, "script_check_concilio_calradi_achievement"),
(try_end),
(else_try), #all loyal lords gain a small bonus with the player
(troop_slot_eq, ":cur_troop", slot_troop_occupation, slto_kingdom_hero),
(store_troop_faction, ":cur_faction", ":cur_troop"),
(eq, ":cur_faction", "$g_notification_menu_var1"),
(call_script, "script_troop_change_relation_with_troop", ":cur_troop", "trp_player", 5),
(try_end),
(try_for_parties, ":cur_party"),
(store_faction_of_party, ":cur_faction", ":cur_party"),
(eq, ":cur_faction", "fac_player_supporters_faction"),
(party_set_faction, ":cur_party", "$g_notification_menu_var1"),
(try_end),
(assign, "$players_kingdom", "$g_notification_menu_var1"),
(try_begin),
(troop_get_slot, ":spouse", "trp_player", slot_troop_spouse),
(is_between, ":spouse", kingdom_ladies_begin, kingdom_ladies_end),
(troop_set_faction, ":spouse", "$g_notification_menu_var1"),
(try_end),
(call_script, "script_add_notification_menu", "mnu_notification_rebels_switched_to_faction", "$g_notification_menu_var1", "$supported_pretender"),
(faction_set_slot, "$g_notification_menu_var1", slot_faction_state, sfs_active),
(faction_set_slot, "fac_player_supporters_faction", slot_faction_state, sfs_inactive),
(faction_get_slot, ":old_leader", "$g_notification_menu_var1", slot_faction_leader),
(troop_set_slot, ":old_leader", slot_troop_change_to_faction, "fac_commoners"),
(faction_set_slot, "$g_notification_menu_var1", slot_faction_leader, "$supported_pretender"),
(troop_set_faction, "$supported_pretender", "$g_notification_menu_var1"),
(faction_get_slot, ":old_marshall", "$g_notification_menu_var1", slot_faction_marshall),
(try_begin),
(ge, ":old_marshall", 0),
(troop_get_slot, ":old_marshall_party", ":old_marshall", slot_troop_leaded_party),
(party_is_active, ":old_marshall_party"),
(party_set_marshall, ":old_marshall_party", 0),
(try_end),
(faction_set_slot, "$g_notification_menu_var1", slot_faction_marshall, "trp_player"),
(faction_set_slot, "$g_notification_menu_var1", slot_faction_ai_state, sfai_default),
(faction_set_slot, "$g_notification_menu_var1", slot_faction_ai_object, -1),
(troop_set_slot, "$supported_pretender", slot_troop_occupation, slto_kingdom_hero),
(troop_set_slot, "$supported_pretender", slot_troop_renown, 1000),
(party_remove_members, "p_main_party", "$supported_pretender", 1),
(call_script, "script_set_player_relation_with_faction", "$g_notification_menu_var1", 0),
(try_for_range, ":cur_kingdom", kingdoms_begin, kingdoms_end),
(faction_slot_eq, ":cur_kingdom", slot_faction_state, sfs_active),
(neq, ":cur_kingdom", "$g_notification_menu_var1"),
(store_relation, ":reln", ":cur_kingdom", "fac_player_supporters_faction"),
(set_relation, ":cur_kingdom", "$g_notification_menu_var1", ":reln"),
(try_end),
(assign, "$supported_pretender", 0),
(assign, "$supported_pretender_old_faction", 0),
(assign, "$g_recalculate_ais", 1),
(call_script, "script_update_all_notes"),
(try_end),
(change_screen_return),
]),
]
),
(
"notification_rebels_switched_to_faction",0,
"Rebellion Success^^ Your rebellion is victorious! Your faction now has the sole claim to the title of {s11}, with {s12} as the single ruler.",
"none",
[
(str_store_faction_name, s11, "$g_notification_menu_var1"),
(str_store_troop_name, s12, "$g_notification_menu_var2"),
(set_fixed_point_multiplier, 100),
(position_set_x, pos0, 65),
(position_set_y, pos0, 30),
(position_set_z, pos0, 170),
(try_begin),
(is_between, "$g_notification_menu_var1", "fac_kingdom_7", kingdoms_end), #Excluding player kingdom
(set_game_menu_tableau_mesh, "tableau_faction_note_mesh_for_menu", "$g_notification_menu_var1", pos0),
(else_try),
(set_game_menu_tableau_mesh, "tableau_faction_note_mesh_banner", "$g_notification_menu_var1", pos0),
(try_end),
],
[
("continue",[],"Continue...",
[
(assign, "$talk_context", tc_rebel_thanks),
(start_map_conversation, "$g_notification_menu_var2", -1),
(change_screen_return),
]),
]
),
(
"notification_player_should_consult",0,
"Your minister send words that there are problems brewing in the realm which, if left untreated, could sap your authority. You should consult with him at your earliest convenience",
"none",
[
],
[
("continue",[],"Continue...",
[
(setup_quest_text, "qst_consult_with_minister"),
(str_store_troop_name, s11, "$g_player_minister"),
(str_store_party_name, s12, "$g_player_court"),
(str_store_string, s2, "str_consult_with_s11_at_your_court_in_s12"),
(call_script, "script_start_quest", "qst_consult_with_minister", -1),
(quest_set_slot, "qst_consult_with_minister", slot_quest_expiration_days, 30),
(quest_set_slot, "qst_consult_with_minister", slot_quest_giver_troop, "$g_player_minister"),
(change_screen_return),
]),
]
),
(
"notification_player_feast_in_progress",0,
"Feast in Preparation^^Your wife has started preparations for a feast in your hall in {s11}",
"none",
[
(str_store_party_name, s11, "$g_notification_menu_var1"),
],
[
("continue",[],"Continue...",
[(change_screen_return),
]),
]
),
(
"notification_lady_requests_visit",0, #add this once around seven days after the last visit, or three weeks, or three months
"An elderly woman approaches your party and passes one of your men a letter, sealed in plain wax. It is addressed to you. When you break the seal, you see it is from {s15}. It reads, 'I so enjoyed your last visit. {s14} I am currently in {s10}.{s12}'",
"none",
[
(assign, ":lady_no", "$g_notification_menu_var1"),
(assign, ":center_no", "$g_notification_menu_var2"),
(str_store_troop_name, s15, ":lady_no"),
(str_store_party_name, s10, ":center_no"),
(store_current_hours, ":hours_since_last_visit"),
(troop_get_slot, ":last_visit_hours", ":lady_no", slot_troop_last_talk_time),
(val_sub, ":hours_since_last_visit", ":last_visit_hours"),
(call_script, "script_get_kingdom_lady_social_determinants", ":lady_no"),
(assign, ":lady_guardian", reg0),
(str_store_troop_name, s16, ":lady_guardian"),
(call_script, "script_troop_get_family_relation_to_troop", ":lady_guardian", ":lady_no"),
(str_clear, s14),
(try_begin),
(lt, ":hours_since_last_visit", 336),
(try_begin),
(troop_slot_eq, ":lady_no", slot_lord_reputation_type, lrep_otherworldly),
(str_store_string, s14, "str_as_brief_as_our_separation_has_been_the_longing_in_my_heart_to_see_you_has_made_it_seem_as_many_years"),
(else_try),
(str_store_string, s14, "str_although_it_has_only_been_a_short_time_since_your_departure_but_i_would_be_most_pleased_to_see_you_again"),
(try_end),
(else_try),
(ge, ":hours_since_last_visit", 336),
(try_begin),
(troop_slot_eq, ":lady_no", slot_lord_reputation_type, lrep_ambitious),
(str_store_string, s14, "str_although_i_have_received_no_word_from_you_for_quite_some_time_i_am_sure_that_you_must_have_been_very_busy_and_that_your_failure_to_come_see_me_in_no_way_indicates_that_your_attentions_to_me_were_insincere_"),
(else_try),
(troop_slot_eq, ":lady_no", slot_lord_reputation_type, lrep_moralist),
(str_store_string, s14, "str_i_trust_that_you_have_comported_yourself_in_a_manner_becoming_a_gentleman_during_our_long_separation_"),
(else_try),
(str_store_string, s14, "str_it_has_been_many_days_since_you_came_and_i_would_very_much_like_to_see_you_again"),
(try_end),
(try_end),
(str_clear, s12),
(str_clear, s18),
(try_begin),
(troop_slot_eq, ":lady_guardian", slot_lord_granted_courtship_permission, 0),
(str_store_string, s12, "str__you_should_ask_my_s11_s16s_permission_but_i_have_no_reason_to_believe_that_he_will_prevent_you_from_coming_to_see_me"),
(str_store_string, s18, "str__you_should_first_ask_her_s11_s16s_permission"),
(else_try),
(troop_slot_eq, ":lady_guardian", slot_lord_granted_courtship_permission, -1),
(str_store_string, s12, "str__alas_as_we_know_my_s11_s16_will_not_permit_me_to_see_you_however_i_believe_that_i_can_arrange_away_for_you_to_enter_undetected"),
(else_try),
(troop_slot_eq, ":lady_guardian", slot_lord_granted_courtship_permission, 1),
(str_store_string, s12, "str__as_my_s11_s16_has_already_granted_permission_for_you_to_see_me_i_shall_expect_your_imminent_arrival"),
(try_end),
],
[
("continue",[],"Tell the woman to inform her mistress that you will come shortly",
[
(assign, ":lady_to_visit", "$g_notification_menu_var1"),
(str_store_troop_name_link, s3, ":lady_to_visit"),
(str_store_party_name_link, s4, "$g_notification_menu_var2"),
(str_store_string, s2, "str_visit_s3_who_was_last_at_s4s18"),
(call_script, "script_start_quest", "qst_visit_lady", ":lady_to_visit"),
(quest_set_slot, "qst_visit_lady", slot_quest_giver_troop, ":lady_to_visit"), #don't know why this is necessary
(try_begin),
(eq, "$cheat_mode", 1),
(quest_get_slot, ":giver_troop", "qst_visit_lady", slot_quest_giver_troop),
(str_store_troop_name, s2, ":giver_troop"),
(display_message, "str_giver_troop_=_s2"),
(try_end),
(quest_set_slot, "qst_visit_lady", slot_quest_expiration_days, 30),
(change_screen_return),
]),
("continue",[],"Tell the woman to inform her mistress that you are indisposed",
[
(troop_set_slot, "$g_notification_menu_var1", slot_lady_no_messages, 1),
(change_screen_return),
]),
]
),
( #pre lady visit
"garden",0,
"{s12}",
"none",
[
(call_script, "script_get_kingdom_lady_social_determinants", "$love_interest_in_town"),
(assign, ":guardian_lord", reg0),
(str_store_troop_name, s11, "$love_interest_in_town"),
(try_begin),
(call_script, "script_npc_decision_checklist_male_guardian_assess_suitor", ":guardian_lord", "trp_player"),
(lt, reg0, 0),
(troop_set_slot, ":guardian_lord", slot_lord_granted_courtship_permission, -1),
(try_end),
(assign, "$nurse_assists_entry", 0),
(try_begin),
(troop_slot_eq, ":guardian_lord", slot_lord_granted_courtship_permission, 1),
(str_store_string, s12, "str_the_guards_at_the_gate_have_been_ordered_to_allow_you_through_you_might_be_imagining_things_but_you_think_one_of_them_may_have_given_you_a_wink"),
(else_try), #the circumstances under which the lady arranges for a surreptitious entry
(call_script, "script_troop_get_relation_with_troop", "trp_player", "$love_interest_in_town"),
(gt, reg0, 0),
(assign, ":player_completed_quest", 0),
(try_begin),
(check_quest_active, "qst_visit_lady"),
(quest_slot_eq, "qst_visit_lady", slot_quest_giver_troop, "$love_interest_in_town"),
(assign, ":player_completed_quest", 1),
(else_try),
(check_quest_active, "qst_formal_marriage_proposal"),
(quest_slot_eq, "qst_formal_marriage_proposal", slot_quest_giver_troop, "$love_interest_in_town"),
(this_or_next|check_quest_succeeded, "qst_formal_marriage_proposal"),
(check_quest_failed, "qst_formal_marriage_proposal"),
(assign, ":player_completed_quest", 1),
(else_try),
(check_quest_active, "qst_duel_courtship_rival"),
(quest_slot_eq, "qst_duel_courtship_rival", slot_quest_giver_troop, "$love_interest_in_town"),
(this_or_next|check_quest_succeeded, "qst_duel_courtship_rival"),
(check_quest_failed, "qst_duel_courtship_rival"),
(assign, ":player_completed_quest", 1),
(try_end),
(try_begin),
(store_current_hours, ":hours_since_last_visit"),
(troop_get_slot, ":last_visit_time", "$love_interest_in_town", slot_troop_last_talk_time),
(val_sub, ":hours_since_last_visit", ":last_visit_time"),
(this_or_next|ge, ":hours_since_last_visit", 96), #at least four days
(eq, ":player_completed_quest", 1),
(try_begin),
(is_between, "$g_encountered_party", towns_begin, towns_end),
(str_store_string, s12, "str_the_guards_glare_at_you_and_you_know_better_than_to_ask_permission_to_enter_however_as_you_walk_back_towards_your_lodgings_an_elderly_lady_dressed_in_black_approaches_you_i_am_s11s_nurse_she_whispers_urgently_don_this_dress_and_throw_the_hood_over_your_face_i_will_smuggle_you_inside_the_castle_to_meet_her_in_the_guise_of_a_skullery_maid__the_guards_will_not_look_too_carefully_but_i_beg_you_for_all_of_our_sakes_be_discrete"),
(assign, "$nurse_assists_entry", 1),
(else_try),
(str_store_string, s12, "str_the_guards_glare_at_you_and_you_know_better_than_to_ask_permission_to_enter_however_as_you_walk_back_towards_your_lodgings_an_elderly_lady_dressed_in_black_approaches_you_i_am_s11s_nurse_she_whispers_urgently_wait_for_a_while_by_the_spring_outside_the_walls_i_will_smuggle_her_ladyship_out_to_meet_you_dressed_in_the_guise_of_a_shepherdess_but_i_beg_you_for_all_of_our_sakes_be_discrete"),
(assign, "$nurse_assists_entry", 2),
(try_end),
(else_try),
(str_store_string, s12, "str_the_guards_glare_at_you_and_you_know_better_than_to_ask_permission_to_enter_however_as_you_walk_back_towards_your_lodgings_an_elderly_lady_dressed_in_black_approaches_you_i_am_s11s_nurse_she_whispers_urgently_her_ladyship_asks_me_to_say_that_yearns_to_see_you_but_that_you_should_bide_your_time_a_bit_her_ladyship_says_that_to_arrange_a_clandestine_meeting_so_soon_after_your_last_encounter_would_be_too_dangerous"),
(try_end),
(else_try),
(str_store_string, s12, "str_the_guards_glare_at_you_and_you_know_better_than_to_ask_permission_to_enter"),
(try_end),
],
[
("enter",
[
(call_script, "script_get_kingdom_lady_social_determinants", "$love_interest_in_town"),
(troop_slot_eq, reg0, slot_lord_granted_courtship_permission, 1)
], "Enter",
[
(jump_to_menu, "mnu_town"),
(call_script, "script_setup_meet_lady", "$love_interest_in_town", "$g_encountered_party"),
]
),
("nurse",
[
(eq, "$nurse_assists_entry", 1),
], "Go with the nurse",
[
(jump_to_menu, "mnu_town"),
(call_script, "script_setup_meet_lady", "$love_interest_in_town", "$g_encountered_party"),
]
),
("nurse",
[
(eq, "$nurse_assists_entry", 2),
], "Wait by the spring",
[
(jump_to_menu, "mnu_town"),
(call_script, "script_setup_meet_lady", "$love_interest_in_town", "$g_encountered_party"),
]
),
("leave",
[],
"Leave",
[(jump_to_menu, "mnu_town")]),
]
),
(
"kill_local_merchant_begin",0,
"You spot your victim and follow him, observing as he turns a corner into a dark alley.\
This will surely be your best opportunity to attack him.",
"none",
[
],
[
("continue",[],"Continue...",
[(set_jump_mission,"mt_back_alley_kill_local_merchant"),
(party_get_slot, ":town_alley", "$qst_kill_local_merchant_center", slot_town_alley),
(modify_visitors_at_site,":town_alley"),
(reset_visitors),
(set_visitor, 0, "trp_player"),
(set_visitor, 1, "trp_local_merchant"),
(jump_to_menu, "mnu_town"),
(jump_to_scene,":town_alley"),
(change_screen_mission),
]),
]
),
(
"debug_alert_from_s65",0,
"DEBUG ALERT: {s65}",
"none",
[
],
[
("continue",[],"Continue...",
[
(assign, "$debug_message_in_queue", 0),
(change_screen_return),
]),
]
),
(
"auto_return_to_map",0,
"stub",
"none",
[(change_screen_map)],
[]
),
(
"bandit_lair",0,
"{s3}",
"none",
[
(try_begin),
(eq, "$loot_screen_shown", 1),
(try_for_range, ":bandit_template", "pt_steppe_bandits", "pt_deserters"),
(party_template_slot_eq, ":bandit_template", slot_party_template_lair_party, "$g_encountered_party"),
(party_template_set_slot, ":bandit_template", slot_party_template_lair_party, 0),
(try_end),
(try_begin),
(ge, "$g_encountered_party", 0),
(party_is_active, "$g_encountered_party"),
(party_get_template_id, ":template", "$g_encountered_party"),
(neq, ":template", "pt_looter_lair"),
(remove_party, "$g_encountered_party"),
(try_end),
(assign, "$g_leave_encounter", 0),
(change_screen_return),
(else_try),
(party_stack_get_troop_id, ":bandit_type", "$g_encountered_party", 0),
(str_store_troop_name_plural, s4, ":bandit_type"),
(str_store_string, s5, "str_bandit_approach_defile"),
(try_begin),
(eq, ":bandit_type", "trp_desert_bandit"),
(str_store_string, s5, "str_bandit_approach_defile"),
(else_try),
(eq, ":bandit_type", "trp_mountain_bandit"),
(str_store_string, s5, "str_bandit_approach_cliffs"),
(else_try),
(eq, ":bandit_type", "trp_forest_bandit"),
(str_store_string, s5, "str_bandit_approach_swamp"),
(else_try),
(eq, ":bandit_type", "trp_taiga_bandit"),
(str_store_string, s5, "str_bandit_approach_swamp"),
(else_try),
(eq, ":bandit_type", "trp_steppe_bandit"),
(str_store_string, s5, "str_bandit_approach_thickets"),
(else_try),
(eq, ":bandit_type", "trp_sea_raider"),
(str_store_string, s5, "str_bandit_approach_cove"),
(try_end),
(try_begin),
(party_slot_eq, "$g_encountered_party", slot_party_ai_substate, 0), #used in place of global variable
(str_store_string, s3, "str_bandit_hideout_preattack"),
(else_try),
(party_get_template_id, ":template", "$g_encountered_party"),
(eq, ":template", "pt_looter_lair"),
(party_slot_eq, "$g_encountered_party", slot_party_ai_substate, 1), #used in place of global variable
(str_store_string, s3, "str_lost_startup_hideout_attack"),
(else_try),
(party_slot_eq, "$g_encountered_party", slot_party_ai_substate, 1), #used in place of global variable
(str_store_string, s3, "str_bandit_hideout_failure"),
(else_try),
(party_slot_eq, "$g_encountered_party", slot_party_ai_substate, 2), #used in place of global variable
(str_store_string, s3, "str_bandit_hideout_success"),
(try_end),
(try_end),
],
[
("continue_1",
[
(party_slot_eq, "$g_encountered_party", slot_party_ai_substate, 0), #used in place of global variable
],
"Attack the hideout...",
[
(party_set_slot, "$g_encountered_party", slot_party_ai_substate, 1),
(party_get_template_id, ":template", "$g_encountered_party"),
(assign, "$g_enemy_party", "$g_encountered_party"),
(try_begin),
(eq, ":template", "pt_sea_raider_lair"),
(assign, ":bandit_troop", "trp_sea_raider"),
(assign, ":scene_to_use", "scn_lair_sea_raiders"),
(else_try),
(eq, ":template", "pt_forest_bandit_lair"),
(assign, ":bandit_troop", "trp_forest_bandit"),
(assign, ":scene_to_use", "scn_lair_forest_bandits"),
(else_try),
(eq, ":template", "pt_desert_bandit_lair"),
(assign, ":bandit_troop", "trp_desert_bandit"),
(assign, ":scene_to_use", "scn_lair_desert_bandits"),
(else_try),
(eq, ":template", "pt_mountain_bandit_lair"),
(assign, ":bandit_troop", "trp_mountain_bandit"),
(assign, ":scene_to_use", "scn_lair_mountain_bandits"),
(else_try),
(eq, ":template", "pt_taiga_bandit_lair"),
(assign, ":bandit_troop", "trp_taiga_bandit"),
(assign, ":scene_to_use", "scn_lair_taiga_bandits"),
(else_try),
(eq, ":template", "pt_steppe_bandit_lair"),
(assign, ":bandit_troop", "trp_steppe_bandit"),
(assign, ":scene_to_use", "scn_lair_steppe_bandits"),
(else_try),
(eq, ":template", "pt_looter_lair"),
(assign, ":bandit_troop", "trp_looter"),
(store_faction_of_party, ":starting_town_faction", "$g_starting_town"),
(try_begin),
(eq, ":starting_town_faction", "fac_kingdom_7"), #player selected swadian city as starting town.
(assign, ":scene_to_use", "scn_lair_forest_bandits"),
(else_try),
(eq, ":starting_town_faction", "fac_kingdom_7"), #player selected Vaegir city as starting town.
(assign, ":scene_to_use", "scn_lair_taiga_bandits"),
(else_try),
(eq, ":starting_town_faction", "fac_kingdom_7"), #player selected Khergit city as starting town.
(assign, ":scene_to_use", "scn_lair_steppe_bandits"),
(else_try),
(eq, ":starting_town_faction", "fac_kingdom_7"), #player selected Nord city as starting town.
(assign, ":scene_to_use", "scn_lair_sea_raiders"),
(else_try),
(eq, ":starting_town_faction", "fac_kingdom_7"), #player selected Rhodok city as starting town.
(assign, ":scene_to_use", "scn_lair_mountain_bandits"),
(else_try),
(eq, ":starting_town_faction", "fac_kingdom_7"), #player selected Sarranid city as starting town.
(assign, ":scene_to_use", "scn_lair_desert_bandits"),
(try_end),
(try_end),
(modify_visitors_at_site,":scene_to_use"),
(reset_visitors),
(store_character_level, ":player_level", "trp_player"),
(store_add, ":number_of_bandits_will_be_spawned_at_each_period", 5, ":player_level"),
(val_div, ":number_of_bandits_will_be_spawned_at_each_period", 3),
(try_for_range, ":unused", 0, ":number_of_bandits_will_be_spawned_at_each_period"),
(store_random_in_range, ":random_entry_point", 2, 11),
(set_visitor, ":random_entry_point", ":bandit_troop", 1),
(try_end),
(party_clear, "p_temp_casualties"),
(set_party_battle_mode),
(set_battle_advantage, 0),
(assign, "$g_battle_result", 0),
(set_jump_mission,"mt_bandit_lair"),
(jump_to_scene, ":scene_to_use"),
(change_screen_mission),
]),
("leave_no_attack",
[
(party_slot_eq, "$g_encountered_party", slot_party_ai_substate, 0),
],
"Leave...",
[
(change_screen_return),
]),
("leave_victory",
[
(party_slot_eq, "$g_encountered_party", slot_party_ai_substate, 2),
],
"Continue...",
[
(try_for_range, ":bandit_template", "pt_steppe_bandits", "pt_deserters"),
(party_template_slot_eq, ":bandit_template", slot_party_template_lair_party, "$g_encountered_party"),
(party_template_set_slot, ":bandit_template", slot_party_template_lair_party, 0),
(try_end),
(party_get_template_id, ":template", "$g_encountered_party"),
(try_begin),
(neq, ":template", "pt_looter_lair"),
(check_quest_active, "qst_destroy_bandit_lair"),
(quest_slot_eq, "qst_destroy_bandit_lair", slot_quest_target_party, "$g_encountered_party"),
(call_script, "script_succeed_quest", "qst_destroy_bandit_lair"),
(try_end),
(assign, "$g_leave_encounter", 0),
(change_screen_return),
(try_begin),
(eq, "$loot_screen_shown", 0),
(assign, "$loot_screen_shown", 1),
# (try_begin),
# (gt, "$g_ally_party", 0),
# (call_script, "script_party_add_party", "$g_ally_party", "p_temp_party"), #Add remaining prisoners to ally TODO: FIX it.
# (else_try),
# (party_get_num_attached_parties, ":num_quick_attachments", "p_main_party"),
# (gt, ":num_quick_attachments", 0),
# (party_get_attached_party_with_rank, ":helper_party", "p_main_party", 0),
# (call_script, "script_party_add_party", ":helper_party", "p_temp_party"), #Add remaining prisoners to our reinforcements
# (try_end),
(troop_clear_inventory, "trp_temp_troop"),
(party_get_num_companion_stacks, ":num_stacks", "p_temp_casualties"),
(try_for_range, ":stack_no", 0, ":num_stacks"),
(party_stack_get_troop_id, ":stack_troop", "p_temp_casualties", ":stack_no"),
(try_begin),
(party_stack_get_size, ":stack_size", "p_temp_casualties", ":stack_no"),
(party_stack_get_troop_id, ":stack_troop", "p_temp_casualties", ":stack_no"),
(gt, ":stack_size", 0),
(party_add_members, "p_total_enemy_casualties", ":stack_troop", ":stack_size"), #addition_to_p_total_enemy_casualties
(party_stack_get_num_wounded, ":stack_wounded_size", "p_temp_casualties", ":stack_no"),
(gt, ":stack_wounded_size", 0),
(party_wound_members, "p_total_enemy_casualties", ":stack_troop", ":stack_wounded_size"),
(try_end),
(try_end),
(call_script, "script_party_calculate_loot", "p_total_enemy_casualties"), #p_encountered_party_backup changed to total_enemy_casualties
(gt, reg0, 0),
(troop_sort_inventory, "trp_temp_troop"),
(change_screen_loot, "trp_temp_troop"),
(try_end),
(try_begin),
(ge, "$g_encountered_party", 0),
(party_is_active, "$g_encountered_party"),
(party_get_template_id, ":template", "$g_encountered_party"),
(eq, ":template", "pt_looter_lair"),
(remove_party, "$g_encountered_party"),
(try_end),
]),
("leave_defeat",
[
(party_slot_eq, "$g_encountered_party", slot_party_ai_substate, 1),
],
"Continue...",
[
(try_for_range, ":bandit_template", "pt_steppe_bandits", "pt_deserters"),
(party_template_slot_eq, ":bandit_template", slot_party_template_lair_party, "$g_encountered_party"),
(party_template_set_slot, ":bandit_template", slot_party_template_lair_party, 0),
(try_end),
(try_begin),
(party_get_template_id, ":template", "$g_encountered_party"),
(neq, ":template", "pt_looter_lair"),
(check_quest_active, "qst_destroy_bandit_lair"),
(quest_slot_eq, "qst_destroy_bandit_lair", slot_quest_target_party, "$g_encountered_party"),
(call_script, "script_fail_quest", "qst_destroy_bandit_lair"),
(try_end),
(try_begin),
(ge, "$g_encountered_party", 0),
(party_is_active, "$g_encountered_party"),
(party_get_template_id, ":template", "$g_encountered_party"),
(neq, ":template", "pt_looter_lair"),
(remove_party, "$g_encountered_party"),
(try_end),
(assign, "$g_leave_encounter", 0),
(try_begin),
(party_is_active, "$g_encountered_party"),
(party_set_slot, "$g_encountered_party", slot_party_ai_substate, 0),
(try_end),
(change_screen_return),
]),
]
),
(
"notification_player_faction_political_issue_resolved",0,
"After consulting with the peers of the realm, {s10} has decided to confer {s11} on {s12}.",
"none",
[
(assign, ":faction_issue_resolved", "$g_notification_menu_var1"),
(assign, ":faction_decision", "$g_notification_menu_var2"),
(faction_get_slot, ":leader", "$players_kingdom", slot_faction_leader),
(str_store_troop_name, s10, ":leader"),
(try_begin),
(eq, ":faction_issue_resolved", 1),
(str_store_string, s11, "str_the_marshalship"),
(else_try),
(str_store_party_name, s11, ":faction_issue_resolved"),
(try_end),
(str_store_troop_name, s12, ":faction_decision"),
],
[
("continue",
[],"Continue...",
[
(change_screen_return),
]),
]
),
(
"notification_player_faction_political_issue_resolved_for_player",0,
"After consulting with the peers of the realm, {s10} has decided to confer {s11} on you. You may decline the honor, but it will probably mean that you will not receive other awards for a little while.{s12}",
"none",
[
(faction_get_slot, ":leader", "$players_kingdom", slot_faction_leader),
(str_store_troop_name, s10, ":leader"),
(faction_get_slot, ":issue", "$players_kingdom", slot_faction_political_issue),
(try_begin),
(eq, ":issue", 1),
(str_store_string, s11, "str_the_marshalship"),
(str_store_string, s12, "@^^Note that so long as you remain marshal, the lords of the realm will be expecting you to lead them on campaign. So, if you are awaiting a feast, either for a wedding or for other purposes, you may wish to resign the marshalship by speaking to your liege."),
(else_try),
(str_clear, s12),
(str_store_party_name, s11, ":issue"),
(try_end),
],
[
("accept",
[],"Accept the honor",
[
(faction_get_slot, ":issue", "$players_kingdom", slot_faction_political_issue),
(try_begin),
(eq, ":issue", 1),
(call_script, "script_check_and_finish_active_army_quests_for_faction", "$players_kingdom"),
(call_script, "script_appoint_faction_marshall", "$players_kingdom", "trp_player"),
(unlock_achievement, ACHIEVEMENT_AUTONOMOUS_COLLECTIVE),
(else_try),
(call_script, "script_give_center_to_lord", ":issue", "trp_player", 0), #Zero means don't add garrison
(try_end),
(faction_set_slot, "$players_kingdom", slot_faction_political_issue, 0),
(try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
(store_faction_of_troop, ":active_npc_faction", ":active_npc"),
(eq, ":active_npc_faction", "$players_kingdom"),
(troop_set_slot, ":active_npc", slot_troop_stance_on_faction_issue, -1),
(try_end),
(change_screen_return),
]),
("decline",
[],"Decline the honor",
[
(faction_get_slot, ":issue", "$players_kingdom", slot_faction_political_issue),
(try_begin),
(is_between, ":issue", centers_begin, centers_end),
(assign, "$g_dont_give_fief_to_player_days", 30),
(else_try),
(assign, "$g_dont_give_marshalship_to_player_days", 30),
(try_end),
(try_for_range, ":active_npc", active_npcs_begin, active_npcs_end),
(store_faction_of_troop, ":active_npc_faction", ":active_npc"),
(eq, ":active_npc_faction", "$players_kingdom"),
(troop_set_slot, ":active_npc", slot_troop_stance_on_faction_issue, -1),
(try_end),
(change_screen_return),
]),
]
),
("start_phase_2_5",mnf_disable_all_keys,
"{!}{s16}",
"none",
[
(str_store_party_name, s1, "$g_starting_town"),
(str_store_string, s16, "$g_journey_string"),
],
[
("continue",[], "Continue...",
[
(jump_to_menu, "mnu_start_phase_3"),
]),
]
),
("start_phase_3",mnf_disable_all_keys,
"{s16}^^You are exhausted by the time you find the inn in {s1}, and fall asleep quickly. However, you awake before dawn and are eager to explore your surroundings. You venture out onto the streets, which are still deserted. All of a sudden, you hear a sound that stands the hairs of your neck on end -- the rasp of a blade sliding from its scabbard...",
"none",
[
(assign, ":continue", 1),
(try_begin),
(eq, "$current_startup_quest_phase", 1),
(try_begin),
(eq, "$g_killed_first_bandit", 1),
(str_store_string, s11, "str_killed_bandit_at_alley_fight"),
(else_try),
(str_store_string, s11, "str_wounded_by_bandit_at_alley_fight"),
(try_end),
(jump_to_menu, "mnu_start_phase_4"),
(assign, ":continue", 0),
(else_try),
(eq, "$current_startup_quest_phase", 3),
(try_begin),
(eq, "$g_killed_first_bandit", 1),
(str_store_string, s11, "str_killed_bandit_at_alley_fight"),
(else_try),
(str_store_string, s11, "str_wounded_by_bandit_at_alley_fight"),
(try_end),
(jump_to_menu, "mnu_start_phase_4"),
(assign, ":continue", 0),
(try_end),
(str_store_party_name, s1, "$g_starting_town"),
(str_clear, s16),
(eq, ":continue", 1),
],
[
("continue",[], "Continue...",
[
(assign, "$g_starting_town", "$current_town"),
(call_script, "script_player_arrived"),
(party_set_morale, "p_main_party", 100),
(set_encountered_party, "$current_town"),
(call_script, "script_prepare_alley_to_fight"),
]),
]
),
("start_phase_4",mnf_disable_all_keys,
"{s11}",
"none",
[
(assign, ":continue", 1),
(try_begin),
(eq, "$current_startup_quest_phase", 2),
(change_screen_return),
(assign, ":continue", 0),
(else_try),
(eq, "$current_startup_quest_phase", 3),
(str_store_string, s11, "str_merchant_and_you_call_some_townsmen_and_guards_to_get_ready_and_you_get_out_from_tavern"),
(else_try),
(eq, "$current_startup_quest_phase", 4),
(try_begin),
(eq, "$g_killed_first_bandit", 1),
(str_store_string, s11, "str_town_fight_ended_you_and_citizens_cleaned_town_from_bandits"),
(else_try),
(str_store_string, s11, "str_town_fight_ended_you_and_citizens_cleaned_town_from_bandits_you_wounded"),
(try_end),
(try_end),
(eq, ":continue", 1),
],
[
("continue",
[
(this_or_next|eq, "$current_startup_quest_phase", 1),
(eq, "$current_startup_quest_phase", 4),
],
"Continue...",
[
(assign, "$town_entered", 1),
(try_begin),
(eq, "$current_town", "p_town_1"),
(assign, ":town_merchant", "trp_nord_merchant"),
(assign, ":town_room_scene", "scn_town_1_room"),
(else_try),
(eq, "$current_town", "p_town_5"),
(assign, ":town_merchant", "trp_rhodok_merchant"),
(assign, ":town_room_scene", "scn_town_5_room"),
(else_try),
(eq, "$current_town", "p_town_6"),
(assign, ":town_merchant", "trp_swadian_merchant"),
(assign, ":town_room_scene", "scn_town_6_room"),
(else_try),
(eq, "$current_town", "p_town_8"),
(assign, ":town_merchant", "trp_vaegir_merchant"),
(assign, ":town_room_scene", "scn_town_8_room"),
(else_try),
(eq, "$current_town", "p_town_10"),
(assign, ":town_merchant", "trp_khergit_merchant"),
(assign, ":town_room_scene", "scn_town_10_room"),
(else_try),
(eq, "$current_town", "p_town_19"),
(assign, ":town_merchant", "trp_sarranid_merchant"),
(assign, ":town_room_scene", "scn_town_19_room"),
(try_end),
(modify_visitors_at_site, ":town_room_scene"),
(reset_visitors),
(set_visitor, 0, "trp_player"),
(set_visitor, 9, ":town_merchant"),
(assign, "$talk_context", tc_merchants_house),
(assign, "$dialog_with_merchant_ended", 0),
(set_jump_mission, "mt_meeting_merchant"),
(jump_to_scene, ":town_room_scene"),
(change_screen_mission),
]),
("continue",
[
(eq, "$current_startup_quest_phase", 3),
],
"Continue...",
[
(call_script, "script_prepare_town_to_fight"),
]),
]
),
("lost_tavern_duel",mnf_disable_all_keys,
"{s11}",
"none",
[
(try_begin),
(agent_get_troop_id, ":type", "$g_main_attacker_agent"),
(eq, ":type", "trp_belligerent_drunk"),
(str_store_string, s11, "str_lost_tavern_duel_ordinary"),
(else_try),
(agent_get_troop_id, ":type", "$g_main_attacker_agent"),
(eq, ":type", "trp_hired_assassin"),
(str_store_string, s11, "str_lost_tavern_duel_assassin"),
(try_end),
(troop_set_slot, "trp_hired_assassin", slot_troop_cur_center, -1),
],
[
("continue",[],"Continue...",
[
(jump_to_menu, "mnu_town"),
]),
]
),
("establish_court",mnf_disable_all_keys,
"To establish {s4} as your court will require a small refurbishment. In particular, you will need a set of tools and a bolt of velvet. it may also take a short while for some of your followers to relocate here. Do you wish to proceed?",
"none",
[
(str_store_party_name, s4, "$g_encountered_party"),
],
[
("establish",[
(player_has_item, "itm_tools"),
(player_has_item, "itm_velvet"),
],"Establish {s4} as your court",
[
(assign, "$g_player_court", "$current_town"),
(troop_remove_item, "trp_player", "itm_tools"),
(troop_remove_item, "trp_player", "itm_velvet"),
(jump_to_menu, "mnu_town"),
]),
("continue",[],"Hold off...",
[
(jump_to_menu, "mnu_town"),
]),
]
),
("notification_relieved_as_marshal", mnf_disable_all_keys,
"{s4} wishes to inform you that your services as marshal are no longer required. In honor of valiant efforts on behalf of the realm over the last {reg4} days, however, {reg8?she:he} offers you a purse of {reg5} denars.",
"none",
[
(assign, reg4, "$g_player_days_as_marshal"),
(store_div, ":renown_gain", "$g_player_days_as_marshal",4),
(val_min, ":renown_gain", 20),
(store_mul, ":denar_gain", "$g_player_days_as_marshal", 50),
(val_max, ":denar_gain", 200),
(val_min, ":denar_gain", 4000),
(troop_add_gold, "trp_player", ":denar_gain"),
(call_script, "script_change_troop_renown", "trp_player", ":renown_gain"),
(assign, "$g_player_days_as_marshal", 0),
(assign, "$g_dont_give_marshalship_to_player_days", 15),
(assign, reg5, ":denar_gain"),
(faction_get_slot, ":faction_leader", "$players_kingdom", slot_faction_leader),
(str_store_troop_name, s4, ":faction_leader"),
(troop_get_type, reg8, ":faction_leader"),
],
[
("continue",[],"Continue",
[
(change_screen_return),
]),
]
),
]
| mit |
cboling/SDNdbg | docs/old-stuff/pydzcvr/doc/neutron/plugins/ml2/drivers/arista/arista_l3_driver.py | 4 | 20045 | # Copyright 2014 Arista Networks, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import hashlib
import socket
import struct
import jsonrpclib
from oslo.config import cfg
from neutron import context as nctx
from neutron.db import db_base_plugin_v2
from neutron.openstack.common.gettextutils import _LE
from neutron.openstack.common import log as logging
from neutron.plugins.ml2.drivers.arista import exceptions as arista_exc
LOG = logging.getLogger(__name__)
EOS_UNREACHABLE_MSG = _('Unable to reach EOS')
DEFAULT_VLAN = 1
MLAG_SWITCHES = 2
VIRTUAL_ROUTER_MAC = '00:11:22:33:44:55'
IPV4_BITS = 32
IPV6_BITS = 128
router_in_vrf = {
'router': {'create': ['vrf definition {0}',
'rd {1}',
'exit'],
'delete': ['no vrf definition {0}']},
'interface': {'add': ['ip routing vrf {1}',
'vlan {0}',
'exit',
'interface vlan {0}',
'vrf forwarding {1}',
'ip address {2}'],
'remove': ['no interface vlan {0}']}}
router_in_default_vrf = {
'router': {'create': [], # Place holder for now.
'delete': []}, # Place holder for now.
'interface': {'add': ['ip routing',
'vlan {0}',
'exit',
'interface vlan {0}',
'ip address {2}'],
'remove': ['no interface vlan {0}']}}
router_in_default_vrf_v6 = {
'router': {'create': [],
'delete': []},
'interface': {'add': ['ipv6 unicast-routing',
'vlan {0}',
'exit',
'interface vlan {0}',
'ipv6 enable',
'ipv6 address {2}'],
'remove': ['no interface vlan {0}']}}
additional_cmds_for_mlag = {
'router': {'create': ['ip virtual-router mac-address {0}'],
'delete': ['no ip virtual-router mac-address']},
'interface': {'add': ['ip virtual-router address {0}'],
'remove': []}}
additional_cmds_for_mlag_v6 = {
'router': {'create': [],
'delete': []},
'interface': {'add': ['ipv6 virtual-router address {0}'],
'remove': []}}
class AristaL3Driver(object):
"""Wraps Arista JSON RPC.
All communications between Neutron and EOS are over JSON RPC.
EOS - operating system used on Arista hardware
Command API - JSON RPC API provided by Arista EOS
"""
def __init__(self):
self._servers = []
self._hosts = []
self.interfaceDict = None
self._validate_config()
host = cfg.CONF.l3_arista.primary_l3_host
self._hosts.append(host)
self._servers.append(jsonrpclib.Server(self._eapi_host_url(host)))
self.mlag_configured = cfg.CONF.l3_arista.mlag_config
self.use_vrf = cfg.CONF.l3_arista.use_vrf
if self.mlag_configured:
host = cfg.CONF.l3_arista.secondary_l3_host
self._hosts.append(host)
self._servers.append(jsonrpclib.Server(self._eapi_host_url(host)))
self._additionalRouterCmdsDict = additional_cmds_for_mlag['router']
self._additionalInterfaceCmdsDict = (
additional_cmds_for_mlag['interface'])
if self.use_vrf:
self.routerDict = router_in_vrf['router']
self.interfaceDict = router_in_vrf['interface']
else:
self.routerDict = router_in_default_vrf['router']
self.interfaceDict = router_in_default_vrf['interface']
def _eapi_host_url(self, host):
user = cfg.CONF.l3_arista.primary_l3_host_username
pwd = cfg.CONF.l3_arista.primary_l3_host_password
eapi_server_url = ('https://%s:%s@%s/command-api' %
(user, pwd, host))
return eapi_server_url
def _validate_config(self):
if cfg.CONF.l3_arista.get('primary_l3_host') == '':
msg = _('Required option primary_l3_host is not set')
LOG.error(msg)
raise arista_exc.AristaSevicePluginConfigError(msg=msg)
if cfg.CONF.l3_arista.get('mlag_config'):
if cfg.CONF.l3_arista.get('secondary_l3_host') == '':
msg = _('Required option secondary_l3_host is not set')
LOG.error(msg)
raise arista_exc.AristaSevicePluginConfigError(msg=msg)
if cfg.CONF.l3_arista.get('primary_l3_host_username') == '':
msg = _('Required option primary_l3_host_username is not set')
LOG.error(msg)
raise arista_exc.AristaSevicePluginConfigError(msg=msg)
def create_router_on_eos(self, router_name, rdm, server):
"""Creates a router on Arista HW Device.
:param router_name: globally unique identifier for router/VRF
:param rdm: A value generated by hashing router name
:param server: Server endpoint on the Arista switch to be configured
"""
cmds = []
rd = "%s:%s" % (rdm, rdm)
for c in self.routerDict['create']:
cmds.append(c.format(router_name, rd))
if self.mlag_configured:
mac = VIRTUAL_ROUTER_MAC
for c in self._additionalRouterCmdsDict['create']:
cmds.append(c.format(mac))
self._run_openstack_l3_cmds(cmds, server)
def delete_router_from_eos(self, router_name, server):
"""Deletes a router from Arista HW Device.
:param router_name: globally unique identifier for router/VRF
:param server: Server endpoint on the Arista switch to be configured
"""
cmds = []
for c in self.routerDict['delete']:
cmds.append(c.format(router_name))
if self.mlag_configured:
for c in self._additionalRouterCmdsDict['delete']:
cmds.append(c)
self._run_openstack_l3_cmds(cmds, server)
def _select_dicts(self, ipv):
if self.use_vrf:
self.interfaceDict = router_in_vrf['interface']
else:
if ipv == 6:
#for IPv6 use IPv6 commmands
self.interfaceDict = router_in_default_vrf_v6['interface']
self._additionalInterfaceCmdsDict = (
additional_cmds_for_mlag_v6['interface'])
else:
self.interfaceDict = router_in_default_vrf['interface']
self._additionalInterfaceCmdsDict = (
additional_cmds_for_mlag['interface'])
def add_interface_to_router(self, segment_id,
router_name, gip, router_ip, mask, server):
"""Adds an interface to existing HW router on Arista HW device.
:param segment_id: VLAN Id associated with interface that is added
:param router_name: globally unique identifier for router/VRF
:param gip: Gateway IP associated with the subnet
:param router_ip: IP address of the router
:param mask: subnet mask to be used
:param server: Server endpoint on the Arista switch to be configured
"""
if not segment_id:
segment_id = DEFAULT_VLAN
cmds = []
for c in self.interfaceDict['add']:
if self.mlag_configured:
ip = router_ip
else:
ip = gip + '/' + mask
cmds.append(c.format(segment_id, router_name, ip))
if self.mlag_configured:
for c in self._additionalInterfaceCmdsDict['add']:
cmds.append(c.format(gip))
self._run_openstack_l3_cmds(cmds, server)
def delete_interface_from_router(self, segment_id, router_name, server):
"""Deletes an interface from existing HW router on Arista HW device.
:param segment_id: VLAN Id associated with interface that is added
:param router_name: globally unique identifier for router/VRF
:param server: Server endpoint on the Arista switch to be configured
"""
if not segment_id:
segment_id = DEFAULT_VLAN
cmds = []
for c in self.interfaceDict['remove']:
cmds.append(c.format(segment_id))
self._run_openstack_l3_cmds(cmds, server)
def create_router(self, context, tenant_id, router):
"""Creates a router on Arista Switch.
Deals with multiple configurations - such as Router per VRF,
a router in default VRF, Virtual Router in MLAG configurations
"""
if router:
router_name = self._arista_router_name(tenant_id, router['name'])
rdm = str(int(hashlib.sha256(router_name).hexdigest(),
16) % 6553)
mlag_peer_failed = False
for s in self._servers:
try:
self.create_router_on_eos(router_name, rdm, s)
mlag_peer_failed = False
except Exception:
if self.mlag_configured and not mlag_peer_failed:
mlag_peer_failed = True
else:
msg = (_('Failed to create router %s on EOS') %
router_name)
LOG.exception(msg)
raise arista_exc.AristaServicePluginRpcError(msg=msg)
def delete_router(self, context, tenant_id, router_id, router):
"""Deletes a router from Arista Switch."""
if router:
router_name = self._arista_router_name(tenant_id, router['name'])
mlag_peer_failed = False
for s in self._servers:
try:
self.delete_router_from_eos(router_name, s)
mlag_peer_failed = False
except Exception:
if self.mlag_configured and not mlag_peer_failed:
mlag_peer_failed = True
else:
msg = (_LE('Failed to delete router %s from EOS') %
router_name)
LOG.exception(msg)
raise arista_exc.AristaServicePluginRpcError(msg=msg)
def update_router(self, context, router_id, original_router, new_router):
"""Updates a router which is already created on Arista Switch.
TODO: (Sukhdev) - to be implemented in next release.
"""
pass
def add_router_interface(self, context, router_info):
"""Adds an interface to a router created on Arista HW router.
This deals with both IPv6 and IPv4 configurations.
"""
if router_info:
self._select_dicts(router_info['ip_version'])
cidr = router_info['cidr']
subnet_mask = cidr.split('/')[1]
router_name = self._arista_router_name(router_info['tenant_id'],
router_info['name'])
if self.mlag_configured:
# For MLAG, we send a specific IP address as opposed to cidr
# For now, we are using x.x.x.253 and x.x.x.254 as virtual IP
mlag_peer_failed = False
for i, server in enumerate(self._servers):
#get appropriate virtual IP address for this router
router_ip = self._get_router_ip(cidr, i,
router_info['ip_version'])
try:
self.add_interface_to_router(router_info['seg_id'],
router_name,
router_info['gip'],
router_ip, subnet_mask,
server)
mlag_peer_failed = False
except Exception:
if not mlag_peer_failed:
mlag_peer_failed = True
else:
msg = (_('Failed to add interface to router '
'%s on EOS') % router_name)
LOG.exception(msg)
raise arista_exc.AristaServicePluginRpcError(
msg=msg)
else:
for s in self._servers:
self.add_interface_to_router(router_info['seg_id'],
router_name,
router_info['gip'],
None, subnet_mask, s)
def remove_router_interface(self, context, router_info):
"""Removes previously configured interface from router on Arista HW.
This deals with both IPv6 and IPv4 configurations.
"""
if router_info:
router_name = self._arista_router_name(router_info['tenant_id'],
router_info['name'])
mlag_peer_failed = False
for s in self._servers:
try:
self.delete_interface_from_router(router_info['seg_id'],
router_name, s)
if self.mlag_configured:
mlag_peer_failed = False
except Exception:
if self.mlag_configured and not mlag_peer_failed:
mlag_peer_failed = True
else:
msg = (_LE('Failed to remove interface from router '
'%s on EOS') % router_name)
LOG.exception(msg)
raise arista_exc.AristaServicePluginRpcError(msg=msg)
def _run_openstack_l3_cmds(self, commands, server):
"""Execute/sends a CAPI (Command API) command to EOS.
In this method, list of commands is appended with prefix and
postfix commands - to make is understandble by EOS.
:param commands : List of command to be executed on EOS.
:param server: Server endpoint on the Arista switch to be configured
"""
command_start = ['enable', 'configure']
command_end = ['exit']
full_command = command_start + commands + command_end
LOG.info(_('Executing command on Arista EOS: %s'), full_command)
try:
# this returns array of return values for every command in
# full_command list
ret = server.runCmds(version=1, cmds=full_command)
LOG.info(_('Results of execution on Arista EOS: %s'), ret)
except Exception:
msg = (_LE("Error occured while trying to execute "
"commands %(cmd)s on EOS %(host)s"),
{'cmd': full_command, 'host': server})
LOG.exception(msg)
raise arista_exc.AristaServicePluginRpcError(msg=msg)
def _arista_router_name(self, tenant_id, name):
# Use a unique name so that OpenStack created routers/SVIs
# can be distinguishged from the user created routers/SVIs
# on Arista HW.
return 'OS' + '-' + tenant_id + '-' + name
def _get_binary_from_ipv4(self, ip_addr):
return struct.unpack("!L", socket.inet_pton(socket.AF_INET,
ip_addr))[0]
def _get_binary_from_ipv6(self, ip_addr):
hi, lo = struct.unpack("!QQ", socket.inet_pton(socket.AF_INET6,
ip_addr))
return (hi << 64) | lo
def _get_ipv4_from_binary(self, bin_addr):
return socket.inet_ntop(socket.AF_INET, struct.pack("!L", bin_addr))
def _get_ipv6_from_binary(self, bin_addr):
hi = bin_addr >> 64
lo = bin_addr & 0xFFFFFFFF
return socket.inet_ntop(socket.AF_INET6, struct.pack("!QQ", hi, lo))
def _get_router_ip(self, cidr, ip_count, ip_ver):
""" For a given IP subnet and IP version type, generate IP for router.
This method takes the network address (cidr) and selects an
IP address that should be assigned to virtual router running
on multiple switches. It uses upper addresses in a subnet address
as IP for the router. Each instace of the router, on each switch,
requires uniqe IP address. For example in IPv4 case, on a 255
subnet, it will pick X.X.X.254 as first addess, X.X.X.253 for next,
and so on.
"""
start_ip = MLAG_SWITCHES + ip_count
network_addr, prefix = cidr.split('/')
if ip_ver == 4:
bits = IPV4_BITS
ip = self._get_binary_from_ipv4(network_addr)
elif ip_ver == 6:
bits = IPV6_BITS
ip = self._get_binary_from_ipv6(network_addr)
mask = (pow(2, bits) - 1) << (bits - int(prefix))
network_addr = ip & mask
router_ip = pow(2, bits - int(prefix)) - start_ip
router_ip = network_addr | router_ip
if ip_ver == 4:
return self._get_ipv4_from_binary(router_ip) + '/' + prefix
else:
return self._get_ipv6_from_binary(router_ip) + '/' + prefix
class NeutronNets(db_base_plugin_v2.NeutronDbPluginV2):
"""Access to Neutron DB.
Provides access to the Neutron Data bases for all provisioned
networks as well ports. This data is used during the synchronization
of DB between ML2 Mechanism Driver and Arista EOS
Names of the networks and ports are not stored in Arista repository
They are pulled from Neutron DB.
"""
def __init__(self):
self.admin_ctx = nctx.get_admin_context()
def get_all_networks_for_tenant(self, tenant_id):
filters = {'tenant_id': [tenant_id]}
return super(NeutronNets,
self).get_networks(self.admin_ctx, filters=filters) or []
def get_all_ports_for_tenant(self, tenant_id):
filters = {'tenant_id': [tenant_id]}
return super(NeutronNets,
self).get_ports(self.admin_ctx, filters=filters) or []
def _get_network(self, tenant_id, network_id):
filters = {'tenant_id': [tenant_id],
'id': [network_id]}
return super(NeutronNets,
self).get_networks(self.admin_ctx, filters=filters) or []
def get_subnet_info(self, subnet_id):
subnet = self.get_subnet(subnet_id)
return subnet
def get_subnet_ip_version(self, subnet_id):
subnet = self.get_subnet(subnet_id)
return subnet['ip_version']
def get_subnet_gateway_ip(self, subnet_id):
subnet = self.get_subnet(subnet_id)
return subnet['gateway_ip']
def get_subnet_cidr(self, subnet_id):
subnet = self.get_subnet(subnet_id)
return subnet['cidr']
def get_network_id(self, subnet_id):
subnet = self.get_subnet(subnet_id)
return subnet['network_id']
def get_network_id_from_port_id(self, port_id):
port = self.get_port(port_id)
return port['network_id']
def get_subnet(self, subnet_id):
return super(NeutronNets,
self).get_subnet(self.admin_ctx, subnet_id) or []
def get_port(self, port_id):
return super(NeutronNets,
self).get_port(self.admin_ctx, port_id) or []
| apache-2.0 |
jamiecaesar/SecureCRT | templates/single_device_template.py | 3 | 2754 | # $language = "python"
# $interface = "1.0"
import os
import sys
import logging
# Add script directory to the PYTHONPATH so we can import our modules (only if run from SecureCRT)
if 'crt' in globals():
script_dir, script_name = os.path.split(crt.ScriptFullName)
if script_dir not in sys.path:
sys.path.insert(0, script_dir)
else:
script_dir, script_name = os.path.split(os.path.realpath(__file__))
# Now we can import our custom modules
from securecrt_tools import scripts
from securecrt_tools import utilities
# Create global logger so we can write debug messages from any function (if debug mode setting is enabled in settings).
logger = logging.getLogger("securecrt")
logger.debug("Starting execution of {0}".format(script_name))
# ################################################ SCRIPT LOGIC ###################################################
def script_main(session):
"""
| SINGLE device script
| Author: XXXXXXXX
| Email: [email protected]
PUT A DESCRIPTION OF THIS SCRIPT HERE. WHAT IT DOES, ETC.
This script assumes it will be run against a connected device.
:param session: A subclass of the sessions.Session object that represents this particular script session (either
SecureCRTSession or DirectSession)
:type session: sessions.Session
"""
# Get script object that owns this session, so we can check settings, get textfsm templates, etc
script = session.script
# Start session with device, i.e. modify term parameters for better interaction (assuming already connected)
session.start_cisco_session()
#
# PUT YOUR CODE HERE
#
# Return terminal parameters back to the original state.
session.end_cisco_session()
# ################################################ SCRIPT LAUNCH ###################################################
# If this script is run from SecureCRT directly, use the SecureCRT specific class
if __name__ == "__builtin__":
# Initialize script object
crt_script = scripts.CRTScript(crt)
# Get session object for the SecureCRT tab that the script was launched from.
crt_session = crt_script.get_main_session()
# Run script's main logic against our session
script_main(crt_session)
# Shutdown logging after
logging.shutdown()
# If the script is being run directly, use the simulation class
elif __name__ == "__main__":
# Initialize script object
direct_script = scripts.DebugScript(os.path.realpath(__file__))
# Get a simulated session object to pass into the script.
sim_session = direct_script.get_main_session()
# Run script's main logic against our session
script_main(sim_session)
# Shutdown logging after
logging.shutdown()
| apache-2.0 |
collects/VTK | Examples/Infovis/Python/hierarchical_graph.py | 17 | 2136 | from vtk import *
source = vtkRandomGraphSource()
source.SetNumberOfVertices(200)
source.SetEdgeProbability(0.01)
source.SetUseEdgeProbability(True)
source.SetStartWithTree(True)
source.IncludeEdgeWeightsOn()
source.AllowParallelEdgesOn()
# Connect to the vtkVertexDegree filter.
degree_filter = vtkVertexDegree()
degree_filter.SetOutputArrayName("vertex_degree")
degree_filter.SetInputConnection(source.GetOutputPort())
# Connect to the boost breath first search filter.
mstTreeSelection = vtkBoostKruskalMinimumSpanningTree()
mstTreeSelection.SetInputConnection(degree_filter.GetOutputPort())
mstTreeSelection.SetEdgeWeightArrayName("edge weight")
mstTreeSelection.NegateEdgeWeightsOn()
# Take selection and extract a graph
extract_graph = vtkExtractSelectedGraph()
extract_graph.AddInputConnection(degree_filter.GetOutputPort())
extract_graph.SetSelectionConnection(mstTreeSelection.GetOutputPort())
# Create a tree from the graph :)
bfsTree = vtkBoostBreadthFirstSearchTree()
bfsTree.AddInputConnection(extract_graph.GetOutputPort())
treeStrat = vtkTreeLayoutStrategy();
treeStrat.RadialOn()
treeStrat.SetAngle(360)
treeStrat.SetLogSpacingValue(1)
forceStrat = vtkSimple2DLayoutStrategy()
forceStrat.SetEdgeWeightField("edge weight")
dummy = vtkHierarchicalGraphView()
# Create Tree/Graph Layout view
view = vtkHierarchicalGraphView()
view.SetHierarchyFromInputConnection(bfsTree.GetOutputPort())
view.SetGraphFromInputConnection(degree_filter.GetOutputPort())
view.SetVertexColorArrayName("VertexDegree")
view.SetColorVertices(True)
view.SetVertexLabelArrayName("VertexDegree")
view.SetVertexLabelVisibility(True)
view.SetEdgeColorArrayName("edge weight")
# FIXME: If you uncomment this line the display locks up
view.SetColorEdges(True)
view.SetEdgeLabelArrayName("edge weight")
view.SetEdgeLabelVisibility(True)
view.SetLayoutStrategy(forceStrat)
view.SetBundlingStrength(.8)
# Set up the theme
theme = vtkViewTheme.CreateMellowTheme()
theme.SetCellColor(.2,.2,.6)
view.ApplyViewTheme(theme)
theme.FastDelete()
view.GetRenderWindow().SetSize(600, 600)
view.ResetCamera()
view.Render()
view.GetInteractor().Start()
| bsd-3-clause |
cstavr/synnefo | snf-pithos-backend/pithos/backends/lib/sqlite/groups.py | 1 | 3735 | # Copyright (C) 2010-2014 GRNET S.A.
#
# 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/>.
from collections import defaultdict
from dbworker import DBWorker
class Groups(DBWorker):
"""Groups are named collections of members, belonging to an owner."""
def __init__(self, **params):
DBWorker.__init__(self, **params)
execute = self.execute
execute(""" create table if not exists groups
( owner text,
name text,
member text,
primary key (owner, name, member) ) """)
execute(""" create index if not exists idx_groups_member
on groups(member) """)
def group_names(self, owner):
"""List all group names belonging to owner."""
q = "select distinct name from groups where owner = ?"
self.execute(q, (owner,))
return [r[0] for r in self.fetchall()]
def group_dict(self, owner):
"""Return a dict mapping group names to member lists for owner."""
q = "select name, member from groups where owner = ?"
self.execute(q, (owner,))
d = defaultdict(list)
for group, member in self.fetchall():
d[group].append(member)
return d
def group_add(self, owner, group, member):
"""Add a member to a group."""
q = ("insert or ignore into groups (owner, name, member) "
"values (?, ?, ?)")
self.execute(q, (owner, group, member))
def group_addmany(self, owner, group, members):
"""Add members to a group."""
q = ("insert or ignore into groups (owner, name, member) "
"values (?, ?, ?)")
self.executemany(q, ((owner, group, member) for member in
sorted(list(members))))
def group_remove(self, owner, group, member):
"""Remove a member from a group."""
q = "delete from groups where owner = ? and name = ? and member = ?"
self.execute(q, (owner, group, member))
def group_delete(self, owner, group):
"""Delete a group."""
q = "delete from groups where owner = ? and name = ?"
self.execute(q, (owner, group))
def group_destroy(self, owner):
"""Delete all groups belonging to owner."""
q = "delete from groups where owner = ?"
self.execute(q, (owner,))
def group_members(self, owner, group):
"""Return the list of members of a group."""
q = "select member from groups where owner = ? and name = ?"
self.execute(q, (owner, group))
return [r[0] for r in self.fetchall()]
def group_check(self, owner, group, member):
"""Check if a member is in a group."""
q = "select 1 from groups where owner = ? and name = ? and member = ?"
self.execute(q, (group, member))
return bool(self.fetchone())
def group_parents(self, member):
"""Return all (owner, group) tuples that contain member."""
q = "select owner, name from groups where member = ?"
self.execute(q, (member,))
return self.fetchall()
| gpl-3.0 |
ProgVal/Limnoria-test | test/test_plugins.py | 9 | 1717 | ###
# Copyright (c) 2002-2005, Jeremiah Fincher
# Copyright (c) 2008, James McCoy
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions, and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions, and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the author of this software nor the name of
# contributors to this software may be used to endorse or promote products
# derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###
from supybot.test import *
import supybot.irclib as irclib
import supybot.plugins as plugins
| bsd-3-clause |
Distrotech/libxml2 | python/tests/reader3.py | 35 | 4153 | #!/usr/bin/python -u
#
# this tests the entities substitutions with the XmlTextReader interface
#
import sys
import libxml2
try:
import StringIO
str_io = StringIO.StringIO
except:
import io
str_io = io.StringIO
docstr="""<?xml version='1.0'?>
<!DOCTYPE doc [
<!ENTITY tst "<p>test</p>">
]>
<doc>&tst;</doc>"""
# Memory debug specific
libxml2.debugMemory(1)
#
# First test, normal don't substitute entities.
#
f = str_io(docstr)
input = libxml2.inputBuffer(f)
reader = input.newTextReader("test_noent")
ret = reader.Read()
if ret != 1:
print("Error reading to root")
sys.exit(1)
if reader.Name() == "doc" or reader.NodeType() == 10:
ret = reader.Read()
if ret != 1:
print("Error reading to root")
sys.exit(1)
if reader.Name() != "doc" or reader.NodeType() != 1:
print("test_normal: Error reading the root element")
sys.exit(1)
ret = reader.Read()
if ret != 1:
print("test_normal: Error reading to the entity")
sys.exit(1)
if reader.Name() != "tst" or reader.NodeType() != 5:
print("test_normal: Error reading the entity")
sys.exit(1)
ret = reader.Read()
if ret != 1:
print("test_normal: Error reading to the end of root")
sys.exit(1)
if reader.Name() != "doc" or reader.NodeType() != 15:
print("test_normal: Error reading the end of the root element")
sys.exit(1)
ret = reader.Read()
if ret != 0:
print("test_normal: Error detecting the end")
sys.exit(1)
#
# Second test, completely substitute the entities.
#
f = str_io(docstr)
input = libxml2.inputBuffer(f)
reader = input.newTextReader("test_noent")
reader.SetParserProp(libxml2.PARSER_SUBST_ENTITIES, 1)
ret = reader.Read()
if ret != 1:
print("Error reading to root")
sys.exit(1)
if reader.Name() == "doc" or reader.NodeType() == 10:
ret = reader.Read()
if ret != 1:
print("Error reading to root")
sys.exit(1)
if reader.Name() != "doc" or reader.NodeType() != 1:
print("test_noent: Error reading the root element")
sys.exit(1)
ret = reader.Read()
if ret != 1:
print("test_noent: Error reading to the entity content")
sys.exit(1)
if reader.Name() != "p" or reader.NodeType() != 1:
print("test_noent: Error reading the p element from entity")
sys.exit(1)
ret = reader.Read()
if ret != 1:
print("test_noent: Error reading to the text node")
sys.exit(1)
if reader.NodeType() != 3 or reader.Value() != "test":
print("test_noent: Error reading the text node")
sys.exit(1)
ret = reader.Read()
if ret != 1:
print("test_noent: Error reading to the end of p element")
sys.exit(1)
if reader.Name() != "p" or reader.NodeType() != 15:
print("test_noent: Error reading the end of the p element")
sys.exit(1)
ret = reader.Read()
if ret != 1:
print("test_noent: Error reading to the end of root")
sys.exit(1)
if reader.Name() != "doc" or reader.NodeType() != 15:
print("test_noent: Error reading the end of the root element")
sys.exit(1)
ret = reader.Read()
if ret != 0:
print("test_noent: Error detecting the end")
sys.exit(1)
#
# third test, crazy stuff about empty element in external parsed entities
#
s = """<!DOCTYPE struct [
<!ENTITY simplestruct2.ent SYSTEM "simplestruct2.ent">
]>
<struct>&simplestruct2.ent;</struct>
"""
expect="""10 struct 0 0
1 struct 0 0
1 descr 1 1
15 struct 0 0
"""
res=""
simplestruct2_ent="""<descr/>"""
def myResolver(URL, ID, ctxt):
if URL == "simplestruct2.ent":
return(str_io(simplestruct2_ent))
return None
libxml2.setEntityLoader(myResolver)
input = libxml2.inputBuffer(str_io(s))
reader = input.newTextReader("test3")
reader.SetParserProp(libxml2.PARSER_SUBST_ENTITIES,1)
while reader.Read() == 1:
res = res + "%s %s %d %d\n" % (reader.NodeType(),reader.Name(),
reader.Depth(),reader.IsEmptyElement())
if res != expect:
print("test3 failed: unexpected output")
print(res)
sys.exit(1)
#
# cleanup
#
del f
del input
del reader
# Memory debug specific
libxml2.cleanupParser()
if libxml2.debugMemory(1) == 0:
print("OK")
else:
print("Memory leak %d bytes" % (libxml2.debugMemory(1)))
libxml2.dumpMemory()
| gpl-3.0 |
onitake/ansible | lib/ansible/modules/network/f5/bigip_gtm_monitor_tcp.py | 4 | 24848 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2017, F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'certified'}
DOCUMENTATION = r'''
---
module: bigip_gtm_monitor_tcp
short_description: Manages F5 BIG-IP GTM tcp monitors
description:
- Manages F5 BIG-IP GTM tcp monitors.
version_added: 2.6
options:
name:
description:
- Monitor name.
required: True
parent:
description:
- The parent template of this monitor template. Once this value has
been set, it cannot be changed. By default, this value is the C(tcp)
parent on the C(Common) partition.
default: /Common/tcp
send:
description:
- The send string for the monitor call.
receive:
description:
- The receive string for the monitor call.
ip:
description:
- IP address part of the IP/port definition. If this parameter is not
provided when creating a new monitor, then the default value will be
'*'.
- If this value is an IP address, then a C(port) number must be specified.
port:
description:
- Port address part of the IP/port definition. If this parameter is not
provided when creating a new monitor, then the default value will be
'*'. Note that if specifying an IP address, a value between 1 and 65535
must be specified
interval:
description:
- The interval specifying how frequently the monitor instance of this
template will run.
- If this parameter is not provided when creating a new monitor, then the
default value will be 30.
- This value B(must) be less than the C(timeout) value.
timeout:
description:
- The number of seconds in which the node or service must respond to
the monitor request. If the target responds within the set time
period, it is considered up. If the target does not respond within
the set time period, it is considered down. You can change this
number to any number you want, however, it should be 3 times the
interval number of seconds plus 1 second.
- If this parameter is not provided when creating a new monitor, then the
default value will be 120.
partition:
description:
- Device partition to manage resources on.
default: Common
state:
description:
- When C(present), ensures that the monitor exists.
- When C(absent), ensures the monitor is removed.
default: present
choices:
- present
- absent
probe_timeout:
description:
- Specifies the number of seconds after which the system times out the probe request
to the system.
- When creating a new monitor, if this parameter is not provided, then the default
value will be C(5).
ignore_down_response:
description:
- Specifies that the monitor allows more than one probe attempt per interval.
- When C(yes), specifies that the monitor ignores down responses for the duration of
the monitor timeout. Once the monitor timeout is reached without the system receiving
an up response, the system marks the object down.
- When C(no), specifies that the monitor immediately marks an object down when it
receives a down response.
- When creating a new monitor, if this parameter is not provided, then the default
value will be C(no).
type: bool
transparent:
description:
- Specifies whether the monitor operates in transparent mode.
- A monitor in transparent mode directs traffic through the associated pool members
or nodes (usually a router or firewall) to the aliased destination (that is, it
probes the C(ip)-C(port) combination specified in the monitor).
- If the monitor cannot successfully reach the aliased destination, the pool member
or node through which the monitor traffic was sent is marked down.
- When creating a new monitor, if this parameter is not provided, then the default
value will be C(no).
type: bool
reverse:
description:
- Instructs the system to mark the target resource down when the test is successful.
This setting is useful, for example, if the content on your web site home page is
dynamic and changes frequently, you may want to set up a reverse ECV service check
that looks for the string Error.
- A match for this string means that the web server was down.
- To use this option, you must specify values for C(send) and C(receive).
type: bool
extends_documentation_fragment: f5
author:
- Tim Rupp (@caphrim007)
- Wojciech Wypior (@wojtek0806)
'''
EXAMPLES = r'''
- name: Create a GTM TCP monitor
bigip_gtm_monitor_tcp:
name: my_monitor
ip: 1.1.1.1
port: 80
send: my send string
receive: my receive string
password: secret
server: lb.mydomain.com
state: present
user: admin
delegate_to: localhost
- name: Remove TCP Monitor
bigip_gtm_monitor_tcp:
name: my_monitor
state: absent
server: lb.mydomain.com
user: admin
password: secret
delegate_to: localhost
- name: Add TCP monitor for all addresses, port 514
bigip_gtm_monitor_tcp:
name: my_monitor
server: lb.mydomain.com
user: admin
port: 514
password: secret
delegate_to: localhost
'''
RETURN = r'''
parent:
description: New parent template of the monitor.
returned: changed
type: string
sample: tcp
ip:
description: The new IP of IP/port definition.
returned: changed
type: string
sample: 10.12.13.14
port:
description: The new port the monitor checks the resource on.
returned: changed
type: string
sample: 8080
interval:
description: The new interval in which to run the monitor check.
returned: changed
type: int
sample: 2
timeout:
description: The new timeout in which the remote system must respond to the monitor.
returned: changed
type: int
sample: 10
ignore_down_response:
description: Whether to ignore the down response or not.
returned: changed
type: bool
sample: True
send:
description: The new send string for this monitor.
returned: changed
type: string
sample: tcp string to send
receive:
description: The new receive string for this monitor.
returned: changed
type: string
sample: tcp string to receive
probe_timeout:
description: The new timeout in which the system will timeout the monitor probe.
returned: changed
type: int
sample: 10
reverse:
description: The new value for whether the monitor operates in reverse mode.
returned: changed
type: bool
sample: False
transparent:
description: The new value for whether the monitor operates in transparent mode.
returned: changed
type: bool
sample: False
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.basic import env_fallback
try:
from library.module_utils.network.f5.bigip import F5RestClient
from library.module_utils.network.f5.common import F5ModuleError
from library.module_utils.network.f5.common import AnsibleF5Parameters
from library.module_utils.network.f5.common import cleanup_tokens
from library.module_utils.network.f5.common import fq_name
from library.module_utils.network.f5.common import f5_argument_spec
from library.module_utils.network.f5.common import transform_name
from library.module_utils.network.f5.common import exit_json
from library.module_utils.network.f5.common import fail_json
from library.module_utils.network.f5.icontrol import module_provisioned
from library.module_utils.network.f5.ipaddress import is_valid_ip
except ImportError:
from ansible.module_utils.network.f5.bigip import F5RestClient
from ansible.module_utils.network.f5.common import F5ModuleError
from ansible.module_utils.network.f5.common import AnsibleF5Parameters
from ansible.module_utils.network.f5.common import cleanup_tokens
from ansible.module_utils.network.f5.common import fq_name
from ansible.module_utils.network.f5.common import f5_argument_spec
from ansible.module_utils.network.f5.common import transform_name
from ansible.module_utils.network.f5.common import exit_json
from ansible.module_utils.network.f5.common import fail_json
from ansible.module_utils.network.f5.icontrol import module_provisioned
from ansible.module_utils.network.f5.ipaddress import is_valid_ip
class Parameters(AnsibleF5Parameters):
api_map = {
'defaultsFrom': 'parent',
'ignoreDownResponse': 'ignore_down_response',
'probeTimeout': 'probe_timeout',
'recv': 'receive',
}
api_attributes = [
'defaultsFrom',
'interval',
'timeout',
'destination',
'transparent',
'probeTimeout',
'ignoreDownResponse',
'reverse',
'send',
'recv',
]
returnables = [
'parent',
'ip',
'port',
'interval',
'timeout',
'transparent',
'probe_timeout',
'ignore_down_response',
'send',
'receive',
'reverse',
]
updatables = [
'destination',
'interval',
'timeout',
'transparent',
'probe_timeout',
'ignore_down_response',
'send',
'receive',
'reverse',
'ip',
'port',
]
class ApiParameters(Parameters):
@property
def ip(self):
ip, port = self._values['destination'].split(':')
return ip
@property
def port(self):
ip, port = self._values['destination'].split(':')
try:
return int(port)
except ValueError:
return port
@property
def ignore_down_response(self):
if self._values['ignore_down_response'] is None:
return None
if self._values['ignore_down_response'] == 'disabled':
return False
return True
@property
def transparent(self):
if self._values['transparent'] is None:
return None
if self._values['transparent'] == 'disabled':
return False
return True
@property
def reverse(self):
if self._values['reverse'] is None:
return None
if self._values['reverse'] == 'disabled':
return False
return True
class ModuleParameters(Parameters):
@property
def interval(self):
if self._values['interval'] is None:
return None
if 1 > int(self._values['interval']) > 86400:
raise F5ModuleError(
"Interval value must be between 1 and 86400"
)
return int(self._values['interval'])
@property
def timeout(self):
if self._values['timeout'] is None:
return None
return int(self._values['timeout'])
@property
def ip(self):
if self._values['ip'] is None:
return None
elif self._values['ip'] in ['*', '0.0.0.0']:
return '*'
elif is_valid_ip(self._values['ip']):
return self._values['ip']
raise F5ModuleError(
"The provided 'ip' parameter is not an IP address."
)
@property
def parent(self):
if self._values['parent'] is None:
return None
result = fq_name(self.partition, self._values['parent'])
return result
@property
def port(self):
if self._values['port'] is None:
return None
elif self._values['port'] == '*':
return '*'
return int(self._values['port'])
@property
def destination(self):
if self.ip is None and self.port is None:
return None
destination = '{0}:{1}'.format(self.ip, self.port)
return destination
@destination.setter
def destination(self, value):
ip, port = value.split(':')
self._values['ip'] = ip
self._values['port'] = port
@property
def probe_timeout(self):
if self._values['probe_timeout'] is None:
return None
return int(self._values['probe_timeout'])
@property
def type(self):
return 'tcp'
class Changes(Parameters):
def to_return(self):
result = {}
try:
for returnable in self.returnables:
result[returnable] = getattr(self, returnable)
result = self._filter_params(result)
except Exception:
pass
return result
class UsableChanges(Changes):
@property
def transparent(self):
if self._values['transparent'] is None:
return None
elif self._values['transparent'] is True:
return 'enabled'
return 'disabled'
@property
def ignore_down_response(self):
if self._values['ignore_down_response'] is None:
return None
elif self._values['ignore_down_response'] is True:
return 'enabled'
return 'disabled'
@property
def reverse(self):
if self._values['reverse'] is None:
return None
elif self._values['reverse'] is True:
return 'enabled'
return 'disabled'
class ReportableChanges(Changes):
@property
def ip(self):
ip, port = self._values['destination'].split(':')
return ip
@property
def port(self):
ip, port = self._values['destination'].split(':')
return int(port)
@property
def transparent(self):
if self._values['transparent'] == 'enabled':
return True
return False
@property
def ignore_down_response(self):
if self._values['ignore_down_response'] == 'enabled':
return True
return False
@property
def reverse(self):
if self._values['reverse'] == 'enabled':
return True
return False
class Difference(object):
def __init__(self, want, have=None):
self.want = want
self.have = have
def compare(self, param):
try:
result = getattr(self, param)
return result
except AttributeError:
return self.__default(param)
def __default(self, param):
attr1 = getattr(self.want, param)
try:
attr2 = getattr(self.have, param)
if attr1 != attr2:
return attr1
except AttributeError:
return attr1
@property
def parent(self):
if self.want.parent != self.have.parent:
raise F5ModuleError(
"The parent monitor cannot be changed"
)
@property
def destination(self):
if self.want.ip is None and self.want.port is None:
return None
if self.want.port is None:
self.want.update({'port': self.have.port})
if self.want.ip is None:
self.want.update({'ip': self.have.ip})
if self.want.port in [None, '*'] and self.want.ip != '*':
raise F5ModuleError(
"Specifying an IP address requires that a port number be specified"
)
if self.want.destination != self.have.destination:
return self.want.destination
@property
def interval(self):
if self.want.timeout is not None and self.want.interval is not None:
if self.want.interval >= self.want.timeout:
raise F5ModuleError(
"Parameter 'interval' must be less than 'timeout'."
)
elif self.want.timeout is not None:
if self.have.interval >= self.want.timeout:
raise F5ModuleError(
"Parameter 'interval' must be less than 'timeout'."
)
elif self.want.interval is not None:
if self.want.interval >= self.have.timeout:
raise F5ModuleError(
"Parameter 'interval' must be less than 'timeout'."
)
if self.want.interval != self.have.interval:
return self.want.interval
class ModuleManager(object):
def __init__(self, *args, **kwargs):
self.module = kwargs.get('module', None)
self.client = kwargs.get('client', None)
self.want = ModuleParameters(params=self.module.params)
self.have = ApiParameters()
self.changes = UsableChanges()
def _set_changed_options(self):
changed = {}
for key in Parameters.returnables:
if getattr(self.want, key) is not None:
changed[key] = getattr(self.want, key)
if changed:
self.changes = UsableChanges(params=changed)
def _update_changed_options(self):
diff = Difference(self.want, self.have)
updatables = Parameters.updatables
changed = dict()
for k in updatables:
change = diff.compare(k)
if change is None:
continue
else:
if isinstance(change, dict):
changed.update(change)
else:
changed[k] = change
if changed:
self.changes = UsableChanges(params=changed)
return True
return False
def _announce_deprecations(self, result):
warnings = result.pop('__warnings', [])
for warning in warnings:
self.client.module.deprecate(
msg=warning['msg'],
version=warning['version']
)
def _set_default_creation_values(self):
if self.want.timeout is None:
self.want.update({'timeout': 120})
if self.want.interval is None:
self.want.update({'interval': 30})
if self.want.probe_timeout is None:
self.want.update({'probe_timeout': 5})
if self.want.ip is None:
self.want.update({'ip': '*'})
if self.want.port is None:
self.want.update({'port': '*'})
if self.want.ignore_down_response is None:
self.want.update({'ignore_down_response': False})
if self.want.transparent is None:
self.want.update({'transparent': False})
def exec_module(self):
if not module_provisioned(self.client, 'gtm'):
raise F5ModuleError(
"GTM must be provisioned to use this module."
)
changed = False
result = dict()
state = self.want.state
if state == "present":
changed = self.present()
elif state == "absent":
changed = self.absent()
reportable = ReportableChanges(params=self.changes.to_return())
changes = reportable.to_return()
result.update(**changes)
result.update(dict(changed=changed))
self._announce_deprecations(result)
return result
def present(self):
if self.exists():
return self.update()
else:
return self.create()
def absent(self):
if self.exists():
return self.remove()
return False
def should_update(self):
result = self._update_changed_options()
if result:
return True
return False
def update(self):
self.have = self.read_current_from_device()
if not self.should_update():
return False
if self.module.check_mode:
return True
self.update_on_device()
return True
def remove(self):
if self.module.check_mode:
return True
self.remove_from_device()
if self.exists():
raise F5ModuleError("Failed to delete the resource.")
return True
def create(self):
self._set_default_creation_values()
self._set_changed_options()
if self.module.check_mode:
return True
self.create_on_device()
return True
def exists(self):
uri = "https://{0}:{1}/mgmt/tm/gtm/monitor/tcp/{2}".format(
self.client.provider['server'],
self.client.provider['server_port'],
transform_name(self.want.partition, self.want.name),
)
resp = self.client.api.get(uri)
try:
response = resp.json()
except ValueError:
return False
if resp.status == 404 or 'code' in response and response['code'] == 404:
return False
return True
def create_on_device(self):
params = self.changes.api_params()
params['name'] = self.want.name
params['partition'] = self.want.partition
uri = "https://{0}:{1}/mgmt/tm/gtm/monitor/tcp/".format(
self.client.provider['server'],
self.client.provider['server_port'],
)
resp = self.client.api.post(uri, json=params)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if 'code' in response and response['code'] in [400, 403]:
if 'message' in response:
raise F5ModuleError(response['message'])
else:
raise F5ModuleError(resp.content)
return response['selfLink']
def update_on_device(self):
params = self.changes.api_params()
uri = "https://{0}:{1}/mgmt/tm/gtm/monitor/tcp/{2}".format(
self.client.provider['server'],
self.client.provider['server_port'],
transform_name(self.want.partition, self.want.name),
)
resp = self.client.api.patch(uri, json=params)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if 'code' in response and response['code'] == 400:
if 'message' in response:
raise F5ModuleError(response['message'])
else:
raise F5ModuleError(resp.content)
def remove_from_device(self):
uri = "https://{0}:{1}/mgmt/tm/gtm/monitor/tcp/{2}".format(
self.client.provider['server'],
self.client.provider['server_port'],
transform_name(self.want.partition, self.want.name),
)
response = self.client.api.delete(uri)
if response.status == 200:
return True
raise F5ModuleError(response.content)
def read_current_from_device(self):
uri = "https://{0}:{1}/mgmt/tm/gtm/monitor/tcp/{2}".format(
self.client.provider['server'],
self.client.provider['server_port'],
transform_name(self.want.partition, self.want.name),
)
resp = self.client.api.get(uri)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if 'code' in response and response['code'] == 400:
if 'message' in response:
raise F5ModuleError(response['message'])
else:
raise F5ModuleError(resp.content)
return ApiParameters(params=response)
class ArgumentSpec(object):
def __init__(self):
self.supports_check_mode = True
argument_spec = dict(
name=dict(required=True),
parent=dict(default='/Common/tcp'),
send=dict(),
receive=dict(),
ip=dict(),
port=dict(),
interval=dict(type='int'),
timeout=dict(type='int'),
ignore_down_response=dict(type='bool'),
transparent=dict(type='bool'),
probe_timeout=dict(type='int'),
reverse=dict(type='bool'),
state=dict(
default='present',
choices=['present', 'absent']
),
partition=dict(
default='Common',
fallback=(env_fallback, ['F5_PARTITION'])
)
)
self.argument_spec = {}
self.argument_spec.update(f5_argument_spec)
self.argument_spec.update(argument_spec)
def main():
spec = ArgumentSpec()
module = AnsibleModule(
argument_spec=spec.argument_spec,
supports_check_mode=spec.supports_check_mode,
)
client = F5RestClient(**module.params)
try:
mm = ModuleManager(module=module, client=client)
results = mm.exec_module()
cleanup_tokens(client)
exit_json(module, results, client)
except F5ModuleError as ex:
cleanup_tokens(client)
fail_json(module, ex, client)
if __name__ == '__main__':
main()
| gpl-3.0 |
datsfosure/ansible | examples/scripts/yaml_to_ini.py | 175 | 7609 | # (c) 2012, Michael DeHaan <[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/>.
import ansible.constants as C
from ansible.inventory.host import Host
from ansible.inventory.group import Group
from ansible import errors
from ansible import utils
import os
import yaml
import sys
class InventoryParserYaml(object):
''' Host inventory parser for ansible '''
def __init__(self, filename=C.DEFAULT_HOST_LIST):
sys.stderr.write("WARNING: YAML inventory files are deprecated in 0.6 and will be removed in 0.7, to migrate" +
" download and run https://github.com/ansible/ansible/blob/devel/examples/scripts/yaml_to_ini.py\n")
fh = open(filename)
data = fh.read()
fh.close()
self._hosts = {}
self._parse(data)
def _make_host(self, hostname):
if hostname in self._hosts:
return self._hosts[hostname]
else:
host = Host(hostname)
self._hosts[hostname] = host
return host
# see file 'test/yaml_hosts' for syntax
def _parse(self, data):
# FIXME: refactor into subfunctions
all = Group('all')
ungrouped = Group('ungrouped')
all.add_child_group(ungrouped)
self.groups = dict(all=all, ungrouped=ungrouped)
grouped_hosts = []
yaml = utils.parse_yaml(data)
# first add all groups
for item in yaml:
if type(item) == dict and 'group' in item:
group = Group(item['group'])
for subresult in item.get('hosts',[]):
if type(subresult) in [ str, unicode ]:
host = self._make_host(subresult)
group.add_host(host)
grouped_hosts.append(host)
elif type(subresult) == dict:
host = self._make_host(subresult['host'])
vars = subresult.get('vars',{})
if type(vars) == list:
for subitem in vars:
for (k,v) in subitem.items():
host.set_variable(k,v)
elif type(vars) == dict:
for (k,v) in subresult.get('vars',{}).items():
host.set_variable(k,v)
else:
raise errors.AnsibleError("unexpected type for variable")
group.add_host(host)
grouped_hosts.append(host)
vars = item.get('vars',{})
if type(vars) == dict:
for (k,v) in item.get('vars',{}).items():
group.set_variable(k,v)
elif type(vars) == list:
for subitem in vars:
if type(subitem) != dict:
raise errors.AnsibleError("expected a dictionary")
for (k,v) in subitem.items():
group.set_variable(k,v)
self.groups[group.name] = group
all.add_child_group(group)
# add host definitions
for item in yaml:
if type(item) in [ str, unicode ]:
host = self._make_host(item)
if host not in grouped_hosts:
ungrouped.add_host(host)
elif type(item) == dict and 'host' in item:
host = self._make_host(item['host'])
vars = item.get('vars', {})
if type(vars)==list:
varlist, vars = vars, {}
for subitem in varlist:
vars.update(subitem)
for (k,v) in vars.items():
host.set_variable(k,v)
groups = item.get('groups', {})
if type(groups) in [ str, unicode ]:
groups = [ groups ]
if type(groups)==list:
for subitem in groups:
if subitem in self.groups:
group = self.groups[subitem]
else:
group = Group(subitem)
self.groups[group.name] = group
all.add_child_group(group)
group.add_host(host)
grouped_hosts.append(host)
if host not in grouped_hosts:
ungrouped.add_host(host)
# make sure ungrouped.hosts is the complement of grouped_hosts
ungrouped_hosts = [host for host in ungrouped.hosts if host not in grouped_hosts]
if __name__ == "__main__":
if len(sys.argv) != 2:
print "usage: yaml_to_ini.py /path/to/ansible/hosts"
sys.exit(1)
result = ""
original = sys.argv[1]
yamlp = InventoryParserYaml(filename=sys.argv[1])
dirname = os.path.dirname(original)
group_names = [ g.name for g in yamlp.groups.values() ]
for group_name in sorted(group_names):
record = yamlp.groups[group_name]
if group_name == 'all':
continue
hosts = record.hosts
result = result + "[%s]\n" % record.name
for h in hosts:
result = result + "%s\n" % h.name
result = result + "\n"
groupfiledir = os.path.join(dirname, "group_vars")
if not os.path.exists(groupfiledir):
print "* creating: %s" % groupfiledir
os.makedirs(groupfiledir)
groupfile = os.path.join(groupfiledir, group_name)
print "* writing group variables for %s into %s" % (group_name, groupfile)
groupfh = open(groupfile, 'w')
groupfh.write(yaml.dump(record.get_variables()))
groupfh.close()
for (host_name, host_record) in yamlp._hosts.iteritems():
hostfiledir = os.path.join(dirname, "host_vars")
if not os.path.exists(hostfiledir):
print "* creating: %s" % hostfiledir
os.makedirs(hostfiledir)
hostfile = os.path.join(hostfiledir, host_record.name)
print "* writing host variables for %s into %s" % (host_record.name, hostfile)
hostfh = open(hostfile, 'w')
hostfh.write(yaml.dump(host_record.get_variables()))
hostfh.close()
# also need to keep a hash of variables per each host
# and variables per each group
# and write those to disk
newfilepath = os.path.join(dirname, "hosts.new")
fdh = open(newfilepath, 'w')
fdh.write(result)
fdh.close()
print "* COMPLETE: review your new inventory file and replace your original when ready"
print "* new inventory file saved as %s" % newfilepath
print "* edit group specific variables in %s/group_vars/" % dirname
print "* edit host specific variables in %s/host_vars/" % dirname
# now need to write this to disk as (oldname).new
# and inform the user
| gpl-3.0 |
Tanmay28/coala | coalib/tests/output/JSONEncoderTest.py | 1 | 2819 | import sys
import json
import unittest
from datetime import datetime
sys.path.insert(0, ".")
from coalib.output.JSONEncoder import JSONEncoder
class TestClass1(object):
def __init__(self):
self.a = 0
class TestClass2(object):
def __init__(self):
self.a = 0
self.b = TestClass1()
class TestClass3(object):
def __init__(self):
self.a = 0
self.b = TestClass1()
@staticmethod
def __getitem__(key):
return "val"
@staticmethod
def keys():
return ["key"]
class PropertiedClass(object):
def __init__(self):
self._a = 5
@property
def prop(self):
return self._a
class JSONAbleClass(object):
@staticmethod
def __json__():
return ['dont', 'panic']
class JSONEncoderTest(unittest.TestCase):
kw = {"cls": JSONEncoder, "sort_keys": True}
def test_builtins(self):
self.assertEquals('"test"', json.dumps("test", **self.kw))
self.assertEquals('1', json.dumps(1, **self.kw))
self.assertEquals('true', json.dumps(True, **self.kw))
self.assertEquals('null', json.dumps(None, **self.kw))
def test_iter(self):
self.assertEquals('[0, 1]', json.dumps([0, 1], **self.kw))
self.assertEquals('[0, 1]', json.dumps((0, 1), **self.kw))
self.assertEquals('[0, 1]', json.dumps(range(2), **self.kw))
def test_dict(self):
self.assertEquals('{"0": 1}', json.dumps({0: 1}, **self.kw))
self.assertEquals('{"0": 1}', json.dumps({"0": 1}, **self.kw))
self.assertEquals('{"0": "1"}', json.dumps({"0": "1"}, **self.kw))
def test_time(self):
tf = datetime.today()
self.assertEquals('"' + tf.isoformat() + '"',
json.dumps(tf, **self.kw))
def test_class1(self):
tc1 = TestClass1()
self.assertEquals('{"a": 0}', json.dumps(tc1, **self.kw))
self.assertEquals('[{"a": 0}]', json.dumps([tc1], **self.kw))
self.assertEquals('{"0": {"a": 0}}', json.dumps({0: tc1}, **self.kw))
def test_class2(self):
tc2 = TestClass2()
self.assertEquals('{"a": 0, "b": {"a": 0}}',
json.dumps(tc2, **self.kw))
def test_class3(self):
tc3 = TestClass3()
self.assertEquals('{"key": "val"}',
json.dumps(tc3, **self.kw))
def test_propertied_class(self):
uut = PropertiedClass()
self.assertEqual('{"prop": 5}', json.dumps(uut, **self.kw))
def test_jsonable_class(self):
uut = JSONAbleClass()
self.assertEqual('["dont", "panic"]', json.dumps(uut, **self.kw))
def test_type_error(self):
with self.assertRaises(TypeError):
json.dumps(1j, **self.kw)
if __name__ == "__main__":
unittest.main(verbosity=2)
| agpl-3.0 |
parkbyte/electrumparkbyte | plugins/trezor/clientbase.py | 7 | 8778 | import time
from electrum.i18n import _
from electrum.util import PrintError, UserCancelled
from electrum.wallet import BIP44_Wallet
class GuiMixin(object):
# Requires: self.proto, self.device
messages = {
3: _("Confirm the transaction output on your %s device"),
4: _("Confirm internal entropy on your %s device to begin"),
5: _("Write down the seed word shown on your %s"),
6: _("Confirm on your %s that you want to wipe it clean"),
7: _("Confirm on your %s device the message to sign"),
8: _("Confirm the total amount spent and the transaction fee on your "
"%s device"),
10: _("Confirm wallet address on your %s device"),
'default': _("Check your %s device to continue"),
}
def callback_Failure(self, msg):
# BaseClient's unfortunate call() implementation forces us to
# raise exceptions on failure in order to unwind the stack.
# However, making the user acknowledge they cancelled
# gets old very quickly, so we suppress those. The NotInitialized
# one is misnamed and indicates a passphrase request was cancelled.
if msg.code in (self.types.Failure_PinCancelled,
self.types.Failure_ActionCancelled,
self.types.Failure_NotInitialized):
raise UserCancelled()
raise RuntimeError(msg.message)
def callback_ButtonRequest(self, msg):
message = self.msg
if not message:
message = self.messages.get(msg.code, self.messages['default'])
self.handler.show_message(message % self.device, self.cancel)
return self.proto.ButtonAck()
def callback_PinMatrixRequest(self, msg):
if msg.type == 2:
msg = _("Enter a new PIN for your %s:")
elif msg.type == 3:
msg = (_("Re-enter the new PIN for your %s.\n\n"
"NOTE: the positions of the numbers have changed!"))
else:
msg = _("Enter your current %s PIN:")
pin = self.handler.get_pin(msg % self.device)
if not pin:
return self.proto.Cancel()
return self.proto.PinMatrixAck(pin=pin)
def callback_PassphraseRequest(self, req):
if self.creating_wallet:
msg = _("Enter a passphrase to generate this wallet. Each time "
"you use this wallet your %s will prompt you for the "
"passphrase. If you forget the passphrase you cannot "
"access the bitcoins in the wallet.") % self.device
else:
msg = _("Enter the passphrase to unlock this wallet:")
passphrase = self.handler.get_passphrase(msg, self.creating_wallet)
if passphrase is None:
return self.proto.Cancel()
passphrase = BIP44_Wallet.normalize_passphrase(passphrase)
return self.proto.PassphraseAck(passphrase=passphrase)
def callback_WordRequest(self, msg):
self.step += 1
msg = _("Step %d/24. Enter seed word as explained on "
"your %s:") % (self.step, self.device)
word = self.handler.get_word(msg)
# Unfortunately the device can't handle self.proto.Cancel()
return self.proto.WordAck(word=word)
def callback_CharacterRequest(self, msg):
char_info = self.handler.get_char(msg)
if not char_info:
return self.proto.Cancel()
return self.proto.CharacterAck(**char_info)
class TrezorClientBase(GuiMixin, PrintError):
def __init__(self, handler, plugin, proto):
assert hasattr(self, 'tx_api') # ProtocolMixin already constructed?
self.proto = proto
self.device = plugin.device
self.handler = handler
self.tx_api = plugin
self.types = plugin.types
self.msg = None
self.creating_wallet = False
self.used()
def __str__(self):
return "%s/%s" % (self.label(), self.features.device_id)
def label(self):
'''The name given by the user to the device.'''
return self.features.label
def is_initialized(self):
'''True if initialized, False if wiped.'''
return self.features.initialized
def is_pairable(self):
return not self.features.bootloader_mode
def used(self):
self.last_operation = time.time()
def prevent_timeouts(self):
self.last_operation = float('inf')
def timeout(self, cutoff):
'''Time out the client if the last operation was before cutoff.'''
if self.last_operation < cutoff:
self.print_error("timed out")
self.clear_session()
@staticmethod
def expand_path(n):
'''Convert bip32 path to list of uint32 integers with prime flags
0/-1/1' -> [0, 0x80000001, 0x80000001]'''
# This code is similar to code in trezorlib where it unforunately
# is not declared as a staticmethod. Our n has an extra element.
PRIME_DERIVATION_FLAG = 0x80000000
path = []
for x in n.split('/')[1:]:
prime = 0
if x.endswith("'"):
x = x.replace('\'', '')
prime = PRIME_DERIVATION_FLAG
if x.startswith('-'):
prime = PRIME_DERIVATION_FLAG
path.append(abs(int(x)) | prime)
return path
def cancel(self):
'''Provided here as in keepkeylib but not trezorlib.'''
self.transport.write(self.proto.Cancel())
def first_address(self, derivation):
return self.address_from_derivation(derivation)
def address_from_derivation(self, derivation):
return self.get_address('Bitcoin', self.expand_path(derivation))
def toggle_passphrase(self):
if self.features.passphrase_protection:
self.msg = _("Confirm on your %s device to disable passphrases")
else:
self.msg = _("Confirm on your %s device to enable passphrases")
enabled = not self.features.passphrase_protection
self.apply_settings(use_passphrase=enabled)
def change_label(self, label):
self.msg = _("Confirm the new label on your %s device")
self.apply_settings(label=label)
def change_homescreen(self, homescreen):
self.msg = _("Confirm on your %s device to change your home screen")
self.apply_settings(homescreen=homescreen)
def set_pin(self, remove):
if remove:
self.msg = _("Confirm on your %s device to disable PIN protection")
elif self.features.pin_protection:
self.msg = _("Confirm on your %s device to change your PIN")
else:
self.msg = _("Confirm on your %s device to set a PIN")
self.change_pin(remove)
def clear_session(self):
'''Clear the session to force pin (and passphrase if enabled)
re-entry. Does not leak exceptions.'''
self.print_error("clear session:", self)
self.prevent_timeouts()
try:
super(TrezorClientBase, self).clear_session()
except BaseException as e:
# If the device was removed it has the same effect...
self.print_error("clear_session: ignoring error", str(e))
pass
def get_public_node(self, address_n, creating):
self.creating_wallet = creating
return super(TrezorClientBase, self).get_public_node(address_n)
def close(self):
'''Called when Our wallet was closed or the device removed.'''
self.print_error("closing client")
self.clear_session()
# Release the device
self.transport.close()
def firmware_version(self):
f = self.features
return (f.major_version, f.minor_version, f.patch_version)
def atleast_version(self, major, minor=0, patch=0):
return cmp(self.firmware_version(), (major, minor, patch))
@staticmethod
def wrapper(func):
'''Wrap methods to clear any message box they opened.'''
def wrapped(self, *args, **kwargs):
try:
self.prevent_timeouts()
return func(self, *args, **kwargs)
finally:
self.used()
self.handler.finished()
self.creating_wallet = False
self.msg = None
return wrapped
@staticmethod
def wrap_methods(cls):
for method in ['apply_settings', 'change_pin', 'decrypt_message',
'get_address', 'get_public_node',
'load_device_by_mnemonic', 'load_device_by_xprv',
'recovery_device', 'reset_device', 'sign_message',
'sign_tx', 'wipe_device']:
setattr(cls, method, cls.wrapper(getattr(cls, method)))
| mit |
Backflipz/plugin.video.excubed | resources/lib/requests/packages/chardet/langbulgarianmodel.py | 2965 | 12784 | ######################## BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Communicator client 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 #########################
# 255: Control characters that usually does not exist in any text
# 254: Carriage/Return
# 253: symbol (punctuation) that does not belong to word
# 252: 0 - 9
# Character Mapping Table:
# this table is modified base on win1251BulgarianCharToOrderMap, so
# only number <64 is sure valid
Latin5_BulgarianCharToOrderMap = (
255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10
253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20
252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30
253, 77, 90, 99,100, 72,109,107,101, 79,185, 81,102, 76, 94, 82, # 40
110,186,108, 91, 74,119, 84, 96,111,187,115,253,253,253,253,253, # 50
253, 65, 69, 70, 66, 63, 68,112,103, 92,194,104, 95, 86, 87, 71, # 60
116,195, 85, 93, 97,113,196,197,198,199,200,253,253,253,253,253, # 70
194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209, # 80
210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225, # 90
81,226,227,228,229,230,105,231,232,233,234,235,236, 45,237,238, # a0
31, 32, 35, 43, 37, 44, 55, 47, 40, 59, 33, 46, 38, 36, 41, 30, # b0
39, 28, 34, 51, 48, 49, 53, 50, 54, 57, 61,239, 67,240, 60, 56, # c0
1, 18, 9, 20, 11, 3, 23, 15, 2, 26, 12, 10, 14, 6, 4, 13, # d0
7, 8, 5, 19, 29, 25, 22, 21, 27, 24, 17, 75, 52,241, 42, 16, # e0
62,242,243,244, 58,245, 98,246,247,248,249,250,251, 91,252,253, # f0
)
win1251BulgarianCharToOrderMap = (
255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10
253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20
252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30
253, 77, 90, 99,100, 72,109,107,101, 79,185, 81,102, 76, 94, 82, # 40
110,186,108, 91, 74,119, 84, 96,111,187,115,253,253,253,253,253, # 50
253, 65, 69, 70, 66, 63, 68,112,103, 92,194,104, 95, 86, 87, 71, # 60
116,195, 85, 93, 97,113,196,197,198,199,200,253,253,253,253,253, # 70
206,207,208,209,210,211,212,213,120,214,215,216,217,218,219,220, # 80
221, 78, 64, 83,121, 98,117,105,222,223,224,225,226,227,228,229, # 90
88,230,231,232,233,122, 89,106,234,235,236,237,238, 45,239,240, # a0
73, 80,118,114,241,242,243,244,245, 62, 58,246,247,248,249,250, # b0
31, 32, 35, 43, 37, 44, 55, 47, 40, 59, 33, 46, 38, 36, 41, 30, # c0
39, 28, 34, 51, 48, 49, 53, 50, 54, 57, 61,251, 67,252, 60, 56, # d0
1, 18, 9, 20, 11, 3, 23, 15, 2, 26, 12, 10, 14, 6, 4, 13, # e0
7, 8, 5, 19, 29, 25, 22, 21, 27, 24, 17, 75, 52,253, 42, 16, # f0
)
# Model Table:
# total sequences: 100%
# first 512 sequences: 96.9392%
# first 1024 sequences:3.0618%
# rest sequences: 0.2992%
# negative sequences: 0.0020%
BulgarianLangModel = (
0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,2,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,3,3,3,2,2,3,2,2,1,2,2,
3,1,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,0,3,3,3,3,3,3,3,3,3,3,0,3,0,1,
0,0,0,0,0,0,0,0,0,0,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,2,3,3,3,3,3,3,3,3,0,3,1,0,
0,1,0,0,0,0,0,0,0,0,1,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
3,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,1,3,2,3,3,3,3,3,3,3,3,0,3,0,0,
0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,2,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,1,3,2,3,3,3,3,3,3,3,3,0,3,0,0,
0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,3,3,3,3,3,3,2,3,2,2,1,3,3,3,3,2,2,2,1,1,2,0,1,0,1,0,0,
0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,1,
3,3,3,3,3,3,3,2,3,2,2,3,3,1,1,2,3,3,2,3,3,3,3,2,1,2,0,2,0,3,0,0,
0,0,0,0,0,0,0,1,0,0,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,1,
3,3,3,3,3,3,3,1,3,3,3,3,3,2,3,2,3,3,3,3,3,2,3,3,1,3,0,3,0,2,0,0,
0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,
3,3,3,3,3,3,3,3,1,3,3,2,3,3,3,1,3,3,2,3,2,2,2,0,0,2,0,2,0,2,0,0,
0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,1,
3,3,3,3,3,3,3,3,3,0,3,3,3,2,2,3,3,3,1,2,2,3,2,1,1,2,0,2,0,0,0,0,
1,0,0,0,0,0,0,0,0,0,2,0,0,1,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,
3,3,3,3,3,3,3,2,3,3,1,2,3,2,2,2,3,3,3,3,3,2,2,3,1,2,0,2,1,2,0,0,
0,0,0,0,0,0,0,0,0,0,3,0,0,1,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,1,
3,3,3,3,3,1,3,3,3,3,3,2,3,3,3,2,3,3,2,3,2,2,2,3,1,2,0,1,0,1,0,0,
0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,
3,3,3,3,3,3,3,3,3,3,3,1,1,1,2,2,1,3,1,3,2,2,3,0,0,1,0,1,0,1,0,0,
0,0,0,1,0,0,0,0,1,0,2,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,
3,3,3,3,3,2,2,3,2,2,3,1,2,1,1,1,2,3,1,3,1,2,2,0,1,1,1,1,0,1,0,0,
0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,
3,3,3,3,3,1,3,2,2,3,3,1,2,3,1,1,3,3,3,3,1,2,2,1,1,1,0,2,0,2,0,1,
0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,1,2,2,3,3,3,2,2,1,1,2,0,2,0,1,0,0,
0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,
3,0,1,2,1,3,3,2,3,3,3,3,3,2,3,2,1,0,3,1,2,1,2,1,2,3,2,1,0,1,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1,1,1,2,3,3,3,3,3,3,3,3,3,3,3,3,0,0,3,1,3,3,2,3,3,2,2,2,0,1,0,0,
0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,3,3,3,3,0,3,3,3,3,3,2,1,1,2,1,3,3,0,3,1,1,1,1,3,2,0,1,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,
3,3,2,2,2,3,3,3,3,3,3,3,3,3,3,3,1,1,3,1,3,3,2,3,2,2,2,3,0,2,0,0,
0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,2,3,3,2,2,3,2,1,1,1,1,1,3,1,3,1,1,0,0,0,1,0,0,0,1,0,0,
0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,2,3,2,0,3,2,0,3,0,2,0,0,2,1,3,1,0,0,1,0,0,0,1,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
3,3,3,3,2,1,1,1,1,2,1,1,2,1,1,1,2,2,1,2,1,1,1,0,1,1,0,1,0,1,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,
3,3,3,3,2,1,3,1,1,2,1,3,2,1,1,0,1,2,3,2,1,1,1,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,3,3,3,3,2,2,1,0,1,0,0,1,0,0,0,2,1,0,3,0,0,1,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
3,3,3,2,3,2,3,3,1,3,2,1,1,1,2,1,1,2,1,3,0,1,0,0,0,1,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,1,1,2,2,3,3,2,3,2,2,2,3,1,2,2,1,1,2,1,1,2,2,0,1,1,0,1,0,2,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,3,3,2,1,3,1,0,2,2,1,3,2,1,0,0,2,0,2,0,1,0,0,0,0,0,0,0,1,0,0,
0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,
3,3,3,3,3,3,1,2,0,2,3,1,2,3,2,0,1,3,1,2,1,1,1,0,0,1,0,0,2,2,2,3,
2,2,2,2,1,2,1,1,2,2,1,1,2,0,1,1,1,0,0,1,1,0,0,1,1,0,0,0,1,1,0,1,
3,3,3,3,3,2,1,2,2,1,2,0,2,0,1,0,1,2,1,2,1,1,0,0,0,1,0,1,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,1,
3,3,2,3,3,1,1,3,1,0,3,2,1,0,0,0,1,2,0,2,0,1,0,0,0,1,0,1,2,1,2,2,
1,1,1,1,1,1,1,2,2,2,1,1,1,1,1,1,1,0,1,2,1,1,1,0,0,0,0,0,1,1,0,0,
3,1,0,1,0,2,3,2,2,2,3,2,2,2,2,2,1,0,2,1,2,1,1,1,0,1,2,1,2,2,2,1,
1,1,2,2,2,2,1,2,1,1,0,1,2,1,2,2,2,1,1,1,0,1,1,1,1,2,0,1,0,0,0,0,
2,3,2,3,3,0,0,2,1,0,2,1,0,0,0,0,2,3,0,2,0,0,0,0,0,1,0,0,2,0,1,2,
2,1,2,1,2,2,1,1,1,2,1,1,1,0,1,2,2,1,1,1,1,1,0,1,1,1,0,0,1,2,0,0,
3,3,2,2,3,0,2,3,1,1,2,0,0,0,1,0,0,2,0,2,0,0,0,1,0,1,0,1,2,0,2,2,
1,1,1,1,2,1,0,1,2,2,2,1,1,1,1,1,1,1,0,1,1,1,0,0,0,0,0,0,1,1,0,0,
2,3,2,3,3,0,0,3,0,1,1,0,1,0,0,0,2,2,1,2,0,0,0,0,0,0,0,0,2,0,1,2,
2,2,1,1,1,1,1,2,2,2,1,0,2,0,1,0,1,0,0,1,0,1,0,0,1,0,0,0,0,1,0,0,
3,3,3,3,2,2,2,2,2,0,2,1,1,1,1,2,1,2,1,1,0,2,0,1,0,1,0,0,2,0,1,2,
1,1,1,1,1,1,1,2,2,1,1,0,2,0,1,0,2,0,0,1,1,1,0,0,2,0,0,0,1,1,0,0,
2,3,3,3,3,1,0,0,0,0,0,0,0,0,0,0,2,0,0,1,1,0,0,0,0,0,0,1,2,0,1,2,
2,2,2,1,1,2,1,1,2,2,2,1,2,0,1,1,1,1,1,1,0,1,1,1,1,0,0,1,1,1,0,0,
2,3,3,3,3,0,2,2,0,2,1,0,0,0,1,1,1,2,0,2,0,0,0,3,0,0,0,0,2,0,2,2,
1,1,1,2,1,2,1,1,2,2,2,1,2,0,1,1,1,0,1,1,1,1,0,2,1,0,0,0,1,1,0,0,
2,3,3,3,3,0,2,1,0,0,2,0,0,0,0,0,1,2,0,2,0,0,0,0,0,0,0,0,2,0,1,2,
1,1,1,2,1,1,1,1,2,2,2,0,1,0,1,1,1,0,0,1,1,1,0,0,1,0,0,0,0,1,0,0,
3,3,2,2,3,0,1,0,1,0,0,0,0,0,0,0,1,1,0,3,0,0,0,0,0,0,0,0,1,0,2,2,
1,1,1,1,1,2,1,1,2,2,1,2,2,1,0,1,1,1,1,1,0,1,0,0,1,0,0,0,1,1,0,0,
3,1,0,1,0,2,2,2,2,3,2,1,1,1,2,3,0,0,1,0,2,1,1,0,1,1,1,1,2,1,1,1,
1,2,2,1,2,1,2,2,1,1,0,1,2,1,2,2,1,1,1,0,0,1,1,1,2,1,0,1,0,0,0,0,
2,1,0,1,0,3,1,2,2,2,2,1,2,2,1,1,1,0,2,1,2,2,1,1,2,1,1,0,2,1,1,1,
1,2,2,2,2,2,2,2,1,2,0,1,1,0,2,1,1,1,1,1,0,0,1,1,1,1,0,1,0,0,0,0,
2,1,1,1,1,2,2,2,2,1,2,2,2,1,2,2,1,1,2,1,2,3,2,2,1,1,1,1,0,1,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,2,2,3,2,0,1,2,0,1,2,1,1,0,1,0,1,2,1,2,0,0,0,1,1,0,0,0,1,0,0,2,
1,1,0,0,1,1,0,1,1,1,1,0,2,0,1,1,1,0,0,1,1,0,0,0,0,1,0,0,0,1,0,0,
2,0,0,0,0,1,2,2,2,2,2,2,2,1,2,1,1,1,1,1,1,1,0,1,1,1,1,1,2,1,1,1,
1,2,2,2,2,1,1,2,1,2,1,1,1,0,2,1,2,1,1,1,0,2,1,1,1,1,0,1,0,0,0,0,
3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,
1,1,0,1,0,1,1,1,1,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,2,2,3,2,0,0,0,0,1,0,0,0,0,0,0,1,1,0,2,0,0,0,0,0,0,0,0,1,0,1,2,
1,1,1,1,1,1,0,0,2,2,2,2,2,0,1,1,0,1,1,1,1,1,0,0,1,0,0,0,1,1,0,1,
2,3,1,2,1,0,1,1,0,2,2,2,0,0,1,0,0,1,1,1,1,0,0,0,0,0,0,0,1,0,1,2,
1,1,1,1,2,1,1,1,1,1,1,1,1,0,1,1,0,1,0,1,0,1,0,0,1,0,0,0,0,1,0,0,
2,2,2,2,2,0,0,2,0,0,2,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,2,0,2,2,
1,1,1,1,1,0,0,1,2,1,1,0,1,0,1,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,
1,2,2,2,2,0,0,2,0,1,1,0,0,0,1,0,0,2,0,2,0,0,0,0,0,0,0,0,0,0,1,1,
0,0,0,1,1,1,1,1,1,1,1,1,1,0,1,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,
1,2,2,3,2,0,0,1,0,0,1,0,0,0,0,0,0,1,0,2,0,0,0,1,0,0,0,0,0,0,0,2,
1,1,0,0,1,0,0,0,1,1,0,0,1,0,1,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,
2,1,2,2,2,1,2,1,2,2,1,1,2,1,1,1,0,1,1,1,1,2,0,1,0,1,1,1,1,0,1,1,
1,1,2,1,1,1,1,1,1,0,0,1,2,1,1,1,1,1,1,0,0,1,1,1,0,0,0,0,0,0,0,0,
1,0,0,1,3,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,2,2,2,1,0,0,1,0,2,0,0,0,0,0,1,1,1,0,1,0,0,0,0,0,0,0,0,2,0,0,1,
0,2,0,1,0,0,1,1,2,0,1,0,1,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,
1,2,2,2,2,0,1,1,0,2,1,0,1,1,1,0,0,1,0,2,0,1,0,0,0,0,0,0,0,0,0,1,
0,1,0,0,1,0,0,0,1,1,0,0,1,0,0,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,
2,2,2,2,2,0,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,1,
0,1,0,1,1,1,0,0,1,1,1,0,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,
2,0,1,0,0,1,2,1,1,1,1,1,1,2,2,1,0,0,1,0,1,0,0,0,0,1,1,1,1,0,0,0,
1,1,2,1,1,1,1,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,2,1,2,1,0,0,1,0,0,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,1,
0,0,0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1,0,0,1,2,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,
0,1,1,0,1,1,1,0,0,1,0,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,
1,0,1,0,0,1,1,1,1,1,1,1,1,1,1,1,0,0,1,0,2,0,0,2,0,1,0,0,1,0,0,1,
1,1,0,0,1,1,0,1,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,
1,1,1,1,1,1,1,2,0,0,0,0,0,0,2,1,0,1,1,0,0,1,1,1,0,1,0,0,0,0,0,0,
2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,0,1,1,1,1,1,0,1,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
)
Latin5BulgarianModel = {
'charToOrderMap': Latin5_BulgarianCharToOrderMap,
'precedenceMatrix': BulgarianLangModel,
'mTypicalPositiveRatio': 0.969392,
'keepEnglishLetter': False,
'charsetName': "ISO-8859-5"
}
Win1251BulgarianModel = {
'charToOrderMap': win1251BulgarianCharToOrderMap,
'precedenceMatrix': BulgarianLangModel,
'mTypicalPositiveRatio': 0.969392,
'keepEnglishLetter': False,
'charsetName': "windows-1251"
}
# flake8: noqa
| gpl-2.0 |
fabioz/pep8 | testsuite/E26.py | 14 | 1225 | #: E261:1:5
pass # an inline comment
#: E262:1:12
x = x + 1 #Increment x
#: E262:1:12
x = x + 1 # Increment x
#: E262:1:12
x = y + 1 #: Increment x
#: E265:1:1
#Block comment
a = 1
#: E265:2:1
m = 42
#! This is important
mx = 42 - 42
#: E266:3:5 E266:6:5
def how_it_feel(r):
### This is a variable ###
a = 42
### Of course it is unused
return
#: E265:1:1 E266:2:1
##if DEBUG:
## logging.error()
#: W291:1:42
#########################################
#:
#: Okay
#!/usr/bin/env python
pass # an inline comment
x = x + 1 # Increment x
y = y + 1 #: Increment x
# Block comment
a = 1
# Block comment1
# Block comment2
aaa = 1
# example of docstring (not parsed)
def oof():
"""
#foo not parsed
"""
###########################################################################
# A SEPARATOR #
###########################################################################
# ####################################################################### #
# ########################## another separator ########################## #
# ####################################################################### #
| mit |
fhaoquan/kbengine | kbe/src/lib/python/Lib/lib2to3/fixes/fix_callable.py | 161 | 1151 | # Copyright 2007 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""Fixer for callable().
This converts callable(obj) into isinstance(obj, collections.Callable), adding a
collections import if needed."""
# Local imports
from lib2to3 import fixer_base
from lib2to3.fixer_util import Call, Name, String, Attr, touch_import
class FixCallable(fixer_base.BaseFix):
BM_compatible = True
order = "pre"
# Ignore callable(*args) or use of keywords.
# Either could be a hint that the builtin callable() is not being used.
PATTERN = """
power< 'callable'
trailer< lpar='('
( not(arglist | argument<any '=' any>) func=any
| func=arglist<(not argument<any '=' any>) any ','> )
rpar=')' >
after=any*
>
"""
def transform(self, node, results):
func = results['func']
touch_import(None, 'collections', node=node)
args = [func.clone(), String(', ')]
args.extend(Attr(Name('collections'), Name('Callable')))
return Call(Name('isinstance'), args, prefix=node.prefix)
| lgpl-3.0 |
pipsiscool/audacity | lib-src/lv2/lv2/plugins/eg02-midigate.lv2/waflib/Tools/compiler_fc.py | 287 | 1846 | #! /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,sys,imp,types
from waflib import Utils,Configure,Options,Logs,Errors
from waflib.Tools import fc
fc_compiler={'win32':['gfortran','ifort'],'darwin':['gfortran','g95','ifort'],'linux':['gfortran','g95','ifort'],'java':['gfortran','g95','ifort'],'default':['gfortran'],'aix':['gfortran']}
def __list_possible_compiler(platform):
try:
return fc_compiler[platform]
except KeyError:
return fc_compiler["default"]
def configure(conf):
try:test_for_compiler=conf.options.check_fc
except AttributeError:conf.fatal("Add options(opt): opt.load('compiler_fc')")
for compiler in test_for_compiler.split():
conf.env.stash()
conf.start_msg('Checking for %r (fortran compiler)'%compiler)
try:
conf.load(compiler)
except conf.errors.ConfigurationError ,e:
conf.env.revert()
conf.end_msg(False)
Logs.debug('compiler_fortran: %r'%e)
else:
if conf.env['FC']:
conf.end_msg(conf.env.get_flat('FC'))
conf.env.COMPILER_FORTRAN=compiler
break
conf.end_msg(False)
else:
conf.fatal('could not configure a fortran compiler!')
def options(opt):
opt.load_special_tools('fc_*.py')
build_platform=Utils.unversioned_sys_platform()
detected_platform=Options.platform
possible_compiler_list=__list_possible_compiler(detected_platform)
test_for_compiler=' '.join(possible_compiler_list)
fortran_compiler_opts=opt.add_option_group("Fortran Compiler Options")
fortran_compiler_opts.add_option('--check-fortran-compiler',default="%s"%test_for_compiler,help='On this platform (%s) the following Fortran Compiler will be checked by default: "%s"'%(detected_platform,test_for_compiler),dest="check_fc")
for compiler in test_for_compiler.split():
opt.load('%s'%compiler)
| mit |
nexgenta/apt | test/pre-upload-check.py | 2 | 5809 | #!/usr/bin/python
import sys
import os
import glob
import os.path
from subprocess import call, PIPE
import unittest
stdout = os.open("/dev/null",0) #sys.stdout
stderr = os.open("/dev/null",0) # sys.stderr
apt_args = [] # ["-o","Debug::pkgAcquire::Auth=true"]
class testAuthentication(unittest.TestCase):
"""
test if the authentication is working, the repository
of the test-data can be found here:
bzr get http://people.ubuntu.com/~mvo/bzr/apt/apt-auth-test-suit/
"""
# some class wide data
apt = "apt-get"
pkg = "libglib2.0-data"
pkgver = "2.13.6-1ubuntu1"
pkgpath = "/var/cache/apt/archives/libglib2.0-data_2.13.6-1ubuntu1_all.deb"
def setUp(self):
for f in glob.glob("testkeys/*,key"):
call(["apt-key", "add", f], stdout=stdout, stderr=stderr)
def _cleanup(self):
" make sure we get new lists and no i-m-s "
call(["rm","-f", "/var/lib/apt/lists/*"])
if os.path.exists(self.pkgpath):
os.unlink(self.pkgpath)
def _expectedRes(self, resultstr):
if resultstr == 'ok':
return 0
elif resultstr == 'broken':
return 100
def testPackages(self):
for f in glob.glob("testsources.list/sources.list*package*"):
self._cleanup()
(prefix, testtype, result) = f.split("-")
expected_res = self._expectedRes(result)
# update first
call([self.apt,"update",
"-o","Dir::Etc::sourcelist=./%s" % f]+apt_args,
stdout=stdout, stderr=stderr)
# then get the pkg
cmd = ["install", "-y", "-d", "--reinstall",
"%s=%s" % (self.pkg, self.pkgver),
"-o","Dir::state::Status=./fake-status"]
res = call([self.apt, "-o","Dir::Etc::sourcelist=./%s" % f]+cmd+apt_args,
stdout=stdout, stderr=stderr)
self.assert_(res == expected_res,
"test '%s' failed (got %s expected %s" % (f,res,expected_res))
def testGPG(self):
for f in glob.glob("testsources.list/sources.list*gpg*"):
self._cleanup()
(prefix, testtype, result) = f.split("-")
expected_res = self._expectedRes(result)
# update first
call([self.apt,"update",
"-o","Dir::Etc::sourcelist=./%s" % f]+apt_args,
stdout=stdout, stderr=stderr)
cmd = ["install", "-y", "-d", "--reinstall",
"%s=%s" % (self.pkg, self.pkgver),
"-o","Dir::state::Status=./fake-status"]
res = call([self.apt, "-o","Dir::Etc::sourcelist=./%s" % f]+
cmd+apt_args,
stdout=stdout, stderr=stderr)
self.assert_(res == expected_res,
"test '%s' failed (got %s expected %s" % (f,res,expected_res))
def testRelease(self):
for f in glob.glob("testsources.list/sources.list*release*"):
self._cleanup()
(prefix, testtype, result) = f.split("-")
expected_res = self._expectedRes(result)
cmd = ["update"]
res = call([self.apt,"-o","Dir::Etc::sourcelist=./%s" % f]+cmd+apt_args,
stdout=stdout, stderr=stderr)
self.assert_(res == expected_res,
"test '%s' failed (got %s expected %s" % (f,res,expected_res))
if expected_res == 0:
self.assert_(len(glob.glob("/var/lib/apt/lists/partial/*")) == 0,
"partial/ dir has leftover files: %s" % glob.glob("/var/lib/apt/lists/partial/*"))
class testLocalRepositories(unittest.TestCase):
" test local repository regressions "
repo_dir = "local-repo"
apt = "apt-get"
pkg = "gdebi-test4"
def setUp(self):
self.repo = os.path.abspath(os.path.join(os.getcwd(), self.repo_dir))
self.sources = os.path.join(self.repo, "sources.list")
s = open(self.sources,"w")
s.write("deb file://%s/ /\n" % self.repo)
s.close()
def testLocalRepoAuth(self):
# two times to get at least one i-m-s hit
for i in range(2):
self.assert_(os.path.exists(self.sources))
cmd = [self.apt,"update","-o", "Dir::Etc::sourcelist=%s" % self.sources]+apt_args
res = call(cmd, stdout=stdout, stderr=stderr)
self.assertEqual(res, 0, "local repo test failed")
self.assert_(os.path.exists(os.path.join(self.repo,"Packages.gz")),
"Packages.gz vanished from local repo")
def testInstallFromLocalRepo(self):
apt = [self.apt,"-o", "Dir::Etc::sourcelist=%s"% self.sources]+apt_args
cmd = apt+["update"]
res = call(cmd, stdout=stdout, stderr=stderr)
self.assertEqual(res, 0)
res = call(apt+["-y","install","--reinstall",self.pkg],
stdout=stdout, stderr=stderr)
self.assert_(res == 0,
"installing %s failed (got %s)" % (self.pkg, res))
res = call(apt+["-y","remove",self.pkg],
stdout=stdout, stderr=stderr)
self.assert_(res == 0,
"removing %s failed (got %s)" % (self.pkg, res))
def testPythonAptInLocalRepo(self):
import apt, apt_pkg
apt_pkg.Config.Set("Dir::Etc::sourcelist",self.sources)
cache = apt.Cache()
cache.update()
pkg = cache["apt"]
self.assert_(pkg.name == 'apt')
if __name__ == "__main__":
print "Runing simple testsuit on current apt-get and libapt"
if len(sys.argv) > 1 and sys.argv[1] == "-v":
stdout = sys.stdout
stderr = sys.stderr
unittest.main()
| gpl-2.0 |
openstack-infra/reviewstats | reviewstats/cmd/openapproved.py | 1 | 3204 | # Copyright (C) 2011 - Soren Hansen
# Copyright (C) 2013 - Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Identify approved and open patches, that are probably just trivial rebases.
Prints out list of approved patches that failed to merge and are currently
still open. Only show patches that are likely to be trivial rebases.
"""
import getpass
import optparse
import sys
from reviewstats import utils
def main(argv=None):
if argv is None:
argv = sys.argv
optparser = optparse.OptionParser()
optparser.add_option(
'-p', '--project', default='projects/nova.json',
help='JSON file describing the project to generate stats for')
optparser.add_option(
'-a', '--all', action='store_true',
help='Generate stats across all known projects (*.json)')
optparser.add_option(
'-u', '--user', default=getpass.getuser(), help='gerrit user')
optparser.add_option(
'-k', '--key', default=None, help='ssh key for gerrit')
optparser.add_option('-s', '--stable', action='store_true',
help='Include stable branch commits')
optparser.add_option(
'--server', default='review.opendev.org',
help='Gerrit server to connect to')
options, args = optparser.parse_args()
projects = utils.get_projects_info(options.project, options.all)
if not projects:
print("Please specify a project.")
sys.exit(1)
changes = utils.get_changes(projects, options.user, options.key,
only_open=True,
server=options.server)
approved_and_rebased = set()
for change in changes:
if 'rowCount' in change:
continue
if not options.stable and 'stable' in change['branch']:
continue
if change['status'] != 'NEW':
# Filter out WORKINPROGRESS
continue
for patch_set in change['patchSets'][:-1]:
if (utils.patch_set_approved(patch_set)
and not utils.patch_set_approved(change['patchSets'][-1])):
if has_negative_feedback(change['patchSets'][-1]):
continue
approved_and_rebased.add("%s %s" % (change['url'],
change['subject']))
for x in approved_and_rebased:
print()
print("total %d" % len(approved_and_rebased))
def has_negative_feedback(patch_set):
approvals = patch_set.get('approvals', [])
for review in approvals:
if review['type'] in ('CRVW', 'VRIF') \
and review['value'] in ('-1', '-2'):
return True
return False
| apache-2.0 |
dparlevliet/zelenka-report-storage | server-db/twisted/web/_auth/basic.py | 66 | 1635 | # -*- test-case-name: twisted.web.test.test_httpauth -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
HTTP BASIC authentication.
@see: U{http://tools.ietf.org/html/rfc1945}
@see: U{http://tools.ietf.org/html/rfc2616}
@see: U{http://tools.ietf.org/html/rfc2617}
"""
import binascii
from zope.interface import implements
from twisted.cred import credentials, error
from twisted.web.iweb import ICredentialFactory
class BasicCredentialFactory(object):
"""
Credential Factory for HTTP Basic Authentication
@type authenticationRealm: C{str}
@ivar authenticationRealm: The HTTP authentication realm which will be issued in
challenges.
"""
implements(ICredentialFactory)
scheme = 'basic'
def __init__(self, authenticationRealm):
self.authenticationRealm = authenticationRealm
def getChallenge(self, request):
"""
Return a challenge including the HTTP authentication realm with which
this factory was created.
"""
return {'realm': self.authenticationRealm}
def decode(self, response, request):
"""
Parse the base64-encoded, colon-separated username and password into a
L{credentials.UsernamePassword} instance.
"""
try:
creds = binascii.a2b_base64(response + '===')
except binascii.Error:
raise error.LoginFailed('Invalid credentials')
creds = creds.split(':', 1)
if len(creds) == 2:
return credentials.UsernamePassword(*creds)
else:
raise error.LoginFailed('Invalid credentials')
| lgpl-3.0 |
marscher/PyEMMA | pyemma/plots/__init__.py | 1 | 1704 |
# This file is part of PyEMMA.
#
# Copyright (c) 2015, 2014 Computational Molecular Biology Group, Freie Universitaet Berlin (GER)
#
# PyEMMA 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 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 Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
r"""
============================================
plots - Plotting tools (:mod:`pyemma.plots`)
============================================
.. currentmodule:: pyemma.plots
User-API
========
**Graph plots**
.. autosummary::
:toctree: generated/
plot_implied_timescales
plot_cktest
**Contour plots**
.. autosummary::
:toctree: generated/
plot_free_energy
scatter_contour
**Network plots**
.. autosummary::
:toctree: generated/
plot_markov_model
plot_flux
plot_network
Classes
========
.. autosummary::
:toctree: generated/
NetworkPlot
"""
from __future__ import absolute_import
from .timescales import plot_implied_timescales
from .plots2d import contour, scatter_contour, plot_free_energy
from .networks import plot_markov_model, plot_flux, plot_network, NetworkPlot
from .markovtests import plot_cktest
from .thermoplots import *
from .plots1d import plot_feature_histograms | lgpl-3.0 |
LogicalKnight/pywinauto | pywinauto/__init__.py | 14 | 1225 | # GUI Application automation and testing library
# Copyright (C) 2006 Mark Mc Mahon
#
# 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
"""
Python package for automating GUI manipulation on Windows
"""
__revision__ = "$Revision$"
__version__ = "0.4.2"
import findwindows
WindowAmbiguousError = findwindows.WindowAmbiguousError
WindowNotFoundError = findwindows.WindowNotFoundError
import findbestmatch
MatchError = findbestmatch.MatchError
from application import Application, WindowSpecification
| lgpl-2.1 |
craigem/MyAdventures | csvBuild.py | 1 | 1286 | # csvBuild from Adventure 6.
# import required modules
import mcpi.minecraft as minecraft
import mcpi.block as block
# connect to minecraft
mc = minecraft.Minecraft.create()
# define some constants
GAP = block.AIR.id
WALL = block.GOLD_BLOCK.id
FLOOR = block.GRASS.id
# Open the file containing maze data
FILENAME = "maze1.csv"
f = open(FILENAME, "r")
# Get the player position:
pos = mc.player.getTilePos()
# Work out coordinates for the bottom corner and avoid the player
ORIGIN_X = pos.x + 1
ORIGIN_Y = pos.y
ORIGIN_Z = pos.z + 1
# Initialise the z value
z = ORIGIN_Z
# Loop through every line in the maze file
for line in f.readlines():
# Remove pesky new lines and any other unwanted whitespace
line = line.rstrip()
# split the line every time a comma is reached
data = line.split(",")
# reset the x coordinate
x = ORIGIN_X
# draw the whole row
for cell in data:
# Differentiate between gap and wall
if cell == "0":
b = GAP
else:
b = WALL
# build the wall
mc.setBlock(x, ORIGIN_Y, z, b)
mc.setBlock(x, ORIGIN_Y + 1, z, b)
mc.setBlock(x, ORIGIN_Y - 1, z, FLOOR)
# Update x for the next cell
x = x + 1
# update z for the next row
z = z + 1
| gpl-3.0 |
Elbagoury/odoo | addons/sale_margin/__init__.py | 441 | 1042 | ##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import sale_margin
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
Elbagoury/odoo | addons/website_report/report.py | 257 | 2124 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2014-Today OpenERP SA (<http://www.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.addons.web.http import request
from openerp.osv import osv
class Report(osv.Model):
_inherit = 'report'
def translate_doc(self, cr, uid, doc_id, model, lang_field, template, values, context=None):
if request and hasattr(request, 'website'):
if request.website is not None:
v = request.website.get_template(template)
request.session['report_view_ids'].append({
'name': v.name,
'id': v.id,
'xml_id': v.xml_id,
'inherit_id': v.inherit_id.id,
'header': False,
'active': v.active,
})
return super(Report, self).translate_doc(cr, uid, doc_id, model, lang_field, template, values, context=context)
def render(self, cr, uid, ids, template, values=None, context=None):
if request and hasattr(request, 'website'):
if request.website is not None:
request.session['report_view_ids'] = []
return super(Report, self).render(cr, uid, ids, template, values=values, context=context)
| agpl-3.0 |
presidentielcoin/presidentielcoin | qa/rpc-tests/test_framework/blockstore.py | 1 | 5425 | #!/usr/bin/env python3
# Copyright (c) 2015-2016 The Presidentielcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# BlockStore: a helper class that keeps a map of blocks and implements
# helper functions for responding to getheaders and getdata,
# and for constructing a getheaders message
#
from .mininode import *
from io import BytesIO
import dbm.dumb as dbmd
class BlockStore(object):
def __init__(self, datadir):
self.blockDB = dbmd.open(datadir + "/blocks", 'c')
self.currentBlock = 0
self.headers_map = dict()
def close(self):
self.blockDB.close()
def erase(self, blockhash):
del self.blockDB[repr(blockhash)]
# lookup an entry and return the item as raw bytes
def get(self, blockhash):
value = None
try:
value = self.blockDB[repr(blockhash)]
except KeyError:
return None
return value
# lookup an entry and return it as a CBlock
def get_block(self, blockhash):
ret = None
serialized_block = self.get(blockhash)
if serialized_block is not None:
f = BytesIO(serialized_block)
ret = CBlock()
ret.deserialize(f)
ret.calc_sha256()
return ret
def get_header(self, blockhash):
try:
return self.headers_map[blockhash]
except KeyError:
return None
# Note: this pulls full blocks out of the database just to retrieve
# the headers -- perhaps we could keep a separate data structure
# to avoid this overhead.
def headers_for(self, locator, hash_stop, current_tip=None):
if current_tip is None:
current_tip = self.currentBlock
current_block_header = self.get_header(current_tip)
if current_block_header is None:
return None
response = msg_headers()
headersList = [ current_block_header ]
maxheaders = 2000
while (headersList[0].sha256 not in locator.vHave):
prevBlockHash = headersList[0].hashPrevBlock
prevBlockHeader = self.get_header(prevBlockHash)
if prevBlockHeader is not None:
headersList.insert(0, prevBlockHeader)
else:
break
headersList = headersList[:maxheaders] # truncate if we have too many
hashList = [x.sha256 for x in headersList]
index = len(headersList)
if (hash_stop in hashList):
index = hashList.index(hash_stop)+1
response.headers = headersList[:index]
return response
def add_block(self, block):
block.calc_sha256()
try:
self.blockDB[repr(block.sha256)] = bytes(block.serialize())
except TypeError as e:
print("Unexpected error: ", sys.exc_info()[0], e.args)
self.currentBlock = block.sha256
self.headers_map[block.sha256] = CBlockHeader(block)
def add_header(self, header):
self.headers_map[header.sha256] = header
# lookup the hashes in "inv", and return p2p messages for delivering
# blocks found.
def get_blocks(self, inv):
responses = []
for i in inv:
if (i.type == 2): # MSG_BLOCK
data = self.get(i.hash)
if data is not None:
# Use msg_generic to avoid re-serialization
responses.append(msg_generic(b"block", data))
return responses
def get_locator(self, current_tip=None):
if current_tip is None:
current_tip = self.currentBlock
r = []
counter = 0
step = 1
lastBlock = self.get_block(current_tip)
while lastBlock is not None:
r.append(lastBlock.hashPrevBlock)
for i in range(step):
lastBlock = self.get_block(lastBlock.hashPrevBlock)
if lastBlock is None:
break
counter += 1
if counter > 10:
step *= 2
locator = CBlockLocator()
locator.vHave = r
return locator
class TxStore(object):
def __init__(self, datadir):
self.txDB = dbmd.open(datadir + "/transactions", 'c')
def close(self):
self.txDB.close()
# lookup an entry and return the item as raw bytes
def get(self, txhash):
value = None
try:
value = self.txDB[repr(txhash)]
except KeyError:
return None
return value
def get_transaction(self, txhash):
ret = None
serialized_tx = self.get(txhash)
if serialized_tx is not None:
f = BytesIO(serialized_tx)
ret = CTransaction()
ret.deserialize(f)
ret.calc_sha256()
return ret
def add_transaction(self, tx):
tx.calc_sha256()
try:
self.txDB[repr(tx.sha256)] = bytes(tx.serialize())
except TypeError as e:
print("Unexpected error: ", sys.exc_info()[0], e.args)
def get_transactions(self, inv):
responses = []
for i in inv:
if (i.type == 1): # MSG_TX
tx = self.get(i.hash)
if tx is not None:
responses.append(msg_generic(b"tx", tx))
return responses
| mit |
jakesyl/pychess | lib/pychess/Players/PyChessFICS.py | 20 | 17313 | from __future__ import print_function
import email.Utils
from gi.repository import Gtk
import math
import pychess
import random
import signal
import subprocess
from threading import Thread
from pychess.compat import urlopen, urlencode
from pychess.Players.PyChess import PyChess
from pychess.System.prefix import addDataPrefix, isInstalled
from pychess.System.repeat import repeat_sleep
from pychess.System import GtkWorker, fident
from pychess.System.Log import log
from pychess.Utils.const import *
from pychess.Utils.lutils.LBoard import LBoard
from pychess.Utils.lutils.lmove import determineAlgebraicNotation, toLAN, parseSAN
from pychess.Utils.lutils import lsearch
from pychess.Utils.repr import reprResult_long, reprReason_long
from pychess.ic.FICSConnection import FICSMainConnection
class PyChessFICS(PyChess):
def __init__ (self, password, from_address, to_address):
PyChess.__init__(self)
self.ports = (23, 5000)
if not password:
self.username = "guest"
else: self.username = "PyChess"
self.owner = "Lobais"
self.password = password
self.from_address = "The PyChess Bot <%s>" % from_address
self.to_address = "Thomas Dybdahl Ahle <%s>" % to_address
# Possible start times
self.minutes = (1,2,3,4,5,6,7,8,9,10)
self.gains = (0,5,10,15,20)
# Possible colors. None == random
self.colors = (WHITE, BLACK, None)
# The amount of random challenges, that PyChess sends with each seek
self.challenges = 10
enableEGTB()
self.sudos = set()
self.ownerOnline = False
self.waitingForPassword = None
self.log = []
self.acceptedTimesettings = []
self.worker = None
repeat_sleep(self.sendChallenges, 60*1)
def __triangular(self, low, high, mode):
"""Triangular distribution.
Continuous distribution bounded by given lower and upper limits,
and having a given mode value in-between.
http://en.wikipedia.org/wiki/Triangular_distribution
"""
u = random.random()
c = (mode - low) / (high - low)
if u > c:
u = 1 - u
c = 1 - c
low, high = high, low
tri = low + (high - low) * (u * c) ** 0.5
if tri < mode:
return int(tri)
elif tri > mode:
return int(math.ceil(tri))
return int(round(tri))
def sendChallenges(self):
if self.connection.bm.isPlaying():
return True
statsbased = ((0.39197722779282, 3, 0),
(0.59341408108783, 5, 0),
(0.77320877377846, 1, 0),
(0.8246379941394, 10, 0),
(0.87388717406441, 2, 12),
(0.91443760169489, 15, 0),
(0.9286423058163, 4, 0),
(0.93891977227793, 2, 0),
(0.94674539138335, 20, 0),
(0.95321476842423, 2, 2),
(0.9594588808257, 5, 2),
(0.96564528079889, 3, 2),
(0.97173859621034, 7, 0),
(0.97774906636184, 3, 1),
(0.98357243654425, 5, 12),
(0.98881309737017, 5, 5),
(0.99319644938247, 6, 0),
(0.99675879556023, 3, 12),
(1, 5, 3))
#n = random.random()
#for culminativeChance, minute, gain in statsbased:
# if n < culminativeChance:
# break
culminativeChance, minute, gain = random.choice(statsbased)
#type = random.choice((TYPE_LIGHTNING, TYPE_BLITZ, TYPE_STANDARD))
#if type == TYPE_LIGHTNING:
# minute = self.__triangular(0,2+1,1)
# mingain = not minute and 1 or 0
# maxgain = int((3-minute)*3/2)
# gain = random.randint(mingain, maxgain)
#elif type == TYPE_BLITZ:
# minute = self.__triangular(0,14+1,5)
# mingain = max(int((3-minute)*3/2+1), 0)
# maxgain = int((15-minute)*3/2)
# gain = random.randint(mingain, maxgain)
#elif type == TYPE_STANDARD:
# minute = self.__triangular(0,20+1,12)
# mingain = max(int((15-minute)*3/2+1), 0)
# maxgain = int((20-minute)*3/2)
# gain = self.__triangular(mingain, maxgain, mingain)
#color = random.choice(self.colors)
self.extendlog(["Seeking %d %d" % (minute, gain)])
self.connection.glm.seek(minute, gain, True)
opps = random.sample(self.connection.players.get_online_playernames(),
self.challenges)
self.extendlog("Challenging %s" % op for op in opps)
for player in opps:
self.connection.om.challenge(player, minute, gain, True)
return True
def makeReady(self):
signal.signal(signal.SIGINT, Gtk.main_quit)
PyChess.makeReady(self)
self.connection = FICSMainConnection("freechess.org", self.ports,
self.username, self.password)
self.connection.connect("connectingMsg", self.__showConnectLog)
self.connection._connect()
self.connection.glm.connect("addPlayer", self.__onAddPlayer)
self.connection.glm.connect("removePlayer", self.__onRemovePlayer)
self.connection.cm.connect("privateMessage", self.__onTell)
self.connection.alm.connect("logOut", self.__onLogOut)
self.connection.bm.connect("playGameCreated", self.__onGameCreated)
self.connection.bm.connect("curGameEnded", self.__onGameEnded)
self.connection.bm.connect("boardUpdate", self.__onBoardUpdate)
self.connection.om.connect("onChallengeAdd", self.__onChallengeAdd)
self.connection.om.connect("onOfferAdd", self.__onOfferAdd)
self.connection.adm.connect("onAdjournmentsList", self.__onAdjournmentsList)
self.connection.em.connect("onAmbiguousMove", self.__onAmbiguousMove)
self.connection.em.connect("onIllegalMove", self.__onAmbiguousMove)
self.connection.adm.queryAdjournments()
self.connection.lvm.setVariable("autoflag", 1)
self.connection.fm.setFingerNote(1,
"PyChess is the chess engine bundled with the PyChess %s " % pychess.VERSION +
"chess client. This instance is owned by %s, but acts " % self.owner +
"quite autonomously.")
self.connection.fm.setFingerNote(2,
"PyChess is 100% Python code and is released under the terms of " +
"the GPL. The evalution function is largely equal to the one of" +
"GnuChess, but it plays quite differently.")
self.connection.fm.setFingerNote(3,
"PyChess runs on an elderly AMD Sempron(tm) Processor 3200+, 512 " +
"MB DDR2 Ram, but is built to take use of 64bit calculating when " +
"accessible, through the gpm library.")
self.connection.fm.setFingerNote(4,
"PyChess uses a small 500 KB openingbook based solely on Kasparov " +
"games. The engine doesn't have much endgame knowledge, but might " +
"in some cases access an online endgamedatabase.")
self.connection.fm.setFingerNote(5,
"PyChess will allow any pause/resume and adjourn wishes, but will " +
"deny takebacks. Draw, abort and switch offers are accepted, " +
"if they are found to be an advance. Flag is auto called, but " +
"PyChess never resigns. We don't want you to forget your basic " +
"mating skills.")
def main(self):
self.connection.run()
self.extendlog([str(self.acceptedTimesettings)])
self.phoneHome("Session ended\n"+"\n".join(self.log))
print("Session ended")
def run(self):
t = Thread(target=self.main, name=fident(self.main))
t.daemon = True
t.start()
Gdk.threads_init()
Gtk.main()
#===========================================================================
# General
#===========================================================================
def __showConnectLog (self, connection, message):
print(message)
def __onLogOut (self, autoLogoutManager):
self.connection.close()
#sys.exit()
def __onAddPlayer (self, gameListManager, player):
if player["name"] in self.sudos:
self.sudos.remove(player["name"])
if player["name"] == self.owner:
self.connection.cm.tellPlayer(self.owner, "Greetings")
self.ownerOnline = True
def __onRemovePlayer (self, gameListManager, playername):
if playername == self.owner:
self.ownerOnline = False
def __onAdjournmentsList (self, adjournManager, adjournments):
for adjournment in adjournments:
if adjournment["online"]:
adjournManager.challenge(adjournment["opponent"])
def __usage (self):
return "|| PyChess bot help file || " +\
"# help 'Displays this help file' " +\
"# sudo <password> <command> 'Lets PyChess execute the given command' "+\
"# sendlog 'Makes PyChess send you its current log'"
def __onTell (self, chatManager, name, title, isadmin, text):
if self.waitingForPassword:
if text.strip() == self.password or (not self.password and text == "none"):
self.sudos.add(name)
self.tellHome("%s gained sudo access" % name)
self.connection.client.run_command(self.waitingForPassword)
else:
chatManager.tellPlayer(name, "Wrong password")
self.tellHome("%s failed sudo access" % name)
self.waitingForPassword = None
return
args = text.split()
#if args == ["help"]:
# chatManager.tellPlayer(name, self.__usage())
if args[0] == "sudo":
command = " ".join(args[1:])
if name in self.sudos or name == self.owner:
# Notice: This can be used to make nasty loops
print(command, file=self.connection.client)
else:
print(repr(name), self.sudos)
chatManager.tellPlayer(name, "Please send me the password")
self.waitingForPassword = command
elif args == ["sendlog"]:
if self.log:
# TODO: Consider email
chatManager.tellPlayer(name, "\\n".join(self.log))
else:
chatManager.tellPlayer(name, "The log is currently empty")
else:
if self.ownerOnline:
self.tellHome("%s told me '%s'" % (name, text))
else:
def onlineanswer (message):
data = urlopen("http://www.pandorabots.com/pandora/talk?botid=8d034368fe360895",
urlencode({"message":message, "botcust2":"x"}).encode("utf-8")).read().decode('utf-8')
ss = "<b>DMPGirl:</b>"
es = "<br>"
answer = data[data.find(ss)+len(ss) : data.find(es,data.find(ss))]
chatManager.tellPlayer(name, answer)
t = Thread(target=onlineanswer,
name=fident(onlineanswer),
args=(text,))
t.daemon = True
t.start()
#chatManager.tellPlayer(name, "Sorry, your request was nonsense.\n"+\
# "Please read my help file for more info")
#===========================================================================
# Challenges and other offers
#===========================================================================
def __onChallengeAdd (self, offerManager, index, match):
#match = {"tp": type, "w": fname, "rt": rating, "color": color,
# "r": rated, "t": mins, "i": incr}
offerManager.acceptIndex(index)
def __onOfferAdd (self, offerManager, offer):
if offer.type in (PAUSE_OFFER, RESUME_OFFER, ADJOURN_OFFER):
offerManager.accept(offer)
elif offer.type in (TAKEBACK_OFFER,):
offerManager.decline(offer)
elif offer.type in (DRAW_OFFER, ABORT_OFFER, SWITCH_OFFER):
if self.__willingToDraw():
offerManager.accept(offer)
else: offerManager.decline(offer)
#===========================================================================
# Playing
#===========================================================================
def __onGameCreated (self, boardManager, ficsgame):
base = int(ficsgame.minutes)*60
inc = int(ficsgame.inc)
self.clock[:] = base, base
self.increment[:] = inc, inc
self.gameno = ficsgame.gameno
self.lastPly = -1
self.acceptedTimesettings.append((base, inc))
self.tellHome("Starting a game (%s, %s) gameno: %s" %
(ficsgame.wplayer.name, ficsgame.bplayer.name, ficsgame.gameno))
if ficsgame.bplayer.name.lower() == self.connection.getUsername().lower():
self.playingAs = BLACK
else:
self.playingAs = WHITE
self.board = LBoard(NORMALCHESS)
# Now we wait until we recieve the board.
def __go (self):
if self.worker:
self.worker.cancel()
self.worker = GtkWorker(lambda worker: PyChess._PyChess__go(self, worker))
self.worker.connect("published", lambda w, msg: self.extendlog(msg))
self.worker.connect("done", self.__onMoveCalculated)
self.worker.execute()
def __willingToDraw (self):
return self.scr <= 0 # FIXME: this misbehaves in all but the simplest use cases
def __onGameEnded (self, boardManager, ficsgame):
self.tellHome(reprResult_long[ficsgame.result] + " " + reprReason_long[ficsgame.reason])
lsearch.searching = False
if self.worker:
self.worker.cancel()
self.worker = None
def __onMoveCalculated (self, worker, sanmove):
if worker.isCancelled() or not sanmove:
return
self.board.applyMove(parseSAN(self.board,sanmove))
self.connection.bm.sendMove(sanmove)
self.extendlog(["Move sent %s" % sanmove])
def __onBoardUpdate (self, boardManager, gameno, ply, curcol, lastmove, fen, wname, bname, wms, bms):
self.extendlog(["","I got move %d %s for gameno %s" % (ply, lastmove, gameno)])
if self.gameno != gameno:
return
self.board.applyFen(fen)
self.clock[:] = wms/1000., bms/1000.
if curcol == self.playingAs:
self.__go()
def __onAmbiguousMove (self, errorManager, move):
# This is really a fix for fics, but sometimes it is necessary
if determineAlgebraicNotation(move) == SAN:
self.board.popMove()
move_ = parseSAN(self.board, move)
lanmove = toLAN(self.board, move_)
self.board.applyMove(move_)
self.connection.bm.sendMove(lanmove)
else:
self.connection.cm.tellOpponent(
"I'm sorry, I wanted to move %s, but FICS called " % move +
"it 'Ambigious'. I can't find another way to express it, " +
"so you can win")
self.connection.bm.resign()
#===========================================================================
# Utils
#===========================================================================
def extendlog(self, messages):
[log.info(m+"\n") for m in messages]
self.log.extend(messages)
del self.log[:-10]
def tellHome(self, message):
print(message)
if self.ownerOnline:
self.connection.cm.tellPlayer(self.owner, message)
def phoneHome(self, message):
SENDMAIL = '/usr/sbin/sendmail'
SUBJECT = "Besked fra botten"
p = subprocess.Popen([SENDMAIL, '-f',
email.Utils.parseaddr(self.from_address)[1],
email.Utils.parseaddr(self.to_address)[1]],
stdin=subprocess.PIPE)
print("MIME-Version: 1.0", file=p.stdin)
print("Content-Type: text/plain; charset=UTF-8", file=p.stdin)
print("Content-Disposition: inline", file=p.stdin)
print("From: %s" % self.from_address, file=p.stdin)
print("To: %s" % self.to_address, file=p.stdin)
print("Subject: %s" % SUBJECT, file=p.stdin)
print(file=p.stdin)
print(message, file=p.stdin)
print("Cheers", file=p.stdin)
p.stdin.close()
p.wait()
| gpl-3.0 |
jasonwzhy/django | django/contrib/admindocs/tests/test_fields.py | 638 | 1172 | from __future__ import unicode_literals
import unittest
from django.contrib.admindocs import views
from django.db import models
from django.db.models import fields
from django.utils.translation import ugettext as _
class CustomField(models.Field):
description = "A custom field type"
class DescriptionLackingField(models.Field):
pass
class TestFieldType(unittest.TestCase):
def setUp(self):
pass
def test_field_name(self):
self.assertRaises(
AttributeError,
views.get_readable_field_data_type, "NotAField"
)
def test_builtin_fields(self):
self.assertEqual(
views.get_readable_field_data_type(fields.BooleanField()),
_('Boolean (Either True or False)')
)
def test_custom_fields(self):
self.assertEqual(
views.get_readable_field_data_type(CustomField()),
'A custom field type'
)
self.assertEqual(
views.get_readable_field_data_type(DescriptionLackingField()),
_('Field of type: %(field_type)s') % {
'field_type': 'DescriptionLackingField'
}
)
| bsd-3-clause |
mrry/tensorflow | tensorflow/python/kernel_tests/slice_op_test.py | 18 | 10265 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Functional tests for slice op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from six.moves import xrange # pylint: disable=redefined-builtin
import tensorflow as tf
class SliceTest(tf.test.TestCase):
def testEmpty(self):
inp = np.random.rand(4, 4).astype("f")
for k in xrange(4):
with self.test_session(use_gpu=True):
a = tf.constant(inp, shape=[4, 4], dtype=tf.float32)
slice_t = a[2, k:k]
slice_val = slice_t.eval()
self.assertAllEqual(slice_val, inp[2, k:k])
def testInt32(self):
inp = np.random.rand(4, 4).astype("i")
for k in xrange(4):
with self.test_session(use_gpu=True):
a = tf.constant(inp, shape=[4, 4], dtype=tf.int32)
slice_t = a[2, k:k]
slice_val = slice_t.eval()
self.assertAllEqual(slice_val, inp[2, k:k])
def testSelectAll(self):
for _ in range(10):
with self.test_session(use_gpu=True):
inp = np.random.rand(4, 4, 4, 4).astype("f")
a = tf.constant(inp, shape=[4, 4, 4, 4],
dtype=tf.float32)
slice_explicit_t = tf.slice(a, [0, 0, 0, 0], [-1, -1, -1, -1])
slice_implicit_t = a[:, :, :, :]
self.assertAllEqual(inp, slice_explicit_t.eval())
self.assertAllEqual(inp, slice_implicit_t.eval())
self.assertEqual(inp.shape, slice_explicit_t.get_shape())
self.assertEqual(inp.shape, slice_implicit_t.get_shape())
def testSingleDimension(self):
for _ in range(10):
with self.test_session(use_gpu=True):
inp = np.random.rand(10).astype("f")
a = tf.constant(inp, shape=[10], dtype=tf.float32)
hi = np.random.randint(0, 9)
scalar_t = a[hi]
scalar_val = scalar_t.eval()
self.assertAllEqual(scalar_val, inp[hi])
if hi > 0:
lo = np.random.randint(0, hi)
else:
lo = 0
slice_t = a[lo:hi]
slice_val = slice_t.eval()
self.assertAllEqual(slice_val, inp[lo:hi])
def testScalarInput(self):
input_val = 0
with self.test_session() as sess:
# Test with constant input; shape inference fails.
with self.assertRaisesWithPredicateMatch(ValueError, "out of range"):
tf.constant(input_val)[:].get_shape()
# Test evaluating with non-constant input; kernel execution fails.
input_t = tf.placeholder(tf.int32)
slice_t = input_t[:]
with self.assertRaisesWithPredicateMatch(tf.errors.InvalidArgumentError,
"out of range"):
sess.run([slice_t], feed_dict={input_t: input_val})
def testInvalidIndex(self):
input_val = [1, 2]
with self.test_session() as sess:
# Test with constant input; shape inference fails.
with self.assertRaisesWithPredicateMatch(ValueError, "out of range"):
tf.constant(input_val)[1:, 1:].get_shape()
# Test evaluating with non-constant input; kernel execution fails.
input_t = tf.placeholder(tf.int32)
slice_t = input_t[1:, 1:]
with self.assertRaisesWithPredicateMatch(tf.errors.InvalidArgumentError,
"out of range"):
sess.run([slice_t], feed_dict={input_t: input_val})
def _testSliceMatrixDim0(self, x, begin, size):
with self.test_session(use_gpu=True):
tf_ans = tf.slice(x, [begin, 0], [size, x.shape[1]]).eval()
np_ans = x[begin:begin+size, :]
self.assertAllEqual(tf_ans, np_ans)
def testSliceMatrixDim0(self):
x = np.random.rand(8, 4).astype("f")
self._testSliceMatrixDim0(x, 1, 2)
self._testSliceMatrixDim0(x, 3, 3)
y = np.random.rand(8, 7).astype("f") # 7 * sizeof(float) is not aligned
self._testSliceMatrixDim0(y, 1, 2)
self._testSliceMatrixDim0(y, 3, 3)
def testSingleElementAll(self):
for _ in range(10):
with self.test_session(use_gpu=True):
inp = np.random.rand(4, 4).astype("f")
a = tf.constant(inp, shape=[4, 4], dtype=tf.float32)
x, y = np.random.randint(0, 3, size=2).tolist()
slice_t = a[x, 0:y]
slice_val = slice_t.eval()
self.assertAllEqual(slice_val, inp[x, 0:y])
def testSimple(self):
with self.test_session(use_gpu=True) as sess:
inp = np.random.rand(4, 4).astype("f")
a = tf.constant([float(x) for x in inp.ravel(order="C")],
shape=[4, 4], dtype=tf.float32)
slice_t = tf.slice(a, [0, 0], [2, 2])
slice2_t = a[:2, :2]
slice_val, slice2_val = sess.run([slice_t, slice2_t])
self.assertAllEqual(slice_val, inp[:2, :2])
self.assertAllEqual(slice2_val, inp[:2, :2])
self.assertEqual(slice_val.shape, slice_t.get_shape())
self.assertEqual(slice2_val.shape, slice2_t.get_shape())
def testComplex(self):
with self.test_session(use_gpu=True):
inp = np.random.rand(4, 10, 10, 4).astype("f")
a = tf.constant(inp, dtype=tf.float32)
x = np.random.randint(0, 9)
z = np.random.randint(0, 9)
if z > 0:
y = np.random.randint(0, z)
else:
y = 0
slice_t = a[:, x, y:z, :]
self.assertAllEqual(slice_t.eval(), inp[:, x, y:z, :])
def testRandom(self):
# Random dims of rank 6
input_shape = np.random.randint(0, 20, size=6)
inp = np.random.rand(*input_shape).astype("f")
with self.test_session(use_gpu=True) as sess:
a = tf.constant([float(x) for x in inp.ravel(order="C")],
shape=input_shape, dtype=tf.float32)
indices = [0 if x == 0 else np.random.randint(x) for x in input_shape]
sizes = [np.random.randint(0, input_shape[i] - indices[i] + 1)
for i in range(6)]
slice_t = tf.slice(a, indices, sizes)
slice2_t = a[indices[0]:indices[0]+sizes[0],
indices[1]:indices[1]+sizes[1],
indices[2]:indices[2]+sizes[2],
indices[3]:indices[3]+sizes[3],
indices[4]:indices[4]+sizes[4],
indices[5]:indices[5]+sizes[5]]
slice_val, slice2_val = sess.run([slice_t, slice2_t])
expected_val = inp[indices[0]:indices[0]+sizes[0],
indices[1]:indices[1]+sizes[1],
indices[2]:indices[2]+sizes[2],
indices[3]:indices[3]+sizes[3],
indices[4]:indices[4]+sizes[4],
indices[5]:indices[5]+sizes[5]]
self.assertAllEqual(slice_val, expected_val)
self.assertAllEqual(slice2_val, expected_val)
self.assertEqual(expected_val.shape, slice_t.get_shape())
self.assertEqual(expected_val.shape, slice2_t.get_shape())
def _testGradientSlice(self, input_shape, slice_begin, slice_size):
with self.test_session(use_gpu=True):
num_inputs = np.prod(input_shape)
num_grads = np.prod(slice_size)
inp = np.random.rand(num_inputs).astype("f").reshape(input_shape)
a = tf.constant([float(x) for x in inp.ravel(order="C")],
shape=input_shape, dtype=tf.float32)
slice_t = tf.slice(a, slice_begin, slice_size)
grads = np.random.rand(num_grads).astype("f").reshape(slice_size)
grad_tensor = tf.constant(grads)
grad = tf.gradients(slice_t, [a], grad_tensor)[0]
result = grad.eval()
# Create a zero tensor of the input shape ane place
# the grads into the right location to compare against TensorFlow.
np_ans = np.zeros(input_shape)
slices = []
for i in xrange(len(input_shape)):
slices.append(slice(slice_begin[i], slice_begin[i] + slice_size[i]))
np_ans[slices] = grads
self.assertAllClose(np_ans, result)
def _testGradientVariableSize(self):
with self.test_session(use_gpu=True):
inp = tf.constant([1.0, 2.0, 3.0], name="in")
out = tf.slice(inp, [1], [-1])
grad_actual = tf.gradients(out, inp)[0].eval()
self.assertAllClose([0., 1., 1.], grad_actual)
def testGradientsAll(self):
# Slice the middle square out of a 4x4 input
self._testGradientSlice([4, 4], [1, 1], [2, 2])
# Slice the upper left square out of a 4x4 input
self._testGradientSlice([4, 4], [0, 0], [2, 2])
# Slice a non-square input starting from (2,1)
self._testGradientSlice([4, 4], [2, 1], [1, 2])
# Slice a 3D tensor
self._testGradientSlice([3, 3, 3], [0, 1, 0], [2, 1, 1])
# Use -1 as a slice dimension.
self._testGradientVariableSize()
def testNotIterable(self):
# NOTE(mrry): If we register __getitem__ as an overloaded
# operator, Python will valiantly attempt to iterate over the
# Tensor from 0 to infinity. This test ensures that this
# unintended behavior is prevented.
c = tf.constant(5.0)
with self.assertRaisesWithPredicateMatch(
TypeError,
lambda e: "'Tensor' object is not iterable" in str(e)):
for _ in c:
pass
def testComputedShape(self):
# NOTE(mrry): We cannot currently handle partially-known values,
# because `tf.slice()` uses -1 to specify a wildcard size, and
# this can't be handled using the
# `tensor_util.constant_value_as_shape()` trick.
a = tf.constant([[1, 2, 3], [4, 5, 6]])
begin = tf.constant(0)
size = tf.constant(1)
b = tf.slice(a, [begin, 0], [size, 2])
self.assertEqual([1, 2], b.get_shape())
begin = tf.placeholder(tf.int32, shape=())
c = tf.slice(a, [begin, 0], [-1, 2])
self.assertEqual([None, 2], c.get_shape().as_list())
if __name__ == "__main__":
tf.test.main()
| apache-2.0 |
andmos/ansible | lib/ansible/modules/clustering/consul.py | 23 | 19949 | #!/usr/bin/python
#
# (c) 2015, Steve Gargan <[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: consul
short_description: "Add, modify & delete services within a consul cluster."
description:
- Registers services and checks for an agent with a consul cluster.
A service is some process running on the agent node that should be advertised by
consul's discovery mechanism. It may optionally supply a check definition,
a periodic service test to notify the consul cluster of service's health.
- "Checks may also be registered per node e.g. disk usage, or cpu usage and
notify the health of the entire node to the cluster.
Service level checks do not require a check name or id as these are derived
by Consul from the Service name and id respectively by appending 'service:'
Node level checks require a check_name and optionally a check_id."
- Currently, there is no complete way to retrieve the script, interval or ttl
metadata for a registered check. Without this metadata it is not possible to
tell if the data supplied with ansible represents a change to a check. As a
result this does not attempt to determine changes and will always report a
changed occurred. An api method is planned to supply this metadata so at that
stage change management will be added.
- "See http://consul.io for more details."
requirements:
- "python >= 2.6"
- python-consul
- requests
version_added: "2.0"
author: "Steve Gargan (@sgargan)"
options:
state:
description:
- register or deregister the consul service, defaults to present
required: true
choices: ['present', 'absent']
service_name:
description:
- Unique name for the service on a node, must be unique per node,
required if registering a service. May be omitted if registering
a node level check
service_id:
description:
- the ID for the service, must be unique per node, defaults to the
service name if the service name is supplied
default: service_name if supplied
host:
description:
- host of the consul agent defaults to localhost
default: localhost
port:
description:
- the port on which the consul agent is running
default: 8500
scheme:
description:
- the protocol scheme on which the consul agent is running
default: http
version_added: "2.1"
validate_certs:
description:
- whether to verify the tls certificate of the consul agent
type: bool
default: 'yes'
version_added: "2.1"
notes:
description:
- Notes to attach to check when registering it.
service_port:
description:
- the port on which the service is listening. Can optionally be supplied for
registration of a service, i.e. if service_name or service_id is set
service_address:
description:
- the address to advertise that the service will be listening on.
This value will be passed as the I(Address) parameter to Consul's
U(/v1/agent/service/register) API method, so refer to the Consul API
documentation for further details.
version_added: "2.1"
tags:
description:
- a list of tags that will be attached to the service registration.
script:
description:
- the script/command that will be run periodically to check the health
of the service. Scripts require an interval and vise versa
interval:
description:
- the interval at which the service check will be run. This is a number
with a s or m suffix to signify the units of seconds or minutes e.g
15s or 1m. If no suffix is supplied, m will be used by default e.g.
1 will be 1m. Required if the script param is specified.
check_id:
description:
- an ID for the service check, defaults to the check name, ignored if
part of a service definition.
check_name:
description:
- a name for the service check, defaults to the check id. required if
standalone, ignored if part of service definition.
ttl:
description:
- checks can be registered with a ttl instead of a script and interval
this means that the service will check in with the agent before the
ttl expires. If it doesn't the check will be considered failed.
Required if registering a check and the script an interval are missing
Similar to the interval this is a number with a s or m suffix to
signify the units of seconds or minutes e.g 15s or 1m. If no suffix
is supplied, m will be used by default e.g. 1 will be 1m
http:
description:
- checks can be registered with an http endpoint. This means that consul
will check that the http endpoint returns a successful http status.
Interval must also be provided with this option.
version_added: "2.0"
timeout:
description:
- A custom HTTP check timeout. The consul default is 10 seconds.
Similar to the interval this is a number with a s or m suffix to
signify the units of seconds or minutes, e.g. 15s or 1m.
version_added: "2.0"
token:
description:
- the token key indentifying an ACL rule set. May be required to register services.
"""
EXAMPLES = '''
- name: register nginx service with the local consul agent
consul:
service_name: nginx
service_port: 80
- name: register nginx service with curl check
consul:
service_name: nginx
service_port: 80
script: curl http://localhost
interval: 60s
- name: register nginx with an http check
consul:
service_name: nginx
service_port: 80
interval: 60s
http: http://localhost:80/status
- name: register external service nginx available at 10.1.5.23
consul:
service_name: nginx
service_port: 80
service_address: 10.1.5.23
- name: register nginx with some service tags
consul:
service_name: nginx
service_port: 80
tags:
- prod
- webservers
- name: remove nginx service
consul:
service_name: nginx
state: absent
- name: register celery worker service
consul:
service_name: celery-worker
tags:
- prod
- worker
- name: create a node level check to test disk usage
consul:
check_name: Disk usage
check_id: disk_usage
script: /opt/disk_usage.py
interval: 5m
- name: register an http check against a service that's already registered
consul:
check_name: nginx-check2
check_id: nginx-check2
service_id: nginx
interval: 60s
http: http://localhost:80/morestatus
'''
try:
import consul
from requests.exceptions import ConnectionError
class PatchedConsulAgentService(consul.Consul.Agent.Service):
def deregister(self, service_id, token=None):
params = {}
if token:
params['token'] = token
return self.agent.http.put(consul.base.CB.bool(),
'/v1/agent/service/deregister/%s' % service_id,
params=params)
python_consul_installed = True
except ImportError:
python_consul_installed = False
from ansible.module_utils.basic import AnsibleModule
def register_with_consul(module):
state = module.params.get('state')
if state == 'present':
add(module)
else:
remove(module)
def add(module):
''' adds a service or a check depending on supplied configuration'''
check = parse_check(module)
service = parse_service(module)
if not service and not check:
module.fail_json(msg='a name and port are required to register a service')
if service:
if check:
service.add_check(check)
add_service(module, service)
elif check:
add_check(module, check)
def remove(module):
''' removes a service or a check '''
service_id = module.params.get('service_id') or module.params.get('service_name')
check_id = module.params.get('check_id') or module.params.get('check_name')
if not (service_id or check_id):
module.fail_json(msg='services and checks are removed by id or name. please supply a service id/name or a check id/name')
if service_id:
remove_service(module, service_id)
else:
remove_check(module, check_id)
def add_check(module, check):
''' registers a check with the given agent. currently there is no way
retrieve the full metadata of an existing check through the consul api.
Without this we can't compare to the supplied check and so we must assume
a change. '''
if not check.name and not check.service_id:
module.fail_json(msg='a check name is required for a node level check, one not attached to a service')
consul_api = get_consul_api(module)
check.register(consul_api)
module.exit_json(changed=True,
check_id=check.check_id,
check_name=check.name,
script=check.script,
interval=check.interval,
ttl=check.ttl,
http=check.http,
timeout=check.timeout,
service_id=check.service_id)
def remove_check(module, check_id):
''' removes a check using its id '''
consul_api = get_consul_api(module)
if check_id in consul_api.agent.checks():
consul_api.agent.check.deregister(check_id)
module.exit_json(changed=True, id=check_id)
module.exit_json(changed=False, id=check_id)
def add_service(module, service):
''' registers a service with the current agent '''
result = service
changed = False
consul_api = get_consul_api(module)
existing = get_service_by_id_or_name(consul_api, service.id)
# there is no way to retrieve the details of checks so if a check is present
# in the service it must be re-registered
if service.has_checks() or not existing or not existing == service:
service.register(consul_api)
# check that it registered correctly
registered = get_service_by_id_or_name(consul_api, service.id)
if registered:
result = registered
changed = True
module.exit_json(changed=changed,
service_id=result.id,
service_name=result.name,
service_port=result.port,
checks=[check.to_dict() for check in service.checks],
tags=result.tags)
def remove_service(module, service_id):
''' deregister a service from the given agent using its service id '''
consul_api = get_consul_api(module)
service = get_service_by_id_or_name(consul_api, service_id)
if service:
consul_api.agent.service.deregister(service_id, token=module.params.get('token'))
module.exit_json(changed=True, id=service_id)
module.exit_json(changed=False, id=service_id)
def get_consul_api(module, token=None):
consulClient = consul.Consul(host=module.params.get('host'),
port=module.params.get('port'),
scheme=module.params.get('scheme'),
verify=module.params.get('validate_certs'),
token=module.params.get('token'))
consulClient.agent.service = PatchedConsulAgentService(consulClient)
return consulClient
def get_service_by_id_or_name(consul_api, service_id_or_name):
''' iterate the registered services and find one with the given id '''
for name, service in consul_api.agent.services().items():
if service['ID'] == service_id_or_name or service['Service'] == service_id_or_name:
return ConsulService(loaded=service)
def parse_check(module):
if len([p for p in (module.params.get('script'), module.params.get('ttl'), module.params.get('http')) if p]) > 1:
module.fail_json(
msg='checks are either script, http or ttl driven, supplying more than one does not make sense')
if module.params.get('check_id') or module.params.get('script') or module.params.get('ttl') or module.params.get('http'):
return ConsulCheck(
module.params.get('check_id'),
module.params.get('check_name'),
module.params.get('check_node'),
module.params.get('check_host'),
module.params.get('script'),
module.params.get('interval'),
module.params.get('ttl'),
module.params.get('notes'),
module.params.get('http'),
module.params.get('timeout'),
module.params.get('service_id'),
)
def parse_service(module):
if module.params.get('service_name'):
return ConsulService(
module.params.get('service_id'),
module.params.get('service_name'),
module.params.get('service_address'),
module.params.get('service_port'),
module.params.get('tags'),
)
elif not module.params.get('service_name'):
module.fail_json(msg="service_name is required to configure a service.")
class ConsulService():
def __init__(self, service_id=None, name=None, address=None, port=-1,
tags=None, loaded=None):
self.id = self.name = name
if service_id:
self.id = service_id
self.address = address
self.port = port
self.tags = tags
self.checks = []
if loaded:
self.id = loaded['ID']
self.name = loaded['Service']
self.port = loaded['Port']
self.tags = loaded['Tags']
def register(self, consul_api):
optional = {}
if self.port:
optional['port'] = self.port
if len(self.checks) > 0:
optional['check'] = self.checks[0].check
consul_api.agent.service.register(
self.name,
service_id=self.id,
address=self.address,
tags=self.tags,
**optional)
def add_check(self, check):
self.checks.append(check)
def checks(self):
return self.checks
def has_checks(self):
return len(self.checks) > 0
def __eq__(self, other):
return (isinstance(other, self.__class__) and
self.id == other.id and
self.name == other.name and
self.port == other.port and
self.tags == other.tags)
def __ne__(self, other):
return not self.__eq__(other)
def to_dict(self):
data = {'id': self.id, "name": self.name}
if self.port:
data['port'] = self.port
if self.tags and len(self.tags) > 0:
data['tags'] = self.tags
if len(self.checks) > 0:
data['check'] = self.checks[0].to_dict()
return data
class ConsulCheck(object):
def __init__(self, check_id, name, node=None, host='localhost',
script=None, interval=None, ttl=None, notes=None, http=None, timeout=None, service_id=None):
self.check_id = self.name = name
if check_id:
self.check_id = check_id
self.service_id = service_id
self.notes = notes
self.node = node
self.host = host
self.interval = self.validate_duration('interval', interval)
self.ttl = self.validate_duration('ttl', ttl)
self.script = script
self.http = http
self.timeout = self.validate_duration('timeout', timeout)
self.check = None
if script:
self.check = consul.Check.script(script, self.interval)
if ttl:
self.check = consul.Check.ttl(self.ttl)
if http:
if interval is None:
raise Exception('http check must specify interval')
self.check = consul.Check.http(http, self.interval, self.timeout)
def validate_duration(self, name, duration):
if duration:
duration_units = ['ns', 'us', 'ms', 's', 'm', 'h']
if not any((duration.endswith(suffix) for suffix in duration_units)):
duration = "{0}s".format(duration)
return duration
def register(self, consul_api):
consul_api.agent.check.register(self.name, check_id=self.check_id, service_id=self.service_id,
notes=self.notes,
check=self.check)
def __eq__(self, other):
return (isinstance(other, self.__class__) and
self.check_id == other.check_id and
self.service_id == other.service_id and
self.name == other.name and
self.script == other.script and
self.interval == other.interval)
def __ne__(self, other):
return not self.__eq__(other)
def to_dict(self):
data = {}
self._add(data, 'id', attr='check_id')
self._add(data, 'name', attr='check_name')
self._add(data, 'script')
self._add(data, 'node')
self._add(data, 'notes')
self._add(data, 'host')
self._add(data, 'interval')
self._add(data, 'ttl')
self._add(data, 'http')
self._add(data, 'timeout')
self._add(data, 'service_id')
return data
def _add(self, data, key, attr=None):
try:
if attr is None:
attr = key
data[key] = getattr(self, attr)
except Exception:
pass
def test_dependencies(module):
if not python_consul_installed:
module.fail_json(msg="python-consul required for this module. see https://python-consul.readthedocs.io/en/latest/#installation")
def main():
module = AnsibleModule(
argument_spec=dict(
host=dict(default='localhost'),
port=dict(default=8500, type='int'),
scheme=dict(required=False, default='http'),
validate_certs=dict(required=False, default=True, type='bool'),
check_id=dict(required=False),
check_name=dict(required=False),
check_node=dict(required=False),
check_host=dict(required=False),
notes=dict(required=False),
script=dict(required=False),
service_id=dict(required=False),
service_name=dict(required=False),
service_address=dict(required=False, type='str', default=None),
service_port=dict(required=False, type='int', default=None),
state=dict(default='present', choices=['present', 'absent']),
interval=dict(required=False, type='str'),
ttl=dict(required=False, type='str'),
http=dict(required=False, type='str'),
timeout=dict(required=False, type='str'),
tags=dict(required=False, type='list'),
token=dict(required=False, no_log=True)
),
supports_check_mode=False,
)
test_dependencies(module)
try:
register_with_consul(module)
except ConnectionError as e:
module.fail_json(msg='Could not connect to consul agent at %s:%s, error was %s' % (
module.params.get('host'), module.params.get('port'), str(e)))
except Exception as e:
module.fail_json(msg=str(e))
if __name__ == '__main__':
main()
| gpl-3.0 |
davidfraser/sqlalchemy | test/ext/test_mutable.py | 21 | 18754 | from sqlalchemy import Integer, ForeignKey, String
from sqlalchemy.types import PickleType, TypeDecorator, VARCHAR
from sqlalchemy.orm import mapper, Session, composite
from sqlalchemy.orm.mapper import Mapper
from sqlalchemy.orm.instrumentation import ClassManager
from sqlalchemy.testing.schema import Table, Column
from sqlalchemy.testing import eq_, assert_raises_message
from sqlalchemy.testing.util import picklers
from sqlalchemy.testing import fixtures
from sqlalchemy.ext.mutable import MutableComposite
from sqlalchemy.ext.mutable import MutableDict
class Foo(fixtures.BasicEntity):
pass
class SubFoo(Foo):
pass
class FooWithEq(object):
def __init__(self, **kw):
for k in kw:
setattr(self, k, kw[k])
def __hash__(self):
return hash(self.id)
def __eq__(self, other):
return self.id == other.id
class Point(MutableComposite):
def __init__(self, x, y):
self.x = x
self.y = y
def __setattr__(self, key, value):
object.__setattr__(self, key, value)
self.changed()
def __composite_values__(self):
return self.x, self.y
def __getstate__(self):
return self.x, self.y
def __setstate__(self, state):
self.x, self.y = state
def __eq__(self, other):
return isinstance(other, Point) and \
other.x == self.x and \
other.y == self.y
class MyPoint(Point):
@classmethod
def coerce(cls, key, value):
if isinstance(value, tuple):
value = Point(*value)
return value
class _MutableDictTestFixture(object):
@classmethod
def _type_fixture(cls):
return MutableDict
def teardown(self):
# clear out mapper events
Mapper.dispatch._clear()
ClassManager.dispatch._clear()
super(_MutableDictTestFixture, self).teardown()
class _MutableDictTestBase(_MutableDictTestFixture):
run_define_tables = 'each'
def setup_mappers(cls):
foo = cls.tables.foo
mapper(Foo, foo)
def test_coerce_none(self):
sess = Session()
f1 = Foo(data=None)
sess.add(f1)
sess.commit()
eq_(f1.data, None)
def test_coerce_raise(self):
assert_raises_message(
ValueError,
"Attribute 'data' does not accept objects of type",
Foo, data=set([1, 2, 3])
)
def test_in_place_mutation(self):
sess = Session()
f1 = Foo(data={'a': 'b'})
sess.add(f1)
sess.commit()
f1.data['a'] = 'c'
sess.commit()
eq_(f1.data, {'a': 'c'})
def test_clear(self):
sess = Session()
f1 = Foo(data={'a': 'b'})
sess.add(f1)
sess.commit()
f1.data.clear()
sess.commit()
eq_(f1.data, {})
def test_update(self):
sess = Session()
f1 = Foo(data={'a': 'b'})
sess.add(f1)
sess.commit()
f1.data.update({'a': 'z'})
sess.commit()
eq_(f1.data, {'a': 'z'})
def test_setdefault(self):
sess = Session()
f1 = Foo(data={'a': 'b'})
sess.add(f1)
sess.commit()
eq_(f1.data.setdefault('c', 'd'), 'd')
sess.commit()
eq_(f1.data, {'a': 'b', 'c': 'd'})
eq_(f1.data.setdefault('c', 'q'), 'd')
sess.commit()
eq_(f1.data, {'a': 'b', 'c': 'd'})
def test_replace(self):
sess = Session()
f1 = Foo(data={'a': 'b'})
sess.add(f1)
sess.flush()
f1.data = {'b': 'c'}
sess.commit()
eq_(f1.data, {'b': 'c'})
def test_replace_itself_still_ok(self):
sess = Session()
f1 = Foo(data={'a': 'b'})
sess.add(f1)
sess.flush()
f1.data = f1.data
f1.data['b'] = 'c'
sess.commit()
eq_(f1.data, {'a': 'b', 'b': 'c'})
def test_pickle_parent(self):
sess = Session()
f1 = Foo(data={'a': 'b'})
sess.add(f1)
sess.commit()
f1.data
sess.close()
for loads, dumps in picklers():
sess = Session()
f2 = loads(dumps(f1))
sess.add(f2)
f2.data['a'] = 'c'
assert f2 in sess.dirty
def test_unrelated_flush(self):
sess = Session()
f1 = Foo(data={"a": "b"}, unrelated_data="unrelated")
sess.add(f1)
sess.flush()
f1.unrelated_data = "unrelated 2"
sess.flush()
f1.data["a"] = "c"
sess.commit()
eq_(f1.data["a"], "c")
def _test_non_mutable(self):
sess = Session()
f1 = Foo(non_mutable_data={'a': 'b'})
sess.add(f1)
sess.commit()
f1.non_mutable_data['a'] = 'c'
sess.commit()
eq_(f1.non_mutable_data, {'a': 'b'})
class MutableColumnDefaultTest(_MutableDictTestFixture, fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
MutableDict = cls._type_fixture()
mutable_pickle = MutableDict.as_mutable(PickleType)
Table(
'foo', metadata,
Column(
'id', Integer, primary_key=True,
test_needs_autoincrement=True),
Column('data', mutable_pickle, default={}),
)
def setup_mappers(cls):
foo = cls.tables.foo
mapper(Foo, foo)
def test_evt_on_flush_refresh(self):
# test for #3427
sess = Session()
f1 = Foo()
sess.add(f1)
sess.flush()
assert isinstance(f1.data, self._type_fixture())
assert f1 not in sess.dirty
f1.data['foo'] = 'bar'
assert f1 in sess.dirty
class MutableWithScalarPickleTest(_MutableDictTestBase, fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
MutableDict = cls._type_fixture()
mutable_pickle = MutableDict.as_mutable(PickleType)
Table('foo', metadata,
Column('id', Integer, primary_key=True,
test_needs_autoincrement=True),
Column('skip', mutable_pickle),
Column('data', mutable_pickle),
Column('non_mutable_data', PickleType),
Column('unrelated_data', String(50))
)
def test_non_mutable(self):
self._test_non_mutable()
class MutableWithScalarJSONTest(_MutableDictTestBase, fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
import json
class JSONEncodedDict(TypeDecorator):
impl = VARCHAR(50)
def process_bind_param(self, value, dialect):
if value is not None:
value = json.dumps(value)
return value
def process_result_value(self, value, dialect):
if value is not None:
value = json.loads(value)
return value
MutableDict = cls._type_fixture()
Table('foo', metadata,
Column('id', Integer, primary_key=True,
test_needs_autoincrement=True),
Column('data', MutableDict.as_mutable(JSONEncodedDict)),
Column('non_mutable_data', JSONEncodedDict),
Column('unrelated_data', String(50))
)
def test_non_mutable(self):
self._test_non_mutable()
class MutableAssocWithAttrInheritTest(_MutableDictTestBase,
fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table('foo', metadata,
Column('id', Integer, primary_key=True,
test_needs_autoincrement=True),
Column('data', PickleType),
Column('non_mutable_data', PickleType),
Column('unrelated_data', String(50))
)
Table('subfoo', metadata,
Column('id', Integer, ForeignKey('foo.id'), primary_key=True),
)
def setup_mappers(cls):
foo = cls.tables.foo
subfoo = cls.tables.subfoo
mapper(Foo, foo)
mapper(SubFoo, subfoo, inherits=Foo)
MutableDict.associate_with_attribute(Foo.data)
def test_in_place_mutation(self):
sess = Session()
f1 = SubFoo(data={'a': 'b'})
sess.add(f1)
sess.commit()
f1.data['a'] = 'c'
sess.commit()
eq_(f1.data, {'a': 'c'})
def test_replace(self):
sess = Session()
f1 = SubFoo(data={'a': 'b'})
sess.add(f1)
sess.flush()
f1.data = {'b': 'c'}
sess.commit()
eq_(f1.data, {'b': 'c'})
class MutableAssociationScalarPickleTest(_MutableDictTestBase,
fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
MutableDict = cls._type_fixture()
MutableDict.associate_with(PickleType)
Table('foo', metadata,
Column('id', Integer, primary_key=True,
test_needs_autoincrement=True),
Column('skip', PickleType),
Column('data', PickleType),
Column('unrelated_data', String(50))
)
class MutableAssociationScalarJSONTest(_MutableDictTestBase,
fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
import json
class JSONEncodedDict(TypeDecorator):
impl = VARCHAR(50)
def process_bind_param(self, value, dialect):
if value is not None:
value = json.dumps(value)
return value
def process_result_value(self, value, dialect):
if value is not None:
value = json.loads(value)
return value
MutableDict = cls._type_fixture()
MutableDict.associate_with(JSONEncodedDict)
Table('foo', metadata,
Column('id', Integer, primary_key=True,
test_needs_autoincrement=True),
Column('data', JSONEncodedDict),
Column('unrelated_data', String(50))
)
class CustomMutableAssociationScalarJSONTest(_MutableDictTestBase,
fixtures.MappedTest):
CustomMutableDict = None
@classmethod
def _type_fixture(cls):
if not(getattr(cls, 'CustomMutableDict')):
MutableDict = super(
CustomMutableAssociationScalarJSONTest, cls)._type_fixture()
class CustomMutableDict(MutableDict):
pass
cls.CustomMutableDict = CustomMutableDict
return cls.CustomMutableDict
@classmethod
def define_tables(cls, metadata):
import json
class JSONEncodedDict(TypeDecorator):
impl = VARCHAR(50)
def process_bind_param(self, value, dialect):
if value is not None:
value = json.dumps(value)
return value
def process_result_value(self, value, dialect):
if value is not None:
value = json.loads(value)
return value
CustomMutableDict = cls._type_fixture()
CustomMutableDict.associate_with(JSONEncodedDict)
Table('foo', metadata,
Column('id', Integer, primary_key=True,
test_needs_autoincrement=True),
Column('data', JSONEncodedDict),
Column('unrelated_data', String(50))
)
def test_pickle_parent(self):
# Picklers don't know how to pickle CustomMutableDict,
# but we aren't testing that here
pass
def test_coerce(self):
sess = Session()
f1 = Foo(data={'a': 'b'})
sess.add(f1)
sess.flush()
eq_(type(f1.data), self._type_fixture())
class _CompositeTestBase(object):
@classmethod
def define_tables(cls, metadata):
Table('foo', metadata,
Column('id', Integer, primary_key=True,
test_needs_autoincrement=True),
Column('x', Integer),
Column('y', Integer),
Column('unrelated_data', String(50))
)
def setup(self):
from sqlalchemy.ext import mutable
mutable._setup_composite_listener()
super(_CompositeTestBase, self).setup()
def teardown(self):
# clear out mapper events
Mapper.dispatch._clear()
ClassManager.dispatch._clear()
super(_CompositeTestBase, self).teardown()
@classmethod
def _type_fixture(cls):
return Point
class MutableCompositeColumnDefaultTest(_CompositeTestBase,
fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
'foo', metadata,
Column('id', Integer, primary_key=True,
test_needs_autoincrement=True),
Column('x', Integer, default=5),
Column('y', Integer, default=9),
Column('unrelated_data', String(50))
)
@classmethod
def setup_mappers(cls):
foo = cls.tables.foo
cls.Point = cls._type_fixture()
mapper(Foo, foo, properties={
'data': composite(cls.Point, foo.c.x, foo.c.y)
})
def test_evt_on_flush_refresh(self):
# this still worked prior to #3427 being fixed in any case
sess = Session()
f1 = Foo(data=self.Point(None, None))
sess.add(f1)
sess.flush()
eq_(f1.data, self.Point(5, 9))
assert f1 not in sess.dirty
f1.data.x = 10
assert f1 in sess.dirty
class MutableCompositesUnpickleTest(_CompositeTestBase, fixtures.MappedTest):
@classmethod
def setup_mappers(cls):
foo = cls.tables.foo
cls.Point = cls._type_fixture()
mapper(FooWithEq, foo, properties={
'data': composite(cls.Point, foo.c.x, foo.c.y)
})
def test_unpickle_modified_eq(self):
u1 = FooWithEq(data=self.Point(3, 5))
for loads, dumps in picklers():
loads(dumps(u1))
class MutableCompositesTest(_CompositeTestBase, fixtures.MappedTest):
@classmethod
def setup_mappers(cls):
foo = cls.tables.foo
Point = cls._type_fixture()
mapper(Foo, foo, properties={
'data': composite(Point, foo.c.x, foo.c.y)
})
def test_in_place_mutation(self):
sess = Session()
d = Point(3, 4)
f1 = Foo(data=d)
sess.add(f1)
sess.commit()
f1.data.y = 5
sess.commit()
eq_(f1.data, Point(3, 5))
def test_pickle_of_parent(self):
sess = Session()
d = Point(3, 4)
f1 = Foo(data=d)
sess.add(f1)
sess.commit()
f1.data
assert 'data' in f1.__dict__
sess.close()
for loads, dumps in picklers():
sess = Session()
f2 = loads(dumps(f1))
sess.add(f2)
f2.data.y = 12
assert f2 in sess.dirty
def test_set_none(self):
sess = Session()
f1 = Foo(data=None)
sess.add(f1)
sess.commit()
eq_(f1.data, Point(None, None))
f1.data.y = 5
sess.commit()
eq_(f1.data, Point(None, 5))
def test_set_illegal(self):
f1 = Foo()
assert_raises_message(
ValueError,
"Attribute 'data' does not accept objects",
setattr, f1, 'data', 'foo'
)
def test_unrelated_flush(self):
sess = Session()
f1 = Foo(data=Point(3, 4), unrelated_data="unrelated")
sess.add(f1)
sess.flush()
f1.unrelated_data = "unrelated 2"
sess.flush()
f1.data.x = 5
sess.commit()
eq_(f1.data.x, 5)
class MutableCompositeCallableTest(_CompositeTestBase, fixtures.MappedTest):
@classmethod
def setup_mappers(cls):
foo = cls.tables.foo
Point = cls._type_fixture()
# in this case, this is not actually a MutableComposite.
# so we don't expect it to track changes
mapper(Foo, foo, properties={
'data': composite(lambda x, y: Point(x, y), foo.c.x, foo.c.y)
})
def test_basic(self):
sess = Session()
f1 = Foo(data=Point(3, 4))
sess.add(f1)
sess.flush()
f1.data.x = 5
sess.commit()
# we didn't get the change.
eq_(f1.data.x, 3)
class MutableCompositeCustomCoerceTest(_CompositeTestBase,
fixtures.MappedTest):
@classmethod
def _type_fixture(cls):
return MyPoint
@classmethod
def setup_mappers(cls):
foo = cls.tables.foo
Point = cls._type_fixture()
mapper(Foo, foo, properties={
'data': composite(Point, foo.c.x, foo.c.y)
})
def test_custom_coerce(self):
f = Foo()
f.data = (3, 4)
eq_(f.data, Point(3, 4))
def test_round_trip_ok(self):
sess = Session()
f = Foo()
f.data = (3, 4)
sess.add(f)
sess.commit()
eq_(f.data, Point(3, 4))
class MutableInheritedCompositesTest(_CompositeTestBase, fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table('foo', metadata,
Column('id', Integer, primary_key=True,
test_needs_autoincrement=True),
Column('x', Integer),
Column('y', Integer)
)
Table('subfoo', metadata,
Column('id', Integer, ForeignKey('foo.id'), primary_key=True),
)
@classmethod
def setup_mappers(cls):
foo = cls.tables.foo
subfoo = cls.tables.subfoo
Point = cls._type_fixture()
mapper(Foo, foo, properties={
'data': composite(Point, foo.c.x, foo.c.y)
})
mapper(SubFoo, subfoo, inherits=Foo)
def test_in_place_mutation_subclass(self):
sess = Session()
d = Point(3, 4)
f1 = SubFoo(data=d)
sess.add(f1)
sess.commit()
f1.data.y = 5
sess.commit()
eq_(f1.data, Point(3, 5))
def test_pickle_of_parent_subclass(self):
sess = Session()
d = Point(3, 4)
f1 = SubFoo(data=d)
sess.add(f1)
sess.commit()
f1.data
assert 'data' in f1.__dict__
sess.close()
for loads, dumps in picklers():
sess = Session()
f2 = loads(dumps(f1))
sess.add(f2)
f2.data.y = 12
assert f2 in sess.dirty
| mit |
ChristineLaMuse/mozillians | vendor-local/lib/python/celery/tests/test_worker/__init__.py | 12 | 33416 | from __future__ import absolute_import
from __future__ import with_statement
import socket
import sys
from collections import deque
from datetime import datetime, timedelta
from Queue import Empty
from kombu.transport.base import Message
from kombu.connection import BrokerConnection
from mock import Mock, patch
from nose import SkipTest
from celery import current_app
from celery.app.defaults import DEFAULTS
from celery.concurrency.base import BasePool
from celery.datastructures import AttributeDict
from celery.exceptions import SystemTerminate
from celery.task import task as task_dec
from celery.task import periodic_task as periodic_task_dec
from celery.utils import uuid
from celery.worker import WorkController
from celery.worker.buckets import FastQueue
from celery.worker.job import Request
from celery.worker.consumer import Consumer as MainConsumer
from celery.worker.consumer import QoS, RUN, PREFETCH_COUNT_MAX, CLOSE
from celery.utils.serialization import pickle
from celery.utils.timer2 import Timer
from celery.tests.utils import AppCase, Case
class PlaceHolder(object):
pass
class MyKombuConsumer(MainConsumer):
broadcast_consumer = Mock()
task_consumer = Mock()
def __init__(self, *args, **kwargs):
kwargs.setdefault("pool", BasePool(2))
super(MyKombuConsumer, self).__init__(*args, **kwargs)
def restart_heartbeat(self):
self.heart = None
class MockNode(object):
commands = []
def handle_message(self, body, message):
self.commands.append(body.pop("command", None))
class MockEventDispatcher(object):
sent = []
closed = False
flushed = False
_outbound_buffer = []
def send(self, event, *args, **kwargs):
self.sent.append(event)
def close(self):
self.closed = True
def flush(self):
self.flushed = True
class MockHeart(object):
closed = False
def stop(self):
self.closed = True
@task_dec()
def foo_task(x, y, z, **kwargs):
return x * y * z
@periodic_task_dec(run_every=60)
def foo_periodic_task():
return "foo"
def create_message(channel, **data):
data.setdefault("id", uuid())
channel.no_ack_consumers = set()
return Message(channel, body=pickle.dumps(dict(**data)),
content_type="application/x-python-serialize",
content_encoding="binary",
delivery_info={"consumer_tag": "mock"})
class test_QoS(Case):
class _QoS(QoS):
def __init__(self, value):
self.value = value
QoS.__init__(self, None, value, None)
def set(self, value):
return value
def test_qos_increment_decrement(self):
qos = self._QoS(10)
self.assertEqual(qos.increment(), 11)
self.assertEqual(qos.increment(3), 14)
self.assertEqual(qos.increment(-30), 14)
self.assertEqual(qos.decrement(7), 7)
self.assertEqual(qos.decrement(), 6)
with self.assertRaises(AssertionError):
qos.decrement(10)
def test_qos_disabled_increment_decrement(self):
qos = self._QoS(0)
self.assertEqual(qos.increment(), 0)
self.assertEqual(qos.increment(3), 0)
self.assertEqual(qos.increment(-30), 0)
self.assertEqual(qos.decrement(7), 0)
self.assertEqual(qos.decrement(), 0)
self.assertEqual(qos.decrement(10), 0)
def test_qos_thread_safe(self):
qos = self._QoS(10)
def add():
for i in xrange(1000):
qos.increment()
def sub():
for i in xrange(1000):
qos.decrement_eventually()
def threaded(funs):
from threading import Thread
threads = [Thread(target=fun) for fun in funs]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
threaded([add, add])
self.assertEqual(qos.value, 2010)
qos.value = 1000
threaded([add, sub]) # n = 2
self.assertEqual(qos.value, 1000)
def test_exceeds_short(self):
qos = QoS(Mock(), PREFETCH_COUNT_MAX - 1,
current_app.log.get_default_logger())
qos.update()
self.assertEqual(qos.value, PREFETCH_COUNT_MAX - 1)
qos.increment()
self.assertEqual(qos.value, PREFETCH_COUNT_MAX)
qos.increment()
self.assertEqual(qos.value, PREFETCH_COUNT_MAX + 1)
qos.decrement()
self.assertEqual(qos.value, PREFETCH_COUNT_MAX)
qos.decrement()
self.assertEqual(qos.value, PREFETCH_COUNT_MAX - 1)
def test_consumer_increment_decrement(self):
consumer = Mock()
qos = QoS(consumer, 10, current_app.log.get_default_logger())
qos.update()
self.assertEqual(qos.value, 10)
self.assertIn({"prefetch_count": 10}, consumer.qos.call_args)
qos.decrement()
self.assertEqual(qos.value, 9)
self.assertIn({"prefetch_count": 9}, consumer.qos.call_args)
qos.decrement_eventually()
self.assertEqual(qos.value, 8)
self.assertIn({"prefetch_count": 9}, consumer.qos.call_args)
# Does not decrement 0 value
qos.value = 0
qos.decrement()
self.assertEqual(qos.value, 0)
qos.increment()
self.assertEqual(qos.value, 0)
def test_consumer_decrement_eventually(self):
consumer = Mock()
qos = QoS(consumer, 10, current_app.log.get_default_logger())
qos.decrement_eventually()
self.assertEqual(qos.value, 9)
qos.value = 0
qos.decrement_eventually()
self.assertEqual(qos.value, 0)
def test_set(self):
consumer = Mock()
qos = QoS(consumer, 10, current_app.log.get_default_logger())
qos.set(12)
self.assertEqual(qos.prev, 12)
qos.set(qos.prev)
class test_Consumer(Case):
def setUp(self):
self.ready_queue = FastQueue()
self.eta_schedule = Timer()
self.logger = current_app.log.get_default_logger()
self.logger.setLevel(0)
def tearDown(self):
self.eta_schedule.stop()
def test_info(self):
l = MyKombuConsumer(self.ready_queue, self.eta_schedule, self.logger,
send_events=False)
l.qos = QoS(l.task_consumer, 10, l.logger)
info = l.info
self.assertEqual(info["prefetch_count"], 10)
self.assertFalse(info["broker"])
l.connection = current_app.broker_connection()
info = l.info
self.assertTrue(info["broker"])
def test_start_when_closed(self):
l = MyKombuConsumer(self.ready_queue, self.eta_schedule, self.logger,
send_events=False)
l._state = CLOSE
l.start()
def test_connection(self):
l = MyKombuConsumer(self.ready_queue, self.eta_schedule, self.logger,
send_events=False)
l.reset_connection()
self.assertIsInstance(l.connection, BrokerConnection)
l._state = RUN
l.event_dispatcher = None
l.stop_consumers(close_connection=False)
self.assertTrue(l.connection)
l._state = RUN
l.stop_consumers()
self.assertIsNone(l.connection)
self.assertIsNone(l.task_consumer)
l.reset_connection()
self.assertIsInstance(l.connection, BrokerConnection)
l.stop_consumers()
l.stop()
l.close_connection()
self.assertIsNone(l.connection)
self.assertIsNone(l.task_consumer)
def test_close_connection(self):
l = MyKombuConsumer(self.ready_queue, self.eta_schedule, self.logger,
send_events=False)
l._state = RUN
l.close_connection()
l = MyKombuConsumer(self.ready_queue, self.eta_schedule, self.logger,
send_events=False)
eventer = l.event_dispatcher = Mock()
eventer.enabled = True
heart = l.heart = MockHeart()
l._state = RUN
l.stop_consumers()
self.assertTrue(eventer.close.call_count)
self.assertTrue(heart.closed)
def test_receive_message_unknown(self):
l = MyKombuConsumer(self.ready_queue, self.eta_schedule, self.logger,
send_events=False)
backend = Mock()
m = create_message(backend, unknown={"baz": "!!!"})
l.event_dispatcher = Mock()
l.pidbox_node = MockNode()
with self.assertWarnsRegex(RuntimeWarning, r'unknown message'):
l.receive_message(m.decode(), m)
@patch("celery.utils.timer2.to_timestamp")
def test_receive_message_eta_OverflowError(self, to_timestamp):
to_timestamp.side_effect = OverflowError()
l = MyKombuConsumer(self.ready_queue, self.eta_schedule, self.logger,
send_events=False)
m = create_message(Mock(), task=foo_task.name,
args=("2, 2"),
kwargs={},
eta=datetime.now().isoformat())
l.event_dispatcher = Mock()
l.pidbox_node = MockNode()
l.update_strategies()
l.receive_message(m.decode(), m)
self.assertTrue(m.acknowledged)
self.assertTrue(to_timestamp.call_count)
def test_receive_message_InvalidTaskError(self):
logger = Mock()
l = MyKombuConsumer(self.ready_queue, self.eta_schedule, logger,
send_events=False)
m = create_message(Mock(), task=foo_task.name,
args=(1, 2), kwargs="foobarbaz", id=1)
l.update_strategies()
l.event_dispatcher = Mock()
l.pidbox_node = MockNode()
l.receive_message(m.decode(), m)
self.assertIn("Received invalid task message",
logger.error.call_args[0][0])
def test_on_decode_error(self):
logger = Mock()
l = MyKombuConsumer(self.ready_queue, self.eta_schedule, logger,
send_events=False)
class MockMessage(Mock):
content_type = "application/x-msgpack"
content_encoding = "binary"
body = "foobarbaz"
message = MockMessage()
l.on_decode_error(message, KeyError("foo"))
self.assertTrue(message.ack.call_count)
self.assertIn("Can't decode message body",
logger.critical.call_args[0][0])
def test_receieve_message(self):
l = MyKombuConsumer(self.ready_queue, self.eta_schedule, self.logger,
send_events=False)
m = create_message(Mock(), task=foo_task.name,
args=[2, 4, 8], kwargs={})
l.update_strategies()
l.event_dispatcher = Mock()
l.receive_message(m.decode(), m)
in_bucket = self.ready_queue.get_nowait()
self.assertIsInstance(in_bucket, Request)
self.assertEqual(in_bucket.task_name, foo_task.name)
self.assertEqual(in_bucket.execute(), 2 * 4 * 8)
self.assertTrue(self.eta_schedule.empty())
def test_start_connection_error(self):
class MockConsumer(MainConsumer):
iterations = 0
def consume_messages(self):
if not self.iterations:
self.iterations = 1
raise KeyError("foo")
raise SyntaxError("bar")
l = MockConsumer(self.ready_queue, self.eta_schedule, self.logger,
send_events=False, pool=BasePool())
l.connection_errors = (KeyError, )
with self.assertRaises(SyntaxError):
l.start()
l.heart.stop()
l.priority_timer.stop()
def test_start_channel_error(self):
# Regression test for AMQPChannelExceptions that can occur within the
# consumer. (i.e. 404 errors)
class MockConsumer(MainConsumer):
iterations = 0
def consume_messages(self):
if not self.iterations:
self.iterations = 1
raise KeyError("foo")
raise SyntaxError("bar")
l = MockConsumer(self.ready_queue, self.eta_schedule, self.logger,
send_events=False, pool=BasePool())
l.channel_errors = (KeyError, )
self.assertRaises(SyntaxError, l.start)
l.heart.stop()
l.priority_timer.stop()
def test_consume_messages_ignores_socket_timeout(self):
class Connection(current_app.broker_connection().__class__):
obj = None
def drain_events(self, **kwargs):
self.obj.connection = None
raise socket.timeout(10)
l = MyKombuConsumer(self.ready_queue, self.eta_schedule, self.logger,
send_events=False)
l.connection = Connection()
l.task_consumer = Mock()
l.connection.obj = l
l.qos = QoS(l.task_consumer, 10, l.logger)
l.consume_messages()
def test_consume_messages_when_socket_error(self):
class Connection(current_app.broker_connection().__class__):
obj = None
def drain_events(self, **kwargs):
self.obj.connection = None
raise socket.error("foo")
l = MyKombuConsumer(self.ready_queue, self.eta_schedule, self.logger,
send_events=False)
l._state = RUN
c = l.connection = Connection()
l.connection.obj = l
l.task_consumer = Mock()
l.qos = QoS(l.task_consumer, 10, l.logger)
with self.assertRaises(socket.error):
l.consume_messages()
l._state = CLOSE
l.connection = c
l.consume_messages()
def test_consume_messages(self):
class Connection(current_app.broker_connection().__class__):
obj = None
def drain_events(self, **kwargs):
self.obj.connection = None
l = MyKombuConsumer(self.ready_queue, self.eta_schedule, self.logger,
send_events=False)
l.connection = Connection()
l.connection.obj = l
l.task_consumer = Mock()
l.qos = QoS(l.task_consumer, 10, l.logger)
l.consume_messages()
l.consume_messages()
self.assertTrue(l.task_consumer.consume.call_count)
l.task_consumer.qos.assert_called_with(prefetch_count=10)
l.qos.decrement()
l.consume_messages()
l.task_consumer.qos.assert_called_with(prefetch_count=9)
def test_maybe_conn_error(self):
l = MyKombuConsumer(self.ready_queue, self.eta_schedule, self.logger,
send_events=False)
l.connection_errors = (KeyError, )
l.channel_errors = (SyntaxError, )
l.maybe_conn_error(Mock(side_effect=AttributeError("foo")))
l.maybe_conn_error(Mock(side_effect=KeyError("foo")))
l.maybe_conn_error(Mock(side_effect=SyntaxError("foo")))
with self.assertRaises(IndexError):
l.maybe_conn_error(Mock(side_effect=IndexError("foo")))
def test_apply_eta_task(self):
from celery.worker import state
l = MyKombuConsumer(self.ready_queue, self.eta_schedule, self.logger,
send_events=False)
l.qos = QoS(None, 10, l.logger)
task = object()
qos = l.qos.value
l.apply_eta_task(task)
self.assertIn(task, state.reserved_requests)
self.assertEqual(l.qos.value, qos - 1)
self.assertIs(self.ready_queue.get_nowait(), task)
def test_receieve_message_eta_isoformat(self):
l = MyKombuConsumer(self.ready_queue, self.eta_schedule, self.logger,
send_events=False)
m = create_message(Mock(), task=foo_task.name,
eta=datetime.now().isoformat(),
args=[2, 4, 8], kwargs={})
l.task_consumer = Mock()
l.qos = QoS(l.task_consumer, l.initial_prefetch_count, l.logger)
l.event_dispatcher = Mock()
l.enabled = False
l.update_strategies()
l.receive_message(m.decode(), m)
l.eta_schedule.stop()
items = [entry[2] for entry in self.eta_schedule.queue]
found = 0
for item in items:
if item.args[0].name == foo_task.name:
found = True
self.assertTrue(found)
self.assertTrue(l.task_consumer.qos.call_count)
l.eta_schedule.stop()
def test_on_control(self):
l = MyKombuConsumer(self.ready_queue, self.eta_schedule, self.logger,
send_events=False)
l.pidbox_node = Mock()
l.reset_pidbox_node = Mock()
l.on_control("foo", "bar")
l.pidbox_node.handle_message.assert_called_with("foo", "bar")
l.pidbox_node = Mock()
l.pidbox_node.handle_message.side_effect = KeyError("foo")
l.on_control("foo", "bar")
l.pidbox_node.handle_message.assert_called_with("foo", "bar")
l.pidbox_node = Mock()
l.pidbox_node.handle_message.side_effect = ValueError("foo")
l.on_control("foo", "bar")
l.pidbox_node.handle_message.assert_called_with("foo", "bar")
l.reset_pidbox_node.assert_called_with()
def test_revoke(self):
ready_queue = FastQueue()
l = MyKombuConsumer(ready_queue, self.eta_schedule, self.logger,
send_events=False)
backend = Mock()
id = uuid()
t = create_message(backend, task=foo_task.name, args=[2, 4, 8],
kwargs={}, id=id)
from celery.worker.state import revoked
revoked.add(id)
l.receive_message(t.decode(), t)
self.assertTrue(ready_queue.empty())
def test_receieve_message_not_registered(self):
l = MyKombuConsumer(self.ready_queue, self.eta_schedule, self.logger,
send_events=False)
backend = Mock()
m = create_message(backend, task="x.X.31x", args=[2, 4, 8], kwargs={})
l.event_dispatcher = Mock()
self.assertFalse(l.receive_message(m.decode(), m))
with self.assertRaises(Empty):
self.ready_queue.get_nowait()
self.assertTrue(self.eta_schedule.empty())
def test_receieve_message_ack_raises(self):
l = MyKombuConsumer(self.ready_queue, self.eta_schedule, self.logger,
send_events=False)
backend = Mock()
m = create_message(backend, args=[2, 4, 8], kwargs={})
l.event_dispatcher = Mock()
l.connection_errors = (socket.error, )
l.logger = Mock()
m.reject = Mock()
m.reject.side_effect = socket.error("foo")
with self.assertWarnsRegex(RuntimeWarning, r'unknown message'):
self.assertFalse(l.receive_message(m.decode(), m))
with self.assertRaises(Empty):
self.ready_queue.get_nowait()
self.assertTrue(self.eta_schedule.empty())
m.reject.assert_called_with()
self.assertTrue(l.logger.critical.call_count)
def test_receieve_message_eta(self):
l = MyKombuConsumer(self.ready_queue, self.eta_schedule, self.logger,
send_events=False)
l.event_dispatcher = Mock()
l.event_dispatcher._outbound_buffer = deque()
backend = Mock()
m = create_message(backend, task=foo_task.name,
args=[2, 4, 8], kwargs={},
eta=(datetime.now() +
timedelta(days=1)).isoformat())
l.reset_connection()
p = l.app.conf.BROKER_CONNECTION_RETRY
l.app.conf.BROKER_CONNECTION_RETRY = False
try:
l.reset_connection()
finally:
l.app.conf.BROKER_CONNECTION_RETRY = p
l.stop_consumers()
l.event_dispatcher = Mock()
l.receive_message(m.decode(), m)
l.eta_schedule.stop()
in_hold = self.eta_schedule.queue[0]
self.assertEqual(len(in_hold), 3)
eta, priority, entry = in_hold
task = entry.args[0]
self.assertIsInstance(task, Request)
self.assertEqual(task.task_name, foo_task.name)
self.assertEqual(task.execute(), 2 * 4 * 8)
with self.assertRaises(Empty):
self.ready_queue.get_nowait()
def test_reset_pidbox_node(self):
l = MyKombuConsumer(self.ready_queue, self.eta_schedule, self.logger,
send_events=False)
l.pidbox_node = Mock()
chan = l.pidbox_node.channel = Mock()
l.connection = Mock()
chan.close.side_effect = socket.error("foo")
l.connection_errors = (socket.error, )
l.reset_pidbox_node()
chan.close.assert_called_with()
def test_reset_pidbox_node_green(self):
l = MyKombuConsumer(self.ready_queue, self.eta_schedule, self.logger,
send_events=False)
l.pool = Mock()
l.pool.is_green = True
l.reset_pidbox_node()
l.pool.spawn_n.assert_called_with(l._green_pidbox_node)
def test__green_pidbox_node(self):
l = MyKombuConsumer(self.ready_queue, self.eta_schedule, self.logger,
send_events=False)
l.pidbox_node = Mock()
class BConsumer(Mock):
def __enter__(self):
self.consume()
return self
def __exit__(self, *exc_info):
self.cancel()
l.pidbox_node.listen = BConsumer()
connections = []
class Connection(object):
def __init__(self, obj):
connections.append(self)
self.obj = obj
self.default_channel = self.channel()
self.closed = False
def __enter__(self):
return self
def __exit__(self, *exc_info):
self.close()
def channel(self):
return Mock()
def drain_events(self, **kwargs):
self.obj.connection = None
self.obj._pidbox_node_shutdown.set()
def close(self):
self.closed = True
l.connection = Mock()
l._open_connection = lambda: Connection(obj=l)
l._green_pidbox_node()
l.pidbox_node.listen.assert_called_with(callback=l.on_control)
self.assertTrue(l.broadcast_consumer)
l.broadcast_consumer.consume.assert_called_with()
self.assertIsNone(l.connection)
self.assertTrue(connections[0].closed)
def test_start__consume_messages(self):
class _QoS(object):
prev = 3
value = 4
def update(self):
self.prev = self.value
class _Consumer(MyKombuConsumer):
iterations = 0
def reset_connection(self):
if self.iterations >= 1:
raise KeyError("foo")
init_callback = Mock()
l = _Consumer(self.ready_queue, self.eta_schedule, self.logger,
send_events=False, init_callback=init_callback)
l.task_consumer = Mock()
l.broadcast_consumer = Mock()
l.qos = _QoS()
l.connection = BrokerConnection()
l.iterations = 0
def raises_KeyError(limit=None):
l.iterations += 1
if l.qos.prev != l.qos.value:
l.qos.update()
if l.iterations >= 2:
raise KeyError("foo")
l.consume_messages = raises_KeyError
with self.assertRaises(KeyError):
l.start()
self.assertTrue(init_callback.call_count)
self.assertEqual(l.iterations, 1)
self.assertEqual(l.qos.prev, l.qos.value)
init_callback.reset_mock()
l = _Consumer(self.ready_queue, self.eta_schedule, self.logger,
send_events=False, init_callback=init_callback)
l.qos = _QoS()
l.task_consumer = Mock()
l.broadcast_consumer = Mock()
l.connection = BrokerConnection()
l.consume_messages = Mock(side_effect=socket.error("foo"))
with self.assertRaises(socket.error):
l.start()
self.assertTrue(init_callback.call_count)
self.assertTrue(l.consume_messages.call_count)
def test_reset_connection_with_no_node(self):
l = MainConsumer(self.ready_queue, self.eta_schedule, self.logger)
self.assertEqual(None, l.pool)
l.reset_connection()
class test_WorkController(AppCase):
def setup(self):
self.worker = self.create_worker()
def create_worker(self, **kw):
worker = WorkController(concurrency=1, loglevel=0, **kw)
worker._shutdown_complete.set()
worker.logger = Mock()
return worker
@patch("celery.platforms.signals")
@patch("celery.platforms.set_mp_process_title")
def test_process_initializer(self, set_mp_process_title, _signals):
from celery import Celery
from celery import signals
from celery.app import _tls
from celery.concurrency.processes import process_initializer
from celery.concurrency.processes import (WORKER_SIGRESET,
WORKER_SIGIGNORE)
def on_worker_process_init(**kwargs):
on_worker_process_init.called = True
on_worker_process_init.called = False
signals.worker_process_init.connect(on_worker_process_init)
loader = Mock()
app = Celery(loader=loader, set_as_current=False)
app.conf = AttributeDict(DEFAULTS)
process_initializer(app, "awesome.worker.com")
self.assertIn((tuple(WORKER_SIGIGNORE), {}),
_signals.ignore.call_args_list)
self.assertIn((tuple(WORKER_SIGRESET), {}),
_signals.reset.call_args_list)
self.assertTrue(app.loader.init_worker.call_count)
self.assertTrue(on_worker_process_init.called)
self.assertIs(_tls.current_app, app)
set_mp_process_title.assert_called_with("celeryd",
hostname="awesome.worker.com")
def test_with_rate_limits_disabled(self):
worker = WorkController(concurrency=1, loglevel=0,
disable_rate_limits=True)
self.assertTrue(hasattr(worker.ready_queue, "put"))
def test_attrs(self):
worker = self.worker
self.assertIsInstance(worker.scheduler, Timer)
self.assertTrue(worker.scheduler)
self.assertTrue(worker.pool)
self.assertTrue(worker.consumer)
self.assertTrue(worker.mediator)
self.assertTrue(worker.components)
def test_with_embedded_celerybeat(self):
worker = WorkController(concurrency=1, loglevel=0,
embed_clockservice=True)
self.assertTrue(worker.beat)
self.assertIn(worker.beat, worker.components)
def test_with_autoscaler(self):
worker = self.create_worker(autoscale=[10, 3], send_events=False,
eta_scheduler_cls="celery.utils.timer2.Timer")
self.assertTrue(worker.autoscaler)
def test_dont_stop_or_terminate(self):
worker = WorkController(concurrency=1, loglevel=0)
worker.stop()
self.assertNotEqual(worker._state, worker.CLOSE)
worker.terminate()
self.assertNotEqual(worker._state, worker.CLOSE)
sigsafe, worker.pool.signal_safe = worker.pool.signal_safe, False
try:
worker._state = worker.RUN
worker.stop(in_sighandler=True)
self.assertNotEqual(worker._state, worker.CLOSE)
worker.terminate(in_sighandler=True)
self.assertNotEqual(worker._state, worker.CLOSE)
finally:
worker.pool.signal_safe = sigsafe
def test_on_timer_error(self):
worker = WorkController(concurrency=1, loglevel=0)
worker.logger = Mock()
try:
raise KeyError("foo")
except KeyError:
exc_info = sys.exc_info()
worker.on_timer_error(exc_info)
msg, args = worker.logger.error.call_args[0]
self.assertIn("KeyError", msg % args)
def test_on_timer_tick(self):
worker = WorkController(concurrency=1, loglevel=10)
worker.logger = Mock()
worker.timer_debug = worker.logger.debug
worker.on_timer_tick(30.0)
xargs = worker.logger.debug.call_args[0]
fmt, arg = xargs[0], xargs[1]
self.assertEqual(30.0, arg)
self.assertIn("Next eta %s secs", fmt)
def test_process_task(self):
worker = self.worker
worker.pool = Mock()
backend = Mock()
m = create_message(backend, task=foo_task.name, args=[4, 8, 10],
kwargs={})
task = Request.from_message(m, m.decode())
worker.process_task(task)
self.assertEqual(worker.pool.apply_async.call_count, 1)
worker.pool.stop()
def test_process_task_raise_base(self):
worker = self.worker
worker.pool = Mock()
worker.pool.apply_async.side_effect = KeyboardInterrupt("Ctrl+C")
backend = Mock()
m = create_message(backend, task=foo_task.name, args=[4, 8, 10],
kwargs={})
task = Request.from_message(m, m.decode())
worker.components = []
worker._state = worker.RUN
with self.assertRaises(KeyboardInterrupt):
worker.process_task(task)
self.assertEqual(worker._state, worker.TERMINATE)
def test_process_task_raise_SystemTerminate(self):
worker = self.worker
worker.pool = Mock()
worker.pool.apply_async.side_effect = SystemTerminate()
backend = Mock()
m = create_message(backend, task=foo_task.name, args=[4, 8, 10],
kwargs={})
task = Request.from_message(m, m.decode())
worker.components = []
worker._state = worker.RUN
with self.assertRaises(SystemExit):
worker.process_task(task)
self.assertEqual(worker._state, worker.TERMINATE)
def test_process_task_raise_regular(self):
worker = self.worker
worker.pool = Mock()
worker.pool.apply_async.side_effect = KeyError("some exception")
backend = Mock()
m = create_message(backend, task=foo_task.name, args=[4, 8, 10],
kwargs={})
task = Request.from_message(m, m.decode())
worker.process_task(task)
worker.pool.stop()
def test_start_catches_base_exceptions(self):
worker1 = self.create_worker()
stc = Mock()
stc.start.side_effect = SystemTerminate()
worker1.components = [stc]
worker1.start()
self.assertTrue(stc.terminate.call_count)
worker2 = self.create_worker()
sec = Mock()
sec.start.side_effect = SystemExit()
sec.terminate = None
worker2.components = [sec]
worker2.start()
self.assertTrue(sec.stop.call_count)
def test_state_db(self):
from celery.worker import state
Persistent = state.Persistent
state.Persistent = Mock()
try:
worker = self.create_worker(state_db="statefilename")
self.assertTrue(worker._persistence)
finally:
state.Persistent = Persistent
def test_disable_rate_limits_solo(self):
worker = self.create_worker(disable_rate_limits=True,
pool_cls="solo")
self.assertIsInstance(worker.ready_queue, FastQueue)
self.assertIsNone(worker.mediator)
self.assertEqual(worker.ready_queue.put, worker.process_task)
def test_disable_rate_limits_processes(self):
try:
worker = self.create_worker(disable_rate_limits=True,
pool_cls="processes")
except ImportError:
raise SkipTest("multiprocessing not supported")
self.assertIsInstance(worker.ready_queue, FastQueue)
self.assertTrue(worker.mediator)
self.assertNotEqual(worker.ready_queue.put, worker.process_task)
def test_start__stop(self):
worker = self.worker
worker._shutdown_complete.set()
worker.components = [Mock(), Mock(), Mock(), Mock()]
worker.start()
for w in worker.components:
self.assertTrue(w.start.call_count)
worker.stop()
for component in worker.components:
self.assertTrue(w.stop.call_count)
def test_start__terminate(self):
worker = self.worker
worker._shutdown_complete.set()
worker.components = [Mock(), Mock(), Mock(), Mock(), Mock()]
for component in worker.components[:3]:
component.terminate = None
worker.start()
for w in worker.components[:3]:
self.assertTrue(w.start.call_count)
self.assertTrue(worker._running, len(worker.components))
self.assertEqual(worker._state, RUN)
worker.terminate()
for component in worker.components[:3]:
self.assertTrue(component.stop.call_count)
self.assertTrue(worker.components[4].terminate.call_count)
| bsd-3-clause |
bloopletech/Comix | src/thumbnail.py | 2 | 6430 | """thumbnail.py - Thumbnail module for Comix implementing (most of) the
freedesktop.org "standard" at http://jens.triq.net/thumbnail-spec/
Only normal size (i.e. 128x128 px) thumbnails are supported.
"""
import os
from urllib import pathname2url, url2pathname
try: # The md5 module is deprecated as of Python 2.5, replaced by hashlib.
from hashlib import md5
except ImportError:
from md5 import new as md5
import re
import shutil
import tempfile
import gtk
import Image
import archive
import constants
import filehandler
_thumbdir = os.path.join(constants.HOME_DIR, '.thumbnails/normal')
def get_thumbnail(path, create=True, dst_dir=_thumbdir):
"""Return a thumbnail pixbuf for the file at <path> by looking in the
directory of stored thumbnails. If a thumbnail for the file doesn't
exist we create a thumbnail pixbuf from the original. If <create>
is True we also save this new thumbnail in the thumbnail directory.
If no thumbnail for <path> can be produced (for whatever reason),
return None.
Images and archives are handled transparently. Note though that
None is always returned for archives where no thumbnail already exist
if <create> is False, since re-creating the thumbnail on the fly each
time would be too costly.
If <dst_dir> is set it is the base thumbnail directory, if not we use
the default .thumbnails/normal/.
"""
thumbpath = _path_to_thumbpath(path, dst_dir)
if not os.path.exists(thumbpath):
return _get_new_thumbnail(path, create, dst_dir)
try:
info = Image.open(thumbpath).info
try:
mtime = int(info['Thumb::MTime'])
except Exception:
mtime = -1
if os.stat(path).st_mtime != mtime:
return _get_new_thumbnail(path, create, dst_dir)
return gtk.gdk.pixbuf_new_from_file(thumbpath)
except Exception:
return None
def delete_thumbnail(path, dst_dir=_thumbdir):
"""Delete the thumbnail (if it exists) for the file at <path>.
If <dst_dir> is set it is the base thumbnail directory, if not we use
the default .thumbnails/normal/.
"""
thumbpath = _path_to_thumbpath(path, dst_dir)
if os.path.isfile(thumbpath):
try:
os.remove(thumbpath)
except Exception:
pass
def _get_new_thumbnail(path, create, dst_dir):
"""Return a new thumbnail pixbuf for the file at <path>. If <create> is
True we also save it to disk with <dst_dir> as the base thumbnail
directory.
"""
if archive.archive_mime_type(path) is not None:
if create:
return _get_new_archive_thumbnail(path, dst_dir)
return None
if create:
return _create_thumbnail(path, dst_dir)
return _get_pixbuf128(path)
def _get_new_archive_thumbnail(path, dst_dir):
"""Return a new thumbnail pixbuf for the archive at <path>, and save it
to disk; <dst_dir> is the base thumbnail directory.
"""
extractor = archive.Extractor()
tmpdir = tempfile.mkdtemp(prefix='comix_archive_thumb.')
condition = extractor.setup(path, tmpdir)
files = extractor.get_files()
wanted = _guess_cover(files)
if wanted is None:
return None
extractor.set_files([wanted])
extractor.extract()
image_path = os.path.join(tmpdir, wanted)
condition.acquire()
while not extractor.is_ready(wanted):
condition.wait()
condition.release()
pixbuf = _create_thumbnail(path, dst_dir, image_path=image_path)
shutil.rmtree(tmpdir)
return pixbuf
def _create_thumbnail(path, dst_dir, image_path=None):
"""Create a thumbnail from the file at <path> and store it if it is
larger than 128x128 px. A pixbuf for the thumbnail is returned.
<dst_dir> is the base thumbnail directory (usually ~/.thumbnails/normal).
If <image_path> is not None it is used as the path to the image file
actually used to create the thumbnail image, although the created
thumbnail will still be saved as if for <path>.
"""
if image_path is None:
image_path = path
pixbuf = _get_pixbuf128(image_path)
if pixbuf is None:
return None
mime, width, height = gtk.gdk.pixbuf_get_file_info(image_path)
if width <= 128 and height <= 128:
return pixbuf
mime = mime['mime_types'][0]
uri = 'file://' + pathname2url(os.path.normpath(path))
thumbpath = _uri_to_thumbpath(uri, dst_dir)
stat = os.stat(path)
mtime = str(int(stat.st_mtime))
size = str(stat.st_size)
width = str(width)
height = str(height)
tEXt_data = {
'tEXt::Thumb::URI': uri,
'tEXt::Thumb::MTime': mtime,
'tEXt::Thumb::Size': size,
'tEXt::Thumb::Mimetype': mime,
'tEXt::Thumb::Image::Width': width,
'tEXt::Thumb::Image::Height': height,
'tEXt::Software': 'Comix %s' % constants.VERSION
}
try:
if not os.path.isdir(dst_dir):
os.makedirs(dst_dir, 0700)
pixbuf.save(thumbpath + '-comixtemp', 'png', tEXt_data)
os.rename(thumbpath + '-comixtemp', thumbpath)
os.chmod(thumbpath, 0600)
except Exception:
print '! thumbnail.py: Could not write', thumbpath, '\n'
return pixbuf
def _path_to_thumbpath(path, dst_dir):
uri = 'file://' + pathname2url(os.path.normpath(path))
return _uri_to_thumbpath(uri, dst_dir)
def _uri_to_thumbpath(uri, dst_dir):
"""Return the full path to the thumbnail for <uri> when <dst_dir> the base
thumbnail directory.
"""
md5hash = md5(uri).hexdigest()
thumbpath = os.path.join(dst_dir, md5hash + '.png')
return thumbpath
def _get_pixbuf128(path):
try:
return gtk.gdk.pixbuf_new_from_file_at_size(path, 128, 128)
except Exception:
return None
def _guess_cover(files):
"""Return the filename within <files> that is the most likely to be the
cover of an archive using some simple heuristics.
"""
filehandler.alphanumeric_sort(files)
ext_re = re.compile(r'\.(jpg|jpeg|png|gif|tif|tiff|bmp)\s*$', re.I)
front_re = re.compile('(cover|front)', re.I)
images = filter(ext_re.search, files)
candidates = filter(front_re.search, images)
candidates = [c for c in candidates if 'back' not in c.lower()]
if candidates:
return candidates[0]
if images:
return images[0]
return None
| gpl-2.0 |
alexsh/Telegram | TMessagesProj/jni/boringssl/third_party/googletest/test/googletest-uninitialized-test.py | 95 | 2474 | #!/usr/bin/env python
#
# Copyright 2008, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Verifies that Google Test warns the user when not initialized properly."""
import gtest_test_utils
COMMAND = gtest_test_utils.GetTestExecutablePath('googletest-uninitialized-test_')
def Assert(condition):
if not condition:
raise AssertionError
def AssertEq(expected, actual):
if expected != actual:
print('Expected: %s' % (expected,))
print(' Actual: %s' % (actual,))
raise AssertionError
def TestExitCodeAndOutput(command):
"""Runs the given command and verifies its exit code and output."""
# Verifies that 'command' exits with code 1.
p = gtest_test_utils.Subprocess(command)
if p.exited and p.exit_code == 0:
Assert('IMPORTANT NOTICE' in p.output);
Assert('InitGoogleTest' in p.output)
class GTestUninitializedTest(gtest_test_utils.TestCase):
def testExitCodeAndOutput(self):
TestExitCodeAndOutput(COMMAND)
if __name__ == '__main__':
gtest_test_utils.Main()
| gpl-2.0 |
v1teka/yo | vendor/psy/psysh/test/tools/gen_unvis_fixtures.py | 536 | 3120 | #! /usr/bin/env python3
import sys
from os.path import abspath, expanduser, dirname, join
from itertools import chain
import json
import argparse
from vis import vis, unvis, VIS_WHITE
__dir__ = dirname(abspath(__file__))
OUTPUT_FILE = join(__dir__, '..', 'fixtures', 'unvis_fixtures.json')
# Add custom fixtures here
CUSTOM_FIXTURES = [
# test long multibyte string
''.join(chr(cp) for cp in range(1024)),
'foo bar',
'foo\nbar',
"$bar = 'baz';",
r'$foo = "\x20\\x20\\\x20\\\\x20"',
'$foo = function($bar) use($baz) {\n\treturn $baz->getFoo()\n};'
]
RANGES = {
# All valid codepoints in the BMP
'bmp': chain(range(0x0000, 0xD800), range(0xE000, 0xFFFF)),
# Smaller set of pertinent? codepoints inside BMP
# see: http://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane
'small': chain(
# latin blocks
range(0x0000, 0x0250),
# Greek, Cyrillic
range(0x0370, 0x0530),
# Hebrew, Arabic
range(0x590, 0x0700),
# CJK radicals
range(0x2E80, 0x2F00),
# Hiragana, Katakana
range(0x3040, 0x3100)
)
}
if __name__ == '__main__':
argp = argparse.ArgumentParser(
description='Generates test data for Psy\\Test\\Util\\StrTest')
argp.add_argument('-f', '--format-output', action='store_true',
help='Indent JSON output to ease debugging')
argp.add_argument('-a', '--all', action='store_true',
help="""Generates test data for all codepoints of the BMP.
(same as --range=bmp). WARNING: You will need quite
a lot of RAM to run the testsuite !
""")
argp.add_argument('-r', '--range',
help="""Choose the range of codepoints used to generate
test data.""",
choices=list(RANGES.keys()),
default='small')
argp.add_argument('-o', '--output-file',
help="""Write test data to OUTPUT_FILE
(defaults to PSYSH_DIR/test/fixtures)""")
args = argp.parse_args()
cp_range = RANGES['bmp'] if args.all else RANGES[args.range]
indent = 2 if args.format_output else None
if args.output_file:
OUTPUT_FILE = abspath(expanduser(args.output_file))
fixtures = []
# use SMALL_RANGE by default, it should be enough.
# use BMP_RANGE for a more complete smoke test
for codepoint in cp_range:
char = chr(codepoint)
encoded = vis(char, VIS_WHITE)
decoded = unvis(encoded)
fixtures.append((encoded, decoded))
# Add our own custom fixtures at the end,
# since they would fail anyway if one of the previous did.
for fixture in CUSTOM_FIXTURES:
encoded = vis(fixture, VIS_WHITE)
decoded = unvis(encoded)
fixtures.append((encoded, decoded))
with open(OUTPUT_FILE, 'w') as fp:
# dump as json to avoid backslashin and quotin nightmare
# between php and python
json.dump(fixtures, fp, indent=indent)
sys.exit(0)
| gpl-3.0 |
tyler-abbot/psid_py | setup.py | 1 | 2486 | """A setup module for psidPy
Based on the pypa sample project.
A tool to download data and build psid panels based on psidR by Florian Oswald.
See:
https://github.com/floswald/psidR
https://github.com/tyler-abbot/psidPy
"""
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the relevant file
with open(path.join(here, 'DESCRIPTION.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='psid_py',
version='1.0.2',
description='A tool to build PSID panels.',
# The project's main homepage
url='https://github.com/tyler-abbot/psidPy',
# Author details
author='Tyler Abbot',
author_email='[email protected]',
# Licensing information
license='MIT',
classifiers=[
#How mature is this project?
# How mature is this project? Common values are
# 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 3 - Alpha',
# Indicate who your project is intended for
'Intended Audience :: Science/Research',
'Topic :: Scientific/Engineering :: Information Analysis',
# Pick your license as you wish (should match "license" above)
'License :: OSI Approved :: MIT License',
# Specify the Python versions you support here. In particular, ensure
# that you indicate whether you support Python 2, Python 3 or both.
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'],
# What does your project relate to?
keywords='statistics econometrics data',
# You can just specify the packages manually here if your project is
# simple. Or you can use find_packages().
packages=find_packages(exclude=['contrib', 'docs', 'tests*']),
# List run-time dependencies here. These will be installed by pip when
# your project is installed. For an analysis of "install_requires" vs pip's
# requirements files see:
# https://packaging.python.org/en/latest/requirements.html
install_requires=['requests',
'pandas',
'beautifulsoup4'],
)
| mit |
victorbriz/omim | 3party/freetype/src/tools/docmaker/utils.py | 153 | 3513 | #
# utils.py
#
# Auxiliary functions for the `docmaker' tool (library file).
#
# Copyright 2002-2015 by
# David Turner.
#
# This file is part of the FreeType project, and may only be used,
# modified, and distributed under the terms of the FreeType project
# license, LICENSE.TXT. By continuing to use, modify, or distribute
# this file you indicate that you have read the license and
# understand and accept it fully.
import string, sys, os, glob, itertools
# current output directory
#
output_dir = None
# A function that generates a sorting key. We want lexicographical order
# (primary key) except that capital letters are sorted before lowercase
# ones (secondary key).
#
# The primary key is implemented by lowercasing the input. The secondary
# key is simply the original data appended, character by character. For
# example, the sort key for `FT_x' is `fFtT__xx', while the sort key for
# `ft_X' is `fftt__xX'. Since ASCII codes of uppercase letters are
# numerically smaller than the codes of lowercase letters, `fFtT__xx' gets
# sorted before `fftt__xX'.
#
def index_key( s ):
return string.join( itertools.chain( *zip( s.lower(), s ) ) )
# Sort `input_list', placing the elements of `order_list' in front.
#
def sort_order_list( input_list, order_list ):
new_list = order_list[:]
for id in input_list:
if not id in order_list:
new_list.append( id )
return new_list
# Divert standard output to a given project documentation file. Use
# `output_dir' to determine the filename location if necessary and save the
# old stdout handle in a tuple that is returned by this function.
#
def open_output( filename ):
global output_dir
if output_dir and output_dir != "":
filename = output_dir + os.sep + filename
old_stdout = sys.stdout
new_file = open( filename, "w" )
sys.stdout = new_file
return ( new_file, old_stdout )
# Close the output that was returned by `open_output'.
#
def close_output( output ):
output[0].close()
sys.stdout = output[1]
# Check output directory.
#
def check_output():
global output_dir
if output_dir:
if output_dir != "":
if not os.path.isdir( output_dir ):
sys.stderr.write( "argument"
+ " '" + output_dir + "' "
+ "is not a valid directory\n" )
sys.exit( 2 )
else:
output_dir = None
def file_exists( pathname ):
"""Check that a given file exists."""
result = 1
try:
file = open( pathname, "r" )
file.close()
except:
result = None
sys.stderr.write( pathname + " couldn't be accessed\n" )
return result
def make_file_list( args = None ):
"""Build a list of input files from command-line arguments."""
file_list = []
# sys.stderr.write( repr( sys.argv[1 :] ) + '\n' )
if not args:
args = sys.argv[1:]
for pathname in args:
if string.find( pathname, '*' ) >= 0:
newpath = glob.glob( pathname )
newpath.sort() # sort files -- this is important because
# of the order of files
else:
newpath = [pathname]
file_list.extend( newpath )
if len( file_list ) == 0:
file_list = None
else:
# now filter the file list to remove non-existing ones
file_list = filter( file_exists, file_list )
return file_list
# eof
| apache-2.0 |
nick-thompson/servo | tests/wpt/web-platform-tests/conformance-checkers/tools/ins-del-datetime.py | 141 | 8457 | # -*- coding: utf-8 -*-
import os
ccdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
template = """<!DOCTYPE html>
<meta charset=utf-8>
"""
errors = {
"date-year-0000": "0000-12-09",
"date-month-00": "2002-00-15",
"date-month-13": "2002-13-15",
"date-0005-02-29": "0005-02-29",
"date-1969-02-29": "1969-02-29",
"date-1900-02-29": "1900-02-29",
"date-2100-02-29": "2100-02-29",
"date-2200-02-29": "2200-02-29",
"date-2014-02-29": "2014-02-29",
"date-day-04-31": "2002-04-31",
"date-day-06-31": "2002-06-31",
"date-day-09-31": "2002-09-31",
"date-day-11-31": "2002-11-31",
"date-day-01-32": "2002-01-32",
"date-day-03-32": "2002-03-32",
"date-day-05-32": "2002-05-32",
"date-day-07-32": "2002-07-32",
"date-day-08-32": "2002-08-32",
"date-day-10-32": "2002-10-32",
"date-day-12-32": "2002-12-32",
"date-iso8601-YYYYMMDD-no-hyphen": "20020929",
"date-leading-whitespace": " 2002-09-29",
"date-trailing-whitespace": "2002-09-29 ",
"date-month-one-digit": "2002-9-29",
"date-month-three-digits": "2002-011-29",
"date-year-three-digits": "782-09-29",
"date-day-one-digit": "2002-09-9",
"date-day-three-digits": "2002-11-009",
"date-day-missing-separator": "2014-0220",
"date-month-missing-separator": "201402-20",
"date-non-ascii-digit": "2002-09-29",
"date-trailing-U+0000": "2002-09-29�",
"date-trailing-pile-of-poo": "2002-09-29💩",
"date-wrong-day-separator": "2014-02:20",
"date-wrong-month-separator": "2014:02-20",
"date-year-negative": "-2002-09-29",
"date-leading-bom": "2002-09-29",
"global-date-and-time-60-minutes": "2011-11-12T00:60:00+08:00",
"global-date-and-time-60-seconds": "2011-11-12T00:00:60+08:00",
"global-date-and-time-2400": "2011-11-12T24:00:00+08:00",
"global-date-and-time-space-before-timezone": "2011-11-12T06:54:39 08:00",
"global-date-and-time-hour-one-digit": "2011-11-12T6:54:39-08:00",
"global-date-and-time-hour-three-digits": "2011-11-12T016:54:39-08:00",
"global-date-and-time-minutes-one-digit": "2011-11-12T16:4:39-08:00",
"global-date-and-time-minutes-three-digits": "2011-11-12T16:354:39-08:00",
"global-date-and-time-seconds-one-digit": "2011-11-12T16:54:9-08:00",
"global-date-and-time-seconds-three-digits": "2011-11-12T16:54:039-08:00",
"global-date-and-time-timezone-with-seconds": "2011-11-12T06:54:39-08:00:00",
"global-date-and-time-timezone-60-minutes": "2011-11-12T06:54:39-08:60",
"global-date-and-time-timezone-one-digit-hour": "2011-11-12T06:54:39-5:00",
"global-date-and-time-timezone-one-digit-minute": "2011-11-12T06:54:39-05:0",
"global-date-and-time-timezone-three-digit-hour": "2011-11-12T06:54:39-005:00",
"global-date-and-time-timezone-three-digit-minute": "2011-11-12T06:54:39-05:000",
"global-date-and-time-nbsp": "2011-11-12 14:54Z",
"global-date-and-time-missing-minutes-separator": "2011-11-12T1454Z",
"global-date-and-time-missing-seconds-separator": "2011-11-12T14:5439Z",
"global-date-and-time-wrong-minutes-separator": "2011-11-12T14-54Z",
"global-date-and-time-wrong-seconds-separator": "2011-11-12T14:54-39Z",
"global-date-and-time-lowercase-z": "2011-11-12T14:54z",
"global-date-and-time-with-both-T-and-space": "2011-11-12T 14:54Z",
"global-date-and-time-zero-digit-fraction": "2011-11-12T06:54:39.-08:00",
"global-date-and-time-four-digit-fraction": "2011-11-12T06:54:39.9291-08:00",
"global-date-and-time-bad-fraction-separator": "2011-11-12T14:54:39,929+0000",
"global-date-and-time-timezone-non-T-character": "2011-11-12+14:54Z",
"global-date-and-time-timezone-lowercase-t": "2011-11-12t14:54Z",
"global-date-and-time-timezone-multiple-spaces": "2011-11-12 14:54Z",
"global-date-and-time-timezone-offset-space-start": "2011-11-12T06:54:39.929 08:00",
"global-date-and-time-timezone-offset-colon-start": "2011-11-12T06:54:39.929:08:00",
"global-date-and-time-timezone-plus-2400": "2011-11-12T06:54:39-24:00",
"global-date-and-time-timezone-minus-2400": "2011-11-12T06:54:39-24:00",
"global-date-and-time-timezone-iso8601-two-digit": "2011-11-12T06:54:39-08",
"global-date-and-time-iso8601-hhmmss-no-colon": "2011-11-12T145439Z",
"global-date-and-time-iso8601-hhmm-no-colon": "2011-11-12T1454Z",
"global-date-and-time-iso8601-hh": "2011-11-12T14Z",
"year": "2006",
"yearless-date": "07-15",
"month": "2011-11",
"week": "2011-W46",
"time": "14:54:39",
"local-date-and-time": "2011-11-12T14:54",
"duration-P-form": "PT4H18M3S",
"duration-time-component": "4h 18m 3s",
}
warnings = {
"global-date-and-time-timezone-plus-1500": "2011-11-12T00:00:00+1500",
"global-date-and-time-timezone-minus-1300": "2011-11-12T00:00:00-1300",
"global-date-and-time-timezone-minutes-15": "2011-11-12T00:00:00+08:15",
"date-0214-09-29": "0214-09-29",
"date-20014-09-29": "20014-09-29",
"date-0004-02-29": "0004-02-29",
"date-year-five-digits": "12014-09-29",
}
non_errors = {
"date": "2002-09-29",
"date-2000-02-29": "2000-02-29",
"date-2400-02-29": "2400-02-29",
"date-1968-02-29": "1968-02-29",
"date-1900-02-28": "1900-02-28",
"date-2100-02-28": "2100-02-28",
"date-2100-02-28": "2100-02-28",
"date-2200-02-28": "2200-02-28",
"date-2014-02-28": "2014-02-28",
"date-day-01-31": "2002-01-31",
"date-day-03-31": "2002-03-31",
"date-day-05-31": "2002-05-31",
"date-day-07-31": "2002-07-31",
"date-day-08-31": "2002-08-31",
"date-day-10-31": "2002-10-31",
"date-day-12-31": "2002-12-31",
"date-day-04-30": "2002-04-30",
"date-day-06-30": "2002-06-30",
"date-day-09-30": "2002-09-30",
"date-day-11-30": "2002-11-30",
"global-date-and-time-no-seconds": "2011-11-12T14:54Z",
"global-date-and-time-with-seconds": "2011-11-12T14:54:39+0000",
"global-date-and-time-with-one-digit-fraction": "2011-11-12T06:54:39.9-08:00",
"global-date-and-time-with-two-digit-fraction": "2011-11-12T06:54:39.92+07:00",
"global-date-and-time-with-three-digit-fraction": "2011-11-12T06:54:39.929-06:00",
"global-date-and-time-space": "2011-11-12 14:54Z",
"global-date-and-time-timezone": "2011-11-12T06:54:39+0900",
"global-date-and-time-timezone-30": "2011-11-12T06:54:39-0830",
"global-date-and-time-timezone-45": "2011-11-12T06:54:39-0845",
"global-date-and-time-timezone-with-colon": "2011-11-12T06:54:39-08:00",
"global-date-and-time-timezone-without-colon": "2011-11-12T06:54:39-0800",
}
for key in errors.keys():
error = errors[key]
template_ins = template
template_del = template
template_ins += '<title>%s</title>\n' % key
template_del += '<title>%s</title>\n' % key
template_ins += '<ins datetime="%s"></ins>' % errors[key]
template_del += '<del datetime="%s"></del>' % errors[key]
ins_file = open(os.path.join(ccdir, "html/elements/ins/%s-novalid.html" % key), 'wb')
ins_file.write(template_ins)
ins_file.close()
del_file = open(os.path.join(ccdir, "html/elements/del/%s-novalid.html" % key), 'wb')
del_file.write(template_del)
del_file.close()
for key in warnings.keys():
non_error = warnings[key]
template_ins = template
template_del = template
template_ins += '<title>%s</title>\n' % key
template_del += '<title>%s</title>\n' % key
template_ins += '<ins datetime="%s"></ins>' % warnings[key]
template_del += '<del datetime="%s"></del>' % warnings[key]
ins_file = open(os.path.join(ccdir, "html/elements/ins/%s-haswarn.html" % key), 'wb')
ins_file.write(template_ins)
ins_file.close()
del_file = open(os.path.join(ccdir, "html/elements/del/%s-haswarn.html" % key), 'wb')
del_file.write(template_del)
del_file.close()
ins_file = open(os.path.join(ccdir, "html/elements/ins/datetime-isvalid.html"), 'wb')
del_file = open(os.path.join(ccdir, "html/elements/del/datetime-isvalid.html"), 'wb')
ins_file.write(template + '<title>valid datetime</title>\n')
del_file.write(template + '<title>valid datetime</title>\n')
for key in non_errors.keys():
non_error = non_errors[key]
ins_file.write('<ins datetime="%s"></ins> <!-- %s -->\n' % (non_errors[key], key))
del_file.write('<del datetime="%s"></del> <!-- %s -->\n' % (non_errors[key], key))
ins_file.close()
del_file.close()
# vim: ts=4:sw=4
| mpl-2.0 |
Sheikh-Aman/Stupid-Simple | Owl/owl.py | 1 | 3536 | import urllib2
import json
# Copyright 2016, Aman Alam
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This script accesses the YouTube Data API, to find out which video
# from a YouTube channel was the most viewed video
# It currently fetches for CokeStudioPK channel, paginates to get all the videos uploaded,
# ignores the channels or playlists, and considers only the videos which have a like count
# greater than 1000.
# You'll need to change the API Key to your own, though. Read the README on the repo to know how
apiKey = "<put-your-own-API-Key-Here>" # Put your API Key here
channelCokeStudioId = "UCM1VesJtJ9vTXcMLLr_FfdQ"
getListUrl = "https://www.googleapis.com/youtube/v3/search?order=date&part=snippet" \
"&channelId={}&maxResults=50&safeSearch=none&&type=video&key={}"
getVideoStatsUrl = "https://www.googleapis.com/youtube/v3/videos?part=contentDetails,statistics" \
"&id={}&key={}"
paramPageToken = "&pageToken="
largestViewCount = 0
viewCountThreshold = 10000 # ignore any video below this view count.
def getjsonfromurl(url):
response_body = urllib2.urlopen(url).read()
return response_body
def getallvideos(channelid):
jsonStr = getjsonfromurl(getListUrl.format(channelid, apiKey))
videoListJsonDict = json.loads(jsonStr)
print "Will get list of ~{} videos..".format(videoListJsonDict['pageInfo']['totalResults'])
items = videoListJsonDict['items']
while ('nextPageToken' in videoListJsonDict):
jsonStr = getjsonfromurl(getListUrl.format(channelid, apiKey)+paramPageToken+videoListJsonDict['nextPageToken'])
videoListJsonDict = json.loads(jsonStr)
items = items+videoListJsonDict['items']
print "Total videos fetched : ", len(items)
return items
print "Querying the API.."
items = getallvideos(channelCokeStudioId)
for idx, val in enumerate(items):
if val['id']['kind'] == "youtube#video":
print 'Getting info for : '+val['snippet']['title']
statsJsonStr = getjsonfromurl(getVideoStatsUrl.format(val['id']['videoId'], apiKey))
videoStatsJsonDict = json.loads(statsJsonStr)
viewCount = int(videoStatsJsonDict['items'][0]['statistics']['viewCount'])
if viewCount > viewCountThreshold:
if largestViewCount < viewCount:
largestViewCount = viewCount
mostViewedVideo = [
# Video Name
val['snippet']['title'],
# View Count
viewCount,
# Like Count
videoStatsJsonDict['items'][0]['statistics']['likeCount'],
# Youtube Url
"https://www.youtube.com/watch?v=" + val['id']['videoId']
]
else:
print "- Skipping short video "+val['snippet']['title']
print "Most viewed Video: "+mostViewedVideo[0]\
+ ",\nView count: "+str(mostViewedVideo[1])\
+ ",\nLike Count: "+mostViewedVideo[2]\
+ ",\nWatch here : "+mostViewedVideo[3]
| apache-2.0 |
squarefactor/sorl | sorl/thumbnail/tests/templatetags.py | 2 | 10486 | import os
from django.conf import settings
from django.template import Template, Context, TemplateSyntaxError
from sorl.thumbnail.tests.classes import BaseTest, RELATIVE_PIC_NAME
class ThumbnailTagTest(BaseTest):
def render_template(self, source):
context = Context({
'source': RELATIVE_PIC_NAME,
'invalid_source': 'not%s' % RELATIVE_PIC_NAME,
'size': (90, 100),
'invalid_size': (90, 'fish'),
'strsize': '80x90',
'invalid_strsize': ('1notasize2'),
'invalid_q': 'notanumber'})
source = '{% load thumbnail %}' + source
return Template(source).render(context)
def testTagInvalid(self):
# No args, or wrong number of args
src = '{% thumbnail %}'
self.assertRaises(TemplateSyntaxError, self.render_template, src)
src = '{% thumbnail source %}'
self.assertRaises(TemplateSyntaxError, self.render_template, src)
src = '{% thumbnail source 80x80 as variable crop %}'
self.assertRaises(TemplateSyntaxError, self.render_template, src)
# Invalid option
src = '{% thumbnail source 240x200 invalid %}'
self.assertRaises(TemplateSyntaxError, self.render_template, src)
# Old comma separated options format can only have an = for quality
src = '{% thumbnail source 80x80 crop=1,quality=1 %}'
self.assertRaises(TemplateSyntaxError, self.render_template, src)
# Invalid quality
src_invalid = '{% thumbnail source 240x200 quality=invalid_q %}'
src_missing = '{% thumbnail source 240x200 quality=missing_q %}'
# ...with THUMBNAIL_DEBUG = False
self.assertEqual(self.render_template(src_invalid), '')
self.assertEqual(self.render_template(src_missing), '')
# ...and with THUMBNAIL_DEBUG = True
self.change_settings.change({'DEBUG': True})
self.assertRaises(TemplateSyntaxError, self.render_template,
src_invalid)
self.assertRaises(TemplateSyntaxError, self.render_template,
src_missing)
# Invalid source
src = '{% thumbnail invalid_source 80x80 %}'
src_on_context = '{% thumbnail invalid_source 80x80 as thumb %}'
# ...with THUMBNAIL_DEBUG = False
self.change_settings.change({'DEBUG': False})
self.assertEqual(self.render_template(src), '')
# ...and with THUMBNAIL_DEBUG = True
self.change_settings.change({'DEBUG': True})
self.assertRaises(TemplateSyntaxError, self.render_template, src)
self.assertRaises(TemplateSyntaxError, self.render_template,
src_on_context)
# Non-existant source
src = '{% thumbnail non_existant_source 80x80 %}'
src_on_context = '{% thumbnail non_existant_source 80x80 as thumb %}'
# ...with THUMBNAIL_DEBUG = False
self.change_settings.change({'DEBUG': False})
self.assertEqual(self.render_template(src), '')
# ...and with THUMBNAIL_DEBUG = True
self.change_settings.change({'DEBUG': True})
self.assertRaises(TemplateSyntaxError, self.render_template, src)
# Invalid size as a tuple:
src = '{% thumbnail source invalid_size %}'
# ...with THUMBNAIL_DEBUG = False
self.change_settings.change({'DEBUG': False})
self.assertEqual(self.render_template(src), '')
# ...and THUMBNAIL_DEBUG = True
self.change_settings.change({'DEBUG': True})
self.assertRaises(TemplateSyntaxError, self.render_template, src)
# Invalid size as a string:
src = '{% thumbnail source invalid_strsize %}'
# ...with THUMBNAIL_DEBUG = False
self.change_settings.change({'DEBUG': False})
self.assertEqual(self.render_template(src), '')
# ...and THUMBNAIL_DEBUG = True
self.change_settings.change({'DEBUG': True})
self.assertRaises(TemplateSyntaxError, self.render_template, src)
# Non-existant size
src = '{% thumbnail source non_existant_size %}'
# ...with THUMBNAIL_DEBUG = False
self.change_settings.change({'DEBUG': False})
self.assertEqual(self.render_template(src), '')
# ...and THUMBNAIL_DEBUG = True
self.change_settings.change({'DEBUG': True})
self.assertRaises(TemplateSyntaxError, self.render_template, src)
def testTag(self):
expected_base = RELATIVE_PIC_NAME.replace('.', '_')
# Set DEBUG = True to make it easier to trace any failures
self.change_settings.change({'DEBUG': True})
# Basic
output = self.render_template('src="'
'{% thumbnail source 240x240 %}"')
expected = '%s_240x240_q85.jpg' % expected_base
expected_fn = os.path.join(settings.MEDIA_ROOT, expected)
self.verify_thumbnail((240, 180), expected_filename=expected_fn)
expected_url = ''.join((settings.MEDIA_URL, expected))
self.assertEqual(output, 'src="%s"' % expected_url)
# Size from context variable
# as a tuple:
output = self.render_template('src="'
'{% thumbnail source size %}"')
expected = '%s_90x100_q85.jpg' % expected_base
expected_fn = os.path.join(settings.MEDIA_ROOT, expected)
self.verify_thumbnail((90, 67), expected_filename=expected_fn)
expected_url = ''.join((settings.MEDIA_URL, expected))
self.assertEqual(output, 'src="%s"' % expected_url)
# as a string:
output = self.render_template('src="'
'{% thumbnail source strsize %}"')
expected = '%s_80x90_q85.jpg' % expected_base
expected_fn = os.path.join(settings.MEDIA_ROOT, expected)
self.verify_thumbnail((80, 60), expected_filename=expected_fn)
expected_url = ''.join((settings.MEDIA_URL, expected))
self.assertEqual(output, 'src="%s"' % expected_url)
# On context
output = self.render_template('height:'
'{% thumbnail source 240x240 as thumb %}{{ thumb.height }}')
self.assertEqual(output, 'height:180')
# With options and quality
output = self.render_template('src="'
'{% thumbnail source 240x240 sharpen crop quality=95 %}"')
# Note that the opts are sorted to ensure a consistent filename.
expected = '%s_240x240_crop_sharpen_q95.jpg' % expected_base
expected_fn = os.path.join(settings.MEDIA_ROOT, expected)
self.verify_thumbnail((240, 240), expected_filename=expected_fn)
expected_url = ''.join((settings.MEDIA_URL, expected))
self.assertEqual(output, 'src="%s"' % expected_url)
# With option and quality on context (also using its unicode method to
# display the url)
output = self.render_template(
'{% thumbnail source 240x240 sharpen crop quality=95 as thumb %}'
'width:{{ thumb.width }}, url:{{ thumb }}')
self.assertEqual(output, 'width:240, url:%s' % expected_url)
# Old comma separated format for options is still supported.
output = self.render_template(
'{% thumbnail source 240x240 sharpen,crop,quality=95 as thumb %}'
'width:{{ thumb.width }}, url:{{ thumb }}')
self.assertEqual(output, 'width:240, url:%s' % expected_url)
filesize_tests = r"""
>>> from sorl.thumbnail.templatetags.thumbnail import filesize
>>> filesize('abc')
'abc'
>>> filesize(100, 'invalid')
100
>>> bytes = 20
>>> filesize(bytes)
'20 B'
>>> filesize(bytes, 'auto1000')
'20 B'
>>> bytes = 1001
>>> filesize(bytes)
'1001 B'
>>> filesize(bytes, 'auto1000')
'1 kB'
>>> bytes = 10100
>>> filesize(bytes)
'9.9 KiB'
# Note that the decimal place is only used if < 10
>>> filesize(bytes, 'auto1000')
'10 kB'
>>> bytes = 190000000
>>> filesize(bytes)
'181 MiB'
>>> filesize(bytes, 'auto1000')
'190 MB'
# 'auto*long' methods use pluralisation:
>>> filesize(1, 'auto1024long')
'1 byte'
>>> filesize(1, 'auto1000long')
'1 byte'
>>> filesize(2, 'auto1024long')
'2 bytes'
>>> filesize(0, 'auto1000long')
'0 bytes'
# Test all 'auto*long' output:
>>> for i in range(1,10):
... print '%s, %s' % (filesize(1024**i, 'auto1024long'),
... filesize(1000**i, 'auto1000long'))
1 kibibyte, 1 kilobyte
1 mebibyte, 1 megabyte
1 gibibyte, 1 gigabyte
1 tebibyte, 1 terabyte
1 pebibyte, 1 petabyte
1 exbibyte, 1 exabyte
1 zebibyte, 1 zettabyte
1 yobibyte, 1 yottabyte
1024 yobibytes, 1000 yottabytes
# Test all fixed outputs (eg 'kB' or 'MiB')
>>> from sorl.thumbnail.templatetags.thumbnail import filesize_formats,\
... filesize_long_formats
>>> for f in filesize_formats:
... print '%s (%siB, %sB):' % (filesize_long_formats[f], f.upper(), f)
... for i in range(0, 10):
... print ' %s, %s' % (filesize(1024**i, '%siB' % f.upper()),
... filesize(1000**i, '%sB' % f))
kilo (KiB, kB):
0.0009765625, 0.001
1.0, 1.0
1024.0, 1000.0
1048576.0, 1000000.0
1073741824.0, 1000000000.0
1.09951162778e+12, 1e+12
1.12589990684e+15, 1e+15
1.15292150461e+18, 1e+18
1.18059162072e+21, 1e+21
1.20892581961e+24, 1e+24
mega (MiB, MB):
0.0, 1e-06
0.0009765625, 0.001
1.0, 1.0
1024.0, 1000.0
1048576.0, 1000000.0
1073741824.0, 1000000000.0
1.09951162778e+12, 1e+12
1.12589990684e+15, 1e+15
1.15292150461e+18, 1e+18
1.18059162072e+21, 1e+21
giga (GiB, GB):
0.0, 1e-09
0.0, 1e-06
0.0009765625, 0.001
1.0, 1.0
1024.0, 1000.0
1048576.0, 1000000.0
1073741824.0, 1000000000.0
1.09951162778e+12, 1e+12
1.12589990684e+15, 1e+15
1.15292150461e+18, 1e+18
tera (TiB, TB):
0.0, 1e-12
0.0, 1e-09
0.0, 1e-06
0.0009765625, 0.001
1.0, 1.0
1024.0, 1000.0
1048576.0, 1000000.0
1073741824.0, 1000000000.0
1.09951162778e+12, 1e+12
1.12589990684e+15, 1e+15
peta (PiB, PB):
0.0, 1e-15
0.0, 1e-12
0.0, 1e-09
0.0, 1e-06
0.0009765625, 0.001
1.0, 1.0
1024.0, 1000.0
1048576.0, 1000000.0
1073741824.0, 1000000000.0
1.09951162778e+12, 1e+12
exa (EiB, EB):
0.0, 1e-18
0.0, 1e-15
0.0, 1e-12
0.0, 1e-09
0.0, 1e-06
0.0009765625, 0.001
1.0, 1.0
1024.0, 1000.0
1048576.0, 1000000.0
1073741824.0, 1000000000.0
zetta (ZiB, ZB):
0.0, 1e-21
0.0, 1e-18
0.0, 1e-15
0.0, 1e-12
0.0, 1e-09
0.0, 1e-06
0.0009765625, 0.001
1.0, 1.0
1024.0, 1000.0
1048576.0, 1000000.0
yotta (YiB, YB):
0.0, 1e-24
0.0, 1e-21
0.0, 1e-18
0.0, 1e-15
0.0, 1e-12
0.0, 1e-09
0.0, 1e-06
0.0009765625, 0.001
1.0, 1.0
1024.0, 1000.0
"""
| bsd-3-clause |
ibinti/intellij-community | python/lib/Lib/site-packages/django/utils/daemonize.py | 452 | 1907 | import os
import sys
if os.name == 'posix':
def become_daemon(our_home_dir='.', out_log='/dev/null',
err_log='/dev/null', umask=022):
"Robustly turn into a UNIX daemon, running in our_home_dir."
# First fork
try:
if os.fork() > 0:
sys.exit(0) # kill off parent
except OSError, e:
sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror))
sys.exit(1)
os.setsid()
os.chdir(our_home_dir)
os.umask(umask)
# Second fork
try:
if os.fork() > 0:
os._exit(0)
except OSError, e:
sys.stderr.write("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror))
os._exit(1)
si = open('/dev/null', 'r')
so = open(out_log, 'a+', 0)
se = open(err_log, 'a+', 0)
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
# Set custom file descriptors so that they get proper buffering.
sys.stdout, sys.stderr = so, se
else:
def become_daemon(our_home_dir='.', out_log=None, err_log=None, umask=022):
"""
If we're not running under a POSIX system, just simulate the daemon
mode by doing redirections and directory changing.
"""
os.chdir(our_home_dir)
os.umask(umask)
sys.stdin.close()
sys.stdout.close()
sys.stderr.close()
if err_log:
sys.stderr = open(err_log, 'a', 0)
else:
sys.stderr = NullDevice()
if out_log:
sys.stdout = open(out_log, 'a', 0)
else:
sys.stdout = NullDevice()
class NullDevice:
"A writeable object that writes to nowhere -- like /dev/null."
def write(self, s):
pass
| apache-2.0 |
minghuascode/pyj | library/pyjamas/ui/DropHandler.py | 9 | 3204 | # Copyright (C) 2010 Jim Washington
#
# 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 pyjamas import DOM
from pyjamas.ui import Event
DROP_EVENTS = [ "dragenter", "dragover", "dragleave", "drop"]
def fireDropEvent(listeners, event):
etype = DOM.eventGetType(event)
if etype == "dragenter":
for listener in listeners:
listener.onDragEnter(event)
return True
elif etype == "dragover":
for listener in listeners:
listener.onDragOver(event)
return True
elif etype == "dragleave":
for listener in listeners:
listener.onDragLeave(event)
return True
elif etype == "drop":
for listener in listeners:
listener.onDrop(event)
return True
return False
class DropHandler(object):
def __init__(self):
self._dropListeners = []
self.sinkEvents(Event.DROPEVENTS)
def onBrowserEvent(self, event):
event_type = DOM.eventGetType(event)
if event_type in DROP_EVENTS:
return fireDropEvent(self._dropListeners, event)
return False
def addDropListener(self, listener):
self._dropListeners.append(listener)
def removeDropListener(self, listener):
self._dropListeners.remove(listener)
def onDragEnter(self,event):
"""
Decide whether to accept the drop.
You may inspect the event's dataTransfer member.
You may get the types using pyjamas.dnd.getTypes(event).
This event is used to determine whether the drop target may
accept the drop. If the drop is to be accepted, then this event has
to be canceled using DOM.eventPreventDefault(event).
"""
pass
def onDragOver(self,event):
"""
This event determines what feedback is to be shown to the user. If
the event is canceled, then the feedback (typically the cursor) is
updated based on the dropEffect attribute's value, as set by the event
handler; otherwise, the default behavior (typically to do nothing)
is used instead.
Setting event.dataTransfer.dropEffect may affect dropping behavior.
Cancel this event with DOM.eventPreventDefault(event) if you want the
drop to succeed.
"""
pass
def onDragLeave(self,event):
"""
This event happens when the mouse leaves the target element.
"""
pass
def onDrop(self,event):
"""allows the actual drop to be performed. This event also needs to be
canceled, so that the dropEffect attribute's value can be used by the
source (otherwise it's reset).
"""
pass
| apache-2.0 |
edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/tests/unittests/test_autoparser.py | 1 | 4415 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Interpreter version: python 2.7
#
# Imports =====================================================================
import pytest
import dhtmlparser
import harvester.edeposit_autoparser as autoparser
# Variables ===================================================================
EXAMPLE_DATA = """
<root>
something something
<sometag>something something</sometag>
<sometag>something something</sometag>
<xax>
something something
<container>i want this</container>
</xax>
<sometag>something something</sometag>
<container id="mycontent">and this</container>
something something
</root>
"""
# Functions & objects =========================================================
def test_create_dom():
data = "<xe>x</xe>"
dom = autoparser._create_dom(data)
assert isinstance(dom, dhtmlparser.HTMLElement)
assert dom.childs[0].parent is dom
# html element from html element
dom = autoparser._create_dom(dom)
assert isinstance(dom, dhtmlparser.HTMLElement)
assert dom.childs[0].parent is dom
def test_locate_element():
data = "<xe>x</xe><xex>x</xex><xer>xx</xer>"
dom = autoparser._create_dom(data)
el = autoparser._locate_element(
dom,
"xx"
)
assert len(el) == 1
assert el[0].isTag()
assert el[0].getTagName() == "xer"
assert el[0].getContent() == "xx"
el = autoparser._locate_element(
dom,
"x"
)
assert len(el) == 2
assert el[0].isTag()
assert el[0].getTagName() == "xe"
assert el[0].getContent() == "x"
def test_locate_element_transformer_param():
data = "<xe>x</xe><xex>x</xex><xer>xx</xer>"
dom = autoparser._create_dom(data)
el = autoparser._locate_element(
dom,
"XX",
lambda x: x.upper()
)
assert len(el) == 1
assert el[0].isTag()
assert el[0].getTagName() == "xer"
assert el[0].getContent() == "xx"
def test_match_elements():
dom = autoparser._create_dom(EXAMPLE_DATA)
matches = {
"first": {
"data": "i want this",
},
"second": {
"data": "and this",
}
}
matching_elements = autoparser._match_elements(dom, matches)
assert matching_elements
assert len(matching_elements) == 2
assert matching_elements["first"].getContent() == matches["first"]["data"]
assert matching_elements["second"].getContent() == matches["second"]["data"]
def test_match_elements_not_found():
dom = autoparser._create_dom(EXAMPLE_DATA)
matches = {
"first": {
"data": "notfound_data",
}
}
with pytest.raises(UserWarning):
autoparser._match_elements(dom, matches)
def test_match_elements_multiple_matches():
dom = autoparser._create_dom(
"""
<root>
something something
<sometag>something something</sometag>
<sometag>something something</sometag>
<xax>
something something
<container>azgabash</container>
</xax>
<sometag>something something</sometag>
<container id="mycontent">azgabash</container>
something something
</root>
"""
)
matches = {
"first": {
"data": "azgabash",
}
}
with pytest.raises(UserWarning):
autoparser._match_elements(dom, matches)
def test_collect_paths():
dom = autoparser._create_dom(EXAMPLE_DATA)
el = dom.find("container")[0]
paths = autoparser._collect_paths(el)
assert paths
assert len(paths) > 5
def test_is_working_path():
dom = autoparser._create_dom(EXAMPLE_DATA)
el = dom.find("container")[0]
paths = autoparser._collect_paths(el)
for path in paths:
assert autoparser._is_working_path(dom, path, el)
def test_select_best_paths():
source = [{
'html': EXAMPLE_DATA,
"vars": {
'first': {
'required': True,
'data': "i want this",
'notfoundmsg': "Can't find variable '$name'."
},
'second': {
'data': 'and this'
},
}
}]
working = autoparser.select_best_paths(source)
assert working
assert len(working) >= 2
| mit |
zerotk/reraiseit | setup.py | 1 | 1574 | #!/bin/env python
from setuptools import setup
setup(
name='zerotk.reraiseit',
use_scm_version=True,
author='Alexandre Andrade',
author_email='[email protected]',
url='https://github.com/zerotk/reraiseit',
description='Reraise exceptions.',
long_description='''A function to re-raise exceptions adding information to the traceback and with unicode support.''',
classifiers=[
# How mature is this project? Common values are
# 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 5 - Production/Stable',
# Indicate who your project is intended for
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
# Pick your license as you wish (should match "license" above)
'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
# Specify the Python versions you support here. In particular, ensure
# that you indicate whether you support Python 2, Python 3 or both.
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
],
include_package_data=True,
packages=['zerotk', 'zerotk.reraiseit'],
namespace_packages=['zerotk'],
keywords=['exception', 'raise', 'reraise'],
install_requires=['six'],
setup_requires=['setuptools_scm', 'pytest-runner'],
tests_require=['pytest', 'coverage', 'cogapp'],
)
| lgpl-3.0 |
rhyolight/nupic | examples/tm/hello_tm.py | 10 | 6174 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
print """
This program shows how to access the Temporal Memory directly by demonstrating
how to create a TM instance, train it with vectors, get predictions, and
inspect the state.
The code here runs a very simple version of sequence learning, with one
cell per column. The TM is trained with the simple sequence A->B->C->D->E
HOMEWORK: once you have understood exactly what is going on here, try changing
cellsPerColumn to 4. What is the difference between once cell per column and 4
cells per column?
PLEASE READ THROUGH THE CODE COMMENTS - THEY EXPLAIN THE OUTPUT IN DETAIL
"""
# Can't live without numpy
import numpy
from itertools import izip as zip, count
from nupic.algorithms.temporal_memory import TemporalMemory as TM
# Utility routine for printing the input vector
def formatRow(x):
s = ''
for c in range(len(x)):
if c > 0 and c % 10 == 0:
s += ' '
s += str(x[c])
s += ' '
return s
# Step 1: create Temporal Pooler instance with appropriate parameters
tm = TM(columnDimensions = (50,),
cellsPerColumn=2,
initialPermanence=0.5,
connectedPermanence=0.5,
minThreshold=8,
maxNewSynapseCount=20,
permanenceIncrement=0.1,
permanenceDecrement=0.0,
activationThreshold=8,
)
# Step 2: create input vectors to feed to the temporal memory. Each input vector
# must be numberOfCols wide. Here we create a simple sequence of 5 vectors
# representing the sequence A -> B -> C -> D -> E
x = numpy.zeros((5, tm.numberOfColumns()), dtype="uint32")
x[0, 0:10] = 1 # Input SDR representing "A", corresponding to columns 0-9
x[1, 10:20] = 1 # Input SDR representing "B", corresponding to columns 10-19
x[2, 20:30] = 1 # Input SDR representing "C", corresponding to columns 20-29
x[3, 30:40] = 1 # Input SDR representing "D", corresponding to columns 30-39
x[4, 40:50] = 1 # Input SDR representing "E", corresponding to columns 40-49
# Step 3: send this simple sequence to the temporal memory for learning
# We repeat the sequence 10 times
for i in range(10):
# Send each letter in the sequence in order
for j in range(5):
activeColumns = set([i for i, j in zip(count(), x[j]) if j == 1])
# The compute method performs one step of learning and/or inference. Note:
# here we just perform learning but you can perform prediction/inference and
# learning in the same step if you want (online learning).
tm.compute(activeColumns, learn = True)
# The following print statements can be ignored.
# Useful for tracing internal states
print("active cells " + str(tm.getActiveCells()))
print("predictive cells " + str(tm.getPredictiveCells()))
print("winner cells " + str(tm.getWinnerCells()))
print("# of active segments " + str(tm.connections.numSegments()))
# The reset command tells the TM that a sequence just ended and essentially
# zeros out all the states. It is not strictly necessary but it's a bit
# messier without resets, and the TM learns quicker with resets.
tm.reset()
#######################################################################
#
# Step 3: send the same sequence of vectors and look at predictions made by
# temporal memory
for j in range(5):
print "\n\n--------","ABCDE"[j],"-----------"
print "Raw input vector : " + formatRow(x[j])
activeColumns = set([i for i, j in zip(count(), x[j]) if j == 1])
# Send each vector to the TM, with learning turned off
tm.compute(activeColumns, learn = False)
# The following print statements prints out the active cells, predictive
# cells, active segments and winner cells.
#
# What you should notice is that the columns where active state is 1
# represent the SDR for the current input pattern and the columns where
# predicted state is 1 represent the SDR for the next expected pattern
print "\nAll the active and predicted cells:"
print("active cells " + str(tm.getActiveCells()))
print("predictive cells " + str(tm.getPredictiveCells()))
print("winner cells " + str(tm.getWinnerCells()))
print("# of active segments " + str(tm.connections.numSegments()))
activeColumnsIndeces = [tm.columnForCell(i) for i in tm.getActiveCells()]
predictedColumnIndeces = [tm.columnForCell(i) for i in tm.getPredictiveCells()]
# Reconstructing the active and inactive columns with 1 as active and 0 as
# inactive representation.
actColState = ['1' if i in activeColumnsIndeces else '0' for i in range(tm.numberOfColumns())]
actColStr = ("".join(actColState))
predColState = ['1' if i in predictedColumnIndeces else '0' for i in range(tm.numberOfColumns())]
predColStr = ("".join(predColState))
# For convenience the cells are grouped
# 10 at a time. When there are multiple cells per column the printout
# is arranged so the cells in a column are stacked together
print "Active columns: " + formatRow(actColStr)
print "Predicted columns: " + formatRow(predColStr)
# predictedCells[c][i] represents the state of the i'th cell in the c'th
# column. To see if a column is predicted, we can simply take the OR
# across all the cells in that column. In numpy we can do this by taking
# the max along axis 1.
| agpl-3.0 |
florian-dacosta/OCB | openerp/addons/test_convert/tests/test_convert.py | 382 | 2303 | import collections
import unittest2
from lxml import etree as ET
from lxml.builder import E
from openerp.tests import common
from openerp.tools.convert import _eval_xml
Field = E.field
Value = E.value
class TestEvalXML(common.TransactionCase):
def eval_xml(self, node, obj=None, idref=None):
return _eval_xml(obj, node, pool=None, cr=self.cr, uid=self.uid,
idref=idref, context=None)
def test_char(self):
self.assertEqual(
self.eval_xml(Field("foo")),
"foo")
self.assertEqual(
self.eval_xml(Field("None")),
"None")
def test_int(self):
self.assertIsNone(
self.eval_xml(Field("None", type='int')),
"what the fuck?")
self.assertEqual(
self.eval_xml(Field(" 42 ", type="int")),
42)
with self.assertRaises(ValueError):
self.eval_xml(Field("4.82", type="int"))
with self.assertRaises(ValueError):
self.eval_xml(Field("Whelp", type="int"))
def test_float(self):
self.assertEqual(
self.eval_xml(Field("4.78", type="float")),
4.78)
with self.assertRaises(ValueError):
self.eval_xml(Field("None", type="float"))
with self.assertRaises(ValueError):
self.eval_xml(Field("Foo", type="float"))
def test_list(self):
self.assertEqual(
self.eval_xml(Field(type="list")),
[])
self.assertEqual(
self.eval_xml(Field(
Value("foo"),
Value("5", type="int"),
Value("4.76", type="float"),
Value("None", type="int"),
type="list"
)),
["foo", 5, 4.76, None])
def test_file(self):
Obj = collections.namedtuple('Obj', 'module')
obj = Obj('test_convert')
self.assertEqual(
self.eval_xml(Field('test_file.txt', type='file'), obj),
'test_convert,test_file.txt')
with self.assertRaises(IOError):
self.eval_xml(Field('test_nofile.txt', type='file'), obj)
@unittest2.skip("not tested")
def test_xml(self):
pass
@unittest2.skip("not tested")
def test_html(self):
pass
| agpl-3.0 |
battlehorse/rhizosphere | appengine/src/py/handlers/showcase/googlecode.py | 1 | 9970 | #!/usr/bin/env python
#
# Copyright 2010 The Rhizosphere 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.
import base64
import datetime
import os.path
import re
_GDATA_LIBS_FOUND = True
try:
import gdata.auth
import gdata.service
import gdata.alt.appengine
except ImportError:
_GDATA_LIBS_FOUND = False
from google.appengine.api import urlfetch
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from py import rhizoglobals
from py.models import googlecode
class BaseHandler(webapp.RequestHandler):
"""Base class with common methods."""
def _GetGDataClient(self):
client = gdata.service.GDataService(server='code.google.com',
source='Rhizosphere')
gdata.alt.appengine.run_on_appengine(client)
return client
def _Respond(self, template_file, template_values):
path = os.path.join(os.path.dirname(__file__),
'../../../templates/showcase/code/%s' % template_file)
self.response.out.write(template.render(path, template_values))
def _RespondError(self, error_msg):
template_values = rhizoglobals.DefaultTemplate(self.request)
template_values.update({'error': error_msg})
self._QueryStringToTemplate(template_values)
platform, device = rhizoglobals.IdentifyPlatformDevice(self.request)
smartphone = rhizoglobals.IsSmartphone(platform, device)
if smartphone:
self._Respond('codeindexmobile.html', template_values)
else:
self._Respond('codeindex.html', template_values)
def _QueryStringToTemplate(self, template_values):
qs = dict((qp, self.request.get(qp)) for qp in self.request.arguments())
template_values['qs'] = qs
class AuthHandler(BaseHandler):
"""Callback for AuthSub requests to access a user private feeds."""
def _ExtractAndSaveToken(self, client):
auth_token = gdata.auth.extract_auth_sub_token_from_url(self.request.url)
if not auth_token:
return None
session_token = client.upgrade_to_session_token(auth_token)
if session_token and users.get_current_user():
client.token_store.add_token(session_token)
elif session_token:
client.current_token = session_token
return session_token
def get(self):
client = self._GetGDataClient()
session_token = self._ExtractAndSaveToken(client)
if not session_token:
# The user hasn't granted access to his feeds.
self._RespondError('Cannot fulfill the request without '
'access to your Google Code data.')
return
# Sets the auth token in a cookie that will live to the end of the
# browser session.
client.current_token = session_token
self.response.headers.add_header(
'Set-Cookie',
'stk=%s' % base64.b64encode(client.GetAuthSubToken()))
# scrub the AuthSub-specific query parameters.
query_string = []
for query_param in self.request.arguments():
if query_param not in ['token', 'auth_sub_scopes']:
query_string.append('%s=%s' % (query_param, self.request.get(query_param)))
# Redirect back to the fetch handler.
self.redirect('/showcase/code/rhizo?%s' % '&'.join(query_string))
class FetchHandler(BaseHandler):
"""Fetches issues from Google Code and feeds them to a Rhizosphere viz."""
def _RedirectToAuthSub(self, client):
next_url = 'http://%s/showcase/code/auth?%s' % (
rhizoglobals.HostName(), self.request.query_string)
scope = 'http://code.google.com/feeds/issues'
auth_sub_url = client.GenerateAuthSubURL(
next_url, scope, secure=False, session=True)
self.response.set_status(302)
self.response.headers['Location'] = auth_sub_url
self.response.clear()
return
def _GetDateParam(self, param):
date_str = self.request.get(param)
if not date_str:
return None
m = re.search('(\d+)([wmd])', date_str)
if not m:
return None
multiplier = {'w': 7, 'm': 31, 'd': 1}
days_ago = int(m.group(1))*multiplier[m.group(2)]
target_date = datetime.datetime.now() - datetime.timedelta(days_ago)
return target_date.strftime('%Y-%m-%dT%H:%M:%S')
def _GetParams(self):
project = self.request.get('p')
if not project:
self._RespondError('You must specify a project name.')
return None
detail = self.request.get('det')
if detail not in ['all', 'compressed']:
detail = 'compressed'
if self.request.get('n') == 'max':
num_results = 10000
else:
num_results = self.request.get_range('n', 1, 10000, 1000)
canned_query = self.request.get('can')
if canned_query not in ['all', 'open', 'owned', 'reported',
'starred', 'new', 'to-verify']:
canned_query = 'all'
created_min = self._GetDateParam('pub')
updated_min = self._GetDateParam('upd')
return {
'project': project,
'detail': detail,
'num_results': num_results,
'canned_query': canned_query,
'created_min': created_min,
'updated_min': updated_min,
}
def _BuildFeedUrl(self, params):
feed_url = '/feeds/issues/p/%s/issues/full?max-results=%d&can=%s' % (
params['project'], params['num_results'], params['canned_query'])
if params.get('created_min'):
feed_url = '%s&published-min=%s' % (feed_url, params['created_min'])
if params.get('updated_min'):
feed_url = '%s&updated-min=%s' % (feed_url, params['updated_min'])
return feed_url
def get(self):
client = self._GetGDataClient()
if 'stk' in self.request.cookies:
token = gdata.auth.AuthSubToken()
token.set_token_string(base64.b64decode(self.request.cookies['stk']))
client.current_token = token
params = self._GetParams()
if not params:
# Params are malformed.
return
if (params['canned_query'] in ['owned', 'reported', 'starred'] and
not client.GetAuthSubToken()):
# We need the user credentials to retrieve this kind of feeds.
self._RedirectToAuthSub(client)
return
try:
feed_url = self._BuildFeedUrl(params)
feed = client.GetFeed(feed_url)
except urlfetch.DownloadError, er:
if 'timed out' in er[0]:
self._RespondError('The request timed out. Try again in a few seconds, '
'or set the advanced options to extract fewer '
'issues.')
else:
self._RespondError(
'An error occurred while fetching %s project data. '
'Try again in a few seconds, or set the advanced options to '
'extract fewer issues. (%s)' %
(params['project'], er))
return
except urlfetch.Error, er:
self._RespondError(
'An error occurred while fetching %s project data. '
'Try again in a few seconds, or set the advanced options to '
'extract fewer issues. (%s)' %
(params['project'], er))
return
except gdata.service.RequestError, er:
if er[0]['status'] == 404:
self._RespondError('Project %s does not exist' % params['project'])
else:
self._RespondError(
'Unable to fetch %s project data: %s' % (
params['project'], er[0]['body']))
return
issues = [ googlecode.Issue(entry) for entry in feed.entry]
if not len(issues):
self._RespondError('Your query didn\'t return any result.')
return
template_values = rhizoglobals.DefaultTemplate(self.request)
template_values.update(params)
if self.request.get('gdatadebug') == '1':
template_values['issues'] = issues
self._Respond('codedebug.html', template_values)
else:
platform, device = rhizoglobals.IdentifyPlatformDevice(self.request)
smartphone = rhizoglobals.IsSmartphone(platform, device)
jsonifier = googlecode.JSONHelper()
json_issues = [jsonifier.IssueToJSON(issue) for issue in issues]
stats = googlecode.IssueStats()
stats.Compute(issues)
json_stats = jsonifier.StatsToJSON(stats)
template_values.update({'issues': json_issues,
'stats': json_stats,
'platform': platform,
'device': device,
'smartphone': smartphone})
self._Respond('coderhizo.html', template_values)
class WelcomeHandler(BaseHandler):
"""Serves the welcome page to the Google Code Hosting showcase app."""
def get(self):
template_values = rhizoglobals.DefaultTemplate(self.request)
if not _GDATA_LIBS_FOUND:
self._RespondError("GData libraries not found. "
"Have you included the GData libraries?")
return
platform, device = rhizoglobals.IdentifyPlatformDevice(self.request)
smartphone = rhizoglobals.IsSmartphone(platform, device)
if smartphone:
self._Respond('codeindexmobile.html', template_values)
else:
self._Respond('codeindex.html', template_values)
application = webapp.WSGIApplication(
[('/showcase/code', WelcomeHandler),
('/showcase/code/', WelcomeHandler),
('/showcase/code/rhizo', FetchHandler),
('/showcase/code/auth', AuthHandler),],
debug=rhizoglobals.appenginedebug)
def main():
run_wsgi_app(application)
if __name__ == '__main__':
main()
| apache-2.0 |
algorhythms/LintCode | Interleaving Positive and Negative Numbers.py | 1 | 1350 | """
Given an array with positive and negative integers. Re-range it to interleaving with positive and negative integers.
Have you met this question in a real interview? Yes
Example
Given [-1, -2, -3, 4, 5, 6], after re-range, it will be [-1, 5, -2, 4, -3, 6] or any other reasonable answer.
Note
You are not necessary to keep the original order of positive integers or negative integers.
Challenge
Do it in-place and without extra memory.
"""
__author__ = 'Daniel'
class Solution(object):
def rerange(self, A):
"""
Algorithm: Two Pointers
:type A: List[int]
:rtype: None, in-place
"""
n = len(A)
pos_cnt = len(filter(lambda x: x > 0, A))
# expecting positive
pos_expt = True if pos_cnt*2 > n else False
neg = 0 # next negative
pos = 0 # next positive
for i in xrange(n):
while neg < n and A[neg] > 0: neg += 1
while pos < n and A[pos] < 0: pos += 1
if pos_expt:
A[i], A[pos] = A[pos], A[i]
else:
A[i], A[neg] = A[neg], A[i]
if i == neg: neg += 1
if i == pos: pos += 1
pos_expt = not pos_expt
if __name__ == "__main__":
A = [-33, -19, 30, 26, 21, -9]
Solution().rerange(A)
assert A == [-33, 30, -19, 26, -9, 21] | apache-2.0 |
barbuza/django | django/contrib/gis/db/backends/mysql/introspection.py | 700 | 1771 | from MySQLdb.constants import FIELD_TYPE
from django.contrib.gis.gdal import OGRGeomType
from django.db.backends.mysql.introspection import DatabaseIntrospection
class MySQLIntrospection(DatabaseIntrospection):
# Updating the data_types_reverse dictionary with the appropriate
# type for Geometry fields.
data_types_reverse = DatabaseIntrospection.data_types_reverse.copy()
data_types_reverse[FIELD_TYPE.GEOMETRY] = 'GeometryField'
def get_geometry_type(self, table_name, geo_col):
cursor = self.connection.cursor()
try:
# In order to get the specific geometry type of the field,
# we introspect on the table definition using `DESCRIBE`.
cursor.execute('DESCRIBE %s' %
self.connection.ops.quote_name(table_name))
# Increment over description info until we get to the geometry
# column.
for column, typ, null, key, default, extra in cursor.fetchall():
if column == geo_col:
# Using OGRGeomType to convert from OGC name to Django field.
# MySQL does not support 3D or SRIDs, so the field params
# are empty.
field_type = OGRGeomType(typ).django
field_params = {}
break
finally:
cursor.close()
return field_type, field_params
def supports_spatial_index(self, cursor, table_name):
# Supported with MyISAM, or InnoDB on MySQL 5.7.5+
storage_engine = self.get_storage_engine(cursor, table_name)
return (
(storage_engine == 'InnoDB' and self.connection.mysql_version >= (5, 7, 5)) or
storage_engine == 'MyISAM'
)
| bsd-3-clause |
UK992/servo | etc/wpt-summarize.py | 4 | 1754 | #!/usr/bin/env python
# Copyright 2019 The Servo Project Developers. See the COPYRIGHT
# file at the top-level directory of this distribution.
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
# option. This file may not be copied, modified, or distributed
# except according to those terms.
# Usage: python wpt-summarize.py /wpt/test/url.html [--full]
#
# Extract all log lines for a particular test file from a WPT
# logs, outputting invidual JSON objects that can be manipulated
# with tools like jq. If a particular URL results in no output,
# the URL is likely used as a reference test's reference file,
# so passing `--full` will find any output from Servo process
# command lines that include the URL.
import sys
import json
full_search = len(sys.argv) > 3 and sys.argv[3] == '--full'
with open(sys.argv[1]) as f:
data = f.readlines()
thread = None
for entry in data:
entry = json.loads(entry)
if thread and "thread" in entry:
if entry["thread"] == thread:
print(json.dumps(entry))
if "action" in entry and entry["action"] == "test_end":
thread = None
else:
if ("action" in entry and
entry["action"] == "test_start" and
entry["test"] == sys.argv[2]):
thread = entry["thread"]
print(json.dumps(entry))
elif (full_search and
"command" in entry and
sys.argv[2] in entry["command"]):
thread = entry["thread"]
print(json.dumps(entry))
| mpl-2.0 |
fichter/grpc | src/python/grpcio/grpc/framework/base/null.py | 39 | 2106 | # Copyright 2015, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Null links that ignore tickets passed to them."""
from grpc.framework.base import interfaces
class _NullForeLink(interfaces.ForeLink):
"""A do-nothing ForeLink."""
def accept_back_to_front_ticket(self, ticket):
pass
def join_rear_link(self, rear_link):
raise NotImplementedError()
class _NullRearLink(interfaces.RearLink):
"""A do-nothing RearLink."""
def accept_front_to_back_ticket(self, ticket):
pass
def join_fore_link(self, fore_link):
raise NotImplementedError()
NULL_FORE_LINK = _NullForeLink()
NULL_REAR_LINK = _NullRearLink()
| bsd-3-clause |
Gjacquenot/PyRayTracer | raytracer/raytrace-receiver2.py | 1 | 38736 | # -*- coding: utf-8 -*-
"""
@author: Jaap Verheggen, Guillaume Jacquenot
"""
from __future__ import division
import vtk
import numpy as np
import vtk.util.numpy_support as ns
import raytracer as ray
cosd = lambda angle: np.cos(angle / 180 * np.pi)
sind = lambda angle: np.sin(angle / 180 * np.pi)
tand = lambda angle: np.tan(angle / 180 * np.pi)
def glyphs(cells, color=(1.0, 1.0, 1.0), size=1):
# Visualize normals as done previously but using refracted or reflected cells
arrow = vtk.vtkArrowSource()
glyphCell = vtk.vtkGlyph3D()
glyphCell.SetInputData(cells)
glyphCell.SetSourceConnection(arrow.GetOutputPort())
glyphCell.SetVectorModeToUseNormal()
glyphCell.SetScaleFactor(size)
glyphMapperCell = vtk.vtkPolyDataMapper()
glyphMapperCell.SetInputConnection(glyphCell.GetOutputPort())
glyphActorCell = vtk.vtkActor()
glyphActorCell.SetMapper(glyphMapperCell)
glyphActorCell.GetProperty().SetColor(color)
return glyphActorCell
def getnormals(surf, vertices=False, flip=False):
# Calculate normals
normals = vtk.vtkPolyDataNormals()
normals.SetOutputPointsPrecision(vtk.vtkAlgorithm.DOUBLE_PRECISION)
normals.SetInputData(surf.GetOutput())
if vertices:
# Enable normal calculation at cell vertices
normals.ComputePointNormalsOn()
# Disable normal calculation at cell centers
normals.ComputeCellNormalsOff()
else:
# Disable normal calculation at cell vertices
normals.ComputePointNormalsOff()
# Enable normal calculation at cell centers
normals.ComputeCellNormalsOn()
# Disable splitting of sharp edges
normals.ConsistencyOn()
normals.SplittingOff()
# Disable global flipping of normal orientation
if flip:
normals.FlipNormalsOn()
print('flip is true')
else:
normals.FlipNormalsOff()
# Enable automatic determination of correct normal orientation
# normals.AutoOrientNormalsOn()
# Perform calculation
normals.Update()
# Create dummy array for glyphs
if vertices:
verticepoints = surf.GetOutput().GetPoints()
normal_polydata = normals.GetOutput()
return normal_polydata, verticepoints
else:
normalcellcenters = vtk.vtkCellCenters()
normalcellcenters.VertexCellsOn()
normalcellcenters.SetInputConnection(normals.GetOutputPort())
normalcellcenters.Update()
#
pointsCellCenters = normalcellcenters.GetOutput(0)
normal_points = vtk.vtkPoints()
normal_points.SetDataTypeToDouble()
# Vectors where intersections are found
normal_vectors = vtk.vtkDoubleArray()
normal_vectors.SetNumberOfComponents(3)
# Loop through all point centers and add a point-actor through 'addPoint'
for idx in range(pointsCellCenters.GetNumberOfPoints()):
normal_points.InsertNextPoint(pointsCellCenters.GetPoint(idx))
normalsurf2 = normalcellcenters.GetOutput().GetCellData().GetNormals().GetTuple(idx)
# Insert the normal vector of the intersection cell in the dummy container
normal_vectors.InsertNextTuple(normalsurf2)
# Need to transform polydatanormals to polydata so I can reuse functions
normal_polydata = vtk.vtkPolyData()
normal_polydata.SetPoints(normal_points)
normal_polydata.GetPointData().SetNormals(normal_vectors)
return normal_polydata, normalcellcenters.GetOutput()
def stop(ren, appendFilter, srf1, srf2):
# rays between two surfaces. A stop.
obbsurf2 = vtk.vtkOBBTree()
obbsurf2.SetDataSet(srf2['surface'].GetOutput())
obbsurf2.BuildLocator()
# where intersections are found
intersection_points = vtk.vtkPoints()
intersection_points.SetDataTypeToDouble()
# Loop through all of surface1 cell-centers
for idx in range(srf1['raypoints'].GetNumberOfPoints()):
# Get coordinates of surface1 cell center
pointSurf1 = srf1['raypoints'].GetPoint(idx)
# Get incident vector at that cell
normalsurf1 = srf1['rays'].GetPointData().GetNormals().GetTuple(idx)
# Calculate the 'target' of the ray based on 'RayCastLength'
pointRaySurf2 = list(np.array(pointSurf1) + ray.RayCastLength * np.array(normalsurf1))
# Check if there are any intersections for the given ray
if ray.isHit(obbsurf2, pointSurf1, pointRaySurf2):
# Retrieve coordinates of intersection points and intersected cell ids
pointsInter, cellIdsInter = ray.getIntersect(obbsurf2, pointSurf1, pointRaySurf2)
# print(cellIdsInter)
# Render lines/rays emanating from the Source. Rays that intersect are
ray.addLine(ren, appendFilter, pointSurf1, pointsInter[0], [1.0, 1.0, 0.0], opacity=0.25)
# Insert the coordinates of the intersection point in the dummy container
intersection_points.InsertNextPoint(pointsInter[0])
return intersection_points
def flat(srf):
# Setup four points
points = vtk.vtkPoints()
points.SetDataTypeToDouble()
points.InsertNextPoint(-0.5 * srf['width'], -0.5 * srf['height'], 0.0)
points.InsertNextPoint(+0.5 * srf['width'], -0.5 * srf['height'], 0.0)
points.InsertNextPoint(+0.5 * srf['width'], +0.5 * srf['height'], 0.0)
points.InsertNextPoint(-0.5 * srf['width'], +0.5 * srf['height'], 0.0)
# Create the polygon
polygon = vtk.vtkPolygon()
polygon.GetPointIds().SetNumberOfIds(4) # make a quad
polygon.GetPointIds().SetId(0, 0)
polygon.GetPointIds().SetId(1, 1)
polygon.GetPointIds().SetId(2, 2)
polygon.GetPointIds().SetId(3, 3)
# Add the polygon to a list of polygons
polygons = vtk.vtkCellArray()
polygons.InsertNextCell(polygon)
# Create a PolyData
polygonPolyData = vtk.vtkPolyData()
polygonPolyData.SetPoints(points)
polygonPolyData.SetPolys(polygons)
# rotate and translate
transform = vtk.vtkTransform()
transform.PostMultiply()
if 'rotateWXYZ' in srf:
transform.RotateWXYZ(srf['rotateWXYZ'][0], srf['rotateWXYZ'][1:])
if 'center' in srf:
transform.Translate(srf['center'])
pgt = vtk.vtkTransformPolyDataFilter()
pgt.SetOutputPointsPrecision(vtk.vtkAlgorithm.DOUBLE_PRECISION)
pgt.SetTransform(transform)
pgt.SetInputData(polygonPolyData)
pgt.Update()
extrude = pgt
# Subdivision filters only work on triangles
triangles = vtk.vtkTriangleFilter()
triangles.SetInputConnection(extrude.GetOutputPort())
triangles.Update()
# Lets subdivide it for no reason at all
return triangles
def cylinder(srf):
source = vtk.vtkArcSource()
z1 = srf['curvx'] - (srf['curvx'] / abs(srf['curvx'])) * np.sqrt(srf['curvx']**2 - (srf['width'] / 2)**2) # s +/- sqrt(s^2-(w/2)^2)
x1 = +0.5 * srf['width']
y1 = -0.5 * srf['height']
source.SetCenter(0, y1, srf['curvx'])
source.SetPoint1(x1, y1, z1)
source.SetPoint2(-x1, y1, z1)
source.SetResolution(srf['resolution'])
# Linear extrude arc
extrude = vtk.vtkLinearExtrusionFilter()
extrude.SetInputConnection(source.GetOutputPort())
extrude.SetExtrusionTypeToVectorExtrusion()
extrude.SetVector(0, 1, 0)
extrude.SetScaleFactor(srf['height'])
extrude.Update()
# Rotate and translate
transform = vtk.vtkTransform()
transform.PostMultiply()
if 'rotateWXYZ' in srf:
transform.RotateWXYZ(srf['rotateWXYZ'][0], srf['rotateWXYZ'][1:])
if 'center' in srf:
transform.Translate(srf['center'])
pgt = vtk.vtkTransformPolyDataFilter()
pgt.SetOutputPointsPrecision(vtk.vtkAlgorithm.DOUBLE_PRECISION)
pgt.SetTransform(transform)
pgt.SetInputData(extrude.GetOutput())
pgt.Update()
extrude = pgt
# Subdivision filters only work on triangles
triangles = vtk.vtkTriangleFilter()
triangles.SetInputConnection(extrude.GetOutputPort())
triangles.Update()
# Lets subdivide it for no reason at all
return triangles
def asphere(srf):
# Delaunay mesh
dr = (srf['diameter']) / 2 / (srf['resolution'] - 1) # radius
R = srf['coeffs']['R']
k = srf['coeffs']['k']
polyVal = lambda x: sum([srf['coeffs']['A' + str(p)] * x**p for p in range(2, 14, 2)])
sizep = [sum([1 + x * 5 for x in range(srf['resolution'])]), 3]
array_xyz = np.empty(sizep)
cnt = 0
for ii in range(srf['resolution']):
for ss in range(1 + ii * 5):
phi = ss * 2 / (1 + ii * 5)
r = dr * ii
xx = np.sin(np.pi * phi) * r
yy = np.cos(np.pi * phi) * r
zz = r**2 / (R * (1 + np.sqrt(1 - (1 + k) * r**2 / R**2))) + polyVal(r)
array_xyz[cnt] = np.array([xx, yy, zz])
cnt += 1
# Second pass optimization
if 'raypoints' in srf:
# Opposite transformations
i_points = vtk.vtkPolyData()
i_points.SetPoints(srf['raypoints'])
transform = vtk.vtkTransform()
transform.PostMultiply()
if 'center' in srf:
transform.Translate([-p for p in srf['center']])
if 'rotateWXYZ' in srf:
transform.RotateWXYZ(-srf['rotateWXYZ'][0], srf['rotateWXYZ'][1:])
pgt = vtk.vtkTransformPolyDataFilter()
pgt.SetOutputPointsPrecision(vtk.vtkAlgorithm.DOUBLE_PRECISION)
pgt.SetTransform(transform)
pgt.SetInputData(i_points)
pgt.Update()
# Get intersection point array
parray_xyz = ns.vtk_to_numpy(i_points.GetPoints().GetData())
# Add 2nd pass arrays ath these points
refine = srf['resolution'] * 100
res = 4 # was srf['resolution']
d2r = (srf['diameter']) / 2 / (refine - 1)
for xyz in parray_xyz:
cnt = 0
rxy = np.hypot(xyz[0], xyz[1])
if rxy > d2r * (res + 1):
phic = np.arctan2(xyz[0], xyz[1])
r_range = int(np.ceil((rxy / (srf['diameter'] / 2)) * refine))
# Counter to get size of array
var = 0
for ii in range(r_range - res, r_range + res): # was 10
phi_range = int(np.ceil((phic / (2 * np.pi)) * (1 + ii * 5)))
for ss in range(phi_range - res, phi_range + res):
var += 1
sizep = [var, 3]
arr2nd_xyz = np.empty(sizep)
for ii in range(r_range - res, r_range + res): # was 10
phi_range = int(np.ceil((phic / (2 * np.pi)) * (1 + ii * 5)))
for ss in range(phi_range - res, phi_range + res):
phi = ss * 2 / (1 + ii * 5)
r = d2r * ii
xx = np.sin(np.pi * phi) * r
yy = np.cos(np.pi * phi) * r
zz = r**2 / (R * (1 + np.sqrt(1 - (1 + k) * r**2 / R**2))) + polyVal(r)
arr2nd_xyz[cnt] = np.array([xx, yy, zz])
cnt += 1
else:
sizep = [sum([1 + x * 5 for x in range(srf['resolution'])]), 3]
arr2nd_xyz = np.empty(sizep)
cnt = 0
for ii in range(srf['resolution']):
for ss in range(1 + ii * 5):
phi = ss * 2 / (1 + ii * 5)
r = d2r * ii
xx = np.sin(np.pi * phi) * r
yy = np.cos(np.pi * phi) * r
zz = r**2 / (R * (1 + np.sqrt(1 - (1 + k) * r**2 / R**2))) + polyVal(r)
arr2nd_xyz[cnt] = np.array([xx, yy, zz])
cnt += 1
array_xyz = np.vstack((array_xyz, arr2nd_xyz))
# Delete non unique values
b = np.ascontiguousarray(array_xyz).view(np.dtype((np.void, array_xyz.dtype.itemsize * array_xyz.shape[1])))
_, idx = np.unique(b, return_index=True)
unique_a = array_xyz[idx]
# I need to sort this in spherical coordinates, first phi, then theta then r
rtp_a = ray.Cartesian2Spherical(unique_a[1:]) # Skip 0,0,0
rtp_a = np.vstack((np.array([0.0, 0.0, 0.0]), rtp_a))
# Now sort
ind = np.lexsort((rtp_a[:, 2], rtp_a[:, 1], rtp_a[:, 0])) # Sort by a, then by b
sorted_rtp = rtp_a[ind]
sorted_xyz = ray.Spherical2Cartesian(sorted_rtp)
else:
sorted_xyz = array_xyz
# numpy array to vtk array
pcoords = ns.numpy_to_vtk(num_array=sorted_xyz, deep=True, array_type=vtk.VTK_DOUBLE)
# Shove coordinates in points container
points = vtk.vtkPoints()
points.SetDataTypeToDouble()
points.SetData(pcoords)
# Create a polydata object
point_pd = vtk.vtkPolyData()
# Set the points and vertices we created as the geometry and topology of the polydata
point_pd.SetPoints(points)
# make the delaunay mesh
delaunay = vtk.vtkDelaunay2D()
if vtk.VTK_MAJOR_VERSION < 6:
delaunay.SetInput(point_pd)
else:
delaunay.SetInputData(point_pd)
# delaunay.SetTolerance(0.00001)
delaunay.Update()
# Rotate and translate
transform = vtk.vtkTransform()
transform.PostMultiply()
if 'rotateWXYZ' in srf:
transform.RotateWXYZ(srf['rotateWXYZ'][0], srf['rotateWXYZ'][1:])
if 'center' in srf:
transform.Translate(srf['center'])
pgt = vtk.vtkTransformPolyDataFilter()
pgt.SetOutputPointsPrecision(vtk.vtkAlgorithm.DOUBLE_PRECISION)
pgt.SetTransform(transform)
if vtk.VTK_MAJOR_VERSION < 6:
pgt.SetInput(delaunay.GetOutput())
else:
pgt.SetInputData(delaunay.GetOutput())
pgt.Update()
delaunay = pgt
# Rotate polydata
return delaunay
def flatcircle(srf):
# Create rotational filter of a straight line
dx = (srf['diameter']) / 2 / (srf['resolution'] - 1) # radius
# print(dx, dx * srf['resolution'])
points = vtk.vtkPoints()
line = vtk.vtkLine()
lines = vtk.vtkCellArray()
for ii in range(srf['resolution']):
xx, yy, zz = dx * ii, 0, 0
points.InsertNextPoint(xx, yy, zz)
if ii != (srf['resolution'] - 1):
line.GetPointIds().SetId(0, ii)
line.GetPointIds().SetId(1, ii + 1)
lines.InsertNextCell(line)
# Create a PolyData
polygonPolyData = vtk.vtkPolyData()
polygonPolyData.SetPoints(points)
polygonPolyData.SetLines(lines)
# Radial extrude polygon
extrude = vtk.vtkRotationalExtrusionFilter()
if vtk.VTK_MAJOR_VERSION < 6:
extrude.SetInput(polygonPolyData)
else:
extrude.SetInputData(polygonPolyData)
extrude.CappingOff()
extrude.SetResolution(srf['angularresolution'])
extrude.Update()
# It would be best to rotate it by 360/res, so simple rays
# don't hit eges and low res can be used
rotate = vtk.vtkTransform()
rotate.RotateWXYZ(180 / srf['angularresolution'], 0, 0, 1)
pgt = vtk.vtkTransformPolyDataFilter()
pgt.SetTransform(rotate)
if vtk.VTK_MAJOR_VERSION < 6:
pgt.SetInput(extrude.GetOutput())
else:
pgt.SetInputData(extrude.GetOutput())
pgt.Update()
extrude = pgt
# stretch, rotate and translate
transform = vtk.vtkTransform()
transform.PostMultiply()
if 'scalex' in srf:
transform.Scale(srf['scalex'], 1.0, 1.0)
if 'rotateWXYZ' in srf:
transform.RotateWXYZ(srf['rotateWXYZ'][0], srf['rotateWXYZ'][1:])
if 'center' in srf:
transform.Translate(srf['center'])
pgt = vtk.vtkTransformPolyDataFilter()
pgt.SetOutputPointsPrecision(vtk.vtkAlgorithm.DOUBLE_PRECISION)
pgt.SetTransform(transform)
if vtk.VTK_MAJOR_VERSION < 6:
pgt.SetInput(extrude.GetOutput())
else:
pgt.SetInputData(extrude.GetOutput())
pgt.Update()
extrude = pgt
# Subdivision filters only work on triangles
triangles = vtk.vtkTriangleFilter()
triangles.SetInputConnection(extrude.GetOutputPort())
triangles.Update()
# Create a mapper and actor
return triangles
def sphere(srf):
# Create and configure sphere, using delaunay mesh
dr = (srf['diameter']) / 2 / (srf['resolution'] - 1) # radius
R = srf['radius']
sizep = [sum([1 + x * 5 for x in range(srf['resolution'])]), 3]
array_xyz = np.empty(sizep)
cnt = 0
for ii in range(srf['resolution']):
for ss in range(1 + ii * 5):
phi = ss * 2 / (1 + ii * 5)
r = dr * ii
xx = np.sin(np.pi * phi) * r
yy = np.cos(np.pi * phi) * r
zz = R * (1 - np.sqrt(1 - (r / R)**2))
array_xyz[cnt] = np.array([xx, yy, zz])
cnt += 1
# Second pass optimization
if 'raypoints' in srf:
# Opposite transformations
i_points = vtk.vtkPolyData()
i_points.SetPoints(srf['raypoints'])
transform = vtk.vtkTransform()
transform.PostMultiply()
if 'center' in srf:
transform.Translate([-p for p in srf['center']])
if 'rotateWXYZ' in srf:
transform.RotateWXYZ(-srf['rotateWXYZ'][0], srf['rotateWXYZ'][1:])
pgt = vtk.vtkTransformPolyDataFilter()
pgt.SetOutputPointsPrecision(vtk.vtkAlgorithm.DOUBLE_PRECISION)
pgt.SetTransform(transform)
pgt.SetInputData(i_points)
if vtk.VTK_MAJOR_VERSION < 6:
pgt.SetInput(i_points)
else:
pgt.SetInputData(i_points)
pgt.Update()
# Get intersection point array
parray_xyz = ns.vtk_to_numpy(pgt.GetOutput().GetPoints().GetData())
# Add 2nd pass arrays ath these points
refine = srf['resolution'] * 100
res = 4 # was srf['resolution']
d2r = (srf['diameter']) / 2 / (refine - 1)
for xyz in parray_xyz:
cnt = 0
rxy = np.hypot(xyz[0], xyz[1])
if rxy > d2r * (res + 1):
phic = np.arctan2(xyz[0], xyz[1])
r_range = int(np.ceil((rxy / (srf['diameter'] / 2)) * refine))
# Counter to get size of array
var = 0
for ii in range(r_range - res, r_range + res): # was 10
phi_range = int(np.ceil((phic / (2 * np.pi)) * (1 + ii * 5)))
for ss in range(phi_range - res, phi_range + res):
var += 1
sizep = [var, 3]
arr2nd_xyz = np.empty(sizep)
for ii in range(r_range - res, r_range + res): # was 10
phi_range = int(np.ceil((phic / (2 * np.pi)) * (1 + ii * 5)))
for ss in range(phi_range - res, phi_range + res):
phi = ss * 2 / (1 + ii * 5)
r = d2r * ii
xx = np.sin(np.pi * phi) * r
yy = np.cos(np.pi * phi) * r
zz = R * (1 - np.sqrt(1 - (r / R)**2))
arr2nd_xyz[cnt] = np.array([xx, yy, zz])
cnt += 1
else:
sizep = [sum([1 + x * 5 for x in range(srf['resolution'])]), 3]
arr2nd_xyz = np.empty(sizep)
cnt = 0
for ii in range(srf['resolution']):
for ss in range(1 + ii * 5):
phi = ss * 2 / (1 + ii * 5)
r = d2r * ii
xx = np.sin(np.pi * phi) * r
yy = np.cos(np.pi * phi) * r
zz = R * (1 - np.sqrt(1 - (r / R)**2))
arr2nd_xyz[cnt] = np.array([xx, yy, zz])
cnt += 1
array_xyz = np.vstack((array_xyz, arr2nd_xyz))
# Delete non unique values
b = np.ascontiguousarray(array_xyz).view(np.dtype((np.void, array_xyz.dtype.itemsize * array_xyz.shape[1])))
_, idx = np.unique(b, return_index=True)
unique_a = array_xyz[idx]
# I need to sort this in spherical coordinates, first phi, then theta then r
rtp_a = ray.Cartesian2Spherical(unique_a[1:]) # Skip 0,0,0
rtp_a = np.vstack((np.array([0.0, 0.0, 0.0]), rtp_a))
# Now sort
ind = np.lexsort((rtp_a[:, 2], rtp_a[:, 1], rtp_a[:, 0])) # Sort by a, then by b
sorted_xyz = unique_a[ind]
else:
sorted_xyz = array_xyz
# numpy array to vtk array
pcoords = ns.numpy_to_vtk(num_array=sorted_xyz, deep=True, array_type=vtk.VTK_DOUBLE)
# Shove coordinates in points container
points = vtk.vtkPoints()
points.SetDataTypeToDouble()
points.SetData(pcoords)
# Create a polydata object
point_pd = vtk.vtkPolyData()
# Set the points and vertices we created as the geometry and topology of the polydata
point_pd.SetPoints(points)
# Make the delaunay mesh
delaunay = vtk.vtkDelaunay2D()
delaunay.SetInputData(point_pd)
# delaunay.SetTolerance(0.00001)
delaunay.Update()
# Rotate and translate
transform = vtk.vtkTransform()
transform.PostMultiply()
if 'rotateWXYZ' in srf:
transform.RotateWXYZ(srf['rotateWXYZ'][0], srf['rotateWXYZ'][1:])
if 'center' in srf:
transform.Translate(srf['center'])
pgt = vtk.vtkTransformPolyDataFilter()
pgt.SetOutputPointsPrecision(vtk.vtkAlgorithm.DOUBLE_PRECISION)
pgt.SetTransform(transform)
pgt.SetInputData(delaunay.GetOutput())
pgt.Update()
delaunay = pgt
# rotate polydata
return delaunay
def objectsource(srf1, srf2, ratio=0.8):
# make points on surface 1 should this be elliptical?
# Use given points, don't create them, so all poitns on vertices of surf1 surface
sourcepoints = [srf1['raypoints'].GetPoint(i) for i in range(srf1['raypoints'].GetNumberOfPoints())]
# Make points on target
targetlist = [[0.0, 0.0, 0.0]]
if 'diameter' in srf2:
targetlist.append([ratio * srf2['diameter'] / 2, 0.0, 0.0])
targetlist.append([0.0, ratio * srf2['diameter'] / 2, 0.0])
targetlist.append([-ratio * srf2['diameter'] / 2, 0.0, 0.0])
targetlist.append([0.0, -ratio * srf2['diameter'] / 2, 0.0])
elif 'width' in srf2 and 'height' in srf2:
targetlist.append([ratio * srf2['width'] / 2, 0.0, 0.0])
targetlist.append([0.0, ratio * srf2['height'] / 2, 0.0])
targetlist.append([-ratio * srf2['width'] / 2, 0.0, 0.0])
targetlist.append([0.0, -ratio * srf2['height'] / 2, 0.0])
else:
print('Could not make targetlist in objectsource')
return
# Transform points, I'm going to cheat and use the vtk functions
points = vtk.vtkPoints()
points.SetDataTypeToDouble()
for tl in targetlist:
points.InsertNextPoint(tl)
polydata = vtk.vtkPolyData()
polydata.SetPoints(points)
transform = vtk.vtkTransform()
transform.PostMultiply()
if 'scalex' in srf2:
transform.Scale(srf2['scalex'], 1.0, 1.0)
if 'rotateWXYZ' in srf2:
transform.RotateWXYZ(srf2['rotateWXYZ'][0], srf2['rotateWXYZ'][1:])
if 'centerH' in srf2:
transform.Translate(srf2['centerH'])
pgt = vtk.vtkTransformPolyDataFilter()
pgt.SetOutputPointsPrecision(vtk.vtkAlgorithm.DOUBLE_PRECISION)
pgt.SetTransform(transform)
pgt.SetInputData(polydata)
pgt.Update()
# And now I'm going to extract the points again
targetpoints = [pgt.GetOutput().GetPoint(i) for i in range(pgt.GetOutput().GetNumberOfPoints())]
# Get normal vector from source to target, 5 vectors per point
object_points = vtk.vtkPoints()
object_points.SetDataTypeToDouble()
object_normalvectors = vtk.vtkDoubleArray()
object_normalvectors.SetNumberOfComponents(3)
for sp in sourcepoints:
for tp in targetpoints:
vec = (tp[0] - sp[0], tp[1] - sp[1], tp[2] - sp[2])
object_normalvectors.InsertNextTuple(list(vec / np.linalg.norm(vec)))
object_points.InsertNextPoint(sp)
object_polydata = vtk.vtkPolyData()
object_polydata.SetPoints(object_points)
object_polydata.GetPointData().SetNormals(object_normalvectors)
return object_polydata, object_points
def pointsource(srf, simple=True):
if simple:
anglex = srf['anglex'] / 180 * np.pi
angley = srf['angley'] / 180 * np.pi
tuples = [(0, 0, 1)]
phix = [1, 0, -1, 0]
phiy = [0, 1, 0, -1]
theta = [anglex, angley, anglex, angley]
x = phix * np.sin(theta)
y = phiy * np.sin(theta)
z = np.cos(theta)
tuples = tuples + ([(xx, yy, zz) for xx, yy, zz in zip(x, y, z)])
# for tp in tuples: #has to be one
# print(np.sqrt(tp[0]**2+tp[1]**2+tp[2]**2))
else:
res = [4, 6, 8]
anglex = srf['anglex'] / 180 * np.pi
angley = srf['angley'] / 180 * np.pi
# Center line
tuples = [(0, 0, 1)]
for rr in res:
# Define pointsource, cylindrical
thetax = (res.index(rr) + 1) / len(res) * anglex
thetay = (res.index(rr) + 1) / len(res) * angley
phi = np.arange(rr) * (2 * np.pi / rr)
theta = thetax * thetay / np.hypot(thetay * np.cos(phi), thetax * np.sin(phi))
x = np.cos(phi) * np.sin(theta)
y = np.sin(phi) * np.sin(theta)
z = np.cos(theta)
tuples = tuples + ([(xx, yy, zz) for xx, yy, zz in zip(x, y, z)])
intersection_points = vtk.vtkPoints()
intersection_points.SetDataTypeToDouble()
normal_vectors = vtk.vtkDoubleArray()
normal_vectors.SetNumberOfComponents(3)
for sp in srf['sourcepoints']:
for tp in tuples:
normal_vectors.InsertNextTuple(tp)
intersection_points.InsertNextPoint(sp)
normal_polydata = vtk.vtkPolyData()
normal_polydata.SetPoints(intersection_points)
normal_polydata.GetPointData().SetNormals(normal_vectors)
return normal_polydata, intersection_points
def surfaceActor(ren, appendFilter, srf):
# Create a mapper and actor
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputData(srf['surface'].GetOutput())
# mapper.SetInputConnection(delaunay.GetOutputPort())
actor = vtk.vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().SetColor([0.0, 0.0, 1.0]) # set color to blue
actor.GetProperty().EdgeVisibilityOn() # show edges/wireframe
actor.GetProperty().SetEdgeColor([1.0, 1.0, 1.0]) # render edges as white
# Plot and save
ren.AddActor(actor)
ren.ResetCamera()
appendFilter.AddInputData(srf['surface'].GetOutput())
appendFilter.Update()
def shape(ren, appendFilter, srf, addActor=False):
if srf['shape'] == 'sphere':
srf['surface'] = sphere(srf)
elif srf['shape'] == 'flat':
srf['surface'] = flat(srf)
elif srf['shape'] == 'flatcircle':
srf['surface'] = flatcircle(srf)
elif srf['shape'] == 'asphere':
srf['surface'] = asphere(srf)
elif srf['shape'] == 'cylinder':
srf['surface'] = cylinder(srf)
elif srf['shape'] == 'pointsource':
pass
else:
print("Couldn't understand shape")
return
if addActor:
surfaceActor(ren, appendFilter, srf)
return srf
def trace(ren, appendFilter, srf1, srf2, addActor=True):
obbsurf2 = vtk.vtkOBBTree()
obbsurf2.SetDataSet(srf2['surface'].GetOutput())
obbsurf2.BuildLocator()
# I dont know from where the ray is coming, use 'curv' for this as a hack
if srf2['shape'] == 'sphere':
if srf2['curv'] == 'positive':
Flip = False
elif srf2['curv'] == 'negative':
Flip = True
else:
print('Misunderstood curv in trace')
elif srf2['shape'] == 'asphere':
if srf2['rn'] >= srf1['rn']:
Flip = False
elif srf2['rn'] < srf1['rn']:
Flip = True
elif srf2['shape'] == 'cylinder':
if srf2['rn'] >= srf1['rn']:
Flip = False
elif srf2['rn'] < srf1['rn']:
Flip = True
elif srf2['shape'] == 'flat':
if srf2['rn'] >= srf1['rn']:
Flip = False
elif srf2['rn'] < srf1['rn']:
Flip = True
else:
Flip = False
srf2['normals'], srf2['normalpoints'] = getnormals(srf2['surface'], flip=Flip)
# #Sometimes, something goes wrong with the number of cells
# count1 = srf2['normals'].GetCellData().GetNormals().GetNumberOfTuples()
# count2 = obbsurf2.GetDataSet().GetNumberOfCells()
# assert count1 == count2, 'The number of normals does not match the number of cells in the obbtree'
# where intersections are found
intersection_points = vtk.vtkPoints()
intersection_points.SetDataTypeToDouble()
# normal vectors at intersection
normal_vectors = vtk.vtkDoubleArray()
normal_vectors.SetNumberOfComponents(3)
# normals of refracted vectors
reflect_vectors = vtk.vtkDoubleArray()
reflect_vectors.SetNumberOfComponents(3)
# Loop through all of surface1 cell-centers
for idx in range(srf1['raypoints'].GetNumberOfPoints()):
# Get coordinates of surface1 cell center
pointSurf1 = srf1['raypoints'].GetPoint(idx)
# Get incident vector at that cell
normalsurf1 = srf1['rays'].GetPointData().GetNormals().GetTuple(idx)
# Calculate the 'target' of the ray based on 'RayCastLength'
pointRaySurf2 = list(np.array(pointSurf1) + ray.RayCastLength * np.array(normalsurf1))
# Check if there are any intersections for the given ray
if ray.isHit(obbsurf2, pointSurf1, pointRaySurf2):
# Retrieve coordinates of intersection points and intersected cell ids
pointsInter, cellIdsInter = ray.getIntersect(obbsurf2, pointSurf1, pointRaySurf2)
# print(cellIdsInter)
# ray.addPoint(ren, False, pointsInter[0], [0.5, 0.5, 0.5])
# Render lines/rays emanating from the Source. Rays that intersect are
if addActor:
ray.addLine(ren, appendFilter, pointSurf1, pointsInter[0], [1.0, 1.0, 0.0], opacity=0.5)
# Insert the coordinates of the intersection point in the dummy container
intersection_points.InsertNextPoint(pointsInter[0])
# Get the normal vector at the surf2 cell that intersected with the ray
normalsurf2 = srf2['normals'].GetPointData().GetNormals().GetTuple(cellIdsInter[0])
# Insert the normal vector of the intersection cell in the dummy container
normal_vectors.InsertNextTuple(normalsurf2)
# Calculate the incident ray vector
vecInc2 = np.array(pointRaySurf2) - np.array(pointSurf1)
vecInc = list(vecInc2 / np.linalg.norm(vecInc2))
# Calculate the reflected ray vector
if srf2['type'] == 'lens':
vecRef = ray.calcVecRefract(vecInc / np.linalg.norm(vecInc), normalsurf2, srf1['rn'], srf2['rn']) # refract
elif srf2['type'] == 'stop' or 'mirror' or 'source':
vecRef = ray.calcVecReflect(vecInc / np.linalg.norm(vecInc), normalsurf2) # reflect
# Add to container
reflect_vectors.InsertNextTuple(vecRef)
# store intersection points
# intersection_points.Update()
# Create a dummy 'vtkPolyData' to store refracted vecs
reflect_polydata = vtk.vtkPolyData()
reflect_polydata.SetPoints(intersection_points)
reflect_polydata.GetPointData().SetNormals(reflect_vectors)
# Create a dummy 'vtkPolyData' to store normal vecs
normal_polydata = vtk.vtkPolyData()
normal_polydata.SetPoints(intersection_points)
normal_polydata.GetPointData().SetNormals(normal_vectors)
return intersection_points, reflect_polydata, normal_polydata
def run(surfaces, project, Directory, scene, refine=True, plot=True):
# Write output to vtp file
writer = vtk.vtkXMLPolyDataWriter()
filename = Directory + project + "%04d.vtp" % scene
writer.SetFileName(filename)
appendFilter = vtk.vtkAppendPolyData()
# Create a render window
ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
renWin.SetSize(600, 600)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
iren.Initialize()
# Set camera position
camera = ren.MakeCamera()
camera.SetPosition(0, 100, 50)
camera.SetFocalPoint(0.0, 0, 0.0)
camera.SetViewAngle(0.0)
camera.SetParallelProjection(1)
ren.SetActiveCamera(camera)
traceit = range(len(surfaces))
for tri in traceit:
# Surface one is source
if tri == 0:
assert surfaces[tri]['type'] == 'source', 'surface zero needs to be source'
if surfaces[tri]['shape'] == 'point': # Use point source
surfaces[tri]['rays'], surfaces[tri]['raypoints'] = pointsource(surfaces[0], simple=True)
else: # Use object source
surfaces[tri] = shape(ren, appendFilter, surfaces[tri], addActor=True)
surfaces[tri]['rays'], surfaces[tri]['raypoints'] = getnormals(surfaces[tri]['surface'], vertices=True, flip=False)
surfaces[tri]['rays'], surfaces[tri]['raypoints'] = objectsource(surfaces[tri], surfaces[tri + 1], ratio=0.3)
glyphsa = glyphs(surfaces[tri]['rays'], color=[0.0, 1.0, 0.0]) # Green
ren.AddActor(glyphsa)
renWin.Render()
elif tri == len(surfaces) - 1:
surfaces[tri] = shape(ren, appendFilter, surfaces[tri], addActor=False) # TODO should be True
surfaces[tri]['raypoints'] = stop(ren, appendFilter, surfaces[tri - 1], surfaces[tri])
renWin.Render()
print('Tracing {0} and {1}'.format(tri - 1, tri))
else:
if refine: # If refine, shape again, trace again
surfaces[tri] = shape(ren, appendFilter, surfaces[tri], addActor=False)
surfaces[tri]['raypoints'], surfaces[tri]['rays'], surfaces[tri]['normals'] = trace(ren, appendFilter, surfaces[tri - 1], surfaces[tri], addActor=False)
surfaces[tri] = shape(ren, appendFilter, surfaces[tri], addActor=True)
surfaces[tri]['raypoints'], surfaces[tri]['rays'], surfaces[tri]['normals'] = trace(ren, appendFilter, surfaces[tri - 1], surfaces[tri])
# Plot glyphs
glyphsa = glyphs(surfaces[tri]['rays'], color=[0.0, 1.0, 0.0], size=1) # Green
ren.AddActor(glyphsa)
glyphsc = glyphs(surfaces[tri]['normals'], color=[0.0, 0.0, 1.0], size=1) # Blue
ren.AddActor(glyphsc)
renWin.Render()
print('Tracing {0} and {1}'.format(tri - 1, tri))
# Write output to vtp file
# appendFilter.Update()
# polydatacontainer = appendFilter
# writer.SetInputData(polydatacontainer.GetOutput())
# writer.Write()
#
# Check results in viewer, by exit screen, proceed
if plot:
iren.Start()
def main():
LBF_254_050 = {'tc': 6.5,
'f': 50.0,
'fb': 46.4,
'R1': -172,
'R2': 30.1,
'rn': 1.5168,
'diameter': 25.4}
LK1037L1 = {'f': -19.0,
'fb': -25.30, # is -20.3
'R1': 'flat',
'R2': 9.8,
'tc': 2.0,
'rn': 1.5168,
'width': 19.0,
'height': 21.0} # extrude over height
LJ1309L1 = {'f': 200.0,
'fb': 189.5, # is -20.3
'R1': 'flat',
'R2': 103.4,
'tc': 15.9,
'rn': 1.5168,
'width': 100,
'height': 90} # extrude over height
LJ1728L1 = {'f': 50.99,
'fb': 36.7, # is -20.3
'R1': 'flat',
'R2': 26.4,
'tc': 21.6,
'rn': 1.5168,
'width': 50.5,
'height': 52.7} # extrude over height
so1h = 100
so1v = 52.1239
si = 2000
angle = 2.0 # graden
surfaces = [{'type': 'source',
'shape': 'flat',
'center': [sind(angle) * si, 0.0, si - cosd(angle) * si],
'width': 2 * tand(0.1) * si, #
'height': 2 * tand(4.44) * si, # could be anything really
'rotateWXYZ': [-angle, 0, 1, 0], # Normal is [0, 0, -1]
'rn': 1.0},
{'type': 'lens',
'shape': 'cylinder',
'centerH': [0.0, 0.0, si - so1h],
'center': [0.0, 0.0, si - (so1h - (LJ1309L1['f'] - LJ1309L1['fb']) + LJ1309L1['tc'])],
# 'rotateWXYZ':[90.0, 0, 0, 1], # Normal is [0, 0, -1] in graden
'width': LJ1309L1['width'],
'height': LJ1309L1['height'],
'resolution': 1000,
'rn': LJ1309L1['rn'], # n-bk7
'curvx': LJ1309L1['R2']},
{'type': 'lens',
'shape': 'flat',
'centerH': [0.0, 0.0, si - so1h], # 2.76 = 4.36
'center': [0.0, 0.0, si - (so1h - (LJ1309L1['f'] - LJ1309L1['fb']))], # 2.91
'width': LJ1309L1['width'],
'height': LJ1309L1['height'],
# 'rotateWXYZ':[90, 0, 0, 1], # Normal is [0, 0, -1]
'rn': 1.0},
{'type': 'lens',
'shape': 'cylinder',
'centerH': [0.0, 0.0, si - so1v],
'center': [0.0, 0.0, si - (so1v - (LJ1728L1['f'] - LJ1728L1['fb']) + LJ1728L1['tc'])],
'rotateWXYZ':[90.0, 0, 0, 1], # Normal is [0, 0, -1] in graden
'width': LJ1728L1['width'],
'height': LJ1728L1['height'],
'resolution': 1000,
'rn': LJ1728L1['rn'], # n-bk7
'curvx': LJ1728L1['R2']},
{'type': 'lens',
'shape': 'flat',
'centerH': [0.0, 0.0, si - so1v], # 2.76 = 4.36
'center': [0.0, 0.0, si - (so1v - (LJ1728L1['f'] - LJ1728L1['fb']))], # 2.91
'width': LJ1728L1['width'],
'height': LJ1728L1['height'],
'rotateWXYZ':[90, 0, 0, 1], # Normal is [0, 0, -1]
'rn': 1.0},
{'type': 'stop',
'shape': 'flat',
'center': [0.0, 0.0, si],
# 'rotateWXYZ': [45, 0, 1, 0], # Normal is [0, 0, -1]
'width': 25.0,
'height': 25.0,
'rn': 1.0}]
import os
project = 'receiverB'
Directory = os.getcwd()
run(surfaces, project, Directory, 0, plot=True)
if __name__ == "__main__":
main()
| mit |
charlescearl/VirtualMesos | third_party/boto-2.0b2/boto/gs/connection.py | 5 | 2004 | # Copyright 2010 Google Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import boto
from boto.s3.connection import S3Connection
from boto.s3.connection import SubdomainCallingFormat
from boto.gs.bucket import Bucket
class GSConnection(S3Connection):
DefaultHost = 'commondatastorage.googleapis.com'
QueryString = 'Signature=%s&Expires=%d&AWSAccessKeyId=%s'
def __init__(self, gs_access_key_id=None, gs_secret_access_key=None,
is_secure=True, port=None, proxy=None, proxy_port=None,
proxy_user=None, proxy_pass=None,
host=DefaultHost, debug=0, https_connection_factory=None,
calling_format=SubdomainCallingFormat(), path='/'):
S3Connection.__init__(self, gs_access_key_id, gs_secret_access_key,
is_secure, port, proxy, proxy_port, proxy_user, proxy_pass,
host, debug, https_connection_factory, calling_format, path,
"google", boto.gs.bucket.Bucket)
| apache-2.0 |
feigames/Odoo | addons/marketing_campaign/report/campaign_analysis.py | 379 | 5310 | # -*- 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 import tools
from openerp.osv import fields, osv
from openerp.addons.decimal_precision import decimal_precision as dp
class campaign_analysis(osv.osv):
_name = "campaign.analysis"
_description = "Campaign Analysis"
_auto = False
_rec_name = 'date'
def _total_cost(self, cr, uid, ids, field_name, arg, context=None):
"""
@param cr: the current row, from the database cursor,
@param uid: the current user’s ID for security checks,
@param ids: List of case and section Data’s IDs
@param context: A standard dictionary for contextual values
"""
result = {}
for ca_obj in self.browse(cr, uid, ids, context=context):
wi_ids = self.pool.get('marketing.campaign.workitem').search(cr, uid,
[('segment_id.campaign_id', '=', ca_obj.campaign_id.id)])
total_cost = ca_obj.activity_id.variable_cost + \
((ca_obj.campaign_id.fixed_cost or 1.00) / len(wi_ids))
result[ca_obj.id] = total_cost
return result
_columns = {
'res_id' : fields.integer('Resource', readonly=True),
'year': fields.char('Year', size=4, readonly=True),
'month': fields.selection([('01','January'), ('02','February'),
('03','March'), ('04','April'),('05','May'), ('06','June'),
('07','July'), ('08','August'), ('09','September'),
('10','October'), ('11','November'), ('12','December')],
'Month', readonly=True),
'day': fields.char('Day', size=10, readonly=True),
'date': fields.date('Date', readonly=True, select=True),
'campaign_id': fields.many2one('marketing.campaign', 'Campaign',
readonly=True),
'activity_id': fields.many2one('marketing.campaign.activity', 'Activity',
readonly=True),
'segment_id': fields.many2one('marketing.campaign.segment', 'Segment',
readonly=True),
'partner_id': fields.many2one('res.partner', 'Partner', readonly=True),
'country_id': fields.related('partner_id', 'country_id',
type='many2one', relation='res.country',string='Country'),
'total_cost' : fields.function(_total_cost, string='Cost',
type="float", digits_compute=dp.get_precision('Account')),
'revenue': fields.float('Revenue', readonly=True, digits_compute=dp.get_precision('Account')),
'count' : fields.integer('# of Actions', readonly=True),
'state': fields.selection([('todo', 'To Do'),
('exception', 'Exception'), ('done', 'Done'),
('cancelled', 'Cancelled')], 'Status', readonly=True),
}
def init(self, cr):
tools.drop_view_if_exists(cr, 'campaign_analysis')
cr.execute("""
create or replace view campaign_analysis as (
select
min(wi.id) as id,
min(wi.res_id) as res_id,
to_char(wi.date::date, 'YYYY') as year,
to_char(wi.date::date, 'MM') as month,
to_char(wi.date::date, 'YYYY-MM-DD') as day,
wi.date::date as date,
s.campaign_id as campaign_id,
wi.activity_id as activity_id,
wi.segment_id as segment_id,
wi.partner_id as partner_id ,
wi.state as state,
sum(act.revenue) as revenue,
count(*) as count
from
marketing_campaign_workitem wi
left join res_partner p on (p.id=wi.partner_id)
left join marketing_campaign_segment s on (s.id=wi.segment_id)
left join marketing_campaign_activity act on (act.id= wi.activity_id)
group by
s.campaign_id,wi.activity_id,wi.segment_id,wi.partner_id,wi.state,
wi.date::date
)
""")
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |