repo
stringlengths
5
75
commit
stringlengths
40
40
message
stringlengths
6
18.2k
diff
stringlengths
60
262k
sammyt/fussy
d076dccfd826fd3235cecabb31baf39774572423
added type signiture filter
diff --git a/src/uk/co/ziazoo/fussy/methods/HasTypeSignature.as b/src/uk/co/ziazoo/fussy/methods/HasTypeSignature.as new file mode 100644 index 0000000..316c5ec --- /dev/null +++ b/src/uk/co/ziazoo/fussy/methods/HasTypeSignature.as @@ -0,0 +1,53 @@ +package uk.co.ziazoo.fussy.methods +{ + import flash.utils.getQualifiedClassName; + + import uk.co.ziazoo.fussy.query.IQueryPart; + + public class HasTypeSignature implements IQueryPart + { + private var types:Array; + + public function HasTypeSignature(...types) + { + this.types = types; + } + + public function filter(data:XMLList):XMLList + { + var filtered:XMLList = new XMLList(<root />); + + for each(var method:XML in data) + { + var parameters:XMLList = method.parameter; + + if (lengthIsCorrect(parameters) + && typesAreCorrect(parameters)) + { + filtered.appendChild(method); + } + } + return filtered.method; + } + + private function lengthIsCorrect(parameters:XMLList):Boolean + { + return types.length == parameters.length(); + } + + private function typesAreCorrect(parameters:XMLList):Boolean + { + for each(var parameter:XML in parameters) + { + var type:Class = types[Number(parameter.@index) - 1] as Class; + var qName:String = getQualifiedClassName(type); + if (parameter.@type != qName) + { + return false; + } + } + + return true; + } + } +} \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/methods/HasTypeSignatureTest.as b/test/uk/co/ziazoo/fussy/methods/HasTypeSignatureTest.as new file mode 100644 index 0000000..7c04f3f --- /dev/null +++ b/test/uk/co/ziazoo/fussy/methods/HasTypeSignatureTest.as @@ -0,0 +1,37 @@ +package uk.co.ziazoo.fussy.methods +{ + import org.flexunit.Assert; + + import uk.co.ziazoo.fussy.Wibble; + + public class HasTypeSignatureTest + { + public function HasTypeSignatureTest() + { + } + + [Test] + public function checkTypes():void + { + var queryPart:HasTypeSignature = new HasTypeSignature(int, String, Wibble); + + var methods:XML = <root> + <method name="bebeboo" declaredBy="uk.co.ziazoo.fussy::Bubbles" returnType="void"> + <parameter index="1" type="Object" optional="false"/> + <parameter index="2" type="Object" optional="false"/> + </method> + <method name="demo" declaredBy="uk.co.ziazoo.fussy::Bubbles" returnType="void"> + <parameter index="1" type="int" optional="false"/> + <parameter index="2" type="String" optional="false"/> + <parameter index="3" type="uk.co.ziazoo.fussy::Wibble" optional="false"/> + <metadata name="Inject"/> + </method> + </root>; + + var result:XMLList = queryPart.filter(methods.method); + + Assert.assertEquals(1, result.length()); + Assert.assertEquals("demo", result.@name); + } + } +} \ No newline at end of file
sammyt/fussy
725f754e015a0c75970edec2d3a2207190164a6f
added docs and additional DSL options which are as yet not implemented
diff --git a/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as b/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as index 16a252f..00a6be7 100644 --- a/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as +++ b/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as @@ -1,50 +1,98 @@ package uk.co.ziazoo.fussy.methods { import uk.co.ziazoo.fussy.parser.IResultParser; import uk.co.ziazoo.fussy.query.AbstractQueryChain; import uk.co.ziazoo.fussy.query.Named; import uk.co.ziazoo.fussy.query.WithMetadata; public class MethodQueryChain extends AbstractQueryChain { public function MethodQueryChain(parser:IResultParser) { super(parser); } override protected function getList(reflection:XML):XMLList { return reflection.factory.method; } + /** + * Filters based on the method name + * @param name of method + * @return MethodQueryChain to allow query DSL + */ public function named(name:String):MethodQueryChain { parts.push(new Named(name)); return this; } + /** + * Allows filtering by the type signature of the arguments + * e.g. hasTypeSignature(String,int,Array) would return all the + * methods which take a string, followed by a int then an array as + * their argument list + * + * @param types the classes of the arguments + * @return MethodQueryChain to allow query DSL + */ + public function hasTypeSignature(...types):MethodQueryChain + { + return this; + } + + /** + * Filters by the number of arguements the method takes + * @param count number of arguments the method has in its signature + * @return MethodQueryChain to allow query DSL + */ + public function argumentsLengthOf(count:int):MethodQueryChain + { + return this; + } + + /** + * Filters by metadata name + * @param named the name of the metadata a method must have to pass through + * this filter + * @return MethodQueryChain to allow query DSL + */ public function withMetadata(named:String):MethodQueryChain { parts.push(new WithMetadata(named)); return this; } + /** + * To find methods that take not arguments + * @return MethodQueryChain to allow query DSL + */ public function noArguments():MethodQueryChain { parts.push(new NoArgs()); return this; } + /** + * To find methods that have no arguments that must be provided. Methods + * with many arguments that have default values can pass this filter + * @return MethodQueryChain to allow query DSL + */ public function noCompulsoryArguments():MethodQueryChain { parts.push(new NoCompulsoryArgs()); return this; } + /** + * To find methods that have one or more arguments + * @return MethodQueryChain to allow query DSL + */ public function withArguments():MethodQueryChain { parts.push(new WithArguments()); return this; } } } \ No newline at end of file
sammyt/fussy
66ccacea9d56160c6c3eca2bf3bbf5347c585156
made type dynamic to pass intellij error checker
diff --git a/src/uk/co/ziazoo/fussy/query/WithMetadata.as b/src/uk/co/ziazoo/fussy/query/WithMetadata.as index cc41b06..8dde29a 100644 --- a/src/uk/co/ziazoo/fussy/query/WithMetadata.as +++ b/src/uk/co/ziazoo/fussy/query/WithMetadata.as @@ -1,21 +1,20 @@ package uk.co.ziazoo.fussy.query { - public class WithMetadata implements IQueryPart + dynamic public class WithMetadata implements IQueryPart { private var name:String; public function WithMetadata(name:String) { this.name = name; } public function filter(data:XMLList):XMLList { - // trace("Filter:", data); return data.( hasOwnProperty("metadata") && metadata.(@name == name).length() > 0 ); } } } \ No newline at end of file
sammyt/fussy
425f7de9841afb5e815c6d893ce4f42cc4987675
fixed issues with metadata filter and implemented some fussy tests
diff --git a/src/uk/co/ziazoo/fussy/accessors/AccessorQueryChain.as b/src/uk/co/ziazoo/fussy/accessors/AccessorQueryChain.as index c1c9ac3..a43d8fd 100644 --- a/src/uk/co/ziazoo/fussy/accessors/AccessorQueryChain.as +++ b/src/uk/co/ziazoo/fussy/accessors/AccessorQueryChain.as @@ -1,43 +1,48 @@ package uk.co.ziazoo.fussy.accessors { import uk.co.ziazoo.fussy.parser.IResultParser; import uk.co.ziazoo.fussy.properties.PropertyQueryChain; public class AccessorQueryChain extends PropertyQueryChain { public function AccessorQueryChain(parser:IResultParser) { super(parser); } + override protected function getList(reflection:XML):XMLList + { + return reflection.factory.accessor; + } + public function readable():AccessorQueryChain { parts.push(new Readable()); return this; } public function writable():AccessorQueryChain { parts.push(new Writable()); return this; } public function readOnly():AccessorQueryChain { parts.push(new ReadOnly()); return this; } public function writeOnly():AccessorQueryChain { parts.push(new WriteOnly()); return this; } public function readAndWrite():AccessorQueryChain { parts.push(new ReadAndWrite()); return this; } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as b/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as index f800448..16a252f 100644 --- a/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as +++ b/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as @@ -1,45 +1,50 @@ package uk.co.ziazoo.fussy.methods { import uk.co.ziazoo.fussy.parser.IResultParser; import uk.co.ziazoo.fussy.query.AbstractQueryChain; import uk.co.ziazoo.fussy.query.Named; import uk.co.ziazoo.fussy.query.WithMetadata; public class MethodQueryChain extends AbstractQueryChain { public function MethodQueryChain(parser:IResultParser) { super(parser); } + override protected function getList(reflection:XML):XMLList + { + return reflection.factory.method; + } + public function named(name:String):MethodQueryChain { parts.push(new Named(name)); return this; } public function withMetadata(named:String):MethodQueryChain { parts.push(new WithMetadata(named)); return this; } public function noArguments():MethodQueryChain { parts.push(new NoArgs()); return this; } public function noCompulsoryArguments():MethodQueryChain { parts.push(new NoCompulsoryArgs()); return this; } public function withArguments():MethodQueryChain { parts.push(new WithArguments()); return this; } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/parser/PropertyParser.as b/src/uk/co/ziazoo/fussy/parser/PropertyParser.as index fc09341..7b8461c 100644 --- a/src/uk/co/ziazoo/fussy/parser/PropertyParser.as +++ b/src/uk/co/ziazoo/fussy/parser/PropertyParser.as @@ -1,23 +1,28 @@ package uk.co.ziazoo.fussy.parser { public class PropertyParser implements IResultParser { private var variableParser:VariableParser; private var accessorParser:AccessorParser; public function PropertyParser(variableParser:VariableParser, accessorParser:AccessorParser) { this.variableParser = variableParser; this.accessorParser = accessorParser; } public function parse(result:XMLList):Array { - var accessors:Array = accessorParser.parse(result.accessor); - var variables:Array = variableParser.parse(result.variable); + trace(result); + var root:XML = <root/>; + root.appendChild(result); + + var accessors:Array = accessorParser.parse(root.accessor); + var variables:Array = variableParser.parse(root.variable); + var properties:Array = accessors.concat(variables); return properties; } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/properties/PropertyQueryChain.as b/src/uk/co/ziazoo/fussy/properties/PropertyQueryChain.as index 01ae7f6..ff54170 100644 --- a/src/uk/co/ziazoo/fussy/properties/PropertyQueryChain.as +++ b/src/uk/co/ziazoo/fussy/properties/PropertyQueryChain.as @@ -1,26 +1,34 @@ package uk.co.ziazoo.fussy.properties { import uk.co.ziazoo.fussy.parser.IResultParser; import uk.co.ziazoo.fussy.query.AbstractQueryChain; import uk.co.ziazoo.fussy.query.WithMetadata; public class PropertyQueryChain extends AbstractQueryChain { public function PropertyQueryChain(parser:IResultParser) { super(parser); } + override protected function getList(reflection:XML):XMLList + { + var p:XMLList = new XMLList(<root/>); + p.appendChild(reflection.factory.variable); + p.appendChild(reflection.factory.accessor); + return p.*; + } + public function ofType(type:Class):PropertyQueryChain { parts.push(new OfType(type)); return this; } public function withMetadata(name:String):PropertyQueryChain { parts.push(new WithMetadata(name)); return this; } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/query/AbstractQueryChain.as b/src/uk/co/ziazoo/fussy/query/AbstractQueryChain.as index 0121271..2e2ba6c 100644 --- a/src/uk/co/ziazoo/fussy/query/AbstractQueryChain.as +++ b/src/uk/co/ziazoo/fussy/query/AbstractQueryChain.as @@ -1,66 +1,68 @@ package uk.co.ziazoo.fussy.query { import flash.utils.describeType; import uk.co.ziazoo.fussy.parser.IResultParser; public class AbstractQueryChain implements IQueryChain { /** * @private */ protected var parts:Array; private var _parser:IResultParser; public function AbstractQueryChain(parser:IResultParser) { parts = []; _parser = parser; } public function forType(type:Class):Array { return parser.parse(xmlForType(type)); } public function xmlForType(type:Class):XMLList { if (parts.length == 0) { return null; } - var reflection:XML = describeType(type); - var methods:XMLList = reflection.factory.method; - var firstPart:IQueryPart = parts[0]; - var lastResult:XMLList = firstPart.filter(methods); + var lastResult:XMLList = firstPart.filter(getList(describeType(type))); + + var i:int = parts.length - 1; - var i:uint = uint(parts.length - 1); - while (i > 0) + while (i >= 0) { var part:IQueryPart = parts[i]; lastResult = part.filter(lastResult); i--; } - return lastResult; } + protected function getList(reflection:XML):XMLList + { + return null; + } + public function get parser():IResultParser { return _parser; } public function set parser(value:IResultParser):void { _parser = value; } public function addQueryPart(part:IQueryPart):void { parts.push(part); } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/query/WithMetadata.as b/src/uk/co/ziazoo/fussy/query/WithMetadata.as index 7b1833e..cc41b06 100644 --- a/src/uk/co/ziazoo/fussy/query/WithMetadata.as +++ b/src/uk/co/ziazoo/fussy/query/WithMetadata.as @@ -1,20 +1,21 @@ package uk.co.ziazoo.fussy.query { - + public class WithMetadata implements IQueryPart { private var name:String; - + public function WithMetadata(name:String) { this.name = name; } - + public function filter(data:XMLList):XMLList { - return data.( - hasOwnProperty("metadata") && metadata.(@name == name) - ); + // trace("Filter:", data); + return data.( + hasOwnProperty("metadata") && metadata.(@name == name).length() > 0 + ); } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/variables/VariableQueryChain.as b/src/uk/co/ziazoo/fussy/variables/VariableQueryChain.as index 47b1897..6ce6331 100644 --- a/src/uk/co/ziazoo/fussy/variables/VariableQueryChain.as +++ b/src/uk/co/ziazoo/fussy/variables/VariableQueryChain.as @@ -1,13 +1,18 @@ package uk.co.ziazoo.fussy.variables { import uk.co.ziazoo.fussy.parser.IResultParser; import uk.co.ziazoo.fussy.properties.PropertyQueryChain; public class VariableQueryChain extends PropertyQueryChain { public function VariableQueryChain(parser:IResultParser) { super(parser); } + + override protected function getList(reflection:XML):XMLList + { + return reflection.factory.varaible; + } } } \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/FussyTest.as b/test/uk/co/ziazoo/fussy/FussyTest.as index a35efda..c7760b4 100644 --- a/test/uk/co/ziazoo/fussy/FussyTest.as +++ b/test/uk/co/ziazoo/fussy/FussyTest.as @@ -1,26 +1,38 @@ package uk.co.ziazoo.fussy { import org.flexunit.Assert; import uk.co.ziazoo.fussy.model.Method; import uk.co.ziazoo.fussy.query.IQuery; public class FussyTest { [Test] public function findInjectableMethods():void { var fussy:Fussy = new Fussy(); var query:IQuery = fussy.query().findMethods().withMetadata("Inject").withArguments(); var list:Array = query.forType(Bubbles); Assert.assertEquals(1, list.length); var method:Method = list[0] as Method; Assert.assertEquals(method.name, "wowowo"); Assert.assertEquals(method.parameters.length, 2); } + + [Test] + public function findInjectableProperties():void + { + var fussy:Fussy = new Fussy(); + + var query:IQuery = fussy.query().findProperties().withMetadata("Inject"); + + var list:Array = query.forType(Bubbles); + + Assert.assertEquals(1, list.length); + } } } \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/parser/PropertyParserTest.as b/test/uk/co/ziazoo/fussy/parser/PropertyParserTest.as index ab65d2b..a19a11a 100644 --- a/test/uk/co/ziazoo/fussy/parser/PropertyParserTest.as +++ b/test/uk/co/ziazoo/fussy/parser/PropertyParserTest.as @@ -1,95 +1,95 @@ package uk.co.ziazoo.fussy.parser { import flash.utils.describeType; import org.flexunit.Assert; import uk.co.ziazoo.fussy.Bubbles; import uk.co.ziazoo.fussy.model.Accessor; import uk.co.ziazoo.fussy.model.Metadata; import uk.co.ziazoo.fussy.model.Property; import uk.co.ziazoo.fussy.model.Variable; public class PropertyParserTest { private var parser:PropertyParser; public function PropertyParserTest() { } [Before] public function setUp():void { var metadataParser:MetadataParser = new MetadataParser(); parser = new PropertyParser( new VariableParser(metadataParser), new AccessorParser(metadataParser)); } [Test] public function tearDown():void { parser = null; } [Test] public function parseSomeProperties():void { var description:XML = describeType(Bubbles); var p:XMLList = new XMLList(<root/>); p.appendChild(description.factory.variable); p.appendChild(description.factory.accessor); - var props:XMLList = p; + var props:XMLList = p.*; trace(props); var properties:Array = parser.parse(props); Assert.assertNotNull(properties); Assert.assertTrue(properties.length == 7); } [Test] public function canParseVariable():void { var v:XMLList = new XMLList(<root> <variable name="wibble" type="uk.co.ziazoo.fussy::Wibble"/> </root>); - var properties:Array = parser.parse(v); + var properties:Array = parser.parse(v.*); Assert.assertNotNull(properties); Assert.assertTrue(properties.length == 1); var prop:Variable = properties[0] as Variable; Assert.assertEquals("wibble", prop.name); Assert.assertEquals("uk.co.ziazoo.fussy::Wibble", prop.type); } [Test] public function canParseAccessor():void { var v:XMLList = new XMLList(<root> <accessor name="thing" access="writeonly" type="String" declaredBy="uk.co.ziazoo.fussy::Bubbles"> <metadata name="Inject"/> </accessor> </root>); - var properties:Array = parser.parse(v); + var properties:Array = parser.parse(v.*); Assert.assertNotNull(properties); Assert.assertTrue(properties.length == 1); var prop:Accessor = properties[0] as Accessor; Assert.assertEquals("thing", prop.name); Assert.assertEquals("String", prop.type); Assert.assertEquals(1, prop.metadata.length); Assert.assertEquals("writeonly", prop.access); Assert.assertEquals("uk.co.ziazoo.fussy::Bubbles", prop.declaredBy); } } } \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/query/WithMetadataTest.as b/test/uk/co/ziazoo/fussy/query/WithMetadataTest.as index 78d5905..e76e1e6 100644 --- a/test/uk/co/ziazoo/fussy/query/WithMetadataTest.as +++ b/test/uk/co/ziazoo/fussy/query/WithMetadataTest.as @@ -1,34 +1,47 @@ package uk.co.ziazoo.fussy.query { import flash.utils.describeType; import org.flexunit.Assert; import uk.co.ziazoo.fussy.Bubbles; public class WithMetadataTest { private var methods:XMLList; + private var props:XMLList; [Before] public function setUp():void { methods = describeType(Bubbles).factory.method; + var p:XMLList = new XMLList(<root/>); + p.appendChild(describeType(Bubbles).factory.variable); + p.appendChild(describeType(Bubbles).factory.accessor); + props = p.*; } [After] public function tearDown():void { methods = null; } [Test] public function filters():void { var withMetadata:WithMetadata = new WithMetadata("Inject"); var result:XMLList = withMetadata.filter(methods); Assert.assertNotNull(result); Assert.assertTrue(result.length() == 2); } + + [Test] + public function filterOnProps():void + { + var withMetadata:WithMetadata = new WithMetadata("Inject"); + var result:XMLList = withMetadata.filter(props); + Assert.assertTrue(result.length() == 1); + } } } \ No newline at end of file
sammyt/fussy
25b70f6aae0c9b65a71036ea996efbc6d25a279c
added parsers to queries
diff --git a/src/uk/co/ziazoo/fussy/Fussy.as b/src/uk/co/ziazoo/fussy/Fussy.as index 4c98e4c..682a76f 100644 --- a/src/uk/co/ziazoo/fussy/Fussy.as +++ b/src/uk/co/ziazoo/fussy/Fussy.as @@ -1,26 +1,36 @@ package uk.co.ziazoo.fussy { + import uk.co.ziazoo.fussy.parser.AccessorParser; + import uk.co.ziazoo.fussy.parser.ConstructorParser; + import uk.co.ziazoo.fussy.parser.IResultParser; + import uk.co.ziazoo.fussy.parser.MetadataParser; + import uk.co.ziazoo.fussy.parser.MethodParser; + import uk.co.ziazoo.fussy.parser.ParameterParser; + import uk.co.ziazoo.fussy.parser.PropertyParser; + import uk.co.ziazoo.fussy.parser.VariableParser; import uk.co.ziazoo.fussy.query.Query; public class Fussy { + private var methodParser:IResultParser; + private var propertyParser:IResultParser; + private var constructorParser:IResultParser; + public function Fussy() { - } + var parameterParser:ParameterParser = new ParameterParser(); + var metadataParser:MetadataParser = new MetadataParser(); - public function forType(type:Class):Type - { - return null; - } + methodParser = new MethodParser(parameterParser, metadataParser); + propertyParser = new PropertyParser( + new VariableParser(metadataParser), new AccessorParser(metadataParser)); - public function forQName(qName:String):Type - { - return null; + constructorParser = new ConstructorParser(parameterParser); } public function query():Query { - return new Query(); + return new Query(methodParser, propertyParser, constructorParser); } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/accessors/AccessorQueryChain.as b/src/uk/co/ziazoo/fussy/accessors/AccessorQueryChain.as index 3318e49..c1c9ac3 100644 --- a/src/uk/co/ziazoo/fussy/accessors/AccessorQueryChain.as +++ b/src/uk/co/ziazoo/fussy/accessors/AccessorQueryChain.as @@ -1,41 +1,43 @@ package uk.co.ziazoo.fussy.accessors { + import uk.co.ziazoo.fussy.parser.IResultParser; import uk.co.ziazoo.fussy.properties.PropertyQueryChain; public class AccessorQueryChain extends PropertyQueryChain { - public function AccessorQueryChain() + public function AccessorQueryChain(parser:IResultParser) { + super(parser); } public function readable():AccessorQueryChain { parts.push(new Readable()); return this; } public function writable():AccessorQueryChain { parts.push(new Writable()); return this; } public function readOnly():AccessorQueryChain { parts.push(new ReadOnly()); return this; } public function writeOnly():AccessorQueryChain { parts.push(new WriteOnly()); return this; } public function readAndWrite():AccessorQueryChain { parts.push(new ReadAndWrite()); return this; } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as b/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as index c1fd7d7..f800448 100644 --- a/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as +++ b/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as @@ -1,27 +1,45 @@ package uk.co.ziazoo.fussy.methods { import uk.co.ziazoo.fussy.parser.IResultParser; import uk.co.ziazoo.fussy.query.AbstractQueryChain; import uk.co.ziazoo.fussy.query.Named; import uk.co.ziazoo.fussy.query.WithMetadata; public class MethodQueryChain extends AbstractQueryChain { public function MethodQueryChain(parser:IResultParser) { - this.parser = parser; + super(parser); } public function named(name:String):MethodQueryChain { parts.push(new Named(name)); return this; } public function withMetadata(named:String):MethodQueryChain { parts.push(new WithMetadata(named)); return this; } + + public function noArguments():MethodQueryChain + { + parts.push(new NoArgs()); + return this; + } + + public function noCompulsoryArguments():MethodQueryChain + { + parts.push(new NoCompulsoryArgs()); + return this; + } + + public function withArguments():MethodQueryChain + { + parts.push(new WithArguments()); + return this; + } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/methods/WithArguments.as b/src/uk/co/ziazoo/fussy/methods/WithArguments.as new file mode 100644 index 0000000..41cdbf0 --- /dev/null +++ b/src/uk/co/ziazoo/fussy/methods/WithArguments.as @@ -0,0 +1,18 @@ +package uk.co.ziazoo.fussy.methods +{ + import uk.co.ziazoo.fussy.query.IQueryPart; + + public class WithArguments implements IQueryPart + { + public function WithArguments() + { + } + + public function filter(data:XMLList):XMLList + { + return data.( + hasOwnProperty("parameter") + ); + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/properties/PropertyQueryChain.as b/src/uk/co/ziazoo/fussy/properties/PropertyQueryChain.as index 73a4b38..01ae7f6 100644 --- a/src/uk/co/ziazoo/fussy/properties/PropertyQueryChain.as +++ b/src/uk/co/ziazoo/fussy/properties/PropertyQueryChain.as @@ -1,24 +1,26 @@ package uk.co.ziazoo.fussy.properties { + import uk.co.ziazoo.fussy.parser.IResultParser; import uk.co.ziazoo.fussy.query.AbstractQueryChain; import uk.co.ziazoo.fussy.query.WithMetadata; public class PropertyQueryChain extends AbstractQueryChain { - public function PropertyQueryChain() + public function PropertyQueryChain(parser:IResultParser) { + super(parser); } public function ofType(type:Class):PropertyQueryChain { parts.push(new OfType(type)); return this; } public function withMetadata(name:String):PropertyQueryChain { parts.push(new WithMetadata(name)); return this; } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/query/AbstractQueryChain.as b/src/uk/co/ziazoo/fussy/query/AbstractQueryChain.as index 4e53ead..0121271 100644 --- a/src/uk/co/ziazoo/fussy/query/AbstractQueryChain.as +++ b/src/uk/co/ziazoo/fussy/query/AbstractQueryChain.as @@ -1,65 +1,66 @@ package uk.co.ziazoo.fussy.query { import flash.utils.describeType; import uk.co.ziazoo.fussy.parser.IResultParser; public class AbstractQueryChain implements IQueryChain { /** * @private */ protected var parts:Array; private var _parser:IResultParser; - public function AbstractQueryChain() + public function AbstractQueryChain(parser:IResultParser) { parts = []; + _parser = parser; } public function forType(type:Class):Array { - return parser.parse(xmlforType(type)); + return parser.parse(xmlForType(type)); } - public function xmlforType(type:Class):XMLList + public function xmlForType(type:Class):XMLList { if (parts.length == 0) { return null; } var reflection:XML = describeType(type); var methods:XMLList = reflection.factory.method; var firstPart:IQueryPart = parts[0]; var lastResult:XMLList = firstPart.filter(methods); var i:uint = uint(parts.length - 1); while (i > 0) { var part:IQueryPart = parts[i]; lastResult = part.filter(lastResult); i--; } return lastResult; } public function get parser():IResultParser { return _parser; } public function set parser(value:IResultParser):void { _parser = value; } public function addQueryPart(part:IQueryPart):void { parts.push(part); } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/query/Query.as b/src/uk/co/ziazoo/fussy/query/Query.as index c2fe019..a7ee044 100644 --- a/src/uk/co/ziazoo/fussy/query/Query.as +++ b/src/uk/co/ziazoo/fussy/query/Query.as @@ -1,34 +1,54 @@ package uk.co.ziazoo.fussy.query { + import uk.co.ziazoo.fussy.Type; import uk.co.ziazoo.fussy.accessors.AccessorQueryChain; import uk.co.ziazoo.fussy.methods.MethodQueryChain; + import uk.co.ziazoo.fussy.parser.IResultParser; import uk.co.ziazoo.fussy.properties.PropertyQueryChain; import uk.co.ziazoo.fussy.variables.VariableQueryChain; public class Query { - public function Query() + private var methodParser:IResultParser; + private var propertyParser:IResultParser; + private var constructorParser:IResultParser; + + public function Query(methodParser:IResultParser, + propertyParser:IResultParser, constructorParser:IResultParser) + { + this.propertyParser = propertyParser; + this.methodParser = methodParser; + this.constructorParser = constructorParser; + } + + public function type(type:Class):Type + { + return null; + } + + public function forQName(qName:String):Type { + return null; } public function findMethods():MethodQueryChain { - return new MethodQueryChain(null); + return new MethodQueryChain(methodParser); } public function findProperties():PropertyQueryChain { - return new PropertyQueryChain(); + return new PropertyQueryChain(propertyParser); } public function findAccessors():AccessorQueryChain { - return new AccessorQueryChain(); + return new AccessorQueryChain(propertyParser); } public function findVariables():VariableQueryChain { - return new VariableQueryChain(); + return new VariableQueryChain(propertyParser); } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/variables/VariableQueryChain.as b/src/uk/co/ziazoo/fussy/variables/VariableQueryChain.as index 8d7c870..47b1897 100644 --- a/src/uk/co/ziazoo/fussy/variables/VariableQueryChain.as +++ b/src/uk/co/ziazoo/fussy/variables/VariableQueryChain.as @@ -1,11 +1,13 @@ package uk.co.ziazoo.fussy.variables { + import uk.co.ziazoo.fussy.parser.IResultParser; import uk.co.ziazoo.fussy.properties.PropertyQueryChain; public class VariableQueryChain extends PropertyQueryChain { - public function VariableQueryChain() + public function VariableQueryChain(parser:IResultParser) { + super(parser); } } } \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/FussyTest.as b/test/uk/co/ziazoo/fussy/FussyTest.as index fc04618..a35efda 100644 --- a/test/uk/co/ziazoo/fussy/FussyTest.as +++ b/test/uk/co/ziazoo/fussy/FussyTest.as @@ -1,21 +1,26 @@ package uk.co.ziazoo.fussy { + import org.flexunit.Assert; + + import uk.co.ziazoo.fussy.model.Method; import uk.co.ziazoo.fussy.query.IQuery; - /** - * nothing useful here yet, just demos of the api - */ public class FussyTest { [Test] - public function createVariableFussy():void + public function findInjectableMethods():void { var fussy:Fussy = new Fussy(); - - var query:IQuery = fussy.query().findMethods().withMetadata("Inject"); + var query:IQuery = fussy.query().findMethods().withMetadata("Inject").withArguments(); var list:Array = query.forType(Bubbles); + + Assert.assertEquals(1, list.length); + + var method:Method = list[0] as Method; + Assert.assertEquals(method.name, "wowowo"); + Assert.assertEquals(method.parameters.length, 2); } } } \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/methods/WithArgumentsTest.as b/test/uk/co/ziazoo/fussy/methods/WithArgumentsTest.as new file mode 100644 index 0000000..de5c566 --- /dev/null +++ b/test/uk/co/ziazoo/fussy/methods/WithArgumentsTest.as @@ -0,0 +1,38 @@ +package uk.co.ziazoo.fussy.methods +{ + import flash.utils.describeType; + + import org.flexunit.Assert; + + import uk.co.ziazoo.fussy.Bubbles; + + public class WithArgumentsTest + { + private var methods:XMLList; + + public function WithArgumentsTest() + { + } + + [Before] + public function setUp():void + { + methods = describeType(Bubbles).factory.method; + } + + [After] + public function tearDown():void + { + methods = null; + } + + [Test] + public function noNeededArgs():void + { + var withArgs:WithArguments = new WithArguments(); + var result:XMLList = withArgs.filter(methods); + Assert.assertNotNull(result); + Assert.assertTrue(result.length() == 3); + } + } +} \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/parser/ConstructorParserTest.as b/test/uk/co/ziazoo/fussy/parser/ConstructorParserTest.as new file mode 100644 index 0000000..800a802 --- /dev/null +++ b/test/uk/co/ziazoo/fussy/parser/ConstructorParserTest.as @@ -0,0 +1,30 @@ +package uk.co.ziazoo.fussy.parser +{ + import flash.utils.describeType; + + import org.flexunit.Assert; + + import uk.co.ziazoo.fussy.Bubbles; + import uk.co.ziazoo.fussy.model.Constructor; + + public class ConstructorParserTest + { + public function ConstructorParserTest() + { + } + + [Test] + public function parseConsructor():void + { + var parser:ConstructorParser = + new ConstructorParser(new ParameterParser()); + + var result:Array = parser.parse(describeType(Bubbles).factory); + + var constructor:Constructor = result[0] as Constructor; + + Assert.assertNotNull(constructor); + Assert.assertEquals(1, constructor.parameters.length); + } + } +} \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/parser/PropertyParserTest.as b/test/uk/co/ziazoo/fussy/parser/PropertyParserTest.as index 5b696a7..ab65d2b 100644 --- a/test/uk/co/ziazoo/fussy/parser/PropertyParserTest.as +++ b/test/uk/co/ziazoo/fussy/parser/PropertyParserTest.as @@ -1,91 +1,95 @@ package uk.co.ziazoo.fussy.parser { import flash.utils.describeType; import org.flexunit.Assert; import uk.co.ziazoo.fussy.Bubbles; + import uk.co.ziazoo.fussy.model.Accessor; import uk.co.ziazoo.fussy.model.Metadata; import uk.co.ziazoo.fussy.model.Property; + import uk.co.ziazoo.fussy.model.Variable; public class PropertyParserTest { private var parser:PropertyParser; public function PropertyParserTest() { } [Before] public function setUp():void { var metadataParser:MetadataParser = new MetadataParser(); parser = new PropertyParser( new VariableParser(metadataParser), new AccessorParser(metadataParser)); } [Test] public function tearDown():void { parser = null; } [Test] public function parseSomeProperties():void { var description:XML = describeType(Bubbles); var p:XMLList = new XMLList(<root/>); p.appendChild(description.factory.variable); p.appendChild(description.factory.accessor); var props:XMLList = p; trace(props); var properties:Array = parser.parse(props); Assert.assertNotNull(properties); Assert.assertTrue(properties.length == 7); } [Test] public function canParseVariable():void { var v:XMLList = new XMLList(<root> <variable name="wibble" type="uk.co.ziazoo.fussy::Wibble"/> </root>); var properties:Array = parser.parse(v); Assert.assertNotNull(properties); Assert.assertTrue(properties.length == 1); - var prop:Property = properties[0] as Property; + var prop:Variable = properties[0] as Variable; Assert.assertEquals("wibble", prop.name); Assert.assertEquals("uk.co.ziazoo.fussy::Wibble", prop.type); } [Test] public function canParseAccessor():void { var v:XMLList = new XMLList(<root> <accessor name="thing" access="writeonly" type="String" declaredBy="uk.co.ziazoo.fussy::Bubbles"> <metadata name="Inject"/> </accessor> </root>); var properties:Array = parser.parse(v); Assert.assertNotNull(properties); Assert.assertTrue(properties.length == 1); - var prop:Property = properties[0] as Property; + var prop:Accessor = properties[0] as Accessor; Assert.assertEquals("thing", prop.name); Assert.assertEquals("String", prop.type); Assert.assertEquals(1, prop.metadata.length); + Assert.assertEquals("writeonly", prop.access); + Assert.assertEquals("uk.co.ziazoo.fussy::Bubbles", prop.declaredBy); } } } \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/query/QueryTest.as b/test/uk/co/ziazoo/fussy/query/QueryTest.as index 093cb10..1a4263c 100644 --- a/test/uk/co/ziazoo/fussy/query/QueryTest.as +++ b/test/uk/co/ziazoo/fussy/query/QueryTest.as @@ -1,24 +1,22 @@ package uk.co.ziazoo.fussy.query { public class QueryTest { [Before] public function setUp():void { } [After] public function tearDown():void { } [Test] public function creation():void { - var query:Query = new Query(); + var query:Query = new Query(null, null, null); query.findMethods().named("getEtc"); - - } } } \ No newline at end of file
sammyt/fussy
42f3113ac003c69cc3e1218fea7dcb5055749f73
continued parser development
diff --git a/src/uk/co/ziazoo/fussy/model/Accessor.as b/src/uk/co/ziazoo/fussy/model/Accessor.as new file mode 100644 index 0000000..9eda123 --- /dev/null +++ b/src/uk/co/ziazoo/fussy/model/Accessor.as @@ -0,0 +1,12 @@ +package uk.co.ziazoo.fussy.model +{ + public class Accessor extends Property + { + public var access:String; + public var declaredBy:String; + + public function Accessor() + { + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/model/Variable.as b/src/uk/co/ziazoo/fussy/model/Variable.as new file mode 100644 index 0000000..21dc9c0 --- /dev/null +++ b/src/uk/co/ziazoo/fussy/model/Variable.as @@ -0,0 +1,9 @@ +package uk.co.ziazoo.fussy.model +{ + public class Variable extends Property + { + public function Variable() + { + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/parser/AccessorParser.as b/src/uk/co/ziazoo/fussy/parser/AccessorParser.as new file mode 100644 index 0000000..8c48860 --- /dev/null +++ b/src/uk/co/ziazoo/fussy/parser/AccessorParser.as @@ -0,0 +1,35 @@ +package uk.co.ziazoo.fussy.parser +{ + import uk.co.ziazoo.fussy.model.Accessor; + + public class AccessorParser implements IResultParser + { + private var metadataParser:MetadataParser; + + public function AccessorParser(metadataParser:MetadataParser) + { + this.metadataParser = metadataParser; + } + + public function parse(result:XMLList):Array + { + var accessors:Array = []; + for each(var xml:XML in result) + { + accessors.push(parseAccessor(xml)); + } + return accessors; + } + + private function parseAccessor(reflection:XML):Accessor + { + var property:Accessor = new Accessor(); + property.name = reflection.@name; + property.type = reflection.@type; + property.declaredBy = reflection.@declaredBy; + property.access = reflection.@access; + property.metadata = metadataParser.parse(reflection.metadata); + return property; + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/parser/MetadataParser.as b/src/uk/co/ziazoo/fussy/parser/MetadataParser.as index cce0de9..c813df1 100644 --- a/src/uk/co/ziazoo/fussy/parser/MetadataParser.as +++ b/src/uk/co/ziazoo/fussy/parser/MetadataParser.as @@ -1,37 +1,37 @@ package uk.co.ziazoo.fussy.parser { import flash.utils.Dictionary; import uk.co.ziazoo.fussy.model.Metadata; public class MetadataParser implements IResultParser { public function MetadataParser() { super(); } public function parse(result:XMLList):Array { - var metadatas:Array = []; - for each(var metadata:XML in result) + var metadata:Array = []; + for each(var m:XML in result) { - metadatas.push(parseMetadata(metadata)); + metadata.push(parseMetadata(m)); } - return null; + return metadata; } public function parseMetadata(reflection:XML):Metadata { var metadata:Metadata = new Metadata(); metadata.name = reflection.@name; metadata.properties = new Dictionary(); for each(var p:XML in reflection.arg) { - metadata.properties[p.@key as String] = p.@value as String; + metadata.properties[String(p.@key)] = String(p.@value); } return metadata; } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/parser/PropertyParser.as b/src/uk/co/ziazoo/fussy/parser/PropertyParser.as index 48d9dbf..fc09341 100644 --- a/src/uk/co/ziazoo/fussy/parser/PropertyParser.as +++ b/src/uk/co/ziazoo/fussy/parser/PropertyParser.as @@ -1,33 +1,23 @@ package uk.co.ziazoo.fussy.parser { - import uk.co.ziazoo.fussy.model.Property; - public class PropertyParser implements IResultParser { - private var metadataParser:MetadataParser; + private var variableParser:VariableParser; + private var accessorParser:AccessorParser; - public function PropertyParser(metadataParser:MetadataParser) + public function PropertyParser(variableParser:VariableParser, + accessorParser:AccessorParser) { - this.metadataParser = metadataParser; + this.variableParser = variableParser; + this.accessorParser = accessorParser; } public function parse(result:XMLList):Array { - var props:Array = []; - for each(var property:XML in result) - { - props.push(parseProperty(property)); - } - return props; - } - - public function parseProperty(reflection:XML):Property - { - var property:Property = new Property(); - property.name = reflection.@name; - property.type = reflection.@type; - property.metadata = metadataParser.parse(reflection.metadata); - return property; + var accessors:Array = accessorParser.parse(result.accessor); + var variables:Array = variableParser.parse(result.variable); + var properties:Array = accessors.concat(variables); + return properties; } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/parser/VariableParser.as b/src/uk/co/ziazoo/fussy/parser/VariableParser.as new file mode 100644 index 0000000..6355c7b --- /dev/null +++ b/src/uk/co/ziazoo/fussy/parser/VariableParser.as @@ -0,0 +1,33 @@ +package uk.co.ziazoo.fussy.parser +{ + import uk.co.ziazoo.fussy.model.Variable; + + public class VariableParser implements IResultParser + { + private var metadataParser:MetadataParser; + + public function VariableParser(metadataParser:MetadataParser) + { + this.metadataParser = metadataParser; + } + + public function parse(result:XMLList):Array + { + var variables:Array = []; + for each(var xml:XML in result) + { + variables.push(parseVariable(xml)); + } + return variables; + } + + private function parseVariable(reflection:XML):Variable + { + var property:Variable = new Variable(); + property.name = reflection.@name; + property.type = reflection.@type; + property.metadata = metadataParser.parse(reflection.metadata); + return property; + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/query/Query.as b/src/uk/co/ziazoo/fussy/query/Query.as index d079283..c2fe019 100644 --- a/src/uk/co/ziazoo/fussy/query/Query.as +++ b/src/uk/co/ziazoo/fussy/query/Query.as @@ -1,69 +1,34 @@ package uk.co.ziazoo.fussy.query { import uk.co.ziazoo.fussy.accessors.AccessorQueryChain; import uk.co.ziazoo.fussy.methods.MethodQueryChain; - import uk.co.ziazoo.fussy.model.Constructor; - import uk.co.ziazoo.fussy.parser.MetadataParser; - import uk.co.ziazoo.fussy.parser.MethodParser; - import uk.co.ziazoo.fussy.parser.ParameterParser; import uk.co.ziazoo.fussy.properties.PropertyQueryChain; import uk.co.ziazoo.fussy.variables.VariableQueryChain; public class Query { - private var methodParser:MethodParser; - private var parameterParser:ParameterParser; - private var metadataParser:MetadataParser; - public function Query() { } public function findMethods():MethodQueryChain { - return new MethodQueryChain(getMetadataParser()); + return new MethodQueryChain(null); } public function findProperties():PropertyQueryChain { return new PropertyQueryChain(); } public function findAccessors():AccessorQueryChain { return new AccessorQueryChain(); } public function findVariables():VariableQueryChain { return new VariableQueryChain(); } - - private function getMethodParser():MethodParser - { - if (!methodParser) - { - methodParser = new MethodParser(getParameterParser(), getMetadataParser()); - } - return methodParser; - } - - private function getParameterParser():ParameterParser - { - if (!parameterParser) - { - parameterParser = new ParameterParser(); - } - return parameterParser; - } - - private function getMetadataParser():MetadataParser - { - if (!metadataParser) - { - metadataParser = new MetadataParser(); - } - return metadataParser; - } } } \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/Bubbles.as b/test/uk/co/ziazoo/fussy/Bubbles.as index 7475298..3b4609d 100644 --- a/test/uk/co/ziazoo/fussy/Bubbles.as +++ b/test/uk/co/ziazoo/fussy/Bubbles.as @@ -1,58 +1,58 @@ package uk.co.ziazoo.fussy { public class Bubbles { public var wibble:Wibble; - + public var wobble:int; - + public var foo:String; - + [Fussy] public var bar:String; - + public function Bubbles(thing:Wibble) { } - + [Inject] public function wowowo(a:int, b:String):void { } - + [Inject] - [Fussy] + [Fussy(thing="bacon")] public function bebeb():void { } - + public function doIt(a:int = 0):void { - + } - + public function bebeboo(h:Object, r:Object):void { } - + public function get sammy():Array { return null; } - + public function get window():Object { return null; } - + public function set window(value:Object):void { } - + [Inject] public function set thing(value:String):void { - + } } } \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/parser/MetadataParserTest.as b/test/uk/co/ziazoo/fussy/parser/MetadataParserTest.as index c753850..be29132 100644 --- a/test/uk/co/ziazoo/fussy/parser/MetadataParserTest.as +++ b/test/uk/co/ziazoo/fussy/parser/MetadataParserTest.as @@ -1,9 +1,52 @@ package uk.co.ziazoo.fussy.parser { + import org.flexunit.Assert; + + import uk.co.ziazoo.fussy.model.Metadata; + public class MetadataParserTest { public function MetadataParserTest() { } + + [Test] + public function parseSomeMetadata():void + { + var parser:MetadataParser = new MetadataParser(); + var root:XML = <root> + <metadata name="Inject"/> + <metadata name="Fussy"> + <arg key="thing" value="bacon"/> + </metadata> + <metadata name="Inject"/> + </root>; + + var all:XMLList = root.metadata; + + var result:Array = parser.parse(all); + + Assert.assertNotNull(result); + Assert.assertTrue(result.length == 3); + } + + [Test] + public function parseOne():void + { + var parser:MetadataParser = new MetadataParser(); + var root:XML = <root> + <metadata name="Fussy"> + <arg key="thing" value="bacon"/> + </metadata> + </root>; + + var one:Array = parser.parse(root.metadata); + + var metadata:Metadata = one[0] as Metadata; + + Assert.assertNotNull(metadata); + Assert.assertTrue(metadata.name == "Fussy"); + Assert.assertTrue(metadata.properties["thing"] == "bacon"); + } } } \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/parser/MethodParserTest.as b/test/uk/co/ziazoo/fussy/parser/MethodParserTest.as new file mode 100644 index 0000000..dabb123 --- /dev/null +++ b/test/uk/co/ziazoo/fussy/parser/MethodParserTest.as @@ -0,0 +1,73 @@ +package uk.co.ziazoo.fussy.parser +{ + import org.flexunit.Assert; + + import uk.co.ziazoo.fussy.model.Method; + + public class MethodParserTest + { + public function MethodParserTest() + { + } + + [Test] + public function parseSomeMethods():void + { + var parser:MethodParser = new MethodParser( + new ParameterParser(), new MetadataParser()); + + var root:XML = <root> + <method name="doIt" declaredBy="uk.co.ziazoo.fussy::Bubbles" returnType="void"> + <parameter index="1" type="int" optional="true"/> + </method> + <method name="bebeboo" declaredBy="uk.co.ziazoo.fussy::Bubbles" returnType="void"> + <parameter index="1" type="Object" optional="false"/> + <parameter index="2" type="Object" optional="false"/> + </method> + <method name="wowowo" declaredBy="uk.co.ziazoo.fussy::Bubbles" returnType="void"> + <parameter index="1" type="int" optional="false"/> + <parameter index="2" type="String" optional="false"/> + <metadata name="Inject"/> + </method> + <method name="bebeb" declaredBy="uk.co.ziazoo.fussy::Bubbles" returnType="void"> + <metadata name="Fussy"> + <arg key="thing" value="bacon"/> + </metadata> + <metadata name="Inject"/> + </method> + </root> + + var result:Array = parser.parse(root.method); + + Assert.assertNotNull(result); + Assert.assertTrue(result.length == 4); + } + + [Test] + public function parseOne():void + { + var parser:MethodParser = new MethodParser( + new ParameterParser(), new MetadataParser()); + + var root:XML = <root> + <method name="wowowo" declaredBy="uk.co.ziazoo.fussy::Bubbles" returnType="void"> + <parameter index="1" type="int" optional="false"/> + <parameter index="2" type="String" optional="false"/> + <metadata name="Inject"/> + </method> + </root>; + + var result:Array = parser.parse(root.method); + + Assert.assertNotNull(result); + Assert.assertTrue(result.length == 1); + + var method:Method; + method = result[0] as Method; + + Assert.assertTrue(method.name == "wowowo"); + Assert.assertTrue(method.parameters.length == 2); + Assert.assertTrue(method.metadata.length == 1); + } + } +} \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/parser/PropertyParserTest.as b/test/uk/co/ziazoo/fussy/parser/PropertyParserTest.as new file mode 100644 index 0000000..5b696a7 --- /dev/null +++ b/test/uk/co/ziazoo/fussy/parser/PropertyParserTest.as @@ -0,0 +1,91 @@ +package uk.co.ziazoo.fussy.parser +{ + import flash.utils.describeType; + + import org.flexunit.Assert; + + import uk.co.ziazoo.fussy.Bubbles; + import uk.co.ziazoo.fussy.model.Metadata; + import uk.co.ziazoo.fussy.model.Property; + + public class PropertyParserTest + { + private var parser:PropertyParser; + + public function PropertyParserTest() + { + } + + [Before] + public function setUp():void + { + var metadataParser:MetadataParser = new MetadataParser(); + parser = new PropertyParser( + new VariableParser(metadataParser), + new AccessorParser(metadataParser)); + } + + [Test] + public function tearDown():void + { + parser = null; + } + + + [Test] + public function parseSomeProperties():void + { + var description:XML = describeType(Bubbles); + var p:XMLList = new XMLList(<root/>); + p.appendChild(description.factory.variable); + p.appendChild(description.factory.accessor); + var props:XMLList = p; + + trace(props); + + var properties:Array = parser.parse(props); + + Assert.assertNotNull(properties); + Assert.assertTrue(properties.length == 7); + } + + [Test] + public function canParseVariable():void + { + var v:XMLList = new XMLList(<root> + <variable name="wibble" type="uk.co.ziazoo.fussy::Wibble"/> + </root>); + + var properties:Array = parser.parse(v); + + Assert.assertNotNull(properties); + Assert.assertTrue(properties.length == 1); + + var prop:Property = properties[0] as Property; + + Assert.assertEquals("wibble", prop.name); + Assert.assertEquals("uk.co.ziazoo.fussy::Wibble", prop.type); + } + + [Test] + public function canParseAccessor():void + { + var v:XMLList = new XMLList(<root> + <accessor name="thing" access="writeonly" type="String" declaredBy="uk.co.ziazoo.fussy::Bubbles"> + <metadata name="Inject"/> + </accessor> + </root>); + + var properties:Array = parser.parse(v); + + Assert.assertNotNull(properties); + Assert.assertTrue(properties.length == 1); + + var prop:Property = properties[0] as Property; + + Assert.assertEquals("thing", prop.name); + Assert.assertEquals("String", prop.type); + Assert.assertEquals(1, prop.metadata.length); + } + } +} \ No newline at end of file
sammyt/fussy
198e73fd2c76c79f1db19f78b1544736e0428427
implementing parsers and tests
diff --git a/src/uk/co/ziazoo/fussy/Fussy.as b/src/uk/co/ziazoo/fussy/Fussy.as index f2471e3..4c98e4c 100644 --- a/src/uk/co/ziazoo/fussy/Fussy.as +++ b/src/uk/co/ziazoo/fussy/Fussy.as @@ -1,19 +1,26 @@ package uk.co.ziazoo.fussy { - import flash.utils.Dictionary; - import flash.utils.describeType; - import uk.co.ziazoo.fussy.query.Query; public class Fussy { public function Fussy() { } + public function forType(type:Class):Type + { + return null; + } + + public function forQName(qName:String):Type + { + return null; + } + public function query():Query { return new Query(); } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/Type.as b/src/uk/co/ziazoo/fussy/Type.as new file mode 100644 index 0000000..2bde79a --- /dev/null +++ b/src/uk/co/ziazoo/fussy/Type.as @@ -0,0 +1,63 @@ +package uk.co.ziazoo.fussy +{ + import uk.co.ziazoo.fussy.model.Constructor; + + /** + * Provides basic information about a class + */ + public class Type + { + public function Type() + { + } + + /** + * The name of a class. For a class with a fully qualified + * name of com.example::Tree the name is Tree + */ + public function get name():String + { + return null; + } + + /** + * The fully qualified of a class + */ + public function get qName():String + { + return null; + } + + /** + * Is this a class that describes a dynamic object + */ + public function get isDynamic():String + { + return null; + } + + /** + * Is this a class that describes a final object + */ + public function get isFinal():String + { + return null; + } + + /** + * The constructor for this object + */ + public function get constructor():Constructor + { + return null; + } + + /** + * Any class level meta data for this class + */ + public function get metaData():Array + { + return null; + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/accessors/AccessorQueryChain.as b/src/uk/co/ziazoo/fussy/accessors/AccessorQueryChain.as index 3a35301..3318e49 100644 --- a/src/uk/co/ziazoo/fussy/accessors/AccessorQueryChain.as +++ b/src/uk/co/ziazoo/fussy/accessors/AccessorQueryChain.as @@ -1,49 +1,41 @@ package uk.co.ziazoo.fussy.accessors { import uk.co.ziazoo.fussy.properties.PropertyQueryChain; public class AccessorQueryChain extends PropertyQueryChain { public function AccessorQueryChain() { } - + public function readable():AccessorQueryChain { parts.push(new Readable()); return this; } - + public function writable():AccessorQueryChain { - /*filtered = getFiltered().( - @access == "readwrite" || @access == "writeonly" - );*/ + parts.push(new Writable()); return this; } - + public function readOnly():AccessorQueryChain { - /*filtered = getFiltered().( - @access == "readonly" - );*/ + parts.push(new ReadOnly()); return this; } - + public function writeOnly():AccessorQueryChain { - /*filtered = getFiltered().( - @access == "writeonly" - );*/ + parts.push(new WriteOnly()); return this; } - + public function readAndWrite():AccessorQueryChain { - /*filtered = getFiltered().( - @access == "readwrite" - );*/ + parts.push(new ReadAndWrite()); return this; } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/accessors/ReadAndWrite.as b/src/uk/co/ziazoo/fussy/accessors/ReadAndWrite.as new file mode 100644 index 0000000..edf0053 --- /dev/null +++ b/src/uk/co/ziazoo/fussy/accessors/ReadAndWrite.as @@ -0,0 +1,18 @@ +package uk.co.ziazoo.fussy.accessors +{ + import uk.co.ziazoo.fussy.query.IQueryPart; + + public class ReadAndWrite implements IQueryPart + { + public function ReadAndWrite() + { + } + + public function filter(data:XMLList):XMLList + { + return data.( + @access == "readwrite" + ); + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/accessors/ReadOnly.as b/src/uk/co/ziazoo/fussy/accessors/ReadOnly.as new file mode 100644 index 0000000..f9f45ef --- /dev/null +++ b/src/uk/co/ziazoo/fussy/accessors/ReadOnly.as @@ -0,0 +1,18 @@ +package uk.co.ziazoo.fussy.accessors +{ + import uk.co.ziazoo.fussy.query.IQueryPart; + + public class ReadOnly implements IQueryPart + { + public function ReadOnly() + { + } + + public function filter(data:XMLList):XMLList + { + return data.( + @access == "readonly" + ); + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/accessors/Readable.as b/src/uk/co/ziazoo/fussy/accessors/Readable.as index c709522..b314663 100644 --- a/src/uk/co/ziazoo/fussy/accessors/Readable.as +++ b/src/uk/co/ziazoo/fussy/accessors/Readable.as @@ -1,18 +1,18 @@ package uk.co.ziazoo.fussy.accessors { import uk.co.ziazoo.fussy.query.IQueryPart; - + public class Readable implements IQueryPart { public function Readable() { } - + public function filter(data:XMLList):XMLList { return data.( @access == "readwrite" || @access == "readonly" - ); + ); } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/accessors/Writable.as b/src/uk/co/ziazoo/fussy/accessors/Writable.as new file mode 100644 index 0000000..1f3248c --- /dev/null +++ b/src/uk/co/ziazoo/fussy/accessors/Writable.as @@ -0,0 +1,18 @@ +package uk.co.ziazoo.fussy.accessors +{ + import uk.co.ziazoo.fussy.query.IQueryPart; + + public class Writable implements IQueryPart + { + public function Writable() + { + } + + public function filter(data:XMLList):XMLList + { + return data.( + @access == "readwrite" || @access == "writeonly" + ); + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/accessors/WriteOnly.as b/src/uk/co/ziazoo/fussy/accessors/WriteOnly.as new file mode 100644 index 0000000..07d1154 --- /dev/null +++ b/src/uk/co/ziazoo/fussy/accessors/WriteOnly.as @@ -0,0 +1,18 @@ +package uk.co.ziazoo.fussy.accessors +{ + import uk.co.ziazoo.fussy.query.IQueryPart; + + public class WriteOnly implements IQueryPart + { + public function WriteOnly() + { + } + + public function filter(data:XMLList):XMLList + { + return data.( + @access == "writeonly" + ); + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as b/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as index 85aaa50..c1fd7d7 100644 --- a/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as +++ b/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as @@ -1,24 +1,27 @@ package uk.co.ziazoo.fussy.methods { + import uk.co.ziazoo.fussy.parser.IResultParser; import uk.co.ziazoo.fussy.query.AbstractQueryChain; + import uk.co.ziazoo.fussy.query.Named; import uk.co.ziazoo.fussy.query.WithMetadata; - + public class MethodQueryChain extends AbstractQueryChain { - public function MethodQueryChain() + public function MethodQueryChain(parser:IResultParser) { + this.parser = parser; } - + public function named(name:String):MethodQueryChain { parts.push(new Named(name)); return this; } - + public function withMetadata(named:String):MethodQueryChain { parts.push(new WithMetadata(named)); return this; } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/methods/NoCompulsoryArgs.as b/src/uk/co/ziazoo/fussy/methods/NoCompulsoryArgs.as index 1270b33..fcd1ccf 100644 --- a/src/uk/co/ziazoo/fussy/methods/NoCompulsoryArgs.as +++ b/src/uk/co/ziazoo/fussy/methods/NoCompulsoryArgs.as @@ -1,18 +1,18 @@ package uk.co.ziazoo.fussy.methods { import uk.co.ziazoo.fussy.query.IQueryPart; - + public class NoCompulsoryArgs implements IQueryPart { public function NoCompulsoryArgs() { } - + public function filter(data:XMLList):XMLList { - return data.( + return data.( !hasOwnProperty("parameter") || parameter.@optional == "true" - ); + ); } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/model/Constructor.as b/src/uk/co/ziazoo/fussy/model/Constructor.as index 0b72f35..febb8e1 100644 --- a/src/uk/co/ziazoo/fussy/model/Constructor.as +++ b/src/uk/co/ziazoo/fussy/model/Constructor.as @@ -1,13 +1,12 @@ -package uk.co.ziazoo.fussy.model +package uk.co.ziazoo.fussy.model { public class Constructor { - public var params:Array; - public var metadatas:Array; - + public var parameters:Array; + public function Constructor() { } } } diff --git a/src/uk/co/ziazoo/fussy/model/Metadata.as b/src/uk/co/ziazoo/fussy/model/Metadata.as index 8315e7a..86b05f4 100644 --- a/src/uk/co/ziazoo/fussy/model/Metadata.as +++ b/src/uk/co/ziazoo/fussy/model/Metadata.as @@ -1,14 +1,14 @@ package uk.co.ziazoo.fussy.model -{ +{ import flash.utils.Dictionary; - + public class Metadata { public var name:String; public var properties:Dictionary; - + public function Metadata() { } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/model/Method.as b/src/uk/co/ziazoo/fussy/model/Method.as index 2e92409..91f6424 100644 --- a/src/uk/co/ziazoo/fussy/model/Method.as +++ b/src/uk/co/ziazoo/fussy/model/Method.as @@ -1,13 +1,13 @@ package uk.co.ziazoo.fussy.model -{ +{ public class Method { public var name:String; - public var params:Array; - public var metadatas:Array; - + public var parameters:Array; + public var metadata:Array; + public function Method() { } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/model/Parser.as b/src/uk/co/ziazoo/fussy/model/Parser.as deleted file mode 100644 index 66b5c79..0000000 --- a/src/uk/co/ziazoo/fussy/model/Parser.as +++ /dev/null @@ -1,77 +0,0 @@ -package uk.co.ziazoo.fussy.model -{ - public class Parser - { - public function Parser() - { - } - - public function parseConstructor( reflection:XML ):Constructor - { - var constructor:Constructor = new Constructor(); - - for each( var p:XML in reflection.constructor.parameter ) - { - constructor.params.push( parseParameter( p ) ); - } - - for each( var m:XML in reflection.metadata ) - { - constructor.metadatas.push( parseMetadata( m ) ); - } - return constructor; - } - - public function parseProperty( prop:XML ):Property - { - var property:Property = new Property(); - property.name = prop.@name; - property.type = prop.@type; - - for each( var m:XML in prop.metadata ) - { - property.metadatas.push( parseMetadata( m ) ); - } - return property; - } - - public function parseMethod( reflection:XML ):Method - { - var method:Method = new Method(); - method.name = reflection.@name; - - for each( var p:XML in reflection.parameter ) - { - method.params.push( parseParameter( p ) ); - } - - for each( var m:XML in reflection.metadata ) - { - method.metadatas.push( parseMetadata( m ) ); - } - - return method; - } - - public function parseMetadata( reflection:XML ):Metadata - { - var metadata:Metadata = new Metadata(); - metadata.name = reflection.@name; - - for each( var p:XML in reflection.arg ) - { - metadata.properties[p.@key as String] = p.@value as String; - } - return metadata; - } - - public function parseParameter( reflection:XML ):Parameter - { - var parameter:Parameter = new Parameter(); - parameter.index = parseInt( reflection.@index ); - parameter.type = reflection.@type; - parameter.optional = reflection.@optional == "true"; - return parameter; - } - } -} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/model/Property.as b/src/uk/co/ziazoo/fussy/model/Property.as index 8ee3d0e..fc26594 100644 --- a/src/uk/co/ziazoo/fussy/model/Property.as +++ b/src/uk/co/ziazoo/fussy/model/Property.as @@ -1,13 +1,13 @@ package uk.co.ziazoo.fussy.model -{ +{ public class Property { public var name:String; public var type:String; - public var metadatas:Array; - + public var metadata:Array; + public function Property() { } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/parser/ConstructorParser.as b/src/uk/co/ziazoo/fussy/parser/ConstructorParser.as index 36a2a21..a801238 100644 --- a/src/uk/co/ziazoo/fussy/parser/ConstructorParser.as +++ b/src/uk/co/ziazoo/fussy/parser/ConstructorParser.as @@ -1,12 +1,21 @@ package uk.co.ziazoo.fussy.parser -{ - public class ConstructorParser +{ + import uk.co.ziazoo.fussy.model.Constructor; + + public class ConstructorParser implements IResultParser { private var parameterParser:ParameterParser; - + public function ConstructorParser(parameterParser:ParameterParser) { this.parameterParser = parameterParser; } + + public function parse(result:XMLList):Array + { + var constructor:Constructor = new Constructor(); + constructor.parameters = parameterParser.parse(result.constructor.parameter); + return [constructor]; + } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/parser/IResultParser.as b/src/uk/co/ziazoo/fussy/parser/IResultParser.as new file mode 100644 index 0000000..b91bfd7 --- /dev/null +++ b/src/uk/co/ziazoo/fussy/parser/IResultParser.as @@ -0,0 +1,7 @@ +package uk.co.ziazoo.fussy.parser +{ + public interface IResultParser + { + function parse(result:XMLList):Array; + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/parser/MetadataParser.as b/src/uk/co/ziazoo/fussy/parser/MetadataParser.as index 3c54879..cce0de9 100644 --- a/src/uk/co/ziazoo/fussy/parser/MetadataParser.as +++ b/src/uk/co/ziazoo/fussy/parser/MetadataParser.as @@ -1,10 +1,37 @@ package uk.co.ziazoo.fussy.parser -{ - public class MetadataParser extends Object +{ + import flash.utils.Dictionary; + + import uk.co.ziazoo.fussy.model.Metadata; + + public class MetadataParser implements IResultParser { public function MetadataParser() { super(); } + + public function parse(result:XMLList):Array + { + var metadatas:Array = []; + for each(var metadata:XML in result) + { + metadatas.push(parseMetadata(metadata)); + } + return null; + } + + public function parseMetadata(reflection:XML):Metadata + { + var metadata:Metadata = new Metadata(); + metadata.name = reflection.@name; + metadata.properties = new Dictionary(); + + for each(var p:XML in reflection.arg) + { + metadata.properties[p.@key as String] = p.@value as String; + } + return metadata; + } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/parser/MethodParser.as b/src/uk/co/ziazoo/fussy/parser/MethodParser.as index b99f35b..c976e18 100644 --- a/src/uk/co/ziazoo/fussy/parser/MethodParser.as +++ b/src/uk/co/ziazoo/fussy/parser/MethodParser.as @@ -1,15 +1,36 @@ package uk.co.ziazoo.fussy.parser -{ - public class MethodParser +{ + import uk.co.ziazoo.fussy.model.Method; + + public class MethodParser implements IResultParser { private var parameterParser:ParameterParser; private var metadataParser:MetadataParser; - + public function MethodParser(parameterParser:ParameterParser, metadataParser:MetadataParser) { this.parameterParser = parameterParser; this.metadataParser = metadataParser; } + + public function parse(result:XMLList):Array + { + var methods:Array = []; + for each(var method:XML in result) + { + methods.push(parseMethod(method)); + } + return methods; + } + + public function parseMethod(reflection:XML):Method + { + var method:Method = new Method(); + method.name = reflection.@name; + method.parameters = parameterParser.parse(reflection.parameter); + method.metadata = metadataParser.parse(reflection.metadata); + return method; + } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/parser/ParameterParser.as b/src/uk/co/ziazoo/fussy/parser/ParameterParser.as index 4a9cd17..67411ce 100644 --- a/src/uk/co/ziazoo/fussy/parser/ParameterParser.as +++ b/src/uk/co/ziazoo/fussy/parser/ParameterParser.as @@ -1,10 +1,32 @@ package uk.co.ziazoo.fussy.parser -{ - public class ParameterParser extends Object +{ + import uk.co.ziazoo.fussy.model.Parameter; + + public class ParameterParser implements IResultParser { public function ParameterParser() { super(); } + + + public function parse(result:XMLList):Array + { + var params:Array = []; + for each(var param:XML in result) + { + params.push(parseParameter(param)); + } + return params; + } + + public function parseParameter(reflection:XML):Parameter + { + var parameter:Parameter = new Parameter(); + parameter.index = parseInt(reflection.@index); + parameter.type = reflection.@type; + parameter.optional = reflection.@optional == "true"; + return parameter; + } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/parser/PropertyParser.as b/src/uk/co/ziazoo/fussy/parser/PropertyParser.as index 971948d..48d9dbf 100644 --- a/src/uk/co/ziazoo/fussy/parser/PropertyParser.as +++ b/src/uk/co/ziazoo/fussy/parser/PropertyParser.as @@ -1,12 +1,33 @@ package uk.co.ziazoo.fussy.parser -{ - public class PropertyParser +{ + import uk.co.ziazoo.fussy.model.Property; + + public class PropertyParser implements IResultParser { private var metadataParser:MetadataParser; - + public function PropertyParser(metadataParser:MetadataParser) { this.metadataParser = metadataParser; } + + public function parse(result:XMLList):Array + { + var props:Array = []; + for each(var property:XML in result) + { + props.push(parseProperty(property)); + } + return props; + } + + public function parseProperty(reflection:XML):Property + { + var property:Property = new Property(); + property.name = reflection.@name; + property.type = reflection.@type; + property.metadata = metadataParser.parse(reflection.metadata); + return property; + } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/properties/OfType.as b/src/uk/co/ziazoo/fussy/properties/OfType.as index e46f864..5ce763b 100644 --- a/src/uk/co/ziazoo/fussy/properties/OfType.as +++ b/src/uk/co/ziazoo/fussy/properties/OfType.as @@ -1,23 +1,23 @@ package uk.co.ziazoo.fussy.properties { import flash.utils.getQualifiedClassName; - + import uk.co.ziazoo.fussy.query.IQueryPart; - + public class OfType implements IQueryPart { private var type:Class; - + public function OfType(type:Class) { this.type = type; } - + public function filter(data:XMLList):XMLList { return data.( @type == getQualifiedClassName(type) - ); + ); } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/properties/PropertyQueryChain.as b/src/uk/co/ziazoo/fussy/properties/PropertyQueryChain.as index 6f32f7e..73a4b38 100644 --- a/src/uk/co/ziazoo/fussy/properties/PropertyQueryChain.as +++ b/src/uk/co/ziazoo/fussy/properties/PropertyQueryChain.as @@ -1,24 +1,24 @@ package uk.co.ziazoo.fussy.properties { import uk.co.ziazoo.fussy.query.AbstractQueryChain; import uk.co.ziazoo.fussy.query.WithMetadata; - + public class PropertyQueryChain extends AbstractQueryChain { public function PropertyQueryChain() { } - + public function ofType(type:Class):PropertyQueryChain { parts.push(new OfType(type)); return this; } - + public function withMetadata(name:String):PropertyQueryChain { parts.push(new WithMetadata(name)); return this; } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/query/AbstractQueryChain.as b/src/uk/co/ziazoo/fussy/query/AbstractQueryChain.as index 69c9fcc..4e53ead 100644 --- a/src/uk/co/ziazoo/fussy/query/AbstractQueryChain.as +++ b/src/uk/co/ziazoo/fussy/query/AbstractQueryChain.as @@ -1,41 +1,65 @@ package uk.co.ziazoo.fussy.query { import flash.utils.describeType; + import uk.co.ziazoo.fussy.parser.IResultParser; + public class AbstractQueryChain implements IQueryChain { /** * @private - */ + */ protected var parts:Array; - + + private var _parser:IResultParser; + public function AbstractQueryChain() { parts = []; } - - public function forType(type:Class):XMLList + + public function forType(type:Class):Array + { + return parser.parse(xmlforType(type)); + } + + public function xmlforType(type:Class):XMLList { - if(parts.length == 0) + if (parts.length == 0) { return null; } - + var reflection:XML = describeType(type); var methods:XMLList = reflection.factory.method; - + var firstPart:IQueryPart = parts[0]; var lastResult:XMLList = firstPart.filter(methods); - + var i:uint = uint(parts.length - 1); - while(i > 0) + while (i > 0) { var part:IQueryPart = parts[i]; lastResult = part.filter(lastResult); i--; } - + return lastResult; } + + public function get parser():IResultParser + { + return _parser; + } + + public function set parser(value:IResultParser):void + { + _parser = value; + } + + public function addQueryPart(part:IQueryPart):void + { + parts.push(part); + } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/query/IQuery.as b/src/uk/co/ziazoo/fussy/query/IQuery.as index f45777d..036243c 100644 --- a/src/uk/co/ziazoo/fussy/query/IQuery.as +++ b/src/uk/co/ziazoo/fussy/query/IQuery.as @@ -1,7 +1,7 @@ package uk.co.ziazoo.fussy.query { public interface IQuery { - function forType(type:Class):XMLList; + function forType(type:Class):Array; } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/query/IQueryChain.as b/src/uk/co/ziazoo/fussy/query/IQueryChain.as index 5832caf..05d80c7 100644 --- a/src/uk/co/ziazoo/fussy/query/IQueryChain.as +++ b/src/uk/co/ziazoo/fussy/query/IQueryChain.as @@ -1,7 +1,13 @@ package uk.co.ziazoo.fussy.query { + import uk.co.ziazoo.fussy.parser.IResultParser; + public interface IQueryChain extends IQuery { - + function addQueryPart(part:IQueryPart):void; + + function get parser():IResultParser; + + function set parser(value:IResultParser):void; } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/methods/Named.as b/src/uk/co/ziazoo/fussy/query/Named.as similarity index 65% rename from src/uk/co/ziazoo/fussy/methods/Named.as rename to src/uk/co/ziazoo/fussy/query/Named.as index 2bcf824..14a467d 100644 --- a/src/uk/co/ziazoo/fussy/methods/Named.as +++ b/src/uk/co/ziazoo/fussy/query/Named.as @@ -1,21 +1,18 @@ -package uk.co.ziazoo.fussy.methods +package uk.co.ziazoo.fussy.query { - import org.flexunit.runner.Result; - - import uk.co.ziazoo.fussy.query.IQueryPart; - + public class Named implements IQueryPart { private var name:String; - + public function Named(name:String) { this.name = name; } - + public function filter(data:XMLList):XMLList { return data.(@name == name); } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/query/Query.as b/src/uk/co/ziazoo/fussy/query/Query.as index cb7c925..d079283 100644 --- a/src/uk/co/ziazoo/fussy/query/Query.as +++ b/src/uk/co/ziazoo/fussy/query/Query.as @@ -1,16 +1,69 @@ package uk.co.ziazoo.fussy.query { + import uk.co.ziazoo.fussy.accessors.AccessorQueryChain; import uk.co.ziazoo.fussy.methods.MethodQueryChain; + import uk.co.ziazoo.fussy.model.Constructor; + import uk.co.ziazoo.fussy.parser.MetadataParser; + import uk.co.ziazoo.fussy.parser.MethodParser; + import uk.co.ziazoo.fussy.parser.ParameterParser; + import uk.co.ziazoo.fussy.properties.PropertyQueryChain; + import uk.co.ziazoo.fussy.variables.VariableQueryChain; public class Query { + private var methodParser:MethodParser; + private var parameterParser:ParameterParser; + private var metadataParser:MetadataParser; + public function Query() { } - + public function findMethods():MethodQueryChain { - return new MethodQueryChain(); + return new MethodQueryChain(getMetadataParser()); + } + + public function findProperties():PropertyQueryChain + { + return new PropertyQueryChain(); + } + + public function findAccessors():AccessorQueryChain + { + return new AccessorQueryChain(); + } + + public function findVariables():VariableQueryChain + { + return new VariableQueryChain(); + } + + private function getMethodParser():MethodParser + { + if (!methodParser) + { + methodParser = new MethodParser(getParameterParser(), getMetadataParser()); + } + return methodParser; + } + + private function getParameterParser():ParameterParser + { + if (!parameterParser) + { + parameterParser = new ParameterParser(); + } + return parameterParser; + } + + private function getMetadataParser():MetadataParser + { + if (!metadataParser) + { + metadataParser = new MetadataParser(); + } + return metadataParser; } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/variables/VariableQueryChain.as b/src/uk/co/ziazoo/fussy/variables/VariableQueryChain.as index a098363..8d7c870 100644 --- a/src/uk/co/ziazoo/fussy/variables/VariableQueryChain.as +++ b/src/uk/co/ziazoo/fussy/variables/VariableQueryChain.as @@ -1,11 +1,11 @@ package uk.co.ziazoo.fussy.variables { import uk.co.ziazoo.fussy.properties.PropertyQueryChain; - + public class VariableQueryChain extends PropertyQueryChain { public function VariableQueryChain() { } } } \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/FussyTest.as b/test/uk/co/ziazoo/fussy/FussyTest.as index f7e1fb1..fc04618 100644 --- a/test/uk/co/ziazoo/fussy/FussyTest.as +++ b/test/uk/co/ziazoo/fussy/FussyTest.as @@ -1,32 +1,21 @@ -package uk.co.ziazoo.fussy +package uk.co.ziazoo.fussy { import uk.co.ziazoo.fussy.query.IQuery; - import uk.co.ziazoo.fussy.query.Query; /** * nothing useful here yet, just demos of the api - */ + */ public class FussyTest - { - + { + [Test] public function createVariableFussy():void { var fussy:Fussy = new Fussy(); - + var query:IQuery = fussy.query().findMethods().withMetadata("Inject"); - - var list:XMLList = query.forType(Bubbles); - - trace(list); - /* - - var factory:XMLList = getFiltered().factory.( - hasOwnProperty("constructor") && - constructor.hasOwnProperty("parameter") - ); - - */ + + var list:Array = query.forType(Bubbles); } } } \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/accessors/ReadAndWriteTest.as b/test/uk/co/ziazoo/fussy/accessors/ReadAndWriteTest.as new file mode 100644 index 0000000..7f1406e --- /dev/null +++ b/test/uk/co/ziazoo/fussy/accessors/ReadAndWriteTest.as @@ -0,0 +1,35 @@ +package uk.co.ziazoo.fussy.accessors +{ + import flash.utils.describeType; + + import org.flexunit.Assert; + + import uk.co.ziazoo.fussy.Bubbles; + + public class ReadAndWriteTest + { + private var accessors:XMLList; + + [Before] + public function setUp():void + { + var description:XML = describeType(Bubbles); + accessors = description.factory.accessor; + } + + [After] + public function tearDown():void + { + accessors = null; + } + + [Test] + public function all_readable_accessors():void + { + var readAndWrite:ReadAndWrite = new ReadAndWrite(); + var result:XMLList = readAndWrite.filter(accessors); + Assert.assertNotNull(result); + Assert.assertTrue(result.length() == 1); + } + } +} \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/accessors/ReadOnlyTest.as b/test/uk/co/ziazoo/fussy/accessors/ReadOnlyTest.as new file mode 100644 index 0000000..8ca54e3 --- /dev/null +++ b/test/uk/co/ziazoo/fussy/accessors/ReadOnlyTest.as @@ -0,0 +1,35 @@ +package uk.co.ziazoo.fussy.accessors +{ + import flash.utils.describeType; + + import org.flexunit.Assert; + + import uk.co.ziazoo.fussy.Bubbles; + + public class ReadOnlyTest + { + private var accessors:XMLList; + + [Before] + public function setUp():void + { + var description:XML = describeType(Bubbles); + accessors = description.factory.accessor; + } + + [After] + public function tearDown():void + { + accessors = null; + } + + [Test] + public function all_readable_accessors():void + { + var readOnly:ReadOnly = new ReadOnly(); + var result:XMLList = readOnly.filter(accessors); + Assert.assertNotNull(result); + Assert.assertTrue(result.length() == 1); + } + } +} \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/accessors/ReadableTest.as b/test/uk/co/ziazoo/fussy/accessors/ReadableTest.as index 5c4e881..7627506 100644 --- a/test/uk/co/ziazoo/fussy/accessors/ReadableTest.as +++ b/test/uk/co/ziazoo/fussy/accessors/ReadableTest.as @@ -1,36 +1,35 @@ package uk.co.ziazoo.fussy.accessors { import flash.utils.describeType; - + import org.flexunit.Assert; - + import uk.co.ziazoo.fussy.Bubbles; - import uk.co.ziazoo.fussy.properties.OfType; - + public class ReadableTest { private var accessors:XMLList; - + [Before] public function setUp():void { var description:XML = describeType(Bubbles); - accessors = description.factory.accessor; + accessors = description.factory.accessor; } - + [After] public function tearDown():void { accessors = null; } - + [Test] public function all_readable_accessors():void { var readable:Readable = new Readable(); var result:XMLList = readable.filter(accessors); Assert.assertNotNull(result); Assert.assertTrue(result.length() == 2); } } } \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/accessors/WritableTest.as b/test/uk/co/ziazoo/fussy/accessors/WritableTest.as new file mode 100644 index 0000000..ffa2abd --- /dev/null +++ b/test/uk/co/ziazoo/fussy/accessors/WritableTest.as @@ -0,0 +1,35 @@ +package uk.co.ziazoo.fussy.accessors +{ + import flash.utils.describeType; + + import org.flexunit.Assert; + + import uk.co.ziazoo.fussy.Bubbles; + + public class WritableTest + { + private var accessors:XMLList; + + [Before] + public function setUp():void + { + var description:XML = describeType(Bubbles); + accessors = description.factory.accessor; + } + + [After] + public function tearDown():void + { + accessors = null; + } + + [Test] + public function all_writeable_accessors():void + { + var writeable:Writable = new Writable(); + var result:XMLList = writeable.filter(accessors); + Assert.assertNotNull(result); + Assert.assertTrue(result.length() == 2); + } + } +} \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/accessors/WriteOnlyTest.as b/test/uk/co/ziazoo/fussy/accessors/WriteOnlyTest.as new file mode 100644 index 0000000..771f67c --- /dev/null +++ b/test/uk/co/ziazoo/fussy/accessors/WriteOnlyTest.as @@ -0,0 +1,35 @@ +package uk.co.ziazoo.fussy.accessors +{ + import flash.utils.describeType; + + import org.flexunit.Assert; + + import uk.co.ziazoo.fussy.Bubbles; + + public class WriteOnlyTest + { + private var accessors:XMLList; + + [Before] + public function setUp():void + { + var description:XML = describeType(Bubbles); + accessors = description.factory.accessor; + } + + [After] + public function tearDown():void + { + accessors = null; + } + + [Test] + public function all_writeable_accessors():void + { + var writeOnly:WriteOnly = new WriteOnly(); + var result:XMLList = writeOnly.filter(accessors); + Assert.assertNotNull(result); + Assert.assertTrue(result.length() == 1); + } + } +} \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/methods/MethodQueryChainTest.as b/test/uk/co/ziazoo/fussy/methods/MethodQueryChainTest.as index 686b24a..3910b00 100644 --- a/test/uk/co/ziazoo/fussy/methods/MethodQueryChainTest.as +++ b/test/uk/co/ziazoo/fussy/methods/MethodQueryChainTest.as @@ -1,31 +1,31 @@ package uk.co.ziazoo.fussy.methods { import flash.utils.describeType; - + import uk.co.ziazoo.fussy.Bubbles; public class MethodQueryChainTest - { + { private var methodsList:XMLList; - + [Before] public function setUp():void { var tmp:XML = describeType(Bubbles); methodsList = tmp.factory.method; } - + [After] public function tearDown():void { methodsList = null; } - + [Test] public function createNameQuery():void { - var chain:MethodQueryChain = new MethodQueryChain(); + var chain:MethodQueryChain = new MethodQueryChain(null); chain.named("wowowo"); } } } \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/methods/NoArgsTest.as b/test/uk/co/ziazoo/fussy/methods/NoArgsTest.as index fa37516..124441b 100644 --- a/test/uk/co/ziazoo/fussy/methods/NoArgsTest.as +++ b/test/uk/co/ziazoo/fussy/methods/NoArgsTest.as @@ -1,34 +1,34 @@ package uk.co.ziazoo.fussy.methods { import flash.utils.describeType; - + import org.flexunit.Assert; - + import uk.co.ziazoo.fussy.Bubbles; - + public class NoArgsTest - { + { private var methods:XMLList; - + [Before] public function setUp():void { methods = describeType(Bubbles).factory.method; } - + [After] public function tearDown():void { methods = null; } - + [Test] public function noNeededArgs():void { var noArgs:NoArgs = new NoArgs(); var result:XMLList = noArgs.filter(methods); Assert.assertNotNull(result); Assert.assertTrue(result.length() == 1); } } } \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/methods/NoCompulsoryArgsTest.as b/test/uk/co/ziazoo/fussy/methods/NoCompulsoryArgsTest.as index 1afbcf5..9390fc6 100644 --- a/test/uk/co/ziazoo/fussy/methods/NoCompulsoryArgsTest.as +++ b/test/uk/co/ziazoo/fussy/methods/NoCompulsoryArgsTest.as @@ -1,34 +1,34 @@ package uk.co.ziazoo.fussy.methods { import flash.utils.describeType; - + import org.flexunit.Assert; - + import uk.co.ziazoo.fussy.Bubbles; public class NoCompulsoryArgsTest - { + { private var methods:XMLList; - + [Before] public function setUp():void { methods = describeType(Bubbles).factory.method; } - + [After] public function tearDown():void { methods = null; } - + [Test] public function noNeededArgs():void { var noArgs:NoCompulsoryArgs = new NoCompulsoryArgs(); var result:XMLList = noArgs.filter(methods); Assert.assertNotNull(result); Assert.assertTrue(result.length() == 2); } } } \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/parser/MetadataParserTest.as b/test/uk/co/ziazoo/fussy/parser/MetadataParserTest.as new file mode 100644 index 0000000..c753850 --- /dev/null +++ b/test/uk/co/ziazoo/fussy/parser/MetadataParserTest.as @@ -0,0 +1,9 @@ +package uk.co.ziazoo.fussy.parser +{ + public class MetadataParserTest + { + public function MetadataParserTest() + { + } + } +} \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/parser/ParameterParserTest.as b/test/uk/co/ziazoo/fussy/parser/ParameterParserTest.as new file mode 100644 index 0000000..2047d91 --- /dev/null +++ b/test/uk/co/ziazoo/fussy/parser/ParameterParserTest.as @@ -0,0 +1,71 @@ +package uk.co.ziazoo.fussy.parser +{ + import uk.co.ziazoo.fussy.model.*; + + import flash.utils.describeType; + + import org.flexunit.Assert; + + import uk.co.ziazoo.fussy.Bubbles; + import uk.co.ziazoo.fussy.parser.ParameterParser; + + public class ParameterParserTest + { + private var paramList:XMLList; + + public function ParameterParserTest() + { + } + + [Before] + public function setUp():void + { + paramList = describeType(Bubbles).factory.method.parameter; + } + + [After] + public function tearDown():void + { + paramList = null; + } + + + [Test] + public function parseListOfParameters():void + { + var parser:ParameterParser = new ParameterParser(); + var parameters:Array = parser.parse(paramList); + + Assert.assertNotNull(parameters); + Assert.assertTrue(parameters.length == 5); + + var index:int = parameters.length - 1; + while (index >= 0) + { + var param:Object = parameters[index]; + Assert.assertNotNull(param); + Assert.assertTrue(param is Parameter); + + index --; + } + } + + [Test] + public function parseOneParam():void + { + var p:XMLList = new XMLList('' + + '<parameter index="1" optional="true" type="uk.co.ziazoo.fussy::Bubbles"/>'); + + var parser:ParameterParser = new ParameterParser(); + var params:Array = parser.parse(p); + + Assert.assertTrue(params.length == 1); + + var param:Parameter = params[0] as Parameter; + Assert.assertNotNull(param); + Assert.assertTrue(param.index == 1); + Assert.assertTrue(param.optional == true); + Assert.assertTrue(param.type == "uk.co.ziazoo.fussy::Bubbles"); + } + } +} \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/properties/OfTypeTest.as b/test/uk/co/ziazoo/fussy/properties/OfTypeTest.as index dea7825..6365416 100644 --- a/test/uk/co/ziazoo/fussy/properties/OfTypeTest.as +++ b/test/uk/co/ziazoo/fussy/properties/OfTypeTest.as @@ -1,39 +1,38 @@ package uk.co.ziazoo.fussy.properties { import flash.utils.describeType; - + import org.flexunit.Assert; - + import uk.co.ziazoo.fussy.Bubbles; - import uk.co.ziazoo.fussy.properties.OfType; - + public class OfTypeTest { private var properties:XMLList; - + [Before] public function setUp():void { var description:XML = describeType(Bubbles); var p:XMLList = new XMLList(<root/>); p.appendChild(description.factory.variable); p.appendChild(description.factory.accessor); - properties = p.*; + properties = p.*; } - + [After] public function tearDown():void { properties = null; } - + [Test] public function all_props_of_string():void { var ofType:OfType = new OfType(String); var result:XMLList = ofType.filter(properties); Assert.assertNotNull(result); Assert.assertTrue(result.length() == 3); } } } \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/methods/NamedTest.as b/test/uk/co/ziazoo/fussy/query/NamedTest.as similarity index 83% rename from test/uk/co/ziazoo/fussy/methods/NamedTest.as rename to test/uk/co/ziazoo/fussy/query/NamedTest.as index 9cfae86..60be5c4 100644 --- a/test/uk/co/ziazoo/fussy/methods/NamedTest.as +++ b/test/uk/co/ziazoo/fussy/query/NamedTest.as @@ -1,35 +1,35 @@ -package uk.co.ziazoo.fussy.methods +package uk.co.ziazoo.fussy.query { import flash.utils.describeType; - + import org.flexunit.Assert; - + import uk.co.ziazoo.fussy.Bubbles; public class NamedTest { private var methods:XMLList; - + [Before] public function setUp():void { methods = describeType(Bubbles).factory.method; } - + [After] public function tearDown():void { methods = null; } - + [Test] public function getOne():void { var named:Named = new Named("wowowo"); var result:XMLList = named.filter(methods); Assert.assertNotNull(result); Assert.assertTrue(result.length() == 1); - Assert.assertTrue(String(result.@name) == "wowowo" ); + Assert.assertTrue(String(result.@name) == "wowowo"); } } } \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/query/QueryTest.as b/test/uk/co/ziazoo/fussy/query/QueryTest.as index 753d239..093cb10 100644 --- a/test/uk/co/ziazoo/fussy/query/QueryTest.as +++ b/test/uk/co/ziazoo/fussy/query/QueryTest.as @@ -1,27 +1,24 @@ package uk.co.ziazoo.fussy.query { - import uk.co.ziazoo.fussy.Fussy; - public class QueryTest - { + { [Before] public function setUp():void { } - + [After] public function tearDown():void { } - + [Test] public function creation():void { var query:Query = new Query(); query.findMethods().named("getEtc"); - - - + + } } } \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/query/WithMetadataTest.as b/test/uk/co/ziazoo/fussy/query/WithMetadataTest.as index 4ac4810..78d5905 100644 --- a/test/uk/co/ziazoo/fussy/query/WithMetadataTest.as +++ b/test/uk/co/ziazoo/fussy/query/WithMetadataTest.as @@ -1,34 +1,34 @@ package uk.co.ziazoo.fussy.query { import flash.utils.describeType; - + import org.flexunit.Assert; - + import uk.co.ziazoo.fussy.Bubbles; public class WithMetadataTest - { + { private var methods:XMLList; - + [Before] public function setUp():void { methods = describeType(Bubbles).factory.method; } - + [After] public function tearDown():void { methods = null; } - + [Test] public function filters():void { var withMetadata:WithMetadata = new WithMetadata("Inject"); var result:XMLList = withMetadata.filter(methods); Assert.assertNotNull(result); Assert.assertTrue(result.length() == 2); - } + } } } \ No newline at end of file
sammyt/fussy
d5c627bbc5333c6421d226ffec69ecb3cffc7a80
refactorying for reusable queries
diff --git a/src/uk/co/ziazoo/fussy/AbstractQuery.as b/src/uk/co/ziazoo/fussy/AbstractQuery.as deleted file mode 100644 index 828ba3a..0000000 --- a/src/uk/co/ziazoo/fussy/AbstractQuery.as +++ /dev/null @@ -1,32 +0,0 @@ -package uk.co.ziazoo.fussy -{ - public class AbstractQuery implements IFilter - { - protected var description:XML; - protected var filtered:XMLList; - - public function AbstractQuery(description:XML) - { - this.description = description; - } - - public function get length():int - { - return filtered.length(); - } - - public function get result():Array - { - return null; - } - - /** - * @private - * just for use in unit tests - */ - internal function getResult():XMLList - { - return filtered; - } - } -} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/AccessorQuery.as b/src/uk/co/ziazoo/fussy/AccessorQuery.as deleted file mode 100644 index 8e7cbe2..0000000 --- a/src/uk/co/ziazoo/fussy/AccessorQuery.as +++ /dev/null @@ -1,85 +0,0 @@ -package uk.co.ziazoo.fussy -{ - import flash.utils.getQualifiedClassName; - - public class AccessorQuery extends AbstractQuery - { - public function AccessorQuery(description:XML) - { - super(description); - } - - public function ofType(type:Class):AccessorQuery - { - filtered = getFiltered().( - @type == getQualifiedClassName(type) - ); - return this; - } - - public function withMetadata(name:String):AccessorQuery - { - filtered = getFiltered().( - hasOwnProperty("metadata") && metadata.(@name == name) - ); - return this; - } - - public function readable():AccessorQuery - { - filtered = getFiltered().( - @access == "readwrite" || @access == "readonly" - ); - return this; - } - - public function writable():AccessorQuery - { - filtered = getFiltered().( - @access == "readwrite" || @access == "writeonly" - ); - return this; - } - - public function readOnly():AccessorQuery - { - filtered = getFiltered().( - @access == "readonly" - ); - return this; - } - - public function writeOnly():AccessorQuery - { - filtered = getFiltered().( - @access == "writeonly" - ); - return this; - } - - public function readAndWrite():AccessorQuery - { - filtered = getFiltered().( - @access == "readwrite" - ); - return this; - } - - protected function getFiltered():XMLList - { - if(!filtered) - { - filtered = description.factory.accessor; - } - return filtered; - } - - /** - * @inheritDoc - */ - override public function get result():Array - { - return null; - } - } -} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/ConstructorQuery.as b/src/uk/co/ziazoo/fussy/ConstructorQuery.as deleted file mode 100644 index 57c4505..0000000 --- a/src/uk/co/ziazoo/fussy/ConstructorQuery.as +++ /dev/null @@ -1,42 +0,0 @@ -package uk.co.ziazoo.fussy -{ - public class ConstructorQuery extends AbstractQuery - { - public function ConstructorQuery(description:XML) - { - super(description); - } - - /** - * @private - * flash fail http://bugs.adobe.com/jira/browse/FP-183 - */ - internal function needsHack():Boolean - { - return hasArgs(); - } - - private function hasArgs():Boolean - { - var factory:XMLList = getFiltered().factory.( - hasOwnProperty("constructor") && - constructor.hasOwnProperty("parameter") - ); - - if(factory.length() == 0) - { - return false; - } - return true; - } - - protected function getFiltered():XMLList - { - if(!filtered) - { - filtered = new XMLList(description); - } - return filtered; - } - } -} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/Fussy.as b/src/uk/co/ziazoo/fussy/Fussy.as index 11307dd..f2471e3 100644 --- a/src/uk/co/ziazoo/fussy/Fussy.as +++ b/src/uk/co/ziazoo/fussy/Fussy.as @@ -1,36 +1,19 @@ package uk.co.ziazoo.fussy { import flash.utils.Dictionary; import flash.utils.describeType; import uk.co.ziazoo.fussy.query.Query; public class Fussy { - private var cache:Dictionary; - public function Fussy() { - this.cache = new Dictionary(); } - - public function forType(type:Class):QueryBuilder - { - return new QueryBuilder(getDescription(type)); - } - - private function getDescription(type:Class):XML - { - if(!cache[type]) - { - cache[type] = describeType(type); - } - return cache[type] as XML - } - + public function query():Query { return new Query(); } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/IFilter.as b/src/uk/co/ziazoo/fussy/IFilter.as deleted file mode 100644 index 63e4e27..0000000 --- a/src/uk/co/ziazoo/fussy/IFilter.as +++ /dev/null @@ -1,8 +0,0 @@ -package uk.co.ziazoo.fussy -{ - public interface IFilter - { - function get length():int; - function get result():Array; - } -} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/MethodQuery.as b/src/uk/co/ziazoo/fussy/MethodQuery.as deleted file mode 100644 index 5df20bf..0000000 --- a/src/uk/co/ziazoo/fussy/MethodQuery.as +++ /dev/null @@ -1,57 +0,0 @@ -package uk.co.ziazoo.fussy -{ - import uk.co.ziazoo.fussy.parser.MethodParser; - - public class MethodQuery extends AbstractQuery - { - private var methodParser:MethodParser; - - public function MethodQuery(description:XML, methodParser:MethodParser) - { - super(description); - - this.methodParser = methodParser; - } - - public function noArgs():MethodQuery - { - filtered = getFiltered().( - !hasOwnProperty("parameter") - ); - return this; - } - - public function argLength(num:int):MethodQuery - { - filtered = getFiltered().( - hasOwnProperty("parameter") && parameter.length() == num - ); - return this; - } - - public function withMetadata(name:String):MethodQuery - { - filtered = getFiltered().( - hasOwnProperty("metadata") && metadata.(@name == name) - ); - return this; - } - - protected function getFiltered():XMLList - { - if(!filtered) - { - filtered = description.factory.method; - } - return filtered; - } - - /** - * @inheritDoc - */ - override public function get result():Array - { - return []; - } - } -} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/PropertyQuery.as b/src/uk/co/ziazoo/fussy/PropertyQuery.as deleted file mode 100644 index b0f8fdb..0000000 --- a/src/uk/co/ziazoo/fussy/PropertyQuery.as +++ /dev/null @@ -1,41 +0,0 @@ -package uk.co.ziazoo.fussy -{ - import flash.utils.getQualifiedClassName; - - public class PropertyQuery extends AbstractQuery - { - public function PropertyQuery(description:XML) - { - super(description); - getFiltered(); - } - - public function ofType(type:Class):PropertyQuery - { - filtered = getFiltered().( - @type == getQualifiedClassName(type) - ); - return this; - } - - public function withMetadata(name:String):PropertyQuery - { - filtered = getFiltered().( - hasOwnProperty("metadata") && metadata.(@name == name) - ); - return this; - } - - protected function getFiltered():XMLList - { - if(!filtered) - { - var properties:XMLList = new XMLList(<root/>); - properties.appendChild(description.factory.variable); - properties.appendChild(description.factory.accessor); - filtered = properties.*; - } - return filtered; - } - } -} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/QueryBuilder.as b/src/uk/co/ziazoo/fussy/QueryBuilder.as deleted file mode 100644 index a757c92..0000000 --- a/src/uk/co/ziazoo/fussy/QueryBuilder.as +++ /dev/null @@ -1,44 +0,0 @@ -package uk.co.ziazoo.fussy -{ - import flex.lang.reflect.Method; - - import uk.co.ziazoo.fussy.parser.MetadataParser; - import uk.co.ziazoo.fussy.parser.MethodParser; - import uk.co.ziazoo.fussy.parser.ParameterParser; - - public class QueryBuilder - { - private var description:XML; - - public function QueryBuilder(description:XML) - { - this.description = description; - } - - public function findMethods():MethodQuery - { - return new MethodQuery(description, - new MethodParser(new ParameterParser(), new MetadataParser())); - } - - public function findVariables():VariableQuery - { - return new VariableQuery(description); - } - - public function findAccessors():AccessorQuery - { - return new AccessorQuery(description); - } - - public function findProperties():PropertyQuery - { - return new PropertyQuery(description); - } - - public function findConstructor():ConstructorQuery - { - return new ConstructorQuery(description); - } - } -} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/VariableQuery.as b/src/uk/co/ziazoo/fussy/VariableQuery.as deleted file mode 100644 index 0675922..0000000 --- a/src/uk/co/ziazoo/fussy/VariableQuery.as +++ /dev/null @@ -1,43 +0,0 @@ -package uk.co.ziazoo.fussy -{ - import flash.utils.getQualifiedClassName; - - public class VariableQuery extends AbstractQuery - { - public function VariableQuery(description:XML) - { - super(description); - } - - public function ofType(type:Class):VariableQuery - { - filtered = getFiltered().(@type == getQualifiedClassName(type)); - return this; - } - - public function withMetadata(name:String):VariableQuery - { - filtered = getFiltered().( - hasOwnProperty("metadata") && metadata.(@name == name) - ); - return this; - } - - protected function getFiltered():XMLList - { - if(!filtered) - { - filtered = description.factory.variable; - } - return filtered; - } - - /** - * @inhertDoc - */ - override public function get result():Array - { - return null; - } - } -} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/accessors/AccessorQueryChain.as b/src/uk/co/ziazoo/fussy/accessors/AccessorQueryChain.as new file mode 100644 index 0000000..3a35301 --- /dev/null +++ b/src/uk/co/ziazoo/fussy/accessors/AccessorQueryChain.as @@ -0,0 +1,49 @@ +package uk.co.ziazoo.fussy.accessors +{ + import uk.co.ziazoo.fussy.properties.PropertyQueryChain; + + public class AccessorQueryChain extends PropertyQueryChain + { + public function AccessorQueryChain() + { + } + + public function readable():AccessorQueryChain + { + parts.push(new Readable()); + return this; + } + + public function writable():AccessorQueryChain + { + /*filtered = getFiltered().( + @access == "readwrite" || @access == "writeonly" + );*/ + return this; + } + + public function readOnly():AccessorQueryChain + { + /*filtered = getFiltered().( + @access == "readonly" + );*/ + return this; + } + + public function writeOnly():AccessorQueryChain + { + /*filtered = getFiltered().( + @access == "writeonly" + );*/ + return this; + } + + public function readAndWrite():AccessorQueryChain + { + /*filtered = getFiltered().( + @access == "readwrite" + );*/ + return this; + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/accessors/Readable.as b/src/uk/co/ziazoo/fussy/accessors/Readable.as new file mode 100644 index 0000000..c709522 --- /dev/null +++ b/src/uk/co/ziazoo/fussy/accessors/Readable.as @@ -0,0 +1,18 @@ +package uk.co.ziazoo.fussy.accessors +{ + import uk.co.ziazoo.fussy.query.IQueryPart; + + public class Readable implements IQueryPart + { + public function Readable() + { + } + + public function filter(data:XMLList):XMLList + { + return data.( + @access == "readwrite" || @access == "readonly" + ); + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as b/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as index 45670b8..85aaa50 100644 --- a/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as +++ b/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as @@ -1,25 +1,24 @@ package uk.co.ziazoo.fussy.methods { - import uk.co.ziazoo.fussy.query.IQueryChain; + import uk.co.ziazoo.fussy.query.AbstractQueryChain; + import uk.co.ziazoo.fussy.query.WithMetadata; - public class MethodQueryChain implements IQueryChain + public class MethodQueryChain extends AbstractQueryChain { - private var parts:Array; - public function MethodQueryChain() { - this.parts = []; } public function named(name:String):MethodQueryChain { parts.push(new Named(name)); return this; } - public function forType(type:Class):void + public function withMetadata(named:String):MethodQueryChain { - + parts.push(new WithMetadata(named)); + return this; } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/methods/Named.as b/src/uk/co/ziazoo/fussy/methods/Named.as index 00db7b3..2bcf824 100644 --- a/src/uk/co/ziazoo/fussy/methods/Named.as +++ b/src/uk/co/ziazoo/fussy/methods/Named.as @@ -1,38 +1,21 @@ package uk.co.ziazoo.fussy.methods { import org.flexunit.runner.Result; import uk.co.ziazoo.fussy.query.IQueryPart; - import uk.co.ziazoo.fussy.query.IQueryPartResult; public class Named implements IQueryPart { private var name:String; public function Named(name:String) { this.name = name; } - public function filter(data:XML):IQueryPartResult + public function filter(data:XMLList):XMLList { - return new Result(data.(@name == name)); + return data.(@name == name); } } -} -import uk.co.ziazoo.fussy.query.IQueryPartResult; - -class Result implements IQueryPartResult -{ - private var _data:XML; - - public function Result(data:XML) - { - _data = data; - } - - public function get data():XML - { - return _data; - } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/methods/NoArgs.as b/src/uk/co/ziazoo/fussy/methods/NoArgs.as new file mode 100644 index 0000000..32dc1ab --- /dev/null +++ b/src/uk/co/ziazoo/fussy/methods/NoArgs.as @@ -0,0 +1,18 @@ +package uk.co.ziazoo.fussy.methods +{ + import uk.co.ziazoo.fussy.query.IQueryPart; + + public class NoArgs implements IQueryPart + { + public function NoArgs() + { + } + + public function filter(data:XMLList):XMLList + { + return data.( + !hasOwnProperty("parameter") + ); + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/methods/NoCompulsoryArgs.as b/src/uk/co/ziazoo/fussy/methods/NoCompulsoryArgs.as new file mode 100644 index 0000000..1270b33 --- /dev/null +++ b/src/uk/co/ziazoo/fussy/methods/NoCompulsoryArgs.as @@ -0,0 +1,18 @@ +package uk.co.ziazoo.fussy.methods +{ + import uk.co.ziazoo.fussy.query.IQueryPart; + + public class NoCompulsoryArgs implements IQueryPart + { + public function NoCompulsoryArgs() + { + } + + public function filter(data:XMLList):XMLList + { + return data.( + !hasOwnProperty("parameter") || parameter.@optional == "true" + ); + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/properties/OfType.as b/src/uk/co/ziazoo/fussy/properties/OfType.as new file mode 100644 index 0000000..e46f864 --- /dev/null +++ b/src/uk/co/ziazoo/fussy/properties/OfType.as @@ -0,0 +1,23 @@ +package uk.co.ziazoo.fussy.properties +{ + import flash.utils.getQualifiedClassName; + + import uk.co.ziazoo.fussy.query.IQueryPart; + + public class OfType implements IQueryPart + { + private var type:Class; + + public function OfType(type:Class) + { + this.type = type; + } + + public function filter(data:XMLList):XMLList + { + return data.( + @type == getQualifiedClassName(type) + ); + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/properties/PropertyQueryChain.as b/src/uk/co/ziazoo/fussy/properties/PropertyQueryChain.as new file mode 100644 index 0000000..6f32f7e --- /dev/null +++ b/src/uk/co/ziazoo/fussy/properties/PropertyQueryChain.as @@ -0,0 +1,24 @@ +package uk.co.ziazoo.fussy.properties +{ + import uk.co.ziazoo.fussy.query.AbstractQueryChain; + import uk.co.ziazoo.fussy.query.WithMetadata; + + public class PropertyQueryChain extends AbstractQueryChain + { + public function PropertyQueryChain() + { + } + + public function ofType(type:Class):PropertyQueryChain + { + parts.push(new OfType(type)); + return this; + } + + public function withMetadata(name:String):PropertyQueryChain + { + parts.push(new WithMetadata(name)); + return this; + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/query/AbstractQueryChain.as b/src/uk/co/ziazoo/fussy/query/AbstractQueryChain.as new file mode 100644 index 0000000..69c9fcc --- /dev/null +++ b/src/uk/co/ziazoo/fussy/query/AbstractQueryChain.as @@ -0,0 +1,41 @@ +package uk.co.ziazoo.fussy.query +{ + import flash.utils.describeType; + + public class AbstractQueryChain implements IQueryChain + { + /** + * @private + */ + protected var parts:Array; + + public function AbstractQueryChain() + { + parts = []; + } + + public function forType(type:Class):XMLList + { + if(parts.length == 0) + { + return null; + } + + var reflection:XML = describeType(type); + var methods:XMLList = reflection.factory.method; + + var firstPart:IQueryPart = parts[0]; + var lastResult:XMLList = firstPart.filter(methods); + + var i:uint = uint(parts.length - 1); + while(i > 0) + { + var part:IQueryPart = parts[i]; + lastResult = part.filter(lastResult); + i--; + } + + return lastResult; + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/query/IQuery.as b/src/uk/co/ziazoo/fussy/query/IQuery.as index 649cc93..f45777d 100644 --- a/src/uk/co/ziazoo/fussy/query/IQuery.as +++ b/src/uk/co/ziazoo/fussy/query/IQuery.as @@ -1,7 +1,7 @@ package uk.co.ziazoo.fussy.query { public interface IQuery { - function forType(type:Class):void; + function forType(type:Class):XMLList; } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/query/IQueryPart.as b/src/uk/co/ziazoo/fussy/query/IQueryPart.as index ee97040..fe89d9f 100644 --- a/src/uk/co/ziazoo/fussy/query/IQueryPart.as +++ b/src/uk/co/ziazoo/fussy/query/IQueryPart.as @@ -1,7 +1,7 @@ package uk.co.ziazoo.fussy.query { public interface IQueryPart { - function filter(data:XML):IQueryPartResult; + function filter(data:XMLList):XMLList; } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/query/IQueryPartResult.as b/src/uk/co/ziazoo/fussy/query/IQueryPartResult.as deleted file mode 100644 index f353b4a..0000000 --- a/src/uk/co/ziazoo/fussy/query/IQueryPartResult.as +++ /dev/null @@ -1,7 +0,0 @@ -package uk.co.ziazoo.fussy.query -{ - public interface IQueryPartResult - { - function get data():XML; - } -} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/query/WithMetadata.as b/src/uk/co/ziazoo/fussy/query/WithMetadata.as new file mode 100644 index 0000000..7b1833e --- /dev/null +++ b/src/uk/co/ziazoo/fussy/query/WithMetadata.as @@ -0,0 +1,20 @@ +package uk.co.ziazoo.fussy.query +{ + + public class WithMetadata implements IQueryPart + { + private var name:String; + + public function WithMetadata(name:String) + { + this.name = name; + } + + public function filter(data:XMLList):XMLList + { + return data.( + hasOwnProperty("metadata") && metadata.(@name == name) + ); + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/variables/VariableQueryChain.as b/src/uk/co/ziazoo/fussy/variables/VariableQueryChain.as new file mode 100644 index 0000000..a098363 --- /dev/null +++ b/src/uk/co/ziazoo/fussy/variables/VariableQueryChain.as @@ -0,0 +1,11 @@ +package uk.co.ziazoo.fussy.variables +{ + import uk.co.ziazoo.fussy.properties.PropertyQueryChain; + + public class VariableQueryChain extends PropertyQueryChain + { + public function VariableQueryChain() + { + } + } +} \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/AccessorQueryTest.as b/test/uk/co/ziazoo/fussy/AccessorQueryTest.as deleted file mode 100644 index 7cfcdad..0000000 --- a/test/uk/co/ziazoo/fussy/AccessorQueryTest.as +++ /dev/null @@ -1,101 +0,0 @@ -package uk.co.ziazoo.fussy -{ - import flash.utils.describeType; - - import org.flexunit.Assert; - - public class AccessorQueryTest - { - [Test] - public function filterOnType():void - { - var accessors:AccessorQuery = new AccessorQuery(describeType(Bubbles)); - var strings:XMLList = accessors.ofType(String).getResult(); - Assert.assertTrue("just onw", strings.length() == 1); - } - - [Test] - public function filterOnMetadata():void - { - var accessors:AccessorQuery = new AccessorQuery(describeType(Bubbles)); - var fussyLot:XMLList = accessors.withMetadata("Inject").getResult() - Assert.assertTrue("only 1", fussyLot.length() == 1); - } - - [Test] - public function filterOnMetadataAndType():void - { - var accessors:AccessorQuery = new AccessorQuery(describeType(Bubbles)); - var fussyLot:XMLList = accessors.withMetadata("Inject").ofType(String).getResult(); - Assert.assertTrue("only 1", fussyLot.length() == 1); - } - - [Test] - public function filterOnMetadataAndTypeNotThere():void - { - var accessors:AccessorQuery = new AccessorQuery(describeType(Bubbles)); - var fussyLot:XMLList = accessors.withMetadata("Inject").ofType(Array).getResult(); - Assert.assertTrue("there are none", fussyLot.length() == 0); - } - - [Test] - public function findReadable():void - { - var accessors:AccessorQuery = new AccessorQuery(describeType(Bubbles)); - var readable:XMLList = accessors.readable().getResult(); - Assert.assertTrue("there are 2", readable.length() == 2); - for each(var r:XML in readable) - { - Assert.assertTrue( ["sammy", "window"].indexOf(String(r.@name)) > -1 ); - } - } - - [Test] - public function findWritable():void - { - var accessors:AccessorQuery = new AccessorQuery(describeType(Bubbles)); - var writable:XMLList = accessors.writable().getResult(); - Assert.assertTrue("there are 2", writable.length() == 2); - for each(var r:XML in writable) - { - Assert.assertTrue( ["thing", "window"].indexOf(String(r.@name)) > -1 ); - } - } - - [Test] - public function findReadOnly():void - { - var accessors:AccessorQuery = new AccessorQuery(describeType(Bubbles)); - var writable:XMLList = accessors.readOnly().getResult(); - Assert.assertTrue("just sammy", writable.length() == 1); - for each(var r:XML in writable) - { - Assert.assertTrue( ["sammy"].indexOf(String(r.@name)) > -1 ); - } - } - - [Test] - public function findWriteOnly():void - { - var accessors:AccessorQuery = new AccessorQuery(describeType(Bubbles)); - var writable:XMLList = accessors.writeOnly().getResult(); - Assert.assertTrue("just thing", writable.length() == 1); - for each(var r:XML in writable) - { - Assert.assertTrue( ["thing"].indexOf(String(r.@name)) > -1 ); - } - } - - [Test] - public function findReadAndWrite():void - { - var accessors:AccessorQuery = new AccessorQuery(describeType(Bubbles)); - var readWrite:XMLList = accessors.readAndWrite().getResult(); - Assert.assertTrue("just window", readWrite.length() == 1); - for each(var r:XML in readWrite) - { - Assert.assertTrue( ["window"].indexOf(String(r.@name)) > -1 ); - } - } - } -} \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/Bubbles.as b/test/uk/co/ziazoo/fussy/Bubbles.as index c4d8ce3..7475298 100644 --- a/test/uk/co/ziazoo/fussy/Bubbles.as +++ b/test/uk/co/ziazoo/fussy/Bubbles.as @@ -1,53 +1,58 @@ package uk.co.ziazoo.fussy { public class Bubbles { public var wibble:Wibble; public var wobble:int; public var foo:String; [Fussy] public var bar:String; public function Bubbles(thing:Wibble) { } [Inject] public function wowowo(a:int, b:String):void { } [Inject] [Fussy] public function bebeb():void { } + public function doIt(a:int = 0):void + { + + } + public function bebeboo(h:Object, r:Object):void { } public function get sammy():Array { return null; } public function get window():Object { return null; } public function set window(value:Object):void { } [Inject] public function set thing(value:String):void { } } } \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/ConstructorQueryTest.as b/test/uk/co/ziazoo/fussy/ConstructorQueryTest.as deleted file mode 100644 index f525cf6..0000000 --- a/test/uk/co/ziazoo/fussy/ConstructorQueryTest.as +++ /dev/null @@ -1,28 +0,0 @@ -package uk.co.ziazoo.fussy -{ - import flash.utils.describeType; - - import org.flexunit.Assert; - - public class ConstructorQueryTest - { - public function ConstructorQueryTest() - { - super(); - } - - [Test] - public function doesItNeedAHack():void - { - var builder:ConstructorQuery = new ConstructorQuery(describeType(Bubbles)); - Assert.assertTrue("this one has a param so needs the hack", builder.needsHack()); - } - - [Test] - public function doesItNeedAHackNope():void - { - var builder:ConstructorQuery = new ConstructorQuery(describeType(Wibble)); - Assert.assertFalse("this one has no params", builder.needsHack()); - } - } -} \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/FussyTest.as b/test/uk/co/ziazoo/fussy/FussyTest.as index c4784f3..f7e1fb1 100644 --- a/test/uk/co/ziazoo/fussy/FussyTest.as +++ b/test/uk/co/ziazoo/fussy/FussyTest.as @@ -1,29 +1,32 @@ package uk.co.ziazoo.fussy { import uk.co.ziazoo.fussy.query.IQuery; import uk.co.ziazoo.fussy.query.Query; /** * nothing useful here yet, just demos of the api */ public class FussyTest { - [Test] - public function createMethodFussy():void - { - var fussy:Fussy = new Fussy(); - var filter:IFilter = fussy.forType(Bubbles).findMethods().withMetadata("Inject"); - } [Test] public function createVariableFussy():void { var fussy:Fussy = new Fussy(); - var filter:IFilter = fussy.forType(Bubbles).findVariables().ofType(String); - var query:IQuery = fussy.query().findMethods().named("getThing"); + var query:IQuery = fussy.query().findMethods().withMetadata("Inject"); + + var list:XMLList = query.forType(Bubbles); + + trace(list); + /* + + var factory:XMLList = getFiltered().factory.( + hasOwnProperty("constructor") && + constructor.hasOwnProperty("parameter") + ); - query.forType(Bubbles); + */ } } } \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/MethodQueryTest.as b/test/uk/co/ziazoo/fussy/MethodQueryTest.as deleted file mode 100644 index b2dc164..0000000 --- a/test/uk/co/ziazoo/fussy/MethodQueryTest.as +++ /dev/null @@ -1,63 +0,0 @@ -package uk.co.ziazoo.fussy -{ - import flash.utils.describeType; - - import org.flexunit.Assert; - - import uk.co.ziazoo.fussy.parser.MetadataParser; - import uk.co.ziazoo.fussy.parser.MethodParser; - import uk.co.ziazoo.fussy.parser.ParameterParser; - - public class MethodQueryTest - { - private function getMethodParser():MethodParser - { - return new MethodParser(new ParameterParser(), new MetadataParser()); - } - - [Test] - public function withParams():void - { - var methods:MethodQuery = - new MethodQuery(describeType(Wibble), getMethodParser()); - var result:XMLList = methods.argLength(1).getResult(); - Assert.assertTrue("one method", result.length() == 1); - } - - [Test] - public function withMetadata():void - { - var methods:MethodQuery = - new MethodQuery(describeType(Wibble), getMethodParser()); - var result:XMLList = methods.withMetadata("Inject").getResult(); - Assert.assertTrue("one method", result.length() == 1); - } - - [Test] - public function metadataAndParams():void - { - var methods:MethodQuery = - new MethodQuery(describeType(Bubbles), getMethodParser()); - var result:XMLList = methods.withMetadata("Inject").argLength(2).getResult(); - Assert.assertTrue("one method", result.length() == 1); - } - - [Test] - public function moreMetadata():void - { - var methods:MethodQuery = - new MethodQuery(describeType(Bubbles), getMethodParser()); - var result:XMLList = methods.withMetadata("Inject").getResult(); - Assert.assertTrue("two methods", result.length() == 2); - } - - [Test] - public function noArgs():void - { - var methods:MethodQuery = - new MethodQuery(describeType(Bubbles), getMethodParser()); - var result:XMLList = methods.noArgs().getResult(); - Assert.assertTrue("two methods", result.length() == 1); - } - } -} \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/PropertyQueryTest.as b/test/uk/co/ziazoo/fussy/PropertyQueryTest.as deleted file mode 100644 index 4ed6a4b..0000000 --- a/test/uk/co/ziazoo/fussy/PropertyQueryTest.as +++ /dev/null @@ -1,41 +0,0 @@ -package uk.co.ziazoo.fussy -{ - import flash.utils.describeType; - - import org.flexunit.Assert; - - public class PropertyQueryTest - { - [Test] - public function filterOnType():void - { - var properties:PropertyQuery = new PropertyQuery(describeType(Bubbles)); - var strings:XMLList = properties.ofType(String).getResult(); - Assert.assertTrue("found 3", strings.length() == 3); - } - - [Test] - public function filterOnMetadata():void - { - var properties:PropertyQuery = new PropertyQuery(describeType(Bubbles)); - var fussyLot:XMLList = properties.withMetadata("Fussy").getResult() - Assert.assertTrue("one var, one accessor", fussyLot.length() == 2); - } - - [Test] - public function filterOnMetadataAndType():void - { - var properties:PropertyQuery = new PropertyQuery(describeType(Bubbles)); - var fussyLot:XMLList = properties.withMetadata("Fussy").ofType(String).getResult(); - Assert.assertTrue("one var, one accessor", fussyLot.length() == 2); - } - - [Test] - public function filterOnMetadataAndTypeNotThere():void - { - var properties:PropertyQuery = new PropertyQuery(describeType(Bubbles)); - var fussyLot:XMLList = properties.withMetadata("Fussy").ofType(Array).getResult(); - Assert.assertTrue("there are none", fussyLot.length() == 0); - } - } -} \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/VariableQueryTest.as b/test/uk/co/ziazoo/fussy/VariableQueryTest.as deleted file mode 100644 index c9d1415..0000000 --- a/test/uk/co/ziazoo/fussy/VariableQueryTest.as +++ /dev/null @@ -1,41 +0,0 @@ -package uk.co.ziazoo.fussy -{ - import flash.utils.describeType; - - import org.flexunit.Assert; - - public class VariableQueryTest - { - [Test] - public function filterOnType():void - { - var variables:VariableQuery = new VariableQuery(describeType(Bubbles)); - var strings:XMLList = variables.ofType(String).getResult(); - Assert.assertTrue("found 2", strings.length() == 2); - } - - [Test] - public function filterOnMetadata():void - { - var variables:VariableQuery = new VariableQuery(describeType(Bubbles)); - var fussyLot:XMLList = variables.withMetadata("Fussy").getResult() - Assert.assertTrue("only 1", fussyLot.length() == 1); - } - - [Test] - public function filterOnMetadataAndType():void - { - var variables:VariableQuery = new VariableQuery(describeType(Bubbles)); - var fussyLot:XMLList = variables.withMetadata("Fussy").ofType(String).getResult(); - Assert.assertTrue("only 1", fussyLot.length() == 1); - } - - [Test] - public function filterOnMetadataAndTypeNotThere():void - { - var variables:VariableQuery = new VariableQuery(describeType(Bubbles)); - var fussyLot:XMLList = variables.withMetadata("Fussy").ofType(Array).getResult(); - Assert.assertTrue("there are none", fussyLot.length() == 0); - } - } -} \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/accessors/ReadableTest.as b/test/uk/co/ziazoo/fussy/accessors/ReadableTest.as new file mode 100644 index 0000000..5c4e881 --- /dev/null +++ b/test/uk/co/ziazoo/fussy/accessors/ReadableTest.as @@ -0,0 +1,36 @@ +package uk.co.ziazoo.fussy.accessors +{ + import flash.utils.describeType; + + import org.flexunit.Assert; + + import uk.co.ziazoo.fussy.Bubbles; + import uk.co.ziazoo.fussy.properties.OfType; + + public class ReadableTest + { + private var accessors:XMLList; + + [Before] + public function setUp():void + { + var description:XML = describeType(Bubbles); + accessors = description.factory.accessor; + } + + [After] + public function tearDown():void + { + accessors = null; + } + + [Test] + public function all_readable_accessors():void + { + var readable:Readable = new Readable(); + var result:XMLList = readable.filter(accessors); + Assert.assertNotNull(result); + Assert.assertTrue(result.length() == 2); + } + } +} \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/methods/NamedTest.as b/test/uk/co/ziazoo/fussy/methods/NamedTest.as new file mode 100644 index 0000000..9cfae86 --- /dev/null +++ b/test/uk/co/ziazoo/fussy/methods/NamedTest.as @@ -0,0 +1,35 @@ +package uk.co.ziazoo.fussy.methods +{ + import flash.utils.describeType; + + import org.flexunit.Assert; + + import uk.co.ziazoo.fussy.Bubbles; + + public class NamedTest + { + private var methods:XMLList; + + [Before] + public function setUp():void + { + methods = describeType(Bubbles).factory.method; + } + + [After] + public function tearDown():void + { + methods = null; + } + + [Test] + public function getOne():void + { + var named:Named = new Named("wowowo"); + var result:XMLList = named.filter(methods); + Assert.assertNotNull(result); + Assert.assertTrue(result.length() == 1); + Assert.assertTrue(String(result.@name) == "wowowo" ); + } + } +} \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/methods/NoArgsTest.as b/test/uk/co/ziazoo/fussy/methods/NoArgsTest.as new file mode 100644 index 0000000..fa37516 --- /dev/null +++ b/test/uk/co/ziazoo/fussy/methods/NoArgsTest.as @@ -0,0 +1,34 @@ +package uk.co.ziazoo.fussy.methods +{ + import flash.utils.describeType; + + import org.flexunit.Assert; + + import uk.co.ziazoo.fussy.Bubbles; + + public class NoArgsTest + { + private var methods:XMLList; + + [Before] + public function setUp():void + { + methods = describeType(Bubbles).factory.method; + } + + [After] + public function tearDown():void + { + methods = null; + } + + [Test] + public function noNeededArgs():void + { + var noArgs:NoArgs = new NoArgs(); + var result:XMLList = noArgs.filter(methods); + Assert.assertNotNull(result); + Assert.assertTrue(result.length() == 1); + } + } +} \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/methods/NoCompulsoryArgsTest.as b/test/uk/co/ziazoo/fussy/methods/NoCompulsoryArgsTest.as new file mode 100644 index 0000000..1afbcf5 --- /dev/null +++ b/test/uk/co/ziazoo/fussy/methods/NoCompulsoryArgsTest.as @@ -0,0 +1,34 @@ +package uk.co.ziazoo.fussy.methods +{ + import flash.utils.describeType; + + import org.flexunit.Assert; + + import uk.co.ziazoo.fussy.Bubbles; + + public class NoCompulsoryArgsTest + { + private var methods:XMLList; + + [Before] + public function setUp():void + { + methods = describeType(Bubbles).factory.method; + } + + [After] + public function tearDown():void + { + methods = null; + } + + [Test] + public function noNeededArgs():void + { + var noArgs:NoCompulsoryArgs = new NoCompulsoryArgs(); + var result:XMLList = noArgs.filter(methods); + Assert.assertNotNull(result); + Assert.assertTrue(result.length() == 2); + } + } +} \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/properties/OfTypeTest.as b/test/uk/co/ziazoo/fussy/properties/OfTypeTest.as new file mode 100644 index 0000000..dea7825 --- /dev/null +++ b/test/uk/co/ziazoo/fussy/properties/OfTypeTest.as @@ -0,0 +1,39 @@ +package uk.co.ziazoo.fussy.properties +{ + import flash.utils.describeType; + + import org.flexunit.Assert; + + import uk.co.ziazoo.fussy.Bubbles; + import uk.co.ziazoo.fussy.properties.OfType; + + public class OfTypeTest + { + private var properties:XMLList; + + [Before] + public function setUp():void + { + var description:XML = describeType(Bubbles); + var p:XMLList = new XMLList(<root/>); + p.appendChild(description.factory.variable); + p.appendChild(description.factory.accessor); + properties = p.*; + } + + [After] + public function tearDown():void + { + properties = null; + } + + [Test] + public function all_props_of_string():void + { + var ofType:OfType = new OfType(String); + var result:XMLList = ofType.filter(properties); + Assert.assertNotNull(result); + Assert.assertTrue(result.length() == 3); + } + } +} \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/query/WithMetadataTest.as b/test/uk/co/ziazoo/fussy/query/WithMetadataTest.as new file mode 100644 index 0000000..4ac4810 --- /dev/null +++ b/test/uk/co/ziazoo/fussy/query/WithMetadataTest.as @@ -0,0 +1,34 @@ +package uk.co.ziazoo.fussy.query +{ + import flash.utils.describeType; + + import org.flexunit.Assert; + + import uk.co.ziazoo.fussy.Bubbles; + + public class WithMetadataTest + { + private var methods:XMLList; + + [Before] + public function setUp():void + { + methods = describeType(Bubbles).factory.method; + } + + [After] + public function tearDown():void + { + methods = null; + } + + [Test] + public function filters():void + { + var withMetadata:WithMetadata = new WithMetadata("Inject"); + var result:XMLList = withMetadata.filter(methods); + Assert.assertNotNull(result); + Assert.assertTrue(result.length() == 2); + } + } +} \ No newline at end of file
sammyt/fussy
27edbcc3d5d1aea1f05560a92e9640ff0fcb68c7
designing new structure of reusable queries
diff --git a/src/uk/co/ziazoo/fussy/AbstractQuery.as b/src/uk/co/ziazoo/fussy/AbstractQuery.as index ab3ec48..828ba3a 100644 --- a/src/uk/co/ziazoo/fussy/AbstractQuery.as +++ b/src/uk/co/ziazoo/fussy/AbstractQuery.as @@ -1,32 +1,32 @@ package uk.co.ziazoo.fussy { - public class AbstractQuery implements IQuery + public class AbstractQuery implements IFilter { protected var description:XML; protected var filtered:XMLList; public function AbstractQuery(description:XML) { this.description = description; } public function get length():int { return filtered.length(); } public function get result():Array { return null; } /** * @private * just for use in unit tests */ internal function getResult():XMLList { return filtered; } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/Fussy.as b/src/uk/co/ziazoo/fussy/Fussy.as index 46100dc..11307dd 100644 --- a/src/uk/co/ziazoo/fussy/Fussy.as +++ b/src/uk/co/ziazoo/fussy/Fussy.as @@ -1,29 +1,36 @@ package uk.co.ziazoo.fussy { import flash.utils.Dictionary; import flash.utils.describeType; + + import uk.co.ziazoo.fussy.query.Query; public class Fussy { private var cache:Dictionary; public function Fussy() { this.cache = new Dictionary(); } public function forType(type:Class):QueryBuilder { return new QueryBuilder(getDescription(type)); } private function getDescription(type:Class):XML { if(!cache[type]) { cache[type] = describeType(type); } return cache[type] as XML } + + public function query():Query + { + return new Query(); + } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/IQuery.as b/src/uk/co/ziazoo/fussy/IFilter.as similarity index 78% rename from src/uk/co/ziazoo/fussy/IQuery.as rename to src/uk/co/ziazoo/fussy/IFilter.as index f6d1c53..63e4e27 100644 --- a/src/uk/co/ziazoo/fussy/IQuery.as +++ b/src/uk/co/ziazoo/fussy/IFilter.as @@ -1,8 +1,8 @@ package uk.co.ziazoo.fussy { - public interface IQuery + public interface IFilter { function get length():int; function get result():Array; } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as b/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as new file mode 100644 index 0000000..45670b8 --- /dev/null +++ b/src/uk/co/ziazoo/fussy/methods/MethodQueryChain.as @@ -0,0 +1,25 @@ +package uk.co.ziazoo.fussy.methods +{ + import uk.co.ziazoo.fussy.query.IQueryChain; + + public class MethodQueryChain implements IQueryChain + { + private var parts:Array; + + public function MethodQueryChain() + { + this.parts = []; + } + + public function named(name:String):MethodQueryChain + { + parts.push(new Named(name)); + return this; + } + + public function forType(type:Class):void + { + + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/methods/Named.as b/src/uk/co/ziazoo/fussy/methods/Named.as new file mode 100644 index 0000000..00db7b3 --- /dev/null +++ b/src/uk/co/ziazoo/fussy/methods/Named.as @@ -0,0 +1,38 @@ +package uk.co.ziazoo.fussy.methods +{ + import org.flexunit.runner.Result; + + import uk.co.ziazoo.fussy.query.IQueryPart; + import uk.co.ziazoo.fussy.query.IQueryPartResult; + + public class Named implements IQueryPart + { + private var name:String; + + public function Named(name:String) + { + this.name = name; + } + + public function filter(data:XML):IQueryPartResult + { + return new Result(data.(@name == name)); + } + } +} +import uk.co.ziazoo.fussy.query.IQueryPartResult; + +class Result implements IQueryPartResult +{ + private var _data:XML; + + public function Result(data:XML) + { + _data = data; + } + + public function get data():XML + { + return _data; + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/query/IQuery.as b/src/uk/co/ziazoo/fussy/query/IQuery.as new file mode 100644 index 0000000..649cc93 --- /dev/null +++ b/src/uk/co/ziazoo/fussy/query/IQuery.as @@ -0,0 +1,7 @@ +package uk.co.ziazoo.fussy.query +{ + public interface IQuery + { + function forType(type:Class):void; + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/query/IQueryChain.as b/src/uk/co/ziazoo/fussy/query/IQueryChain.as new file mode 100644 index 0000000..5832caf --- /dev/null +++ b/src/uk/co/ziazoo/fussy/query/IQueryChain.as @@ -0,0 +1,7 @@ +package uk.co.ziazoo.fussy.query +{ + public interface IQueryChain extends IQuery + { + + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/query/IQueryPart.as b/src/uk/co/ziazoo/fussy/query/IQueryPart.as new file mode 100644 index 0000000..ee97040 --- /dev/null +++ b/src/uk/co/ziazoo/fussy/query/IQueryPart.as @@ -0,0 +1,7 @@ +package uk.co.ziazoo.fussy.query +{ + public interface IQueryPart + { + function filter(data:XML):IQueryPartResult; + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/query/IQueryPartResult.as b/src/uk/co/ziazoo/fussy/query/IQueryPartResult.as new file mode 100644 index 0000000..f353b4a --- /dev/null +++ b/src/uk/co/ziazoo/fussy/query/IQueryPartResult.as @@ -0,0 +1,7 @@ +package uk.co.ziazoo.fussy.query +{ + public interface IQueryPartResult + { + function get data():XML; + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/query/Query.as b/src/uk/co/ziazoo/fussy/query/Query.as new file mode 100644 index 0000000..cb7c925 --- /dev/null +++ b/src/uk/co/ziazoo/fussy/query/Query.as @@ -0,0 +1,16 @@ +package uk.co.ziazoo.fussy.query +{ + import uk.co.ziazoo.fussy.methods.MethodQueryChain; + + public class Query + { + public function Query() + { + } + + public function findMethods():MethodQueryChain + { + return new MethodQueryChain(); + } + } +} \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/FussyTest.as b/test/uk/co/ziazoo/fussy/FussyTest.as index 67765c5..c4784f3 100644 --- a/test/uk/co/ziazoo/fussy/FussyTest.as +++ b/test/uk/co/ziazoo/fussy/FussyTest.as @@ -1,36 +1,29 @@ package uk.co.ziazoo.fussy { + import uk.co.ziazoo.fussy.query.IQuery; + import uk.co.ziazoo.fussy.query.Query; + /** * nothing useful here yet, just demos of the api */ public class FussyTest { [Test] public function createMethodFussy():void { var fussy:Fussy = new Fussy(); - var query:IQuery = fussy.forType(Bubbles).findMethods().withMetadata("Inject"); + var filter:IFilter = fussy.forType(Bubbles).findMethods().withMetadata("Inject"); } [Test] public function createVariableFussy():void { var fussy:Fussy = new Fussy(); - var query:IQuery = fussy.forType(Bubbles).findVariables().ofType(String); + var filter:IFilter = fussy.forType(Bubbles).findVariables().ofType(String); - /* - THINKING - fussy.validateThat(Bubbles).hasMethod().withMethdata("Execute").argCount(1); + var query:IQuery = fussy.query().findMethods().named("getThing"); - // [Named(index,name)] - validator = - - var v = fussy.validateFor(Bubbles).metadata("Named").mustHave("index","name"); - - var scheme:MetadataScheme = fussy.metadataSchemeFor("Named").mustHave("index","name"); - - // is validation different from queries? - */ + query.forType(Bubbles); } } } \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/methods/MethodQueryChainTest.as b/test/uk/co/ziazoo/fussy/methods/MethodQueryChainTest.as new file mode 100644 index 0000000..686b24a --- /dev/null +++ b/test/uk/co/ziazoo/fussy/methods/MethodQueryChainTest.as @@ -0,0 +1,31 @@ +package uk.co.ziazoo.fussy.methods +{ + import flash.utils.describeType; + + import uk.co.ziazoo.fussy.Bubbles; + + public class MethodQueryChainTest + { + private var methodsList:XMLList; + + [Before] + public function setUp():void + { + var tmp:XML = describeType(Bubbles); + methodsList = tmp.factory.method; + } + + [After] + public function tearDown():void + { + methodsList = null; + } + + [Test] + public function createNameQuery():void + { + var chain:MethodQueryChain = new MethodQueryChain(); + chain.named("wowowo"); + } + } +} \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/query/QueryTest.as b/test/uk/co/ziazoo/fussy/query/QueryTest.as new file mode 100644 index 0000000..753d239 --- /dev/null +++ b/test/uk/co/ziazoo/fussy/query/QueryTest.as @@ -0,0 +1,27 @@ +package uk.co.ziazoo.fussy.query +{ + import uk.co.ziazoo.fussy.Fussy; + + public class QueryTest + { + [Before] + public function setUp():void + { + } + + [After] + public function tearDown():void + { + } + + [Test] + public function creation():void + { + var query:Query = new Query(); + query.findMethods().named("getEtc"); + + + + } + } +} \ No newline at end of file
sammyt/fussy
062ff4f43db2da435d478fbdbeb3aeffb2e3bc75
begining parser ideas
diff --git a/.gitignore b/.gitignore index d4a5f8b..d5617ef 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,7 @@ *.settings *.actionScriptProperties *.flexLibProperties *.FlexUnitSettings *.project +*.DS_Store +*bin/ diff --git a/src/uk/co/ziazoo/fussy/ConstructorQuery.as b/src/uk/co/ziazoo/fussy/ConstructorQuery.as new file mode 100644 index 0000000..57c4505 --- /dev/null +++ b/src/uk/co/ziazoo/fussy/ConstructorQuery.as @@ -0,0 +1,42 @@ +package uk.co.ziazoo.fussy +{ + public class ConstructorQuery extends AbstractQuery + { + public function ConstructorQuery(description:XML) + { + super(description); + } + + /** + * @private + * flash fail http://bugs.adobe.com/jira/browse/FP-183 + */ + internal function needsHack():Boolean + { + return hasArgs(); + } + + private function hasArgs():Boolean + { + var factory:XMLList = getFiltered().factory.( + hasOwnProperty("constructor") && + constructor.hasOwnProperty("parameter") + ); + + if(factory.length() == 0) + { + return false; + } + return true; + } + + protected function getFiltered():XMLList + { + if(!filtered) + { + filtered = new XMLList(description); + } + return filtered; + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/InstanceCreator.as b/src/uk/co/ziazoo/fussy/InstanceCreator.as new file mode 100644 index 0000000..0baf4e4 --- /dev/null +++ b/src/uk/co/ziazoo/fussy/InstanceCreator.as @@ -0,0 +1,40 @@ +package uk.co.ziazoo.fussy +{ + public class InstanceCreator + { + public static function create( type:Class, params:Array ):Object + { + if( !params ) + { + return new type(); + } + + switch ( params.length ) { + case 0: + return new type(); + case 1: + return new type(params[0]); + case 2: + return new type(params[0], params[1]); + case 3: + return new type(params[0], params[1], params[2]); + case 4: + return new type(params[0], params[1], params[2], params[3]); + case 5: + return new type(params[0], params[1], params[2], params[3], params[4]); + case 6: + return new type(params[0], params[1], params[2], params[3], params[4], params[5]); + case 7: + return new type(params[0], params[1], params[2], params[3], params[4], params[5], params[6]); + case 8: + return new type(params[0], params[1], params[2], params[3], params[4], params[5], params[6], params[7]); + case 9: + return new type(params[0], params[1], params[2], params[3], params[4], params[5], params[6], params[7], params[8]); + case 10: + return new type(params[0], params[1], params[2], params[3], params[4], params[5], params[6], params[7], params[8], params[9]); + } + return null; + } + } +} + diff --git a/src/uk/co/ziazoo/fussy/MethodQuery.as b/src/uk/co/ziazoo/fussy/MethodQuery.as index fc9ebed..5df20bf 100644 --- a/src/uk/co/ziazoo/fussy/MethodQuery.as +++ b/src/uk/co/ziazoo/fussy/MethodQuery.as @@ -1,51 +1,57 @@ package uk.co.ziazoo.fussy { + import uk.co.ziazoo.fussy.parser.MethodParser; + public class MethodQuery extends AbstractQuery { - public function MethodQuery(description:XML) + private var methodParser:MethodParser; + + public function MethodQuery(description:XML, methodParser:MethodParser) { super(description); + + this.methodParser = methodParser; } public function noArgs():MethodQuery { filtered = getFiltered().( !hasOwnProperty("parameter") ); return this; } public function argLength(num:int):MethodQuery { filtered = getFiltered().( hasOwnProperty("parameter") && parameter.length() == num ); return this; } public function withMetadata(name:String):MethodQuery { filtered = getFiltered().( hasOwnProperty("metadata") && metadata.(@name == name) ); return this; } protected function getFiltered():XMLList { if(!filtered) { filtered = description.factory.method; } return filtered; } /** * @inheritDoc */ override public function get result():Array { return []; } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/QueryBuilder.as b/src/uk/co/ziazoo/fussy/QueryBuilder.as index 7984a91..a757c92 100644 --- a/src/uk/co/ziazoo/fussy/QueryBuilder.as +++ b/src/uk/co/ziazoo/fussy/QueryBuilder.as @@ -1,32 +1,44 @@ package uk.co.ziazoo.fussy { + import flex.lang.reflect.Method; + + import uk.co.ziazoo.fussy.parser.MetadataParser; + import uk.co.ziazoo.fussy.parser.MethodParser; + import uk.co.ziazoo.fussy.parser.ParameterParser; + public class QueryBuilder { private var description:XML; public function QueryBuilder(description:XML) { this.description = description; } public function findMethods():MethodQuery { - return new MethodQuery(description); + return new MethodQuery(description, + new MethodParser(new ParameterParser(), new MetadataParser())); } public function findVariables():VariableQuery { return new VariableQuery(description); } public function findAccessors():AccessorQuery { return new AccessorQuery(description); } public function findProperties():PropertyQuery { return new PropertyQuery(description); } + + public function findConstructor():ConstructorQuery + { + return new ConstructorQuery(description); + } } } \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/model/Constructor.as b/src/uk/co/ziazoo/fussy/model/Constructor.as new file mode 100644 index 0000000..0b72f35 --- /dev/null +++ b/src/uk/co/ziazoo/fussy/model/Constructor.as @@ -0,0 +1,13 @@ +package uk.co.ziazoo.fussy.model +{ + public class Constructor + { + public var params:Array; + public var metadatas:Array; + + public function Constructor() + { + } + } +} + diff --git a/src/uk/co/ziazoo/fussy/model/Metadata.as b/src/uk/co/ziazoo/fussy/model/Metadata.as new file mode 100644 index 0000000..8315e7a --- /dev/null +++ b/src/uk/co/ziazoo/fussy/model/Metadata.as @@ -0,0 +1,14 @@ +package uk.co.ziazoo.fussy.model +{ + import flash.utils.Dictionary; + + public class Metadata + { + public var name:String; + public var properties:Dictionary; + + public function Metadata() + { + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/model/Method.as b/src/uk/co/ziazoo/fussy/model/Method.as new file mode 100644 index 0000000..2e92409 --- /dev/null +++ b/src/uk/co/ziazoo/fussy/model/Method.as @@ -0,0 +1,13 @@ +package uk.co.ziazoo.fussy.model +{ + public class Method + { + public var name:String; + public var params:Array; + public var metadatas:Array; + + public function Method() + { + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/model/Parameter.as b/src/uk/co/ziazoo/fussy/model/Parameter.as new file mode 100644 index 0000000..2db5d58 --- /dev/null +++ b/src/uk/co/ziazoo/fussy/model/Parameter.as @@ -0,0 +1,13 @@ +package uk.co.ziazoo.fussy.model +{ + public class Parameter + { + public var index:int; + public var type:String; + public var optional:Boolean; + + public function Parameter() + { + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/model/Parser.as b/src/uk/co/ziazoo/fussy/model/Parser.as new file mode 100644 index 0000000..66b5c79 --- /dev/null +++ b/src/uk/co/ziazoo/fussy/model/Parser.as @@ -0,0 +1,77 @@ +package uk.co.ziazoo.fussy.model +{ + public class Parser + { + public function Parser() + { + } + + public function parseConstructor( reflection:XML ):Constructor + { + var constructor:Constructor = new Constructor(); + + for each( var p:XML in reflection.constructor.parameter ) + { + constructor.params.push( parseParameter( p ) ); + } + + for each( var m:XML in reflection.metadata ) + { + constructor.metadatas.push( parseMetadata( m ) ); + } + return constructor; + } + + public function parseProperty( prop:XML ):Property + { + var property:Property = new Property(); + property.name = prop.@name; + property.type = prop.@type; + + for each( var m:XML in prop.metadata ) + { + property.metadatas.push( parseMetadata( m ) ); + } + return property; + } + + public function parseMethod( reflection:XML ):Method + { + var method:Method = new Method(); + method.name = reflection.@name; + + for each( var p:XML in reflection.parameter ) + { + method.params.push( parseParameter( p ) ); + } + + for each( var m:XML in reflection.metadata ) + { + method.metadatas.push( parseMetadata( m ) ); + } + + return method; + } + + public function parseMetadata( reflection:XML ):Metadata + { + var metadata:Metadata = new Metadata(); + metadata.name = reflection.@name; + + for each( var p:XML in reflection.arg ) + { + metadata.properties[p.@key as String] = p.@value as String; + } + return metadata; + } + + public function parseParameter( reflection:XML ):Parameter + { + var parameter:Parameter = new Parameter(); + parameter.index = parseInt( reflection.@index ); + parameter.type = reflection.@type; + parameter.optional = reflection.@optional == "true"; + return parameter; + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/model/Property.as b/src/uk/co/ziazoo/fussy/model/Property.as new file mode 100644 index 0000000..8ee3d0e --- /dev/null +++ b/src/uk/co/ziazoo/fussy/model/Property.as @@ -0,0 +1,13 @@ +package uk.co.ziazoo.fussy.model +{ + public class Property + { + public var name:String; + public var type:String; + public var metadatas:Array; + + public function Property() + { + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/parser/ConstructorParser.as b/src/uk/co/ziazoo/fussy/parser/ConstructorParser.as new file mode 100644 index 0000000..36a2a21 --- /dev/null +++ b/src/uk/co/ziazoo/fussy/parser/ConstructorParser.as @@ -0,0 +1,12 @@ +package uk.co.ziazoo.fussy.parser +{ + public class ConstructorParser + { + private var parameterParser:ParameterParser; + + public function ConstructorParser(parameterParser:ParameterParser) + { + this.parameterParser = parameterParser; + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/parser/MetadataParser.as b/src/uk/co/ziazoo/fussy/parser/MetadataParser.as new file mode 100644 index 0000000..3c54879 --- /dev/null +++ b/src/uk/co/ziazoo/fussy/parser/MetadataParser.as @@ -0,0 +1,10 @@ +package uk.co.ziazoo.fussy.parser +{ + public class MetadataParser extends Object + { + public function MetadataParser() + { + super(); + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/parser/MethodParser.as b/src/uk/co/ziazoo/fussy/parser/MethodParser.as new file mode 100644 index 0000000..b99f35b --- /dev/null +++ b/src/uk/co/ziazoo/fussy/parser/MethodParser.as @@ -0,0 +1,15 @@ +package uk.co.ziazoo.fussy.parser +{ + public class MethodParser + { + private var parameterParser:ParameterParser; + private var metadataParser:MetadataParser; + + public function MethodParser(parameterParser:ParameterParser, + metadataParser:MetadataParser) + { + this.parameterParser = parameterParser; + this.metadataParser = metadataParser; + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/parser/ParameterParser.as b/src/uk/co/ziazoo/fussy/parser/ParameterParser.as new file mode 100644 index 0000000..4a9cd17 --- /dev/null +++ b/src/uk/co/ziazoo/fussy/parser/ParameterParser.as @@ -0,0 +1,10 @@ +package uk.co.ziazoo.fussy.parser +{ + public class ParameterParser extends Object + { + public function ParameterParser() + { + super(); + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/parser/PropertyParser.as b/src/uk/co/ziazoo/fussy/parser/PropertyParser.as new file mode 100644 index 0000000..971948d --- /dev/null +++ b/src/uk/co/ziazoo/fussy/parser/PropertyParser.as @@ -0,0 +1,12 @@ +package uk.co.ziazoo.fussy.parser +{ + public class PropertyParser + { + private var metadataParser:MetadataParser; + + public function PropertyParser(metadataParser:MetadataParser) + { + this.metadataParser = metadataParser; + } + } +} \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/Bubbles.as b/test/uk/co/ziazoo/fussy/Bubbles.as index 2667d9b..c4d8ce3 100644 --- a/test/uk/co/ziazoo/fussy/Bubbles.as +++ b/test/uk/co/ziazoo/fussy/Bubbles.as @@ -1,53 +1,53 @@ package uk.co.ziazoo.fussy { public class Bubbles { public var wibble:Wibble; public var wobble:int; public var foo:String; [Fussy] public var bar:String; - public function Bubbles() + public function Bubbles(thing:Wibble) { } [Inject] public function wowowo(a:int, b:String):void { } [Inject] [Fussy] public function bebeb():void { } public function bebeboo(h:Object, r:Object):void { } public function get sammy():Array { return null; } public function get window():Object { return null; } public function set window(value:Object):void { } [Inject] public function set thing(value:String):void { } } } \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/ConstructorQueryTest.as b/test/uk/co/ziazoo/fussy/ConstructorQueryTest.as new file mode 100644 index 0000000..f525cf6 --- /dev/null +++ b/test/uk/co/ziazoo/fussy/ConstructorQueryTest.as @@ -0,0 +1,28 @@ +package uk.co.ziazoo.fussy +{ + import flash.utils.describeType; + + import org.flexunit.Assert; + + public class ConstructorQueryTest + { + public function ConstructorQueryTest() + { + super(); + } + + [Test] + public function doesItNeedAHack():void + { + var builder:ConstructorQuery = new ConstructorQuery(describeType(Bubbles)); + Assert.assertTrue("this one has a param so needs the hack", builder.needsHack()); + } + + [Test] + public function doesItNeedAHackNope():void + { + var builder:ConstructorQuery = new ConstructorQuery(describeType(Wibble)); + Assert.assertFalse("this one has no params", builder.needsHack()); + } + } +} \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/FussyTest.as b/test/uk/co/ziazoo/fussy/FussyTest.as index 5f75bc8..67765c5 100644 --- a/test/uk/co/ziazoo/fussy/FussyTest.as +++ b/test/uk/co/ziazoo/fussy/FussyTest.as @@ -1,22 +1,36 @@ package uk.co.ziazoo.fussy { /** * nothing useful here yet, just demos of the api */ public class FussyTest { [Test] public function createMethodFussy():void { var fussy:Fussy = new Fussy(); var query:IQuery = fussy.forType(Bubbles).findMethods().withMetadata("Inject"); } [Test] public function createVariableFussy():void { var fussy:Fussy = new Fussy(); var query:IQuery = fussy.forType(Bubbles).findVariables().ofType(String); + + /* + THINKING + fussy.validateThat(Bubbles).hasMethod().withMethdata("Execute").argCount(1); + + // [Named(index,name)] + validator = + + var v = fussy.validateFor(Bubbles).metadata("Named").mustHave("index","name"); + + var scheme:MetadataScheme = fussy.metadataSchemeFor("Named").mustHave("index","name"); + + // is validation different from queries? + */ } } } \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/MethodQueryTest.as b/test/uk/co/ziazoo/fussy/MethodQueryTest.as index 5702f58..b2dc164 100644 --- a/test/uk/co/ziazoo/fussy/MethodQueryTest.as +++ b/test/uk/co/ziazoo/fussy/MethodQueryTest.as @@ -1,49 +1,63 @@ package uk.co.ziazoo.fussy { import flash.utils.describeType; import org.flexunit.Assert; + + import uk.co.ziazoo.fussy.parser.MetadataParser; + import uk.co.ziazoo.fussy.parser.MethodParser; + import uk.co.ziazoo.fussy.parser.ParameterParser; public class MethodQueryTest { + private function getMethodParser():MethodParser + { + return new MethodParser(new ParameterParser(), new MetadataParser()); + } + [Test] public function withParams():void { - var methods:MethodQuery = new MethodQuery(describeType(Wibble)) + var methods:MethodQuery = + new MethodQuery(describeType(Wibble), getMethodParser()); var result:XMLList = methods.argLength(1).getResult(); Assert.assertTrue("one method", result.length() == 1); } [Test] public function withMetadata():void { - var methods:MethodQuery = new MethodQuery(describeType(Wibble)); + var methods:MethodQuery = + new MethodQuery(describeType(Wibble), getMethodParser()); var result:XMLList = methods.withMetadata("Inject").getResult(); Assert.assertTrue("one method", result.length() == 1); } [Test] public function metadataAndParams():void { - var methods:MethodQuery = new MethodQuery(describeType(Bubbles)); + var methods:MethodQuery = + new MethodQuery(describeType(Bubbles), getMethodParser()); var result:XMLList = methods.withMetadata("Inject").argLength(2).getResult(); Assert.assertTrue("one method", result.length() == 1); } [Test] public function moreMetadata():void { - var methods:MethodQuery = new MethodQuery(describeType(Bubbles)); + var methods:MethodQuery = + new MethodQuery(describeType(Bubbles), getMethodParser()); var result:XMLList = methods.withMetadata("Inject").getResult(); Assert.assertTrue("two methods", result.length() == 2); } [Test] public function noArgs():void { - var methods:MethodQuery = new MethodQuery(describeType(Bubbles)); + var methods:MethodQuery = + new MethodQuery(describeType(Bubbles), getMethodParser()); var result:XMLList = methods.noArgs().getResult(); Assert.assertTrue("two methods", result.length() == 1); } } } \ No newline at end of file
sammyt/fussy
55abe8c280ead7ad9373ed9e5a8c8b314c8c817a
I think its 'an' before a vowel?
diff --git a/README.md b/README.md index dc025c7..2a760da 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,10 @@ -# fussy is a actionscript reflection query language # +# fussy is an actionscript reflection query language # Its still in development, give me a couple more days Mind you, this kind of thing works... <pre> var query:IQuery = fussy.forType(Bubbles).findMethods().withMetadata("Inject"); var query:IQuery = fussy.forType(Bubbles).findAccessors().ofType(Array).readOnly(); </pre> \ No newline at end of file
sammyt/fussy
638057b0eb837f7cbdd8253abe7d6ca28cd02819
added maven build
diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..0a7e850 --- /dev/null +++ b/pom.xml @@ -0,0 +1,63 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <groupId>uk.co.ziazoo</groupId> + <artifactId>fussy</artifactId> + <version>0.1-SNAPSHOT</version> + <packaging>swc</packaging> + <name>Fussy query language</name> + <properties> + <flexversion>3.5.0.12683</flexversion> + <mojoversion>3.5.0</mojoversion> + </properties> + <build> + <sourceDirectory>src</sourceDirectory> + <testSourceDirectory>test</testSourceDirectory> + <plugins> + <plugin> + <groupId>org.sonatype.flexmojos</groupId> + <artifactId>flexmojos-maven-plugin</artifactId> + <version>${mojoversion}</version> + <extensions>true</extensions> + <configuration> + <keepAs3Metadatas> + <!-- can i just keep these for tests? --> + <keepAs3Metadata>Inject</keepAs3Metadata> + <keepAs3Metadata>Fussy</keepAs3Metadata> + </keepAs3Metadatas> + </configuration> + <dependencies> + <dependency> + <groupId>com.adobe.flex</groupId> + <artifactId>compiler</artifactId> + <version>${flexversion}</version> + <type>pom</type> + </dependency> + </dependencies> + </plugin> + </plugins> + </build> + <dependencies> + <dependency> + <groupId>com.adobe.flex.framework</groupId> + <artifactId>flex-framework</artifactId> + <version>${flexversion}</version> + <type>pom</type> + </dependency> + <dependency> + <groupId>org.sonatype.flexmojos</groupId> + <artifactId>flexmojos-unittest-support</artifactId> + <version>${mojoversion}</version> + <type>swc</type> + <scope>test</scope> + </dependency> + <dependency> + <groupId>com.adobe.flexunit</groupId> + <artifactId>flexunit</artifactId> + <version>4.0-rc-1</version> + <type>swc</type> + <scope>test</scope> + </dependency> + </dependencies> +</project> \ No newline at end of file
sammyt/fussy
4dcf9d2e54350a3003deba665c6cfa7707b0407b
basic readme
diff --git a/README.md b/README.md new file mode 100644 index 0000000..6832d60 --- /dev/null +++ b/README.md @@ -0,0 +1,10 @@ +h1. fussy is a actionscript reflection query language + +Its still in development, give me a couple more days + +Mind you, this kind of thing works... + +<pre> +var query:IQuery = fussy.forType(Bubbles).findMethods().withMetadata("Inject"); +var query:IQuery = fussy.forType(Bubbles).findAccessors().ofType(Array).readOnly(); +</pre> \ No newline at end of file
sammyt/fussy
c85125f880566f78321cac644af30e01042a0d36
first pass at fussy queries
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d4a5f8b --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +*.settings +*.actionScriptProperties +*.flexLibProperties +*.FlexUnitSettings +*.project diff --git a/src/uk/co/ziazoo/fussy/AbstractQuery.as b/src/uk/co/ziazoo/fussy/AbstractQuery.as new file mode 100644 index 0000000..ab3ec48 --- /dev/null +++ b/src/uk/co/ziazoo/fussy/AbstractQuery.as @@ -0,0 +1,32 @@ +package uk.co.ziazoo.fussy +{ + public class AbstractQuery implements IQuery + { + protected var description:XML; + protected var filtered:XMLList; + + public function AbstractQuery(description:XML) + { + this.description = description; + } + + public function get length():int + { + return filtered.length(); + } + + public function get result():Array + { + return null; + } + + /** + * @private + * just for use in unit tests + */ + internal function getResult():XMLList + { + return filtered; + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/AccessorQuery.as b/src/uk/co/ziazoo/fussy/AccessorQuery.as new file mode 100644 index 0000000..8e7cbe2 --- /dev/null +++ b/src/uk/co/ziazoo/fussy/AccessorQuery.as @@ -0,0 +1,85 @@ +package uk.co.ziazoo.fussy +{ + import flash.utils.getQualifiedClassName; + + public class AccessorQuery extends AbstractQuery + { + public function AccessorQuery(description:XML) + { + super(description); + } + + public function ofType(type:Class):AccessorQuery + { + filtered = getFiltered().( + @type == getQualifiedClassName(type) + ); + return this; + } + + public function withMetadata(name:String):AccessorQuery + { + filtered = getFiltered().( + hasOwnProperty("metadata") && metadata.(@name == name) + ); + return this; + } + + public function readable():AccessorQuery + { + filtered = getFiltered().( + @access == "readwrite" || @access == "readonly" + ); + return this; + } + + public function writable():AccessorQuery + { + filtered = getFiltered().( + @access == "readwrite" || @access == "writeonly" + ); + return this; + } + + public function readOnly():AccessorQuery + { + filtered = getFiltered().( + @access == "readonly" + ); + return this; + } + + public function writeOnly():AccessorQuery + { + filtered = getFiltered().( + @access == "writeonly" + ); + return this; + } + + public function readAndWrite():AccessorQuery + { + filtered = getFiltered().( + @access == "readwrite" + ); + return this; + } + + protected function getFiltered():XMLList + { + if(!filtered) + { + filtered = description.factory.accessor; + } + return filtered; + } + + /** + * @inheritDoc + */ + override public function get result():Array + { + return null; + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/Fussy.as b/src/uk/co/ziazoo/fussy/Fussy.as new file mode 100644 index 0000000..46100dc --- /dev/null +++ b/src/uk/co/ziazoo/fussy/Fussy.as @@ -0,0 +1,29 @@ +package uk.co.ziazoo.fussy +{ + import flash.utils.Dictionary; + import flash.utils.describeType; + + public class Fussy + { + private var cache:Dictionary; + + public function Fussy() + { + this.cache = new Dictionary(); + } + + public function forType(type:Class):QueryBuilder + { + return new QueryBuilder(getDescription(type)); + } + + private function getDescription(type:Class):XML + { + if(!cache[type]) + { + cache[type] = describeType(type); + } + return cache[type] as XML + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/IQuery.as b/src/uk/co/ziazoo/fussy/IQuery.as new file mode 100644 index 0000000..f6d1c53 --- /dev/null +++ b/src/uk/co/ziazoo/fussy/IQuery.as @@ -0,0 +1,8 @@ +package uk.co.ziazoo.fussy +{ + public interface IQuery + { + function get length():int; + function get result():Array; + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/MethodQuery.as b/src/uk/co/ziazoo/fussy/MethodQuery.as new file mode 100644 index 0000000..fc9ebed --- /dev/null +++ b/src/uk/co/ziazoo/fussy/MethodQuery.as @@ -0,0 +1,51 @@ +package uk.co.ziazoo.fussy +{ + public class MethodQuery extends AbstractQuery + { + public function MethodQuery(description:XML) + { + super(description); + } + + public function noArgs():MethodQuery + { + filtered = getFiltered().( + !hasOwnProperty("parameter") + ); + return this; + } + + public function argLength(num:int):MethodQuery + { + filtered = getFiltered().( + hasOwnProperty("parameter") && parameter.length() == num + ); + return this; + } + + public function withMetadata(name:String):MethodQuery + { + filtered = getFiltered().( + hasOwnProperty("metadata") && metadata.(@name == name) + ); + return this; + } + + protected function getFiltered():XMLList + { + if(!filtered) + { + filtered = description.factory.method; + } + return filtered; + } + + /** + * @inheritDoc + */ + override public function get result():Array + { + return []; + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/PropertyQuery.as b/src/uk/co/ziazoo/fussy/PropertyQuery.as new file mode 100644 index 0000000..b0f8fdb --- /dev/null +++ b/src/uk/co/ziazoo/fussy/PropertyQuery.as @@ -0,0 +1,41 @@ +package uk.co.ziazoo.fussy +{ + import flash.utils.getQualifiedClassName; + + public class PropertyQuery extends AbstractQuery + { + public function PropertyQuery(description:XML) + { + super(description); + getFiltered(); + } + + public function ofType(type:Class):PropertyQuery + { + filtered = getFiltered().( + @type == getQualifiedClassName(type) + ); + return this; + } + + public function withMetadata(name:String):PropertyQuery + { + filtered = getFiltered().( + hasOwnProperty("metadata") && metadata.(@name == name) + ); + return this; + } + + protected function getFiltered():XMLList + { + if(!filtered) + { + var properties:XMLList = new XMLList(<root/>); + properties.appendChild(description.factory.variable); + properties.appendChild(description.factory.accessor); + filtered = properties.*; + } + return filtered; + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/QueryBuilder.as b/src/uk/co/ziazoo/fussy/QueryBuilder.as new file mode 100644 index 0000000..7984a91 --- /dev/null +++ b/src/uk/co/ziazoo/fussy/QueryBuilder.as @@ -0,0 +1,32 @@ +package uk.co.ziazoo.fussy +{ + public class QueryBuilder + { + private var description:XML; + + public function QueryBuilder(description:XML) + { + this.description = description; + } + + public function findMethods():MethodQuery + { + return new MethodQuery(description); + } + + public function findVariables():VariableQuery + { + return new VariableQuery(description); + } + + public function findAccessors():AccessorQuery + { + return new AccessorQuery(description); + } + + public function findProperties():PropertyQuery + { + return new PropertyQuery(description); + } + } +} \ No newline at end of file diff --git a/src/uk/co/ziazoo/fussy/VariableQuery.as b/src/uk/co/ziazoo/fussy/VariableQuery.as new file mode 100644 index 0000000..0675922 --- /dev/null +++ b/src/uk/co/ziazoo/fussy/VariableQuery.as @@ -0,0 +1,43 @@ +package uk.co.ziazoo.fussy +{ + import flash.utils.getQualifiedClassName; + + public class VariableQuery extends AbstractQuery + { + public function VariableQuery(description:XML) + { + super(description); + } + + public function ofType(type:Class):VariableQuery + { + filtered = getFiltered().(@type == getQualifiedClassName(type)); + return this; + } + + public function withMetadata(name:String):VariableQuery + { + filtered = getFiltered().( + hasOwnProperty("metadata") && metadata.(@name == name) + ); + return this; + } + + protected function getFiltered():XMLList + { + if(!filtered) + { + filtered = description.factory.variable; + } + return filtered; + } + + /** + * @inhertDoc + */ + override public function get result():Array + { + return null; + } + } +} \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/AccessorQueryTest.as b/test/uk/co/ziazoo/fussy/AccessorQueryTest.as new file mode 100644 index 0000000..7cfcdad --- /dev/null +++ b/test/uk/co/ziazoo/fussy/AccessorQueryTest.as @@ -0,0 +1,101 @@ +package uk.co.ziazoo.fussy +{ + import flash.utils.describeType; + + import org.flexunit.Assert; + + public class AccessorQueryTest + { + [Test] + public function filterOnType():void + { + var accessors:AccessorQuery = new AccessorQuery(describeType(Bubbles)); + var strings:XMLList = accessors.ofType(String).getResult(); + Assert.assertTrue("just onw", strings.length() == 1); + } + + [Test] + public function filterOnMetadata():void + { + var accessors:AccessorQuery = new AccessorQuery(describeType(Bubbles)); + var fussyLot:XMLList = accessors.withMetadata("Inject").getResult() + Assert.assertTrue("only 1", fussyLot.length() == 1); + } + + [Test] + public function filterOnMetadataAndType():void + { + var accessors:AccessorQuery = new AccessorQuery(describeType(Bubbles)); + var fussyLot:XMLList = accessors.withMetadata("Inject").ofType(String).getResult(); + Assert.assertTrue("only 1", fussyLot.length() == 1); + } + + [Test] + public function filterOnMetadataAndTypeNotThere():void + { + var accessors:AccessorQuery = new AccessorQuery(describeType(Bubbles)); + var fussyLot:XMLList = accessors.withMetadata("Inject").ofType(Array).getResult(); + Assert.assertTrue("there are none", fussyLot.length() == 0); + } + + [Test] + public function findReadable():void + { + var accessors:AccessorQuery = new AccessorQuery(describeType(Bubbles)); + var readable:XMLList = accessors.readable().getResult(); + Assert.assertTrue("there are 2", readable.length() == 2); + for each(var r:XML in readable) + { + Assert.assertTrue( ["sammy", "window"].indexOf(String(r.@name)) > -1 ); + } + } + + [Test] + public function findWritable():void + { + var accessors:AccessorQuery = new AccessorQuery(describeType(Bubbles)); + var writable:XMLList = accessors.writable().getResult(); + Assert.assertTrue("there are 2", writable.length() == 2); + for each(var r:XML in writable) + { + Assert.assertTrue( ["thing", "window"].indexOf(String(r.@name)) > -1 ); + } + } + + [Test] + public function findReadOnly():void + { + var accessors:AccessorQuery = new AccessorQuery(describeType(Bubbles)); + var writable:XMLList = accessors.readOnly().getResult(); + Assert.assertTrue("just sammy", writable.length() == 1); + for each(var r:XML in writable) + { + Assert.assertTrue( ["sammy"].indexOf(String(r.@name)) > -1 ); + } + } + + [Test] + public function findWriteOnly():void + { + var accessors:AccessorQuery = new AccessorQuery(describeType(Bubbles)); + var writable:XMLList = accessors.writeOnly().getResult(); + Assert.assertTrue("just thing", writable.length() == 1); + for each(var r:XML in writable) + { + Assert.assertTrue( ["thing"].indexOf(String(r.@name)) > -1 ); + } + } + + [Test] + public function findReadAndWrite():void + { + var accessors:AccessorQuery = new AccessorQuery(describeType(Bubbles)); + var readWrite:XMLList = accessors.readAndWrite().getResult(); + Assert.assertTrue("just window", readWrite.length() == 1); + for each(var r:XML in readWrite) + { + Assert.assertTrue( ["window"].indexOf(String(r.@name)) > -1 ); + } + } + } +} \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/Bubbles.as b/test/uk/co/ziazoo/fussy/Bubbles.as new file mode 100644 index 0000000..2667d9b --- /dev/null +++ b/test/uk/co/ziazoo/fussy/Bubbles.as @@ -0,0 +1,53 @@ +package uk.co.ziazoo.fussy +{ + public class Bubbles + { + public var wibble:Wibble; + + public var wobble:int; + + public var foo:String; + + [Fussy] + public var bar:String; + + public function Bubbles() + { + } + + [Inject] + public function wowowo(a:int, b:String):void + { + } + + [Inject] + [Fussy] + public function bebeb():void + { + } + + public function bebeboo(h:Object, r:Object):void + { + } + + public function get sammy():Array + { + return null; + } + + public function get window():Object + { + return null; + } + + public function set window(value:Object):void + { + } + + [Inject] + public function set thing(value:String):void + { + + } + } +} \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/FussyTest.as b/test/uk/co/ziazoo/fussy/FussyTest.as new file mode 100644 index 0000000..5f75bc8 --- /dev/null +++ b/test/uk/co/ziazoo/fussy/FussyTest.as @@ -0,0 +1,22 @@ +package uk.co.ziazoo.fussy +{ + /** + * nothing useful here yet, just demos of the api + */ + public class FussyTest + { + [Test] + public function createMethodFussy():void + { + var fussy:Fussy = new Fussy(); + var query:IQuery = fussy.forType(Bubbles).findMethods().withMetadata("Inject"); + } + + [Test] + public function createVariableFussy():void + { + var fussy:Fussy = new Fussy(); + var query:IQuery = fussy.forType(Bubbles).findVariables().ofType(String); + } + } +} \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/MethodQueryTest.as b/test/uk/co/ziazoo/fussy/MethodQueryTest.as new file mode 100644 index 0000000..5702f58 --- /dev/null +++ b/test/uk/co/ziazoo/fussy/MethodQueryTest.as @@ -0,0 +1,49 @@ +package uk.co.ziazoo.fussy +{ + import flash.utils.describeType; + + import org.flexunit.Assert; + + public class MethodQueryTest + { + [Test] + public function withParams():void + { + var methods:MethodQuery = new MethodQuery(describeType(Wibble)) + var result:XMLList = methods.argLength(1).getResult(); + Assert.assertTrue("one method", result.length() == 1); + } + + [Test] + public function withMetadata():void + { + var methods:MethodQuery = new MethodQuery(describeType(Wibble)); + var result:XMLList = methods.withMetadata("Inject").getResult(); + Assert.assertTrue("one method", result.length() == 1); + } + + [Test] + public function metadataAndParams():void + { + var methods:MethodQuery = new MethodQuery(describeType(Bubbles)); + var result:XMLList = methods.withMetadata("Inject").argLength(2).getResult(); + Assert.assertTrue("one method", result.length() == 1); + } + + [Test] + public function moreMetadata():void + { + var methods:MethodQuery = new MethodQuery(describeType(Bubbles)); + var result:XMLList = methods.withMetadata("Inject").getResult(); + Assert.assertTrue("two methods", result.length() == 2); + } + + [Test] + public function noArgs():void + { + var methods:MethodQuery = new MethodQuery(describeType(Bubbles)); + var result:XMLList = methods.noArgs().getResult(); + Assert.assertTrue("two methods", result.length() == 1); + } + } +} \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/PropertyQueryTest.as b/test/uk/co/ziazoo/fussy/PropertyQueryTest.as new file mode 100644 index 0000000..4ed6a4b --- /dev/null +++ b/test/uk/co/ziazoo/fussy/PropertyQueryTest.as @@ -0,0 +1,41 @@ +package uk.co.ziazoo.fussy +{ + import flash.utils.describeType; + + import org.flexunit.Assert; + + public class PropertyQueryTest + { + [Test] + public function filterOnType():void + { + var properties:PropertyQuery = new PropertyQuery(describeType(Bubbles)); + var strings:XMLList = properties.ofType(String).getResult(); + Assert.assertTrue("found 3", strings.length() == 3); + } + + [Test] + public function filterOnMetadata():void + { + var properties:PropertyQuery = new PropertyQuery(describeType(Bubbles)); + var fussyLot:XMLList = properties.withMetadata("Fussy").getResult() + Assert.assertTrue("one var, one accessor", fussyLot.length() == 2); + } + + [Test] + public function filterOnMetadataAndType():void + { + var properties:PropertyQuery = new PropertyQuery(describeType(Bubbles)); + var fussyLot:XMLList = properties.withMetadata("Fussy").ofType(String).getResult(); + Assert.assertTrue("one var, one accessor", fussyLot.length() == 2); + } + + [Test] + public function filterOnMetadataAndTypeNotThere():void + { + var properties:PropertyQuery = new PropertyQuery(describeType(Bubbles)); + var fussyLot:XMLList = properties.withMetadata("Fussy").ofType(Array).getResult(); + Assert.assertTrue("there are none", fussyLot.length() == 0); + } + } +} \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/VariableQueryTest.as b/test/uk/co/ziazoo/fussy/VariableQueryTest.as new file mode 100644 index 0000000..c9d1415 --- /dev/null +++ b/test/uk/co/ziazoo/fussy/VariableQueryTest.as @@ -0,0 +1,41 @@ +package uk.co.ziazoo.fussy +{ + import flash.utils.describeType; + + import org.flexunit.Assert; + + public class VariableQueryTest + { + [Test] + public function filterOnType():void + { + var variables:VariableQuery = new VariableQuery(describeType(Bubbles)); + var strings:XMLList = variables.ofType(String).getResult(); + Assert.assertTrue("found 2", strings.length() == 2); + } + + [Test] + public function filterOnMetadata():void + { + var variables:VariableQuery = new VariableQuery(describeType(Bubbles)); + var fussyLot:XMLList = variables.withMetadata("Fussy").getResult() + Assert.assertTrue("only 1", fussyLot.length() == 1); + } + + [Test] + public function filterOnMetadataAndType():void + { + var variables:VariableQuery = new VariableQuery(describeType(Bubbles)); + var fussyLot:XMLList = variables.withMetadata("Fussy").ofType(String).getResult(); + Assert.assertTrue("only 1", fussyLot.length() == 1); + } + + [Test] + public function filterOnMetadataAndTypeNotThere():void + { + var variables:VariableQuery = new VariableQuery(describeType(Bubbles)); + var fussyLot:XMLList = variables.withMetadata("Fussy").ofType(Array).getResult(); + Assert.assertTrue("there are none", fussyLot.length() == 0); + } + } +} \ No newline at end of file diff --git a/test/uk/co/ziazoo/fussy/Wibble.as b/test/uk/co/ziazoo/fussy/Wibble.as new file mode 100644 index 0000000..35af876 --- /dev/null +++ b/test/uk/co/ziazoo/fussy/Wibble.as @@ -0,0 +1,25 @@ +package uk.co.ziazoo.fussy +{ + public class Wibble + { + public function Wibble() + { + } + + [Inject] + public function doIt():void + { + + } + + public function wobble(list:Array):String + { + return null; + } + + public function set aaa(value:Object):void + { + + } + } +} \ No newline at end of file
kaineer/nac
f9a50638278eb0823abb4083f4158c6e575c5519
Playable, but dummy
diff --git a/features/field.feature b/features/field.feature index ecf027e..f159961 100644 --- a/features/field.feature +++ b/features/field.feature @@ -1,62 +1,127 @@ @field Feature: Not a conway game field In order to play not-a-conway game Player will need game field Scenario: Create empty field Given I have an empty default game field Then game field should look like this: | . . . . . | | . . . . . | | . . . . . | | . . . . . | | . . . . . | Scenario: Create custom sized field Given I have an empty 7x6 game field Then game field should look like this: | . . . . . . . | | . . . . . . . | | . . . . . . . | | . . . . . . . | | . . . . . . . | | . . . . . . . | Scenario: Pieces counts on board created Given I have an empty default game field Then I have no gold pieces on board And I have no silver pieces on board Scenario: Placing coins and counting Given I have an empty default game field And I place gold pieces at: | 0 0 | | 1 1 | | 2 2 | And I place silver pieces at: | 1 0 | | 2 1 | Then I have 3 gold pieces on board And I have 2 silver pieces on board And game field should look like this: | G S . . . | | . G S . . | | . . G . . | | . . . . . | | . . . . . | Scenario: Placing coins and overwriting Given I have an empty default game field And I place gold pieces at: | 0 0 | | 1 1 | And I place silver pieces at: | 0 0 | Then I have 1 gold piece on board And I have 1 silver piece on board And game field should look like this: | S . . . . | | . G . . . | | . . . . . | | . . . . . | | . . . . . | + + @conway + Scenario: Conway case 1, alone piece dies + Given I have an empty 3x3 game field + And I place gold piece at: + | 1 1 | + And I apply gold conway wave to field + Then game field should look like this: + | . . . | + | . . . | + | . . . | + + @conway + Scenario: Conway case 2, group of two pieces dies + Given I have an empty 4x4 game field + And I place gold pieces at: + | 1 1 | + | 2 2 | + And I apply gold conway wave to field + Then game field should look like this: + | . . . . | + | . . . . | + | . . . . | + | . . . . | + + @conway + Scenario: Conway case 3, birth in strange place + Given I have an empty 7x6 game field + And I place gold pieces at: + | 2 0 | + | 3 0 | + | 4 0 | + | 1 1 | + | 1 2 | + | 1 3 | + | 2 4 | + | 3 4 | + | 4 4 | + | 5 1 | + | 5 2 | + | 5 3 | + And I apply gold conway wave to field + Then game field should look like this: + | . . G G G . . | + | . G . G . G . | + | G G G . G G G | + | . G . G . G . | + | . . G G G . . | + | . . . G . . . | + + @conway + Scenario: Conway case 4, birth and death + Given I have an empty 4x4 game field + And I place gold pieces at: + | 0 2 | + | 1 1 | + | 2 0 | + | 2 3 | + | 3 2 | + And I apply gold conway wave to field + Then game field should look like this: + | . . G . | + | . G G . | + | G G G . | + | . . . . | diff --git a/features/step_definitions/field_steps.rb b/features/step_definitions/field_steps.rb index da7e0c9..62cfc86 100644 --- a/features/step_definitions/field_steps.rb +++ b/features/step_definitions/field_steps.rb @@ -1,51 +1,55 @@ require 'nac' module Nac class Field def visualize_item( item ) case item when NilClass then "." when :gold then "G" when :silver then "S" else "E" end end def visualize @items.map{|row| row.map {|item| visualize_item( item )}.join } end end end Given /^I have an empty default game field$/ do @field = Nac::Field.new end Then /^game field should look like this:$/ do |table| assert_equal( table.raw.flatten.map {|str| str.gsub( /\s+/, "" ) }, @field.visualize ) end Given /^I have an empty (\d+)x(\d+) game field$/ do |width, height| @field = Nac::Field.new( width.to_i, height.to_i ) end Then /^I have (\S+) (\S+) pieces? on board$/ do |count, color| quantity = ( count == "no" ) ? 0 : count.to_i item = color.to_sym assert_equal( quantity, @field.count( item ) ) end -Given /^I place (\S+) pieces at:$/ do |color, table| +Given /^I place (\S+) pieces? at:$/ do |color, table| item = color.to_sym table.raw.flatten.each do |coords| x, y = coords.split( /\s+/ ).map{|s|s.to_i} @field[ x, y ] = item end end + +Given /^I apply (\S+) conway wave to field$/ do |color| + @field.conway( color.to_sym ) +end diff --git a/lib/nac.rb b/lib/nac.rb index 6159055..2a66fb1 100644 --- a/lib/nac.rb +++ b/lib/nac.rb @@ -1,11 +1,27 @@ # --- Not a conway # # require File.join( File.dirname( __FILE__ ), "nac/field" ) require File.join( File.dirname( __FILE__ ), "nac/game" ) module Nac VERSION = "0.0.1" DATE = "2009.12.18" end + +if $0 == __FILE__ + require File.join( File.dirname( __FILE__ ), "nac/visualizers/console" ) + require File.join( File.dirname( __FILE__ ), "nac/pause_input" ) + require File.join( File.dirname( __FILE__ ), "nac/console_input" ) + + game = Nac::Game.new( Nac::Field.new( 7 ), + :visualizer => Nac::ConsoleVisualizer , + :command_source => Nac::ConsoleInput.new + # :command_source => Nac::PauseInput.new( 0.1 ) + ) + + loop do + game.round + end +end diff --git a/lib/nac/console_input.rb b/lib/nac/console_input.rb new file mode 100644 index 0000000..883af32 --- /dev/null +++ b/lib/nac/console_input.rb @@ -0,0 +1,16 @@ +module Nac + class ConsoleInput + def get_commands( side ) + if side == :silver + str = gets.chomp + return [] if str.nil? || str.empty? + str.split( ";" ).map{|s| + x, y, dir = s.split( "," ) + [ x.to_i, y.to_i, dir.downcase ] + } + else + [] + end + end + end +end diff --git a/lib/nac/field.rb b/lib/nac/field.rb index 11efc2b..1232660 100644 --- a/lib/nac/field.rb +++ b/lib/nac/field.rb @@ -1,127 +1,137 @@ # # # module Nac class Field def initialize( width = 5, height = nil ) @width = width @height = height || @width init_field end attr_reader :width, :height def []( x, y ) @items[ y ][ x ] end def []=( x, y, v ) @items[ y ][ x ] = v end def count( sym ) @items.flatten.select{|s|s == sym}.size end def in_limits( x, y ) (0...@width).include?( x ) && (0...@height).include?( y ) end def shift_coords( x, y, dir ) sx, sy = x, y case dir when "up" then sy -= 1 when "down" then sy += 1 when "left" then sx -= 1 when "right" then sx += 1 end sx = sy = nil unless in_limits( sx, sy ) [ sx, sy ] end + def visualize( visualizer ) + visualizer.display_items( @items ) + end + def move( x, y, dir ) dir = dir.downcase item = self[ x, y ] sx, sy = shift_coords( x, y, dir ) # moving to empty place only if sx && sy && !self[ sx, sy ] self[ x, y ] = nil self[ sx, sy ] = item end end def neibours( x, y ) cells = [] ((x-1)..(x+1)).each do |cx| ((y-1)..(y+1)).each do |cy| if !( cx == x && cy == y ) && in_limits( cx, cy ) && @wave_item == self[ cx, cy ] cells << [ cx, cy ] end end end cells end def conway( item ) @wave_item = item init_states apply_states end protected def empty_rectangle Array.new( @height ) {|| Array.new( @width )} end def init_field @items = empty_rectangle end def for_all_coordinates( &block ) (0...@width).each do |x| (0...@height).each do |y| block.call( x, y ) end end end def init_states + @states = nil @states = empty_rectangle for_all_coordinates do |x, y| ngb = neibours( x, y ) + # plain alone + if ngb.size == 0 && self[ x, y ] == @wave_item + @states[ y ][ x ] = :death + end + # too lonely if ngb.size == 1 && self[ x, y ] == @wave_item ngb2 = neibours( *(ngb.first) ) @states[ y ][ x ] = :death if ngb2.size < 2 end # time to birth if ngb.size == 3 && self[ x, y ] != @wave_item @states[ y ][ x ] = :birth end # too crowded if ngb.size >= 4 && self[ x, y ] == @wave_item @states[ y ][ x ] = :death end end end def apply_states for_all_coordinates do |x, y| case @states[ y ][ x ] when :death then self[ x, y ] = nil when :birth then self[ x, y ] = @wave_item end end end end end diff --git a/lib/nac/game.rb b/lib/nac/game.rb index 5476d10..b70fe80 100644 --- a/lib/nac/game.rb +++ b/lib/nac/game.rb @@ -1,102 +1,103 @@ # # # module Nac class Game def initialize( field, opts = {} ) @field = field @command_source = opts[ :command_source ] @visualizer = opts[ :visualizer ] @playing_sides = [ :gold, :silver ] @current_side = @playing_sides.first @sides_initialized = {} end attr_reader :moving_side, :steps_count def middle @field.width / 2 end def run until self.finished? self.round end end def round unless @sides_initialized[ @current_side ] init_side( @current_side ) + @sides_initialized[ @current_side ] = true end - @field.conway( @current_side ) + conway( @current_side ) # TODO: visualize @field.visualize( @visualizer ) if @visualizer # TODO: make_a_move if @command_source run_commands( @command_source.get_commands( @current_side ) ) else puts "Press ENTER to continue" - gets if @visualiser + gets if @visualizer end select_next_side end def run_commands( commands ) commands.each do |cmd| break if @steps_count <= 0 break unless @field.move( *cmd ) @steps_count -= 1 end end def finished? @field.count( @current_side ) == 0 end def select_next_side @current_side = case @current_side when :gold then :silver when :silver then :gold end end def start init_gold end def conway( item ) @field.conway( item ) @moving_side = item @steps_count = [ 0, @field.count( item ) - 3 ].max end def init_side( side ) case side when :gold then init_gold when :silver then init_silver end end def init_gold @field[ middle - 1, 2 ] = :gold @field[ middle + 0, 1 ] = :gold @field[ middle + 1, 2 ] = :gold end def init_silver - bottom = @height - 2 + bottom = @field.height - 2 @field[ middle - 1, bottom - 1 ] = :silver @field[ middle + 0, bottom ] = :silver @field[ middle + 1, bottom - 1 ] = :silver end end end diff --git a/lib/nac/pause_input.rb b/lib/nac/pause_input.rb new file mode 100644 index 0000000..add00c1 --- /dev/null +++ b/lib/nac/pause_input.rb @@ -0,0 +1,13 @@ +module Nac + class PauseInput + def initialize( timeout = 0.5 ) + @timeout = timeout + end + + def get_commands( side ) + puts + Kernel::sleep( @timeout ) + return [] + end + end +end diff --git a/lib/nac/visualizers/console.rb b/lib/nac/visualizers/console.rb new file mode 100644 index 0000000..73d8a4c --- /dev/null +++ b/lib/nac/visualizers/console.rb @@ -0,0 +1,22 @@ +module Nac + module ConsoleVisualizer + def self.esc( sym, color ) + "\e[#{color}m#{sym}\e[0m" + end + + + def self.visualize_single_item( item ) + case item + when NilClass then "." + when :gold then esc( "G", "31" ) + when :silver then esc( "S", "32" ) + end + end + + def self.display_items( items ) + items.each do |row| + puts row.map {|item| visualize_single_item( item )} * " " + end + end + end +end
shimaore/fdnvoip
3579db32daaeb2a49ad151b1432bdc48dc54dc71
Details de tests
diff --git a/protocole_de_test.txt b/protocole_de_test.txt index c8729ef..9a1e77d 100644 --- a/protocole_de_test.txt +++ b/protocole_de_test.txt @@ -1,59 +1,63 @@ Protocole de test -- Appels entants +- Appels entrants Appeler depuis une ligne fixe vers le numéro avec ringing 180 puis 200 l'appelant raccroche l'appelé raccroche avec ringing 183 + SDP puis 200 l'appelant raccroche l'appelé raccroche avec ringing mais sans réponse (pas de 200) -- laisser sonner avec ringing + CANCEL -- raccrocher avant la réponse + dans tous les cas, vérifier que le son passe dans les deux sens (two-way audio) + Appeler depuis un portable vers le numéro même protocole, vérifier la présentation du numéro Appeler depuis un numéro international même protocole, vérifier la présentation du numéro Fax vérifier le switchover vers T.38 sur CED -- générer par l'appelé + réception d'un fax long (plusieurs pages - une dizaine) DTMF vérifier que RFC2833 est présenté vérifier la bonne réception des DTMFs (e.g. pas le mode Asterisk 1.2 avec durée constante) vérifier le bon envoi des DTMFs Appel longue durée placer un appel et le laisser connecté pendant 1h - Appels sortants Appeler depuis SIP appel connecté l'appelant raccroche l'appelé raccroche sans réponse -- laisser sonner sans réponse, appel annulé (CANCEL) -- raccrocher avant la réponse Protocole vers destinations: appel vers un numéro fixe mobile vert international urgences Fax vérifier le switchover vers T.38 sur CED -- détecté par le fournisseur sur CNG -- provoqué par l'appelant + envoi d'un fax long (plusieurs pages - une dizaine) DTMF vérifier que RFC2833 est présenté vérifier la bonne réception des DTMFs (e.g. pas le mode Asterisk 1.2 avec durée constante) vérifier le bon envoi des DTMFs Appel longue durée placer un appel et le laisser connecté pendant 1h
shimaore/fdnvoip
3b5e1719f64181bef91c98d37584ff24542ac7a5
More details on T.38 testing
diff --git a/protocole_de_test.txt b/protocole_de_test.txt index b492fb4..c8729ef 100644 --- a/protocole_de_test.txt +++ b/protocole_de_test.txt @@ -1,56 +1,59 @@ Protocole de test - Appels entants Appeler depuis une ligne fixe vers le numéro avec ringing 180 puis 200 l'appelant raccroche l'appelé raccroche avec ringing 183 + SDP puis 200 l'appelant raccroche l'appelé raccroche avec ringing mais sans réponse (pas de 200) -- laisser sonner avec ringing + CANCEL -- raccrocher avant la réponse Appeler depuis un portable vers le numéro même protocole, vérifier la présentation du numéro Appeler depuis un numéro international même protocole, vérifier la présentation du numéro Fax vérifier le switchover vers T.38 + sur CED -- générer par l'appelé DTMF vérifier que RFC2833 est présenté vérifier la bonne réception des DTMFs (e.g. pas le mode Asterisk 1.2 avec durée constante) vérifier le bon envoi des DTMFs Appel longue durée placer un appel et le laisser connecté pendant 1h - Appels sortants Appeler depuis SIP appel connecté l'appelant raccroche l'appelé raccroche sans réponse -- laisser sonner sans réponse, appel annulé (CANCEL) -- raccrocher avant la réponse Protocole vers destinations: appel vers un numéro fixe mobile vert international urgences Fax vérifier le switchover vers T.38 + sur CED -- détecté par le fournisseur + sur CNG -- provoqué par l'appelant DTMF vérifier que RFC2833 est présenté vérifier la bonne réception des DTMFs (e.g. pas le mode Asterisk 1.2 avec durée constante) vérifier le bon envoi des DTMFs Appel longue durée placer un appel et le laisser connecté pendant 1h
shimaore/fdnvoip
1b7742aa69ef194f9b6abf87e62e93c09bd50af2
Spaces, not tabs
diff --git a/protocole_de_test.txt b/protocole_de_test.txt index ce837c0..b492fb4 100644 --- a/protocole_de_test.txt +++ b/protocole_de_test.txt @@ -1,56 +1,56 @@ Protocole de test - Appels entants Appeler depuis une ligne fixe vers le numéro avec ringing 180 puis 200 l'appelant raccroche l'appelé raccroche avec ringing 183 + SDP puis 200 - l'appelant raccroche - l'appelé raccroche + l'appelant raccroche + l'appelé raccroche avec ringing mais sans réponse (pas de 200) -- laisser sonner avec ringing + CANCEL -- raccrocher avant la réponse Appeler depuis un portable vers le numéro même protocole, vérifier la présentation du numéro Appeler depuis un numéro international - même protocole, vérifier la présentation du numéro + même protocole, vérifier la présentation du numéro Fax vérifier le switchover vers T.38 DTMF vérifier que RFC2833 est présenté vérifier la bonne réception des DTMFs (e.g. pas le mode Asterisk 1.2 avec durée constante) vérifier le bon envoi des DTMFs Appel longue durée placer un appel et le laisser connecté pendant 1h - Appels sortants Appeler depuis SIP appel connecté - l'appelant raccroche - l'appelé raccroche + l'appelant raccroche + l'appelé raccroche sans réponse -- laisser sonner sans réponse, appel annulé (CANCEL) -- raccrocher avant la réponse Protocole vers destinations: appel vers un numéro fixe - mobile - vert - international - urgences + mobile + vert + international + urgences Fax vérifier le switchover vers T.38 DTMF vérifier que RFC2833 est présenté vérifier la bonne réception des DTMFs (e.g. pas le mode Asterisk 1.2 avec durée constante) vérifier le bon envoi des DTMFs Appel longue durée placer un appel et le laisser connecté pendant 1h
shimaore/fdnvoip
2d97329d72bc45caaca30e0c8ee4b80639a82431
Protocole de test
diff --git a/protocole_de_tet.txt b/protocole_de_tet.txt new file mode 100644 index 0000000..ce837c0 --- /dev/null +++ b/protocole_de_tet.txt @@ -0,0 +1,56 @@ +Protocole de test + +- Appels entants + + Appeler depuis une ligne fixe vers le numéro + avec ringing 180 puis 200 + l'appelant raccroche + l'appelé raccroche + avec ringing 183 + SDP puis 200 + l'appelant raccroche + l'appelé raccroche + avec ringing mais sans réponse (pas de 200) -- laisser sonner + avec ringing + CANCEL -- raccrocher avant la réponse + + Appeler depuis un portable vers le numéro + même protocole, vérifier la présentation du numéro + + Appeler depuis un numéro international + même protocole, vérifier la présentation du numéro + + Fax + vérifier le switchover vers T.38 + + DTMF + vérifier que RFC2833 est présenté + vérifier la bonne réception des DTMFs (e.g. pas le mode Asterisk 1.2 avec durée constante) + vérifier le bon envoi des DTMFs + + Appel longue durée + placer un appel et le laisser connecté pendant 1h + +- Appels sortants + Appeler depuis SIP + appel connecté + l'appelant raccroche + l'appelé raccroche + sans réponse -- laisser sonner + sans réponse, appel annulé (CANCEL) -- raccrocher avant la réponse + + Protocole vers destinations: + appel vers un numéro fixe + mobile + vert + international + urgences + + Fax + vérifier le switchover vers T.38 + + DTMF + vérifier que RFC2833 est présenté + vérifier la bonne réception des DTMFs (e.g. pas le mode Asterisk 1.2 avec durée constante) + vérifier le bon envoi des DTMFs + + Appel longue durée + placer un appel et le laisser connecté pendant 1h
relrod/urbanterror-gem
012d084c06f0c8d2a92b8d7336a59490a2fd31fc
Add jump mode
diff --git a/lib/urbanterror.rb b/lib/urbanterror.rb index f4215e2..55f9940 100644 --- a/lib/urbanterror.rb +++ b/lib/urbanterror.rb @@ -1,93 +1,94 @@ #!/usr/bin/env ruby require 'socket' require 'pp' class UrbanTerror def initialize(server, port=nil, rcon=nil) @server = server @port = port || 27960 @rcon = rcon || '' @socket = UDPSocket.open end def send_command(command) magic = "\377\377\377\377" @socket.send("#{magic}#{command}\n", 0, @server, @port) @socket.recv(2048) end def get(command) send_command("get#{command}") end def rcon(command) send_command("rcon #{@rcon} #{command}") end # settings() returns a hash of settings => values. # We /were/ going to accept an optional setting arg, but it would be # doing the same thing and just selecting one from the Hash, so # why not just let the user do server.settings['map'] or whatever. def settings result = get_parts("status", 1).split("\\").reject(&:empty?) Hash[*result] end # players() returns a list of hashes. Each hash contains # name, score, ping. def players results = get_parts("status", 2..-1) results.map do |player| player = player.split(" ", 3) { :name => player[2][1..-2], :ping => player[1].to_i, :score => player[0].to_i } end end GEAR_TYPES = { 'knives' => 0, 'grenades' => 1, 'snipers' => 2, 'spas' => 4, 'pistols' => 8, 'autos' => 16, 'negev' => 32 } MAX_GEAR = 63 def self.gear_calc(gear_array) gear_array.each{ |w| raise "No such gear type '#{w}'" unless GEAR_TYPES.has_key?(w) } MAX_GEAR - gear_array.map{|w| GEAR_TYPES[w] }.reduce(:+) end def self.reverse_gear_calc(number) raise "#{number} is outside of the range 0 to 63." unless (0..63).include?(number) GEAR_TYPES.select{|weapon, gear_val| number & gear_val == 0 }.map(&:first) end GAME_MODES = { 0 => ['Free For All', 'FFA'], 1 => ['Last Man Standing', 'LMS'], 3 => ['Team Death Match', 'TDM'], 4 => ['Team Survivor', 'TS'], 5 => ['Follow the Leader', 'FTL'], 6 => ['Capture and Hold', 'CAH'], 7 => ['Capture the Flag', 'CTF'], - 8 => ['Bomb mode', 'BOMB'] + 8 => ['Bomb mode', 'BOMB'], + 9 => ['Jump mode', 'JUMP'] } def self.match_type(number, abbreviate=false) raise "#{number} is not a valid gametype." unless GAME_MODES.has_key? number GAME_MODES[number][abbreviate ? 1 : 0] end private def get_parts(command, i) get(command).split("\n")[i] end end
relrod/urbanterror-gem
3c19c4980841caf728772bc283f998dce8d6c0b8
release 3.0.0.
diff --git a/lib/urbanterror.rb b/lib/urbanterror.rb index 1b00157..f4215e2 100644 --- a/lib/urbanterror.rb +++ b/lib/urbanterror.rb @@ -1,91 +1,93 @@ #!/usr/bin/env ruby require 'socket' require 'pp' class UrbanTerror def initialize(server, port=nil, rcon=nil) @server = server - @port = port.nil? ? 27960 : port - @rcon = rcon.nil? ? '' : rcon + @port = port || 27960 + @rcon = rcon || '' @socket = UDPSocket.open end - def sendCommand(command) + def send_command(command) magic = "\377\377\377\377" @socket.send("#{magic}#{command}\n", 0, @server, @port) @socket.recv(2048) end def get(command) - sendCommand("get#{command}") + send_command("get#{command}") end - def getparts(command, i) - get(command).split("\n")[i] - end - def rcon(command) - sendCommand("rcon #{@rcon} #{command}") + send_command("rcon #{@rcon} #{command}") end # settings() returns a hash of settings => values. # We /were/ going to accept an optional setting arg, but it would be # doing the same thing and just selecting one from the Hash, so # why not just let the user do server.settings['map'] or whatever. def settings - result = getparts("status", 1).split("\\").reject(&:empty?) + result = get_parts("status", 1).split("\\").reject(&:empty?) Hash[*result] end # players() returns a list of hashes. Each hash contains # name, score, ping. def players - results = getparts("status", 2..-1) + results = get_parts("status", 2..-1) results.map do |player| player = player.split(" ", 3) { :name => player[2][1..-2], :ping => player[1].to_i, :score => player[0].to_i } end end GEAR_TYPES = { 'knives' => 0, 'grenades' => 1, 'snipers' => 2, 'spas' => 4, 'pistols' => 8, 'autos' => 16, 'negev' => 32 } MAX_GEAR = 63 - def self.gearCalc(gearArray) - gearArray.each{ |w| raise "No such gear type '#{w}'" unless GEAR_TYPES.has_key?(w) } - MAX_GEAR - gearArray.map{|w| GEAR_TYPES[w] }.reduce(:+) + def self.gear_calc(gear_array) + gear_array.each{ |w| raise "No such gear type '#{w}'" unless GEAR_TYPES.has_key?(w) } + MAX_GEAR - gear_array.map{|w| GEAR_TYPES[w] }.reduce(:+) end - def self.reverseGearCalc(number) + def self.reverse_gear_calc(number) raise "#{number} is outside of the range 0 to 63." unless (0..63).include?(number) GEAR_TYPES.select{|weapon, gear_val| number & gear_val == 0 }.map(&:first) end GAME_MODES = { 0 => ['Free For All', 'FFA'], + 1 => ['Last Man Standing', 'LMS'], 3 => ['Team Death Match', 'TDM'], 4 => ['Team Survivor', 'TS'], 5 => ['Follow the Leader', 'FTL'], 6 => ['Capture and Hold', 'CAH'], 7 => ['Capture the Flag', 'CTF'], 8 => ['Bomb mode', 'BOMB'] } - def self.matchType(number, abbreviate=false) + def self.match_type(number, abbreviate=false) raise "#{number} is not a valid gametype." unless GAME_MODES.has_key? number GAME_MODES[number][abbreviate ? 1 : 0] end + + private + def get_parts(command, i) + get(command).split("\n")[i] + end end diff --git a/urbanterror.gemspec b/urbanterror.gemspec index f15e8ac..ddb2614 100644 --- a/urbanterror.gemspec +++ b/urbanterror.gemspec @@ -1,10 +1,11 @@ Gem::Specification.new do |s| s.name = 'urbanterror' - s.version = '1.0' - s.date = '2010-08-29' + s.version = '3.0.0' + s.date = '2012-08-09' s.authors = ['Ricky Elrod'] s.email = '[email protected]' + s.license = 'MIT' s.summary = 'Provides a class to access and control Urban Terror servers via RCON over UDP.' s.description = 'Provides a class to access and control Urban Terror servers via RCON over UDP.' s.files = ['lib/urbanterror.rb'] end
relrod/urbanterror-gem
ef3543fcca2efd77afabc76257b87f64b660c17c
Add LICENSE file.... this is MIT, so shouldn't conflict with any projects that are already using the gem. Sorry for not including it sooner. If there are any questions about use of the gem before this point, please contact me. Ricky Elrod <[email protected]>.
diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..98b2ad4 --- /dev/null +++ b/LICENSE @@ -0,0 +1,20 @@ +Copyright (C) 2012-present Ricky Elrod <[email protected]> + +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. +
relrod/urbanterror-gem
253a1166478a9e7aa4b205ea9ceb2251d4540905
add knives to gear types.
diff --git a/lib/urbanterror.rb b/lib/urbanterror.rb index dcf9d18..1b00157 100644 --- a/lib/urbanterror.rb +++ b/lib/urbanterror.rb @@ -1,90 +1,91 @@ #!/usr/bin/env ruby require 'socket' require 'pp' class UrbanTerror def initialize(server, port=nil, rcon=nil) @server = server @port = port.nil? ? 27960 : port @rcon = rcon.nil? ? '' : rcon @socket = UDPSocket.open end def sendCommand(command) magic = "\377\377\377\377" @socket.send("#{magic}#{command}\n", 0, @server, @port) @socket.recv(2048) end def get(command) sendCommand("get#{command}") end def getparts(command, i) get(command).split("\n")[i] end def rcon(command) sendCommand("rcon #{@rcon} #{command}") end # settings() returns a hash of settings => values. # We /were/ going to accept an optional setting arg, but it would be # doing the same thing and just selecting one from the Hash, so # why not just let the user do server.settings['map'] or whatever. def settings result = getparts("status", 1).split("\\").reject(&:empty?) Hash[*result] end # players() returns a list of hashes. Each hash contains # name, score, ping. def players results = getparts("status", 2..-1) results.map do |player| player = player.split(" ", 3) { :name => player[2][1..-2], :ping => player[1].to_i, :score => player[0].to_i } end end GEAR_TYPES = { + 'knives' => 0, 'grenades' => 1, 'snipers' => 2, 'spas' => 4, 'pistols' => 8, 'autos' => 16, 'negev' => 32 } MAX_GEAR = 63 def self.gearCalc(gearArray) gearArray.each{ |w| raise "No such gear type '#{w}'" unless GEAR_TYPES.has_key?(w) } MAX_GEAR - gearArray.map{|w| GEAR_TYPES[w] }.reduce(:+) end def self.reverseGearCalc(number) raise "#{number} is outside of the range 0 to 63." unless (0..63).include?(number) GEAR_TYPES.select{|weapon, gear_val| number & gear_val == 0 }.map(&:first) end GAME_MODES = { 0 => ['Free For All', 'FFA'], 3 => ['Team Death Match', 'TDM'], 4 => ['Team Survivor', 'TS'], 5 => ['Follow the Leader', 'FTL'], 6 => ['Capture and Hold', 'CAH'], 7 => ['Capture the Flag', 'CTF'], 8 => ['Bomb mode', 'BOMB'] } def self.matchType(number, abbreviate=false) raise "#{number} is not a valid gametype." unless GAME_MODES.has_key? number GAME_MODES[number][abbreviate ? 1 : 0] end end
relrod/urbanterror-gem
8734f127235e655d1b90769d5b9c6f00f1111548
Bug fix, and throw some exceptions in certain cases in the gear() functions. Marking this as version 1.0.
diff --git a/lib/urbanterror.rb b/lib/urbanterror.rb index 8f04070..dcf9d18 100644 --- a/lib/urbanterror.rb +++ b/lib/urbanterror.rb @@ -1,88 +1,90 @@ #!/usr/bin/env ruby require 'socket' require 'pp' class UrbanTerror def initialize(server, port=nil, rcon=nil) @server = server @port = port.nil? ? 27960 : port @rcon = rcon.nil? ? '' : rcon @socket = UDPSocket.open end def sendCommand(command) magic = "\377\377\377\377" @socket.send("#{magic}#{command}\n", 0, @server, @port) @socket.recv(2048) end def get(command) sendCommand("get#{command}") end def getparts(command, i) get(command).split("\n")[i] end def rcon(command) sendCommand("rcon #{@rcon} #{command}") end # settings() returns a hash of settings => values. # We /were/ going to accept an optional setting arg, but it would be # doing the same thing and just selecting one from the Hash, so # why not just let the user do server.settings['map'] or whatever. def settings result = getparts("status", 1).split("\\").reject(&:empty?) Hash[*result] end # players() returns a list of hashes. Each hash contains # name, score, ping. def players results = getparts("status", 2..-1) results.map do |player| player = player.split(" ", 3) { :name => player[2][1..-2], :ping => player[1].to_i, :score => player[0].to_i } end end GEAR_TYPES = { 'grenades' => 1, 'snipers' => 2, 'spas' => 4, 'pistols' => 8, 'autos' => 16, 'negev' => 32 } MAX_GEAR = 63 def self.gearCalc(gearArray) - MAX_GEAR - gearArray.select{|w| GEAR_TYPES.has_key? w }.map{|w| GEAR_TYPES[w] }.reduce(:+) + gearArray.each{ |w| raise "No such gear type '#{w}'" unless GEAR_TYPES.has_key?(w) } + MAX_GEAR - gearArray.map{|w| GEAR_TYPES[w] }.reduce(:+) end def self.reverseGearCalc(number) + raise "#{number} is outside of the range 0 to 63." unless (0..63).include?(number) GEAR_TYPES.select{|weapon, gear_val| number & gear_val == 0 }.map(&:first) end GAME_MODES = { 0 => ['Free For All', 'FFA'], 3 => ['Team Death Match', 'TDM'], 4 => ['Team Survivor', 'TS'], 5 => ['Follow the Leader', 'FTL'], 6 => ['Capture and Hold', 'CAH'], 7 => ['Capture the Flag', 'CTF'], 8 => ['Bomb mode', 'BOMB'] } def self.matchType(number, abbreviate=false) raise "#{number} is not a valid gametype." unless GAME_MODES.has_key? number - match[number][abbreviate ? 1 : 0] + GAME_MODES[number][abbreviate ? 1 : 0] end end diff --git a/urbanterror.gemspec b/urbanterror.gemspec index afa919d..f15e8ac 100644 --- a/urbanterror.gemspec +++ b/urbanterror.gemspec @@ -1,10 +1,10 @@ Gem::Specification.new do |s| s.name = 'urbanterror' - s.version = '0.5' - s.date = '2010-08-28' + s.version = '1.0' + s.date = '2010-08-29' s.authors = ['Ricky Elrod'] s.email = '[email protected]' s.summary = 'Provides a class to access and control Urban Terror servers via RCON over UDP.' s.description = 'Provides a class to access and control Urban Terror servers via RCON over UDP.' s.files = ['lib/urbanterror.rb'] end
relrod/urbanterror-gem
26152240400e23c2ac4a36800d0c5cad932e487c
0.5 and here's the part where scott does stuff all clean and nice, and shows me how much I suck. :D
diff --git a/urbanterror.gemspec b/urbanterror.gemspec index 8fbeecd..afa919d 100644 --- a/urbanterror.gemspec +++ b/urbanterror.gemspec @@ -1,10 +1,10 @@ Gem::Specification.new do |s| s.name = 'urbanterror' - s.version = '0.4' + s.version = '0.5' s.date = '2010-08-28' s.authors = ['Ricky Elrod'] s.email = '[email protected]' s.summary = 'Provides a class to access and control Urban Terror servers via RCON over UDP.' s.description = 'Provides a class to access and control Urban Terror servers via RCON over UDP.' s.files = ['lib/urbanterror.rb'] end
relrod/urbanterror-gem
f5f8a08a35012ca9f147df1135de43e88883b7e4
Oops...
diff --git a/lib/urbanterror.rb b/lib/urbanterror.rb index 2418a90..8f04070 100644 --- a/lib/urbanterror.rb +++ b/lib/urbanterror.rb @@ -1,88 +1,88 @@ #!/usr/bin/env ruby require 'socket' require 'pp' class UrbanTerror def initialize(server, port=nil, rcon=nil) @server = server @port = port.nil? ? 27960 : port @rcon = rcon.nil? ? '' : rcon @socket = UDPSocket.open end def sendCommand(command) magic = "\377\377\377\377" @socket.send("#{magic}#{command}\n", 0, @server, @port) @socket.recv(2048) end def get(command) sendCommand("get#{command}") end def getparts(command, i) get(command).split("\n")[i] end def rcon(command) sendCommand("rcon #{@rcon} #{command}") end # settings() returns a hash of settings => values. # We /were/ going to accept an optional setting arg, but it would be # doing the same thing and just selecting one from the Hash, so # why not just let the user do server.settings['map'] or whatever. def settings result = getparts("status", 1).split("\\").reject(&:empty?) Hash[*result] end # players() returns a list of hashes. Each hash contains # name, score, ping. def players results = getparts("status", 2..-1) results.map do |player| player = player.split(" ", 3) { :name => player[2][1..-2], :ping => player[1].to_i, :score => player[0].to_i } end end GEAR_TYPES = { 'grenades' => 1, 'snipers' => 2, 'spas' => 4, 'pistols' => 8, 'autos' => 16, 'negev' => 32 } MAX_GEAR = 63 def self.gearCalc(gearArray) - MAX_GEAR - gearArray.select{|w| GEAR_TYPES.has_key? w }.reduce(:+) + MAX_GEAR - gearArray.select{|w| GEAR_TYPES.has_key? w }.map{|w| GEAR_TYPES[w] }.reduce(:+) end def self.reverseGearCalc(number) GEAR_TYPES.select{|weapon, gear_val| number & gear_val == 0 }.map(&:first) end GAME_MODES = { 0 => ['Free For All', 'FFA'], 3 => ['Team Death Match', 'TDM'], 4 => ['Team Survivor', 'TS'], 5 => ['Follow the Leader', 'FTL'], 6 => ['Capture and Hold', 'CAH'], 7 => ['Capture the Flag', 'CTF'], 8 => ['Bomb mode', 'BOMB'] } def self.matchType(number, abbreviate=false) raise "#{number} is not a valid gametype." unless GAME_MODES.has_key? number match[number][abbreviate ? 1 : 0] end end
relrod/urbanterror-gem
55e108eb860aa0c1050d1132b418abe874fde835
Improvments to the gear and game mode calculation.
diff --git a/lib/urbanterror.rb b/lib/urbanterror.rb index 18dc74c..2418a90 100644 --- a/lib/urbanterror.rb +++ b/lib/urbanterror.rb @@ -1,116 +1,88 @@ #!/usr/bin/env ruby require 'socket' require 'pp' class UrbanTerror def initialize(server, port=nil, rcon=nil) @server = server @port = port.nil? ? 27960 : port @rcon = rcon.nil? ? '' : rcon @socket = UDPSocket.open end def sendCommand(command) magic = "\377\377\377\377" @socket.send("#{magic}#{command}\n", 0, @server, @port) @socket.recv(2048) end def get(command) sendCommand("get#{command}") end def getparts(command, i) get(command).split("\n")[i] end def rcon(command) sendCommand("rcon #{@rcon} #{command}") end # settings() returns a hash of settings => values. # We /were/ going to accept an optional setting arg, but it would be # doing the same thing and just selecting one from the Hash, so # why not just let the user do server.settings['map'] or whatever. def settings result = getparts("status", 1).split("\\").reject(&:empty?) Hash[*result] end # players() returns a list of hashes. Each hash contains # name, score, ping. def players results = getparts("status", 2..-1) results.map do |player| player = player.split(" ", 3) { :name => player[2][1..-2], :ping => player[1].to_i, :score => player[0].to_i } end end - def self.gearCalc(gearArray) - initial = 63 - selected_i = 0 - selected = [] - gearMaster = { - 'grenades' => 1, - 'snipers' => 2, - 'spas' => 4, - 'pistols' => 8, - 'autos' => 16, - 'negev' => 32 - } - - gearArray.each do |w| - if gearMaster.has_key? w - selected << gearMaster[w] - end - end + GEAR_TYPES = { + 'grenades' => 1, + 'snipers' => 2, + 'spas' => 4, + 'pistols' => 8, + 'autos' => 16, + 'negev' => 32 + } - selected_i = selected.inject(:+) - return initial - selected_i + MAX_GEAR = 63 + + def self.gearCalc(gearArray) + MAX_GEAR - gearArray.select{|w| GEAR_TYPES.has_key? w }.reduce(:+) end def self.reverseGearCalc(number) - weapons = [] - gearMaster = { - 1 => 'grenades', - 2 => 'snipers', - 4 => 'spas', - 8 => 'pistols', - 16 => 'autos', - 32 => 'negev' - } - - gearMaster.each do |num, weapon| - if number & num == 0 - weapons << weapon - end - end - return weapons + GEAR_TYPES.select{|weapon, gear_val| number & gear_val == 0 }.map(&:first) end + + GAME_MODES = { + 0 => ['Free For All', 'FFA'], + 3 => ['Team Death Match', 'TDM'], + 4 => ['Team Survivor', 'TS'], + 5 => ['Follow the Leader', 'FTL'], + 6 => ['Capture and Hold', 'CAH'], + 7 => ['Capture the Flag', 'CTF'], + 8 => ['Bomb mode', 'BOMB'] + } def self.matchType(number, abbreviate=false) - # 0=FreeForAll, 3=TeamDeathMatch, 4=Team Survivor, 5=Follow the Leader, 6=Capture and Hold, 7=Capture The Flag, 8=Bombmode - match = { - 0 => ['Free For All', 'FFA'], - 3 => ['Team Death Match', 'TDM'], - 4 => ['Team Survivor', 'TS'], - 5 => ['Follow the Leader', 'FTL'], - 6 => ['Capture and Hold', 'CAH'], - 7 => ['Capture the Flag', 'CTF'], - 8 => ['Bomb mode', 'BOMB'] - } - - throw "#{number} is not a valid gametype." if not match.has_key? number - if abbreviate - match[number][1] - else - match[number][0] - end + raise "#{number} is not a valid gametype." unless GAME_MODES.has_key? number + match[number][abbreviate ? 1 : 0] end -end \ No newline at end of file +end
relrod/urbanterror-gem
06276c15bdcc80f84f58f4eda49c0170cd5d4459
Version 0.4. Includes UrbanTerror.reverseGearCalc(anInteger), returns a list of weapons (as Strings)
diff --git a/lib/urbanterror.rb b/lib/urbanterror.rb index bf4748b..18dc74c 100644 --- a/lib/urbanterror.rb +++ b/lib/urbanterror.rb @@ -1,98 +1,116 @@ #!/usr/bin/env ruby require 'socket' require 'pp' class UrbanTerror def initialize(server, port=nil, rcon=nil) @server = server @port = port.nil? ? 27960 : port @rcon = rcon.nil? ? '' : rcon @socket = UDPSocket.open end def sendCommand(command) magic = "\377\377\377\377" @socket.send("#{magic}#{command}\n", 0, @server, @port) @socket.recv(2048) end def get(command) sendCommand("get#{command}") end def getparts(command, i) get(command).split("\n")[i] end def rcon(command) sendCommand("rcon #{@rcon} #{command}") end # settings() returns a hash of settings => values. # We /were/ going to accept an optional setting arg, but it would be # doing the same thing and just selecting one from the Hash, so # why not just let the user do server.settings['map'] or whatever. def settings result = getparts("status", 1).split("\\").reject(&:empty?) Hash[*result] end # players() returns a list of hashes. Each hash contains # name, score, ping. def players results = getparts("status", 2..-1) results.map do |player| player = player.split(" ", 3) { :name => player[2][1..-2], :ping => player[1].to_i, :score => player[0].to_i } end end def self.gearCalc(gearArray) initial = 63 selected_i = 0 selected = [] gearMaster = { 'grenades' => 1, 'snipers' => 2, 'spas' => 4, 'pistols' => 8, 'autos' => 16, 'negev' => 32 } gearArray.each do |w| if gearMaster.has_key? w selected << gearMaster[w] end end selected_i = selected.inject(:+) return initial - selected_i end + def self.reverseGearCalc(number) + weapons = [] + gearMaster = { + 1 => 'grenades', + 2 => 'snipers', + 4 => 'spas', + 8 => 'pistols', + 16 => 'autos', + 32 => 'negev' + } + + gearMaster.each do |num, weapon| + if number & num == 0 + weapons << weapon + end + end + return weapons + end + def self.matchType(number, abbreviate=false) # 0=FreeForAll, 3=TeamDeathMatch, 4=Team Survivor, 5=Follow the Leader, 6=Capture and Hold, 7=Capture The Flag, 8=Bombmode match = { 0 => ['Free For All', 'FFA'], 3 => ['Team Death Match', 'TDM'], 4 => ['Team Survivor', 'TS'], 5 => ['Follow the Leader', 'FTL'], 6 => ['Capture and Hold', 'CAH'], 7 => ['Capture the Flag', 'CTF'], 8 => ['Bomb mode', 'BOMB'] } throw "#{number} is not a valid gametype." if not match.has_key? number if abbreviate match[number][1] else match[number][0] end - end -end -# puts UrbanTerror.matchType 3 \ No newline at end of file + end +end \ No newline at end of file diff --git a/urbanterror.gemspec b/urbanterror.gemspec index a4f2ae6..8fbeecd 100644 --- a/urbanterror.gemspec +++ b/urbanterror.gemspec @@ -1,10 +1,10 @@ Gem::Specification.new do |s| s.name = 'urbanterror' - s.version = '0.3' - s.date = '2010-08-23' + s.version = '0.4' + s.date = '2010-08-28' s.authors = ['Ricky Elrod'] s.email = '[email protected]' s.summary = 'Provides a class to access and control Urban Terror servers via RCON over UDP.' s.description = 'Provides a class to access and control Urban Terror servers via RCON over UDP.' s.files = ['lib/urbanterror.rb'] end
relrod/urbanterror-gem
78ddf3851a47e4e8ff309d6645a523a9cea3df4d
remove some whitespace. hah.
diff --git a/lib/urbanterror.rb b/lib/urbanterror.rb index dc9577b..bf4748b 100644 --- a/lib/urbanterror.rb +++ b/lib/urbanterror.rb @@ -1,99 +1,98 @@ #!/usr/bin/env ruby require 'socket' require 'pp' class UrbanTerror def initialize(server, port=nil, rcon=nil) @server = server @port = port.nil? ? 27960 : port @rcon = rcon.nil? ? '' : rcon @socket = UDPSocket.open end def sendCommand(command) magic = "\377\377\377\377" @socket.send("#{magic}#{command}\n", 0, @server, @port) @socket.recv(2048) end def get(command) sendCommand("get#{command}") end def getparts(command, i) get(command).split("\n")[i] end def rcon(command) sendCommand("rcon #{@rcon} #{command}") end # settings() returns a hash of settings => values. # We /were/ going to accept an optional setting arg, but it would be # doing the same thing and just selecting one from the Hash, so # why not just let the user do server.settings['map'] or whatever. def settings result = getparts("status", 1).split("\\").reject(&:empty?) Hash[*result] end # players() returns a list of hashes. Each hash contains # name, score, ping. def players results = getparts("status", 2..-1) results.map do |player| player = player.split(" ", 3) { :name => player[2][1..-2], :ping => player[1].to_i, :score => player[0].to_i } end end def self.gearCalc(gearArray) initial = 63 selected_i = 0 selected = [] gearMaster = { 'grenades' => 1, 'snipers' => 2, 'spas' => 4, 'pistols' => 8, 'autos' => 16, 'negev' => 32 } gearArray.each do |w| if gearMaster.has_key? w selected << gearMaster[w] end end selected_i = selected.inject(:+) return initial - selected_i end def self.matchType(number, abbreviate=false) # 0=FreeForAll, 3=TeamDeathMatch, 4=Team Survivor, 5=Follow the Leader, 6=Capture and Hold, 7=Capture The Flag, 8=Bombmode match = { 0 => ['Free For All', 'FFA'], 3 => ['Team Death Match', 'TDM'], 4 => ['Team Survivor', 'TS'], 5 => ['Follow the Leader', 'FTL'], 6 => ['Capture and Hold', 'CAH'], 7 => ['Capture the Flag', 'CTF'], 8 => ['Bomb mode', 'BOMB'] } throw "#{number} is not a valid gametype." if not match.has_key? number if abbreviate match[number][1] else match[number][0] end end - end # puts UrbanTerror.matchType 3 \ No newline at end of file
relrod/urbanterror-gem
5b3db2478f0c53591100e1d559db017ef581aedd
Cleaner implementation
diff --git a/lib/urbanterror.rb b/lib/urbanterror.rb index efffbbd..dc9577b 100644 --- a/lib/urbanterror.rb +++ b/lib/urbanterror.rb @@ -1,108 +1,99 @@ #!/usr/bin/env ruby require 'socket' require 'pp' class UrbanTerror def initialize(server, port=nil, rcon=nil) @server = server @port = port.nil? ? 27960 : port @rcon = rcon.nil? ? '' : rcon @socket = UDPSocket.open end def sendCommand(command) magic = "\377\377\377\377" @socket.send("#{magic}#{command}\n", 0, @server, @port) @socket.recv(2048) end def get(command) sendCommand("get#{command}") end def getparts(command, i) get(command).split("\n")[i] end def rcon(command) sendCommand("rcon #{@rcon} #{command}") end # settings() returns a hash of settings => values. # We /were/ going to accept an optional setting arg, but it would be # doing the same thing and just selecting one from the Hash, so # why not just let the user do server.settings['map'] or whatever. def settings result = getparts("status", 1).split("\\").reject(&:empty?) Hash[*result] end # players() returns a list of hashes. Each hash contains # name, score, ping. def players results = getparts("status", 2..-1) results.map do |player| player = player.split(" ", 3) { :name => player[2][1..-2], :ping => player[1].to_i, :score => player[0].to_i } end end def self.gearCalc(gearArray) initial = 63 selected_i = 0 selected = [] gearMaster = { 'grenades' => 1, 'snipers' => 2, 'spas' => 4, 'pistols' => 8, 'autos' => 16, 'negev' => 32 } gearArray.each do |w| if gearMaster.has_key? w selected << gearMaster[w] end end selected_i = selected.inject(:+) return initial - selected_i end def self.matchType(number, abbreviate=false) # 0=FreeForAll, 3=TeamDeathMatch, 4=Team Survivor, 5=Follow the Leader, 6=Capture and Hold, 7=Capture The Flag, 8=Bombmode + match = { + 0 => ['Free For All', 'FFA'], + 3 => ['Team Death Match', 'TDM'], + 4 => ['Team Survivor', 'TS'], + 5 => ['Follow the Leader', 'FTL'], + 6 => ['Capture and Hold', 'CAH'], + 7 => ['Capture the Flag', 'CTF'], + 8 => ['Bomb mode', 'BOMB'] + } + + throw "#{number} is not a valid gametype." if not match.has_key? number if abbreviate - match = { - 0 => 'FFA', - 3 => 'TDM', - 4 => 'TS', - 5 => 'FTL', - 6 => 'CAH', - 7 => 'CTF', - 8 => 'BOMB' - } + match[number][1] else - match = { - 0 => 'Free For All', - 3 => 'Team Death Match', - 4 => 'Team Survivor', - 5 => 'Follow the Leader', - 6 => 'Capture and Hold', - 7 => 'Capture the Flag', - 8 => 'Bomb Mode' - } + match[number][0] end - - throw "#{number} is not a valid gametype." if not match.has_key? number - match[number] end end - # puts UrbanTerror.matchType 3 \ No newline at end of file
relrod/urbanterror-gem
720c2e10ecc93e9102b845495155d87d52823f73
gemspec
diff --git a/urbanterror.gemspec b/urbanterror.gemspec index 0949008..a4f2ae6 100644 --- a/urbanterror.gemspec +++ b/urbanterror.gemspec @@ -1,10 +1,10 @@ Gem::Specification.new do |s| s.name = 'urbanterror' - s.version = '0.2' + s.version = '0.3' s.date = '2010-08-23' s.authors = ['Ricky Elrod'] s.email = '[email protected]' s.summary = 'Provides a class to access and control Urban Terror servers via RCON over UDP.' s.description = 'Provides a class to access and control Urban Terror servers via RCON over UDP.' s.files = ['lib/urbanterror.rb'] end
relrod/urbanterror-gem
6b284dae84521c2fdb62228e00252bbd4bad3b5a
Optional abbreviate flag to matchType()
diff --git a/lib/urbanterror.rb b/lib/urbanterror.rb index e689512..efffbbd 100644 --- a/lib/urbanterror.rb +++ b/lib/urbanterror.rb @@ -1,96 +1,108 @@ #!/usr/bin/env ruby require 'socket' require 'pp' class UrbanTerror def initialize(server, port=nil, rcon=nil) @server = server @port = port.nil? ? 27960 : port @rcon = rcon.nil? ? '' : rcon @socket = UDPSocket.open end def sendCommand(command) magic = "\377\377\377\377" @socket.send("#{magic}#{command}\n", 0, @server, @port) @socket.recv(2048) end def get(command) sendCommand("get#{command}") end def getparts(command, i) get(command).split("\n")[i] end def rcon(command) sendCommand("rcon #{@rcon} #{command}") end # settings() returns a hash of settings => values. # We /were/ going to accept an optional setting arg, but it would be # doing the same thing and just selecting one from the Hash, so # why not just let the user do server.settings['map'] or whatever. def settings result = getparts("status", 1).split("\\").reject(&:empty?) Hash[*result] end # players() returns a list of hashes. Each hash contains # name, score, ping. def players results = getparts("status", 2..-1) results.map do |player| player = player.split(" ", 3) { :name => player[2][1..-2], :ping => player[1].to_i, :score => player[0].to_i } end end def self.gearCalc(gearArray) initial = 63 selected_i = 0 selected = [] gearMaster = { 'grenades' => 1, 'snipers' => 2, 'spas' => 4, 'pistols' => 8, 'autos' => 16, 'negev' => 32 } gearArray.each do |w| if gearMaster.has_key? w selected << gearMaster[w] end end selected_i = selected.inject(:+) return initial - selected_i end - def self.matchType(number) + def self.matchType(number, abbreviate=false) # 0=FreeForAll, 3=TeamDeathMatch, 4=Team Survivor, 5=Follow the Leader, 6=Capture and Hold, 7=Capture The Flag, 8=Bombmode - match = { - 0 => 'Free For All', - 3 => 'Team Death Match', - 4 => 'Team Survivor', - 5 => 'Follow the Leader', - 6 => 'Capture and Hold', - 7 => 'Capture the Flag', - 8 => 'Bomb Mode' - } + if abbreviate + match = { + 0 => 'FFA', + 3 => 'TDM', + 4 => 'TS', + 5 => 'FTL', + 6 => 'CAH', + 7 => 'CTF', + 8 => 'BOMB' + } + else + match = { + 0 => 'Free For All', + 3 => 'Team Death Match', + 4 => 'Team Survivor', + 5 => 'Follow the Leader', + 6 => 'Capture and Hold', + 7 => 'Capture the Flag', + 8 => 'Bomb Mode' + } + end throw "#{number} is not a valid gametype." if not match.has_key? number match[number] end end # puts UrbanTerror.matchType 3 \ No newline at end of file
relrod/urbanterror-gem
d79bbc1285e973fa70806bbd46f8ea9fa5dabb6d
Oops - remove some debug.
diff --git a/lib/urbanterror.rb b/lib/urbanterror.rb index f2d50bf..e689512 100644 --- a/lib/urbanterror.rb +++ b/lib/urbanterror.rb @@ -1,97 +1,96 @@ #!/usr/bin/env ruby require 'socket' require 'pp' class UrbanTerror def initialize(server, port=nil, rcon=nil) @server = server @port = port.nil? ? 27960 : port @rcon = rcon.nil? ? '' : rcon @socket = UDPSocket.open end def sendCommand(command) magic = "\377\377\377\377" @socket.send("#{magic}#{command}\n", 0, @server, @port) @socket.recv(2048) end def get(command) sendCommand("get#{command}") end def getparts(command, i) get(command).split("\n")[i] end def rcon(command) sendCommand("rcon #{@rcon} #{command}") end # settings() returns a hash of settings => values. # We /were/ going to accept an optional setting arg, but it would be # doing the same thing and just selecting one from the Hash, so # why not just let the user do server.settings['map'] or whatever. def settings result = getparts("status", 1).split("\\").reject(&:empty?) Hash[*result] end # players() returns a list of hashes. Each hash contains # name, score, ping. def players results = getparts("status", 2..-1) - return results results.map do |player| player = player.split(" ", 3) { :name => player[2][1..-2], :ping => player[1].to_i, :score => player[0].to_i } end end def self.gearCalc(gearArray) initial = 63 selected_i = 0 selected = [] gearMaster = { 'grenades' => 1, 'snipers' => 2, 'spas' => 4, 'pistols' => 8, 'autos' => 16, 'negev' => 32 } gearArray.each do |w| if gearMaster.has_key? w selected << gearMaster[w] end end selected_i = selected.inject(:+) return initial - selected_i end def self.matchType(number) # 0=FreeForAll, 3=TeamDeathMatch, 4=Team Survivor, 5=Follow the Leader, 6=Capture and Hold, 7=Capture The Flag, 8=Bombmode match = { 0 => 'Free For All', 3 => 'Team Death Match', 4 => 'Team Survivor', 5 => 'Follow the Leader', 6 => 'Capture and Hold', 7 => 'Capture the Flag', 8 => 'Bomb Mode' } throw "#{number} is not a valid gametype." if not match.has_key? number match[number] end end # puts UrbanTerror.matchType 3 \ No newline at end of file
relrod/urbanterror-gem
69ff9269aae3b8d4ad7df5b873915df01c97a068
Add a self.matchType so we can convert from a number of a match to a string.
diff --git a/lib/urbanterror.rb b/lib/urbanterror.rb index fbb4343..f2d50bf 100644 --- a/lib/urbanterror.rb +++ b/lib/urbanterror.rb @@ -1,77 +1,97 @@ #!/usr/bin/env ruby require 'socket' require 'pp' class UrbanTerror def initialize(server, port=nil, rcon=nil) @server = server @port = port.nil? ? 27960 : port @rcon = rcon.nil? ? '' : rcon @socket = UDPSocket.open end def sendCommand(command) magic = "\377\377\377\377" @socket.send("#{magic}#{command}\n", 0, @server, @port) @socket.recv(2048) end def get(command) sendCommand("get#{command}") end def getparts(command, i) get(command).split("\n")[i] end def rcon(command) sendCommand("rcon #{@rcon} #{command}") end # settings() returns a hash of settings => values. # We /were/ going to accept an optional setting arg, but it would be # doing the same thing and just selecting one from the Hash, so # why not just let the user do server.settings['map'] or whatever. def settings result = getparts("status", 1).split("\\").reject(&:empty?) Hash[*result] end # players() returns a list of hashes. Each hash contains # name, score, ping. def players results = getparts("status", 2..-1) + return results results.map do |player| player = player.split(" ", 3) { :name => player[2][1..-2], :ping => player[1].to_i, :score => player[0].to_i } end end def self.gearCalc(gearArray) initial = 63 selected_i = 0 selected = [] gearMaster = { 'grenades' => 1, 'snipers' => 2, 'spas' => 4, 'pistols' => 8, 'autos' => 16, 'negev' => 32 } gearArray.each do |w| if gearMaster.has_key? w selected << gearMaster[w] end end selected_i = selected.inject(:+) return initial - selected_i end + + def self.matchType(number) + # 0=FreeForAll, 3=TeamDeathMatch, 4=Team Survivor, 5=Follow the Leader, 6=Capture and Hold, 7=Capture The Flag, 8=Bombmode + match = { + 0 => 'Free For All', + 3 => 'Team Death Match', + 4 => 'Team Survivor', + 5 => 'Follow the Leader', + 6 => 'Capture and Hold', + 7 => 'Capture the Flag', + 8 => 'Bomb Mode' + } + + throw "#{number} is not a valid gametype." if not match.has_key? number + match[number] + end + end + +# puts UrbanTerror.matchType 3 \ No newline at end of file
relrod/urbanterror-gem
2dfc8e410aa64ac9ccf7fe32acf92ffdc8845a98
urbanterror gem.
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c111b33 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +*.gem diff --git a/lib/urbanterror.rb b/lib/urbanterror.rb new file mode 100644 index 0000000..fbb4343 --- /dev/null +++ b/lib/urbanterror.rb @@ -0,0 +1,77 @@ +#!/usr/bin/env ruby + +require 'socket' +require 'pp' + +class UrbanTerror + def initialize(server, port=nil, rcon=nil) + @server = server + @port = port.nil? ? 27960 : port + @rcon = rcon.nil? ? '' : rcon + @socket = UDPSocket.open + end + + def sendCommand(command) + magic = "\377\377\377\377" + @socket.send("#{magic}#{command}\n", 0, @server, @port) + @socket.recv(2048) + end + + def get(command) + sendCommand("get#{command}") + end + + def getparts(command, i) + get(command).split("\n")[i] + end + + def rcon(command) + sendCommand("rcon #{@rcon} #{command}") + end + + # settings() returns a hash of settings => values. + # We /were/ going to accept an optional setting arg, but it would be + # doing the same thing and just selecting one from the Hash, so + # why not just let the user do server.settings['map'] or whatever. + def settings + result = getparts("status", 1).split("\\").reject(&:empty?) + Hash[*result] + end + + # players() returns a list of hashes. Each hash contains + # name, score, ping. + def players + results = getparts("status", 2..-1) + results.map do |player| + player = player.split(" ", 3) + { + :name => player[2][1..-2], + :ping => player[1].to_i, + :score => player[0].to_i + } + end + end + + def self.gearCalc(gearArray) + initial = 63 + selected_i = 0 + selected = [] + gearMaster = { + 'grenades' => 1, + 'snipers' => 2, + 'spas' => 4, + 'pistols' => 8, + 'autos' => 16, + 'negev' => 32 + } + + gearArray.each do |w| + if gearMaster.has_key? w + selected << gearMaster[w] + end + end + + selected_i = selected.inject(:+) + return initial - selected_i + end +end diff --git a/urbanterror.gemspec b/urbanterror.gemspec new file mode 100644 index 0000000..72b8ef5 --- /dev/null +++ b/urbanterror.gemspec @@ -0,0 +1,10 @@ +Gem::Specification.new do |s| + s.name = 'urbanterror' + s.version = '0.1' + s.date = '2010-08-22' + s.authors = ['Ricky Elrod'] + s.email = '[email protected]' + s.summary = 'Provides a class to access and control Urban Terror servers via RCON over UDP.' + s.description = 'Provides a class to access and control Urban Terror servers via RCON over UDP.' + s.files = ['lib/urbanterror.rb'] +end
sbogutyn/krypto
204ad5a02976e0c4ea6543407c5f35be92447477
zmiana deszyfrowania
diff --git a/mdes/crypto.txt b/mdes/crypto.txt new file mode 100644 index 0000000..e69de29 diff --git a/mdes/minides.rb b/mdes/minides.rb index 6f219a1..7731a2b 100755 --- a/mdes/minides.rb +++ b/mdes/minides.rb @@ -1,92 +1,100 @@ #!/usr/bin/ruby -w # dwa S-boksy [4]->[3] to # 101 010 001 110 011 100 111 000 # 001 100 110 010 000 111 101 011 # # 100 000 110 101 111 001 011 010 # 101 011 000 111 110 010 001 100 # # klucz jest 9-bitowy, klucz dla kazdej runy i (1..8) jest osmiobitowy # i zaczyna sie od i-tego bitu klucza. # bloki 12 bitowe, dzielone sa na dwa po 6 bitow , LO, RO # w kazdej rundzie Li=[Ri-1] Ri = L[i-1]+f(R[i-1], Ki) w ostatniej osmej # jeszcze zamiana L8 i R8 # f:[6+8]->[6] jest zdefiniowane # f(R,K)=S1xS2(E(R)+K) # Opcje wywolania: # -e -d -a # # -e szyfrowanie - program czyta z pliku ciag 12 zer i jedynek # a z pliku key 9 zer i jedynek i zapisyje na crypto wynik szyfrowania # -d deszyfrowanie - czyta crypto i zapisuje w decrypt # -a analiza dzialania programu require 'optparse' # nazwy plików PLAIN = "plain.txt" CRYPTO = "crypto.txt" DECRYPT = "decrypt.txt" KEY = "key.txt" class Szyfrowanie def initialize(tekst, klucz) @tekst = tekst @klucz = klucz end def to_s "Szyfrowanie: \"#{@tekst}\" z kluczem: \"#{@klucz}\"" end end class Deszyfrowanie + + def initialize(tekst, klucz) + @tekst = tekst + @klucz = klucz + end + def to_s - "Deszyfrowanie" + "Deszyfrowanie tekstu: \"#{@tekst}\" z kluczem \"#{@klucz}\"" end end class Analiza def to_s "Analiza" end end def czytaj_plik(nazwa_pliku) tekst = "" File.foreach(nazwa_pliku) do |line| tekst << line end tekst.chomp! end options = {} optparse = OptionParser.new do |opts| opts.banner = "Usage: minides.rb [opcje]" opts.on('-e', '--szyfrowanie', 'Szyfrowanie tekstu z plain.txt do crypto.txt') do tekst = czytaj_plik(PLAIN) klucz = czytaj_plik(KEY) puts Szyfrowanie.new(tekst, klucz) end opts.on('-d', '--deszyfrowanie', 'Deszyfrowanie tekstu z pliku crypto.txt do decrypt.txt') do - puts Deszyfrowanie.new + tekst = czytaj_plik(CRYPTO) + klucz = czytaj_plik(KEY) + puts Deszyfrowanie.new(tekst, klucz) end opts.on('-a', '--analiza', 'Analiza dzialania programu') do puts Analiza.new end opts.on( '-h', '--help', 'Pokaz pomoc' ) do puts opts exit end end optparse.parse!
sbogutyn/krypto
414e9709146e329e463a89a1d6a899a764f9dc33
zmiana minides
diff --git a/mdes/key.txt b/mdes/key.txt old mode 100644 new mode 100755 index e69de29..77eccb9 --- a/mdes/key.txt +++ b/mdes/key.txt @@ -0,0 +1 @@ +111010101 diff --git a/mdes/minides.rb b/mdes/minides.rb index f3241e5..6f219a1 100755 --- a/mdes/minides.rb +++ b/mdes/minides.rb @@ -1,95 +1,92 @@ #!/usr/bin/ruby -w # dwa S-boksy [4]->[3] to # 101 010 001 110 011 100 111 000 # 001 100 110 010 000 111 101 011 # # 100 000 110 101 111 001 011 010 # 101 011 000 111 110 010 001 100 # # klucz jest 9-bitowy, klucz dla kazdej runy i (1..8) jest osmiobitowy # i zaczyna sie od i-tego bitu klucza. # bloki 12 bitowe, dzielone sa na dwa po 6 bitow , LO, RO # w kazdej rundzie Li=[Ri-1] Ri = L[i-1]+f(R[i-1], Ki) w ostatniej osmej # jeszcze zamiana L8 i R8 # f:[6+8]->[6] jest zdefiniowane # f(R,K)=S1xS2(E(R)+K) # Opcje wywolania: # -e -d -a # # -e szyfrowanie - program czyta z pliku ciag 12 zer i jedynek # a z pliku key 9 zer i jedynek i zapisyje na crypto wynik szyfrowania # -d deszyfrowanie - czyta crypto i zapisuje w decrypt # -a analiza dzialania programu require 'optparse' -options = {} - +# nazwy plików PLAIN = "plain.txt" CRYPTO = "crypto.txt" DECRYPT = "decrypt.txt" KEY = "key.txt" - class Szyfrowanie - def initialize(tekst) + def initialize(tekst, klucz) @tekst = tekst + @klucz = klucz end + def to_s - "Szyfrowanie: #{@tekst} " + "Szyfrowanie: \"#{@tekst}\" z kluczem: \"#{@klucz}\"" end end class Deszyfrowanie def to_s "Deszyfrowanie" end end class Analiza def to_s "Analiza" end end def czytaj_plik(nazwa_pliku) tekst = "" File.foreach(nazwa_pliku) do |line| tekst << line end - tekst + tekst.chomp! end +options = {} + optparse = OptionParser.new do |opts| opts.banner = "Usage: minides.rb [opcje]" - options[:szyfrowanie] = false - options[:deszyfrowanie] = false - options[:analiza] = false opts.on('-e', '--szyfrowanie', 'Szyfrowanie tekstu z plain.txt do crypto.txt') do - tekst = czytaj_plik(PLAIN).chomp! - klucz = czytaj_plik(KEY).chomp! - puts tekst - puts tekst.length - puts Szyfrowanie.new("tekst do zaszyfrowania") + tekst = czytaj_plik(PLAIN) + klucz = czytaj_plik(KEY) + puts Szyfrowanie.new(tekst, klucz) end opts.on('-d', '--deszyfrowanie', 'Deszyfrowanie tekstu z pliku crypto.txt do decrypt.txt') do puts Deszyfrowanie.new end opts.on('-a', '--analiza', 'Analiza dzialania programu') do puts Analiza.new end opts.on( '-h', '--help', 'Pokaz pomoc' ) do puts opts exit end end optparse.parse! diff --git a/mdes/plain.txt b/mdes/plain.txt index 9daeafb..74e3abe 100755 --- a/mdes/plain.txt +++ b/mdes/plain.txt @@ -1 +1 @@ -test +100110101010
sbogutyn/krypto
120da365395deba4548d1ffccd0fc59163738a6b
dodanie testu nwd
diff --git a/afiniczny/afine.pyc b/afiniczny/afine.pyc old mode 100755 new mode 100644 index 7724707..4186b73 Binary files a/afiniczny/afine.pyc and b/afiniczny/afine.pyc differ diff --git a/afiniczny/test_afine.py b/afiniczny/test_afine.py index a77a04e..9c27235 100755 --- a/afiniczny/test_afine.py +++ b/afiniczny/test_afine.py @@ -1,27 +1,28 @@ +#!/usr/bin/env python import unittest import afine class TestAfiniczneSzyfrowanie(unittest.TestCase): def setup(self): pass def test_szyfruj_litere(self): self.assertEqual('b', afine.zaszyfruj_litere('a', 1, 1)) def test_bledne_szyfrowanie_litery(self): self.assertNotEqual('b', afine.zaszyfruj_litere('a', 5, 5)) def test_szyfruj_tekst(self): self.assertEqual("bcd", afine.zaszyfruj_tekst("abc", 1, 1)) def test_nwd(self): - self.assertEqual(1, nwd(1, 26)) - self.assertEqual(1, nwd(3, 26)) - self.assertEqual(1, nwd(5, 26)) + self.assertEqual(1, afine.nwd(1, 26)) + self.assertEqual(1, afine.nwd(3, 26)) + self.assertEqual(1, afine.nwd(5, 26)) if __name__ == "__main__": unittest.main() \ No newline at end of file
sbogutyn/krypto
01c8cda93e8446aa428e3b456e836142b530c5d2
poprawki w kodzie afinicznego
diff --git a/afiniczny/afine.py b/afiniczny/afine.py index a39a84e..cc6b1e1 100755 --- a/afiniczny/afine.py +++ b/afiniczny/afine.py @@ -1,214 +1,185 @@ #!/usr/bin/env python from string import ascii_lowercase, ascii_uppercase, letters, maketrans from optparse import OptionParser # szyfruje pojedyncza litera afinicznym (cezar to afiniczny z a = 1) def zaszyfruj_litere(litera,a,b): + litery = None if (litera >= 'a' and litera <= 'z'): - kod = list(ascii_lowercase).index(litera) - nowy_kod = (kod * a + b) % 26 - return list(ascii_lowercase)[nowy_kod] + litery = ascii_lowercase elif (litera >= 'A' and litera <= 'Z'): - kod = list(ascii_uppercase).index(litera) - nowy_kod = (kod * a + b) % 26 - return list(ascii_uppercase)[nowy_kod] + litery = ascii_uppercase else: return litera; + kod = list(litery).index(litera) + nowy_kod = (kod * a + b) % 26 + return list(litery)[nowy_kod] def zaszyfruj_alfabet(a, b): - szyfr = lambda x : zaszyfruj_litere(x, a, b); - return ''.join(map(szyfr, list(letters))) + return ''.join(map(lambda x : zaszyfruj_litere(x, a, b), list(letters))) def znajdz_odwrotnosc(a, modn): for i in xrange(modn): if sprawdz_odwrotnosc(a, i, modn): return i return -1 def sprawdz_odwrotnosc(a, b, modn): if ((a * b) % modn) == 1: return True else: return False def odszyfruj_litere(litera, a, b): odw_a = znajdz_odwrotnosc(a, 26) + litery = None if odw_a != -1: if (litera >= 'A' and litera <= 'Z'): - kod = list(ascii_uppercase).index(litera) - nowy_kod = (odw_a * (kod - b)) % 26 - return list(ascii_uppercase)[nowy_kod] + litery = ascii_uppercase elif (litera >= 'a' and litera <= 'z'): - kod = list(ascii_lowercase).index(litera) - nowy_kod = (odw_a * (kod - b)) % 26 - return list(ascii_lowercase)[nowy_kod] + litery = ascii_lowercase else: return litera + kod = list(litery).index(litera) + nowy_kod = (odw_a * (kod - b)) % 26 + return list(litery)[nowy_kod] def odszyfruj_alfabet(alfabet, a, b): - odszyfruj = lambda x : odszyfruj_litere(x, a, b) - return ''.join(map(odszyfruj, list(alfabet))) + return ''.join(map(lambda x : odszyfruj_litere(x, a, b), list(alfabet))) def tlumacz_tekst(tekst, alfabet1, alfabet2): - transtab = maketrans(alfabet1, alfabet2) - return tekst.translate(transtab) + return tekst.translate(maketrans(alfabet1, alfabet2)) def zaszyfruj_tekst(tekst, a, b): - zaszyfrowany_alfabet = zaszyfruj_alfabet(a, b) - return tlumacz_tekst(tekst,letters, zaszyfrowany_alfabet) + return tlumacz_tekst(tekst,letters, zaszyfruj_alfabet(a, b)) def odszyfruj_tekst(tekst, a, b): - zaszyfrowany_alfabet = zaszyfruj_alfabet(a, b) - return tlumacz_tekst(tekst, zaszyfrowany_alfabet, letters) + return tlumacz_tekst(tekst, zaszyfruj_alfabet(a, b), letters) def nwd(a, b): x = a y = b while (y != 0): c = x % y x = y y = c return x def odczytaj_plik(nazwa_pliku): plik = open(nazwa_pliku, "r") tresc = plik.read() plik.close() return tresc def zapisz_do_pliku(nazwa_pliku, tresc): plik = open(nazwa_pliku, "w+") plik.write(tresc) plik.close() def wczytaj_klucz(nazwa_pliku): tresc = odczytaj_plik(nazwa_pliku) wartosci = tresc.split(',') if len(wartosci) == 1: return (int(wartosci[0])) elif len(wartosci) == 2: return (int(wartosci[0]), int(wartosci[1])) if __name__ == "__main__": PLIK_PLAIN="plain.txt" PLIK_CRYPTO="crypto.txt" PLIK_DECRYPT="decrypt.txt" PLIK_EXTRA="extra.txt" PLIK_KEY="key.txt" parser = OptionParser(usage="Program szyfrujacy i deszyfrujacy.", version="%prog 1.0") parser.add_option("-c", "--cezar", action="store_true", dest="cezar_flag", default=False, help="uzyj szyfru cezara") parser.add_option("-a", "--afiniczny", action="store_true", dest="afiniczny_flag", default=False, help="uzyj szyfru afinicznego") parser.add_option("-d", "--deszyfrowanie", action="store_true", dest="deszyfruj_flag", default=False, help="deszyfrowanie pliku crypto.txt") parser.add_option("-e", "--szyfrowanie", action="store_true", dest="szyfruj_flag", default=False, help="szyfrowanie pliku plain.txt") parser.add_option("-j", "--jawny", action="store_true", dest="jawny_flag", default=False, help="kryptoanaliza z tekstem jawnym") parser.add_option("-k", "--krypto", action="store_true", dest="krypto_flag", default=False, help="kryptoanaliza tylko za pomoca kryptogramu") (options, args) = parser.parse_args() if len(args) != 0: parser.error("zla liczba argumentow") + a = b = 0 if options.afiniczny_flag: - if options.szyfruj_flag: - print "Szyfrowanie afinicznym" - klucze = wczytaj_klucz(PLIK_KEY) - tekst = odczytaj_plik(PLIK_PLAIN) - zapisz_do_pliku(PLIK_CRYPTO, zaszyfruj_tekst(tekst, klucze[0], klucze[1])) - elif options.deszyfruj_flag: - print "Deszyfrowanie afinicznym" - klucze = wczytaj_klucz(PLIK_KEY) - zaszyfrowany_tekst = odczytaj_plik(PLIK_CRYPTO) - zapisz_do_pliku(PLIK_DECRYPT, odszyfruj_tekst(zaszyfrowany_tekst, klucze[0], klucze[1])) - elif options.jawny_flag: - print "kryptoanaliza z tekstem jawnym" - pomoc = odczytaj_plik(PLIK_EXTRA).strip() - zaszyfrowany_tekst = odczytaj_plik(PLIK_CRYPTO) - if (len(pomoc) < len(zaszyfrowany_tekst)): - dlugosc = len(pomoc) - else: - dlugosc = len(zaszyfrowany_tekst) - wyniki = set() - for i in xrange(dlugosc): - wynik = set() - for a in range(26): - if nwd (a, 26) == 1: - for b in range(26): - if odszyfruj_litere(zaszyfrowany_tekst[i], a ,b) == pomoc[i]: - wynik.add( (a, b) ) - if len(wyniki) == 0: - for i in wynik: - wyniki.add(i) - else: - print "wyniki = ", wyniki, " & ", wynik - wyniki = wyniki & wynik - print pomoc[dlugosc - 1] - print zaszyfrowany_tekst[dlugosc - 1] - print wyniki - - - - elif options.krypto_flag: - zaszyfrowany_tekst = odczytaj_plik(PLIK_CRYPTO) - tekst = "" + (a, b) = wczytaj_klucz(PLIK_KEY) + elif options.cezar_flag: + a, b = 1 , wczytaj_klucz(PLIK_KEY)[0] + else: + print "Musisz wybrac szyfr afiniczny lub cezara" + + if options.szyfruj_flag: + print "Szyfrowanie afinicznym" + klucze = wczytaj_klucz(PLIK_KEY) + tekst = odczytaj_plik(PLIK_PLAIN) + zapisz_do_pliku(PLIK_CRYPTO, zaszyfruj_tekst(tekst, a, b)) + elif options.deszyfruj_flag: + print "Deszyfrowanie afinicznym" + klucze = wczytaj_klucz(PLIK_KEY) + zaszyfrowany_tekst = odczytaj_plik(PLIK_CRYPTO) + zapisz_do_pliku(PLIK_DECRYPT, odszyfruj_tekst(zaszyfrowany_tekst, a, b)) + elif options.jawny_flag: + print "kryptoanaliza z tekstem jawnym" + pomoc = odczytaj_plik(PLIK_EXTRA).strip() + zaszyfrowany_tekst = odczytaj_plik(PLIK_CRYPTO) + if (len(pomoc) < len(zaszyfrowany_tekst)): + dlugosc = len(pomoc) + else: + dlugosc = len(zaszyfrowany_tekst) + wyniki = set() + for i in xrange(dlugosc): + wynik = set() for a in range(26): - if nwd(a, 26) == 1: + if nwd (a, 26) == 1: for b in range(26): - tekst += odszyfruj_tekst(zaszyfrowany_tekst, a, b) + "\n" + if odszyfruj_litere(zaszyfrowany_tekst[i], a ,b) == pomoc[i]: + wynik.add( (a, b) ) + if len(wyniki) == 0: + for i in wynik: + wyniki.add(i) + else: + wyniki = wyniki & wynik + if len(wyniki) == 1: + (a, b) = wyniki.pop() + tekst = odszyfruj_tekst(zaszyfrowany_tekst, a, b) zapisz_do_pliku(PLIK_DECRYPT, tekst) - - print "kryptoanaliza za pomoca kryptogramu" + + + elif options.krypto_flag: + zaszyfrowany_tekst = odczytaj_plik(PLIK_CRYPTO) + tekst = "" + for x in range(26): + if nwd(x , 26) == 1: + for y in range(26): + tekst += odszyfruj_tekst(zaszyfrowany_tekst, x , y) + "\n" + zapisz_do_pliku(PLIK_DECRYPT, tekst) + + print "kryptoanaliza za pomoca kryptogramu" - elif options.cezar_flag: - print "cezar!" - if options.szyfruj_flag: - print "szyfrowanie" - elif options.deszyfruj_flag: - print "deszyfrowanie" - elif options.jawny_flag: - print "kryptoanaliza z tekstem jawnym" - elif options.krypto_flag: - print "kryptoanaliza za pomoca kryptogramu" - else: - print "Klucze: ", wczytaj_klucz(PLIK_KEY) - print zaszyfruj_litere('A', 1, 1) - print zaszyfruj_litere('B', 2, 1) - print zaszyfruj_litere('Z', 1, 1) - print zaszyfruj_alfabet(1,1) - for i in range(1, 25): - if nwd(i, 26) == 1: - print "a = ", i - print "Zaszyfrowany: ", zaszyfruj_tekst("ala ma kota", i, 1) - print "Odszyfrowany: ", odszyfruj_tekst(zaszyfruj_tekst("ala ma kota", i, 1), i, 1) - try: - print odszyfruj_alfabet(zaszyfruj_alfabet(26, 3), 26, 3) - except TypeError: - print "NWD(a, 26) != 1" - try: - for i in xrange(26): - print "Odwrotnosc: ", i , " to: ", znajdz_odwrotnosc(i ,26) - except TypeError: - print "brak odwrotnosci" diff --git a/afiniczny/afine.pyc b/afiniczny/afine.pyc new file mode 100755 index 0000000..7724707 Binary files /dev/null and b/afiniczny/afine.pyc differ diff --git a/afiniczny/decrypt.txt b/afiniczny/decrypt.txt index 4dad810..a01609a 100755 --- a/afiniczny/decrypt.txt +++ b/afiniczny/decrypt.txt @@ -1,1560 +1,4 @@ -Vauadkpx rp d lvkx nvqexqrxqu, cgxorigx, dqs avjxkczg grikdkt cvk adkprqh nvlldqs-grqx vaurvqp umdq umx vgs hxuvau lvszgx. -vauadkpx zpxp d lvkx sxngdkdurex putgx vc nvlldqs-grqx adkprqh: tvz nkxdux dq rqpudqnx vc VaurvqAdkpxk, avazgdux ru jrum vaurvqp, -dqs adkpx umx nvlldqs grqx. vauadkpx dggvjp zpxkp uv paxnrct vaurvqp rq umx nvqexqurvqdg HQZ/AVPRO ptqudo, dqs dssrurvqdggt hxqxkduxp -zpdhx dqs mxga lxppdhxp cvk tvz. - -Uztzcjow qo c kujw mupdwpqwpt, bfwnqhfw, cpr zuiwjbyf fqhjcjs buj zcjoqpg mukkcpr-fqpw uztqupo tlcp tlw ufr gwtuzt kuryfw. -uztzcjow yowo c kujw rwmfcjctqdw otsfw ub mukkcpr-fqpw zcjoqpg: suy mjwctw cp qpotcpmw ub UztqupZcjowj, zuzyfctw qt iqtl uztqupo, -cpr zcjow tlw mukkcpr fqpw. uztzcjow cffuio yowjo tu ozwmqbs uztqupo qp tlw mupdwptqupcf GPY/ZUOQN osptcn, cpr crrqtqupcffs gwpwjctwo -yocgw cpr lwfz kwoocgwo buj suy. - -Tysybinv pn b jtiv ltocvopvos, aevmpgev, boq ythviaxe epgibir ati ybinpof ltjjboq-epov tyspton skbo skv teq fvstys jtqxev. -tysybinv xnvn b jtiv qvlebibspcv nsrev ta ltjjboq-epov ybinpof: rtx livbsv bo ponsbolv ta TysptoYbinvi, ytyxebsv ps hpsk tyspton, -boq ybinv skv ltjjboq epov. tysybinv beethn xnvin st nyvlpar tyspton po skv ltocvosptobe FOX/YTNPM nrosbm, boq bqqpsptobeer fvovibsvn -xnbfv boq kvey jvnnbfvn ati rtx. - -Sxrxahmu om a ishu ksnbunounr, zdulofdu, anp xsguhzwd dofhahq zsh xahmone ksiianp-donu sxrosnm rjan rju sdp eursxr ispwdu. -sxrxahmu wmum a ishu pukdaharobu mrqdu sz ksiianp-donu xahmone: qsw khuaru an onmranku sz SxrosnXahmuh, xsxwdaru or gorj sxrosnm, -anp xahmu rju ksiianp donu. sxrxahmu addsgm wmuhm rs mxukozq sxrosnm on rju ksnbunrosnad ENW/XSMOL mqnral, anp apporosnaddq eunuharum -wmaeu anp judx iummaeum zsh qsw. - -Rwqwzglt nl z hrgt jrmatmntmq, yctknect, zmo wrftgyvc cnegzgp yrg wzglnmd jrhhzmo-cnmt rwqnrml qizm qit rco dtqrwq hrovct. -rwqwzglt vltl z hrgt otjczgzqnat lqpct ry jrhhzmo-cnmt wzglnmd: prv jgtzqt zm nmlqzmjt ry RwqnrmWzgltg, wrwvczqt nq fnqi rwqnrml, -zmo wzglt qit jrhhzmo cnmt. rwqwzglt zccrfl vltgl qr lwtjnyp rwqnrml nm qit jrmatmqnrmzc DMV/WRLNK lpmqzk, zmo zoonqnrmzccp dtmtgzqtl -vlzdt zmo itcw htllzdtl yrg prv. - -Qvpvyfks mk y gqfs iqlzslmslp, xbsjmdbs, yln vqesfxub bmdfyfo xqf vyfkmlc iqggyln-bmls qvpmqlk phyl phs qbn cspqvp gqnubs. -qvpvyfks uksk y gqfs nsibyfypmzs kpobs qx iqggyln-bmls vyfkmlc: oqu ifsyps yl mlkpylis qx QvpmqlVyfksf, vqvubyps mp emph qvpmqlk, -yln vyfks phs iqggyln bmls. qvpvyfks ybbqek uksfk pq kvsimxo qvpmqlk ml phs iqlzslpmqlyb CLU/VQKMJ kolpyj, yln ynnmpmqlybbo cslsfypsk -ukycs yln hsbv gskkycsk xqf oqu. - -Puouxejr lj x fper hpkyrklrko, warilcar, xkm updrewta alcexen wpe uxejlkb hpffxkm-alkr puolpkj ogxk ogr pam bropuo fpmtar. -puouxejr tjrj x fper mrhaxexolyr jonar pw hpffxkm-alkr uxejlkb: npt herxor xk lkjoxkhr pw PuolpkUxejre, uputaxor lo dlog puolpkj, -xkm uxejr ogr hpffxkm alkr. puouxejr xaapdj tjrej op jurhlwn puolpkj lk ogr hpkyrkolpkxa BKT/UPJLI jnkoxi, xkm xmmlolpkxaan brkrexorj -tjxbr xkm grau frjjxbrj wpe npt. - -Otntwdiq ki w eodq gojxqjkqjn, vzqhkbzq, wjl tocqdvsz zkbdwdm vod twdikja goeewjl-zkjq otnkoji nfwj nfq ozl aqnotn eolszq. -otntwdiq siqi w eodq lqgzwdwnkxq inmzq ov goeewjl-zkjq twdikja: mos gdqwnq wj kjinwjgq ov OtnkojTwdiqd, totszwnq kn cknf otnkoji, -wjl twdiq nfq goeewjl zkjq. otntwdiq wzzoci siqdi no itqgkvm otnkoji kj nfq gojxqjnkojwz AJS/TOIKH imjnwh, wjl wllknkojwzzm aqjqdwnqi -siwaq wjl fqzt eqiiwaqi vod mos. - -Nsmsvchp jh v dncp fniwpijpim, uypgjayp, vik snbpcury yjacvcl unc svchjiz fnddvik-yjip nsmjnih mevi mep nyk zpmnsm dnkryp. -nsmsvchp rhph v dncp kpfyvcvmjwp hmlyp nu fnddvik-yjip svchjiz: lnr fcpvmp vi jihmvifp nu NsmjniSvchpc, snsryvmp jm bjme nsmjnih, -vik svchp mep fnddvik yjip. nsmsvchp vyynbh rhpch mn hspfjul nsmjnih ji mep fniwpimjnivy ZIR/SNHJG hlimvg, vik vkkjmjnivyyl zpipcvmph -rhvzp vik epys dphhvzph unc lnr. - -Mrlrubgo ig u cmbo emhvohiohl, txofizxo, uhj rmaobtqx xizbubk tmb rubgihy emccuhj-xiho mrlimhg lduh ldo mxj yolmrl cmjqxo. -mrlrubgo qgog u cmbo joexubulivo glkxo mt emccuhj-xiho rubgihy: kmq eboulo uh ihgluheo mt MrlimhRubgob, rmrqxulo il aild mrlimhg, -uhj rubgo ldo emccuhj xiho. mrlrubgo uxxmag qgobg lm groeitk mrlimhg ih ldo emhvohlimhux YHQ/RMGIF gkhluf, uhj ujjilimhuxxk yohobulog -qguyo uhj doxr cogguyog tmb kmq. - -Lqkqtafn hf t blan dlgunghngk, swnehywn, tgi qlznaspw whyataj sla qtafhgx dlbbtgi-whgn lqkhlgf kctg kcn lwi xnklqk blipwn. -lqkqtafn pfnf t blan indwtatkhun fkjwn ls dlbbtgi-whgn qtafhgx: jlp dantkn tg hgfktgdn ls LqkhlgQtafna, qlqpwtkn hk zhkc lqkhlgf, -tgi qtafn kcn dlbbtgi whgn. lqkqtafn twwlzf pfnaf kl fqndhsj lqkhlgf hg kcn dlgungkhlgtw XGP/QLFHE fjgkte, tgi tiihkhlgtwwj xngnatknf -pftxn tgi cnwq bnfftxnf sla jlp. - -Kpjpszem ge s akzm ckftmfgmfj, rvmdgxvm, sfh pkymzrov vgxzszi rkz pszegfw ckaasfh-vgfm kpjgkfe jbsf jbm kvh wmjkpj akhovm. -kpjpszem oeme s akzm hmcvszsjgtm ejivm kr ckaasfh-vgfm pszegfw: iko czmsjm sf gfejsfcm kr KpjgkfPszemz, pkpovsjm gj ygjb kpjgkfe, -sfh pszem jbm ckaasfh vgfm. kpjpszem svvkye oemze jk epmcgri kpjgkfe gf jbm ckftmfjgkfsv WFO/PKEGD eifjsd, sfh shhgjgkfsvvi wmfmzsjme -oeswm sfh bmvp ameeswme rkz iko. - -Joiorydl fd r zjyl bjesleflei, qulcfwul, reg ojxlyqnu ufwyryh qjy orydfev bjzzreg-ufel joifjed iare ial jug vlijoi zjgnul. -joiorydl ndld r zjyl glburyrifsl dihul jq bjzzreg-ufel orydfev: hjn bylril re fedirebl jq JoifjeOrydly, ojonuril fi xfia joifjed, -reg orydl ial bjzzreg ufel. joiorydl ruujxd ndlyd ij dolbfqh joifjed fe ial bjesleifjeru VEN/OJDFC dheirc, reg rggfifjeruuh vlelyrild -ndrvl reg aluo zlddrvld qjy hjn. - -Inhnqxck ec q yixk aidrkdekdh, ptkbevtk, qdf niwkxpmt tevxqxg pix nqxcedu aiyyqdf-tedk inheidc hzqd hzk itf ukhinh yifmtk. -inhnqxck mckc q yixk fkatqxqherk chgtk ip aiyyqdf-tedk nqxcedu: gim axkqhk qd edchqdak ip InheidNqxckx, ninmtqhk eh wehz inheidc, -qdf nqxck hzk aiyyqdf tedk. inhnqxck qttiwc mckxc hi cnkaepg inheidc ed hzk aidrkdheidqt UDM/NICEB cgdhqb, qdf qffeheidqttg ukdkxqhkc -mcquk qdf zktn ykccqukc pix gim. - -Hmgmpwbj db p xhwj zhcqjcdjcg, osjadusj, pce mhvjwols sduwpwf ohw mpwbdct zhxxpce-sdcj hmgdhcb gypc gyj hse tjghmg xhelsj. -hmgmpwbj lbjb p xhwj ejzspwpgdqj bgfsj ho zhxxpce-sdcj mpwbdct: fhl zwjpgj pc dcbgpczj ho HmgdhcMpwbjw, mhmlspgj dg vdgy hmgdhcb, -pce mpwbj gyj zhxxpce sdcj. hmgmpwbj psshvb lbjwb gh bmjzdof hmgdhcb dc gyj zhcqjcgdhcps TCL/MHBDA bfcgpa, pce peedgdhcpssf tjcjwpgjb -lbptj pce yjsm xjbbptjb ohw fhl. - -Glflovai ca o wgvi ygbpibcibf, nrizctri, obd lguivnkr rctvove ngv lovacbs ygwwobd-rcbi glfcgba fxob fxi grd sifglf wgdkri. -glflovai kaia o wgvi diyrovofcpi aferi gn ygwwobd-rcbi lovacbs: egk yviofi ob cbafobyi gn GlfcgbLovaiv, lglkrofi cf ucfx glfcgba, -obd lovai fxi ygwwobd rcbi. glflovai orrgua kaiva fg aliycne glfcgba cb fxi ygbpibfcgbor SBK/LGACZ aebfoz, obd oddcfcgborre sibivofia -kaosi obd xirl wiaaosia ngv egk. - -Fkeknuzh bz n vfuh xfaohabhae, mqhybsqh, nac kfthumjq qbsunud mfu knuzbar xfvvnac-qbah fkebfaz ewna ewh fqc rhefke vfcjqh. -fkeknuzh jzhz n vfuh chxqnuneboh zedqh fm xfvvnac-qbah knuzbar: dfj xuhneh na bazenaxh fm FkebfaKnuzhu, kfkjqneh be tbew fkebfaz, -nac knuzh ewh xfvvnac qbah. fkeknuzh nqqftz jzhuz ef zkhxbmd fkebfaz ba ewh xfaohaebfanq RAJ/KFZBY zdaeny, nac nccbebfanqqd rhahunehz -jznrh nac whqk vhzznrhz mfu dfj. - -Ejdjmtyg ay m uetg wezngzagzd, lpgxarpg, mzb jesgtlip partmtc let jmtyazq weuumzb-pazg ejdaezy dvmz dvg epb qgdejd uebipg. -ejdjmtyg iygy m uetg bgwpmtmdang ydcpg el weuumzb-pazg jmtyazq: cei wtgmdg mz azydmzwg el EjdaezJmtygt, jejipmdg ad sadv ejdaezy, -mzb jmtyg dvg weuumzb pazg. ejdjmtyg mppesy iygty de yjgwalc ejdaezy az dvg wezngzdaezmp QZI/JEYAX yczdmx, mzb mbbadaezmppc qgzgtmdgy -iymqg mzb vgpj ugyymqgy let cei. - -Dicilsxf zx l tdsf vdymfyzfyc, kofwzqof, lya idrfskho ozqslsb kds ilsxzyp vdttlya-ozyf diczdyx culy cuf doa pfcdic tdahof. -dicilsxf hxfx l tdsf afvolslczmf xcbof dk vdttlya-ozyf ilsxzyp: bdh vsflcf ly zyxclyvf dk DiczdyIlsxfs, idiholcf zc rzcu diczdyx, -lya ilsxf cuf vdttlya ozyf. dicilsxf loodrx hxfsx cd xifvzkb diczdyx zy cuf vdymfyczdylo PYH/IDXZW xbyclw, lya laazczdyloob pfyfslcfx -hxlpf lya ufoi tfxxlpfx kds bdh. - -Chbhkrwe yw k scre ucxlexyexb, jnevypne, kxz hcqerjgn nyprkra jcr hkrwyxo ucsskxz-nyxe chbycxw btkx bte cnz oebchb sczgne. -chbhkrwe gwew k scre zeunkrkbyle wbane cj ucsskxz-nyxe hkrwyxo: acg urekbe kx yxwbkxue cj ChbycxHkrwer, hchgnkbe yb qybt chbycxw, -kxz hkrwe bte ucsskxz nyxe. chbhkrwe knncqw gwerw bc wheuyja chbycxw yx bte ucxlexbycxkn OXG/HCWYV waxbkv, kxz kzzybycxknna oexerkbew -gwkoe kxz tenh sewwkoew jcr acg. - -Bgagjqvd xv j rbqd tbwkdwxdwa, imduxomd, jwy gbpdqifm mxoqjqz ibq gjqvxwn tbrrjwy-mxwd bgaxbwv asjw asd bmy ndabga rbyfmd. -bgagjqvd fvdv j rbqd ydtmjqjaxkd vazmd bi tbrrjwy-mxwd gjqvxwn: zbf tqdjad jw xwvajwtd bi BgaxbwGjqvdq, gbgfmjad xa pxas bgaxbwv, -jwy gjqvd asd tbrrjwy mxwd. bgagjqvd jmmbpv fvdqv ab vgdtxiz bgaxbwv xw asd tbwkdwaxbwjm NWF/GBVXU vzwaju, jwy jyyxaxbwjmmz ndwdqjadv -fvjnd jwy sdmg rdvvjndv ibq zbf. - -Afzfipuc wu i qapc savjcvwcvz, hlctwnlc, ivx faocphel lwnpipy hap fipuwvm saqqivx-lwvc afzwavu zriv zrc alx mczafz qaxelc. -afzfipuc eucu i qapc xcslipizwjc uzylc ah saqqivx-lwvc fipuwvm: yae spcizc iv wvuzivsc ah AfzwavFipucp, fafelizc wz owzr afzwavu, -ivx fipuc zrc saqqivx lwvc. afzfipuc illaou eucpu za ufcswhy afzwavu wv zrc savjcvzwavil MVE/FAUWT uyvzit, ivx ixxwzwavilly mcvcpizcu -euimc ivx rclf qcuuimcu hap yae. - -Zeyehotb vt h pzob rzuibuvbuy, gkbsvmkb, huw eznbogdk kvmohox gzo ehotvul rzpphuw-kvub zeyvzut yqhu yqb zkw lbyzey pzwdkb. -zeyehotb dtbt h pzob wbrkhohyvib tyxkb zg rzpphuw-kvub ehotvul: xzd robhyb hu vutyhurb zg ZeyvzuEhotbo, ezedkhyb vy nvyq zeyvzut, -huw ehotb yqb rzpphuw kvub. zeyehotb hkkznt dtbot yz tebrvgx zeyvzut vu yqb rzuibuyvzuhk LUD/EZTVS txuyhs, huw hwwvyvzuhkkx lbubohybt -dthlb huw qbke pbtthlbt gzo xzd. - -Ydxdgnsa us g oyna qythatuatx, fjarulja, gtv dymanfcj julngnw fyn dgnsutk qyoogtv-juta ydxuyts xpgt xpa yjv kaxydx oyvcja. -ydxdgnsa csas g oyna vaqjgngxuha sxwja yf qyoogtv-juta dgnsutk: wyc qnagxa gt utsxgtqa yf YdxuytDgnsan, dydcjgxa ux muxp ydxuyts, -gtv dgnsa xpa qyoogtv juta. ydxdgnsa gjjyms csans xy sdaqufw ydxuyts ut xpa qythatxuytgj KTC/DYSUR swtxgr, gtv gvvuxuytgjjw katangxas -csgka gtv pajd oassgkas fyn wyc. - -Xcwcfmrz tr f nxmz pxsgzstzsw, eizqtkiz, fsu cxlzmebi itkmfmv exm cfmrtsj pxnnfsu-itsz xcwtxsr wofs woz xiu jzwxcw nxubiz. -xcwcfmrz brzr f nxmz uzpifmfwtgz rwviz xe pxnnfsu-itsz cfmrtsj: vxb pmzfwz fs tsrwfspz xe XcwtxsCfmrzm, cxcbifwz tw ltwo xcwtxsr, -fsu cfmrz woz pxnnfsu itsz. xcwcfmrz fiixlr brzmr wx rczptev xcwtxsr ts woz pxsgzswtxsfi JSB/CXRTQ rvswfq, fsu fuutwtxsfiiv jzszmfwzr -brfjz fsu ozic nzrrfjzr exm vxb. - -Wbvbelqy sq e mwly owrfyrsyrv, dhypsjhy, ert bwkyldah hsjlelu dwl belqsri owmmert-hsry wbvswrq vner vny wht iyvwbv mwtahy. -wbvbelqy aqyq e mwly tyohelevsfy qvuhy wd owmmert-hsry belqsri: uwa olyevy er srqveroy wd WbvswrBelqyl, bwbahevy sv ksvn wbvswrq, -ert belqy vny owmmert hsry. wbvbelqy ehhwkq aqylq vw qbyosdu wbvswrq sr vny owrfyrvswreh IRA/BWQSP qurvep, ert ettsvswrehhu iyrylevyq -aqeiy ert nyhb myqqeiyq dwl uwa. - -Hayabmfz xf b vhmz nhokzoxzoy, sczwxucz, bog ahdzmsrc cxumbmp shm abmfxol nhvvbog-cxoz hayxhof yebo yez hcg lzyhay vhgrcz. -hayabmfz rfzf b vhmz gzncbmbyxkz fypcz hs nhvvbog-cxoz abmfxol: phr nmzbyz bo xofybonz hs HayxhoAbmfzm, aharcbyz xy dxye hayxhof, -bog abmfz yez nhvvbog cxoz. hayabmfz bcchdf rfzmf yh faznxsp hayxhof xo yez nhokzoyxhobc LOR/AHFXW fpoybw, bog bggxyxhobccp lzozmbyzf -rfblz bog ezca vzffblzf shm phr. - -Yrprsdwq ow s mydq eyfbqfoqfp, jtqnoltq, sfx ryuqdjit toldsdg jyd rsdwofc eymmsfx-tofq yrpoyfw pvsf pvq ytx cqpyrp myxitq. -yrprsdwq iwqw s mydq xqetsdspobq wpgtq yj eymmsfx-tofq rsdwofc: gyi edqspq sf ofwpsfeq yj YrpoyfRsdwqd, ryritspq op uopv yrpoyfw, -sfx rsdwq pvq eymmsfx tofq. yrprsdwq sttyuw iwqdw py wrqeojg yrpoyfw of pvq eyfbqfpoyfst CFI/RYWON wgfpsn, sfx sxxopoyfsttg cqfqdspqw -iwscq sfx vqtr mqwwscqw jyd gyi. - -Pigijunh fn j dpuh vpwshwfhwg, akhefckh, jwo iplhuazk kfcujux apu ijunfwt vpddjwo-kfwh pigfpwn gmjw gmh pko thgpig dpozkh. -pigijunh znhn j dpuh ohvkjujgfsh ngxkh pa vpddjwo-kfwh ijunfwt: xpz vuhjgh jw fwngjwvh pa PigfpwIjunhu, ipizkjgh fg lfgm pigfpwn, -jwo ijunh gmh vpddjwo kfwh. pigijunh jkkpln znhun gp nihvfax pigfpwn fw gmh vpwshwgfpwjk TWZ/IPNFE nxwgje, jwo joofgfpwjkkx thwhujghn -znjth jwo mhki dhnnjthn apu xpz. - -Gzxzaley we a ugly mgnjynwynx, rbyvwtby, anf zgcylrqb bwtlalo rgl zalewnk mguuanf-bwny gzxwgne xdan xdy gbf kyxgzx ugfqby. -gzxzaley qeye a ugly fymbalaxwjy exoby gr mguuanf-bwny zalewnk: ogq mlyaxy an wnexanmy gr GzxwgnZaleyl, zgzqbaxy wx cwxd gzxwgne, -anf zaley xdy mguuanf bwny. gzxzaley abbgce qeyle xg ezymwro gzxwgne wn xdy mgnjynxwgnab KNQ/ZGEWV eonxav, anf affwxwgnabbo kynylaxye -qeaky anf dybz uyeeakye rgl ogq. - -Xqoqrcvp nv r lxcp dxeapenpeo, ispmnksp, rew qxtpcihs snkcrcf ixc qrcvneb dxllrew-snep xqonxev oure oup xsw bpoxqo lxwhsp. -xqoqrcvp hvpv r lxcp wpdsrcronap vofsp xi dxllrew-snep qrcvneb: fxh dcprop re nevoredp xi XqonxeQrcvpc, qxqhsrop no tnou xqonxev, -rew qrcvp oup dxllrew snep. xqoqrcvp rssxtv hvpcv ox vqpdnif xqonxev ne oup dxeapeonxers BEH/QXVNM vfeorm, rew rwwnonxerssf bpepcropv -hvrbp rew upsq lpvvrbpv ixc fxh. - -Ohfhitmg em i cotg uovrgvegvf, zjgdebjg, ivn hokgtzyj jebtitw zot hitmevs uoccivn-jevg ohfeovm fliv flg ojn sgfohf conyjg. -ohfhitmg ymgm i cotg ngujitiferg mfwjg oz uoccivn-jevg hitmevs: woy utgifg iv evmfivug oz OhfeovHitmgt, hohyjifg ef kefl ohfeovm, -ivn hitmg flg uoccivn jevg. ohfhitmg ijjokm ymgtm fo mhguezw ohfeovm ev flg uovrgvfeovij SVY/HOMED mwvfid, ivn innefeovijjw sgvgtifgm -ymisg ivn lgjh cgmmisgm zot woy. - -Fywyzkdx vd z tfkx lfmixmvxmw, qaxuvsax, zme yfbxkqpa avskzkn qfk yzkdvmj lfttzme-avmx fywvfmd wczm wcx fae jxwfyw tfepax. -fywyzkdx pdxd z tfkx exlazkzwvix dwnax fq lfttzme-avmx yzkdvmj: nfp lkxzwx zm vmdwzmlx fq FywvfmYzkdxk, yfypazwx vw bvwc fywvfmd, -zme yzkdx wcx lfttzme avmx. fywyzkdx zaafbd pdxkd wf dyxlvqn fywvfmd vm wcx lfmixmwvfmza JMP/YFDVU dnmwzu, zme zeevwvfmzaan jxmxkzwxd -pdzjx zme cxay txddzjxd qfk nfp. - -Wpnpqbuo mu q kwbo cwdzodmodn, hrolmjro, qdv pwsobhgr rmjbqbe hwb pqbumda cwkkqdv-rmdo wpnmwdu ntqd nto wrv aonwpn kwvgro. -wpnpqbuo guou q kwbo vocrqbqnmzo unero wh cwkkqdv-rmdo pqbumda: ewg cboqno qd mdunqdco wh WpnmwdPqbuob, pwpgrqno mn smnt wpnmwdu, -qdv pqbuo nto cwkkqdv rmdo. wpnpqbuo qrrwsu guobu nw upocmhe wpnmwdu md nto cwdzodnmwdqr ADG/PWUML uednql, qdv qvvmnmwdqrre aodobqnou -guqao qdv torp kouuqaou hwb ewg. - -Ngeghslf dl h bnsf tnuqfudfue, yifcdaif, hum gnjfsyxi idashsv yns ghsldur tnbbhum-iduf ngednul ekhu ekf nim rfenge bnmxif. -ngeghslf xlfl h bnsf mftihshedqf levif ny tnbbhum-iduf ghsldur: vnx tsfhef hu dulehutf ny NgednuGhslfs, gngxihef de jdek ngednul, -hum ghslf ekf tnbbhum iduf. ngeghslf hiinjl xlfsl en lgftdyv ngednul du ekf tnuqfuednuhi RUX/GNLDC lvuehc, hum hmmdednuhiiv rfufshefl -xlhrf hum kfig bfllhrfl yns vnx. - -Exvxyjcw uc y sejw kelhwluwlv, pzwturzw, yld xeawjpoz zurjyjm pej xyjculi kessyld-zulw exvuelc vbyl vbw ezd iwvexv sedozw. -exvxyjcw ocwc y sejw dwkzyjyvuhw cvmzw ep kessyld-zulw xyjculi: meo kjwyvw yl ulcvylkw ep ExvuelXyjcwj, xexozyvw uv auvb exvuelc, -yld xyjcw vbw kessyld zulw. exvxyjcw yzzeac ocwjc ve cxwkupm exvuelc ul vbw kelhwlvuelyz ILO/XECUT cmlvyt, yld ydduvuelyzzm iwlwjyvwc -ocyiw yld bwzx swccyiwc pej meo. - -Vomopatn lt p jvan bvcynclncm, gqnkliqn, pcu ovrnagfq qliapad gva opatlcz bvjjpcu-qlcn vomlvct mspc msn vqu znmvom jvufqn. -vomopatn ftnt p jvan unbqpapmlyn tmdqn vg bvjjpcu-qlcn opatlcz: dvf banpmn pc lctmpcbn vg VomlvcOpatna, ovofqpmn lm rlms vomlvct, -pcu opatn msn bvjjpcu qlcn. vomopatn pqqvrt ftnat mv tonblgd vomlvct lc msn bvcyncmlvcpq ZCF/OVTLK tdcmpk, pcu puulmlvcpqqd zncnapmnt -ftpzn pcu snqo jnttpznt gva dvf. - -Mfdfgrke ck g amre smtpetcetd, xhebczhe, gtl fmierxwh hczrgru xmr fgrkctq smaagtl-hcte mfdcmtk djgt dje mhl qedmfd amlwhe. -mfdfgrke wkek g amre leshgrgdcpe kduhe mx smaagtl-hcte fgrkctq: umw sregde gt ctkdgtse mx MfdcmtFgrker, fmfwhgde cd icdj mfdcmtk, -gtl fgrke dje smaagtl hcte. mfdfgrke ghhmik wkerk dm kfescxu mfdcmtk ct dje smtpetdcmtgh QTW/FMKCB kutdgb, gtl gllcdcmtghhu qetergdek -wkgqe gtl jehf aekkgqek xmr umw. - -Dwuwxibv tb x rdiv jdkgvktvku, oyvstqyv, xkc wdzviony ytqixil odi wxibtkh jdrrxkc-ytkv dwutdkb uaxk uav dyc hvudwu rdcnyv. -dwuwxibv nbvb x rdiv cvjyxixutgv bulyv do jdrrxkc-ytkv wxibtkh: ldn jivxuv xk tkbuxkjv do DwutdkWxibvi, wdwnyxuv tu ztua dwutdkb, -xkc wxibv uav jdrrxkc ytkv. dwuwxibv xyydzb nbvib ud bwvjtol dwutdkb tk uav jdkgvkutdkxy HKN/WDBTS blkuxs, xkc xcctutdkxyyl hvkvixuvb -nbxhv xkc avyw rvbbxhvb odi ldn. - -Unlnozsm ks o iuzm aubxmbkmbl, fpmjkhpm, obt nuqmzfep pkhzozc fuz nozskby auiiobt-pkbm unlkubs lrob lrm upt ymlunl iutepm. -unlnozsm esms o iuzm tmapozolkxm slcpm uf auiiobt-pkbm nozskby: cue azmolm ob kbslobam uf UnlkubNozsmz, nunepolm kl qklr unlkubs, -obt nozsm lrm auiiobt pkbm. unlnozsm oppuqs esmzs lu snmakfc unlkubs kb lrm aubxmblkubop YBE/NUSKJ scbloj, obt ottklkuboppc ymbmzolms -esoym obt rmpn imssoyms fuz cue. - -Lecefqjd bj f zlqd rlsodsbdsc, wgdabygd, fsk elhdqwvg gbyqfqt wlq efqjbsp rlzzfsk-gbsd lecblsj cifs cid lgk pdclec zlkvgd. -lecefqjd vjdj f zlqd kdrgfqfcbod jctgd lw rlzzfsk-gbsd efqjbsp: tlv rqdfcd fs bsjcfsrd lw LecblsEfqjdq, elevgfcd bc hbci lecblsj, -fsk efqjd cid rlzzfsk gbsd. lecefqjd fgglhj vjdqj cl jedrbwt lecblsj bs cid rlsodscblsfg PSV/ELJBA jtscfa, fsk fkkbcblsfggt pdsdqfcdj -vjfpd fsk idge zdjjfpdj wlq tlv. - -Cvtvwhau sa w qchu icjfujsujt, nxurspxu, wjb vcyuhnmx xsphwhk nch vwhasjg icqqwjb-xsju cvtscja tzwj tzu cxb gutcvt qcbmxu. -cvtvwhau maua w qchu buixwhwtsfu atkxu cn icqqwjb-xsju vwhasjg: kcm ihuwtu wj sjatwjiu cn CvtscjVwhauh, vcvmxwtu st ystz cvtscja, -wjb vwhau tzu icqqwjb xsju. cvtvwhau wxxcya mauha tc avuisnk cvtscja sj tzu icjfujtscjwx GJM/VCASR akjtwr, wjb wbbstscjwxxk gujuhwtua -mawgu wjb zuxv quaawgua nch kcm. - -Tmkmnyrl jr n htyl ztawlajlak, eolijgol, nas mtplyedo ojgynyb ety mnyrjax zthhnas-ojal tmkjtar kqna kql tos xlktmk htsdol. -tmkmnyrl drlr n htyl slzonynkjwl rkbol te zthhnas-ojal mnyrjax: btd zylnkl na jarknazl te TmkjtaMnyrly, mtmdonkl jk pjkq tmkjtar, -nas mnyrl kql zthhnas ojal. tmkmnyrl nootpr drlyr kt rmlzjeb tmkjtar ja kql ztawlakjtano XAD/MTRJI rbakni, nas nssjkjtanoob xlalynklr -drnxl nas qlom hlrrnxlr ety btd. - -Kdbdepic ai e ykpc qkrncracrb, vfczaxfc, erj dkgcpvuf faxpeps vkp depiaro qkyyerj-farc kdbakri bher bhc kfj ocbkdb ykjufc. -kdbdepic uici e ykpc jcqfepebanc ibsfc kv qkyyerj-farc depiaro: sku qpcebc er ariberqc kv KdbakrDepicp, dkdufebc ab gabh kdbakri, -erj depic bhc qkyyerj farc. kdbdepic effkgi uicpi bk idcqavs kdbakri ar bhc qkrncrbakref ORU/DKIAZ isrbez, erj ejjabakreffs ocrcpebci -uieoc erj hcfd yciieoci vkp sku. - -Busuvgzt rz v pbgt hbietirtis, mwtqrowt, via ubxtgmlw wrogvgj mbg uvgzrif hbppvia-writ busrbiz syvi syt bwa ftsbus pbalwt. -busuvgzt lztz v pbgt athwvgvsret zsjwt bm hbppvia-writ uvgzrif: jbl hgtvst vi rizsviht bm BusrbiUvgztg, ubulwvst rs xrsy busrbiz, -via uvgzt syt hbppvia writ. busuvgzt vwwbxz lztgz sb zuthrmj busrbiz ri syt hbietisrbivw FIL/UBZRQ zjisvq, via vaarsrbivwwj ftitgvstz -lzvft via ytwu ptzzvftz mbg jbl. - -Sljlmxqk iq m gsxk yszvkzikzj, dnkhifnk, mzr lsokxdcn nifxmxa dsx lmxqizw ysggmzr-nizk sljiszq jpmz jpk snr wkjslj gsrcnk. -sljlmxqk cqkq m gsxk rkynmxmjivk qjank sd ysggmzr-nizk lmxqizw: asc yxkmjk mz izqjmzyk sd SljiszLmxqkx, lslcnmjk ij oijp sljiszq, -mzr lmxqk jpk ysggmzr nizk. sljlmxqk mnnsoq cqkxq js qlkyida sljiszq iz jpk yszvkzjiszmn WZC/LSQIH qazjmh, mzr mrrijiszmnna wkzkxmjkq -cqmwk mzr pknl gkqqmwkq dsx asc. - -Jcacdohb zh d xjob pjqmbqzbqa, uebyzweb, dqi cjfboute ezwodor ujo cdohzqn pjxxdqi-ezqb jcazjqh agdq agb jei nbajca xjiteb. -jcacdohb thbh d xjob ibpedodazmb hareb ju pjxxdqi-ezqb cdohzqn: rjt pobdab dq zqhadqpb ju JcazjqCdohbo, cjctedab za fzag jcazjqh, -dqi cdohb agb pjxxdqi ezqb. jcacdohb deejfh thboh aj hcbpzur jcazjqh zq agb pjqmbqazjqde NQT/CJHZY hrqady, dqi diizazjqdeer nbqbodabh -thdnb dqi gbec xbhhdnbh ujo rjt. - -Atrtufys qy u oafs gahdshqshr, lvspqnvs, uhz tawsflkv vqnfufi laf tufyqhe gaoouhz-vqhs atrqahy rxuh rxs avz esratr oazkvs. -atrtufys kysy u oafs zsgvufurqds yrivs al gaoouhz-vqhs tufyqhe: iak gfsurs uh qhyruhgs al AtrqahTufysf, tatkvurs qr wqrx atrqahy, -uhz tufys rxs gaoouhz vqhs. atrtufys uvvawy kysfy ra ytsgqli atrqahy qh rxs gahdshrqahuv EHK/TAYQP yihrup, uhz uzzqrqahuvvi eshsfursy -kyues uhz xsvt osyyuesy laf iak. - -Rkiklwpj hp l frwj xryujyhjyi, cmjghemj, lyq krnjwcbm mhewlwz crw klwphyv xrfflyq-mhyj rkihryp ioly ioj rmq vjirki frqbmj. -rkiklwpj bpjp l frwj qjxmlwlihuj pizmj rc xrfflyq-mhyj klwphyv: zrb xwjlij ly hypilyxj rc RkihryKlwpjw, krkbmlij hi nhio rkihryp, -lyq klwpj ioj xrfflyq mhyj. rkiklwpj lmmrnp bpjwp ir pkjxhcz rkihryp hy ioj xryujyihrylm VYB/KRPHG pzyilg, lyq lqqhihrylmmz vjyjwlijp -bplvj lyq ojmk fjpplvjp crw zrb. - -Ibzbcnga yg c wina oiplapyapz, tdaxyvda, cph bieantsd dyvncnq tin bcngypm oiwwcph-dypa ibzyipg zfcp zfa idh mazibz wihsda. -ibzbcnga sgag c wina haodcnczyla gzqda it oiwwcph-dypa bcngypm: qis onacza cp ypgzcpoa it IbzyipBcngan, bibsdcza yz eyzf ibzyipg, -cph bcnga zfa oiwwcph dypa. ibzbcnga cddieg sgang zi gbaoytq ibzyipg yp zfa oiplapzyipcd MPS/BIGYX gqpzcx, cph chhyzyipcddq mapanczag -sgcma cph fadb waggcmag tin qis. - -Zsqstexr px t nzer fzgcrgprgq, kuropmur, tgy szvrekju upmeteh kze stexpgd fznntgy-upgr zsqpzgx qwtg qwr zuy drqzsq nzyjur. -zsqstexr jxrx t nzer yrfutetqpcr xqhur zk fznntgy-upgr stexpgd: hzj fertqr tg pgxqtgfr zk ZsqpzgStexre, szsjutqr pq vpqw zsqpzgx, -tgy stexr qwr fznntgy upgr. zsqstexr tuuzvx jxrex qz xsrfpkh zsqpzgx pg qwr fzgcrgqpzgtu DGJ/SZXPO xhgqto, tgy tyypqpzgtuuh drgretqrx -jxtdr tgy wrus nrxxtdrx kze hzj. - -Qjhjkvoi go k eqvi wqxtixgixh, blifgdli, kxp jqmivbal lgdvkvy bqv jkvogxu wqeekxp-lgxi qjhgqxo hnkx hni qlp uihqjh eqpali. -qjhjkvoi aoio k eqvi piwlkvkhgti ohyli qb wqeekxp-lgxi jkvogxu: yqa wvikhi kx gxohkxwi qb QjhgqxJkvoiv, jqjalkhi gh mghn qjhgqxo, -kxp jkvoi hni wqeekxp lgxi. qjhjkvoi kllqmo aoivo hq ojiwgby qjhgqxo gx hni wqxtixhgqxkl UXA/JQOGF oyxhkf, kxp kppghgqxklly uixivkhio -aokui kxp nilj eiookuio bqv yqa. - -Zaealcdp td l xzcp nzygpytpye, qwpitmwp, lyo azhpcqfw wtmclcj qzc alcdtyr nzxxlyo-wtyp zaetzyd esly esp zwo rpezae xzofwp. -zaealcdp fdpd l xzcp opnwlcletgp dejwp zq nzxxlyo-wtyp alcdtyr: jzf ncplep ly tydelynp zq ZaetzyAlcdpc, azafwlep te htes zaetzyd, -lyo alcdp esp nzxxlyo wtyp. zaealcdp lwwzhd fdpcd ez dapntqj zaetzyd ty esp nzygpyetzylw RYF/AZDTI djyeli, lyo lootetzylwwj rpypclepd -fdlrp lyo spwa xpddlrpd qzc jzf. - -Efjfqhiu yi q cehu sedludyudj, vbunyrbu, qdt femuhvkb byrhqho veh fqhiydw seccqdt-bydu efjyedi jxqd jxu ebt wujefj cetkbu. -efjfqhiu kiui q cehu tusbqhqjylu ijobu ev seccqdt-bydu fqhiydw: oek shuqju qd ydijqdsu ev EfjyedFqhiuh, fefkbqju yj myjx efjyedi, -qdt fqhiu jxu seccqdt bydu. efjfqhiu qbbemi kiuhi je ifusyvo efjyedi yd jxu sedludjyedqb WDK/FEIYN iodjqn, qdt qttyjyedqbbo wuduhqjui -kiqwu qdt xubf cuiiqwui veh oek. - -Jkokvmnz dn v hjmz xjiqzidzio, agzsdwgz, viy kjrzmapg gdwmvmt ajm kvmndib xjhhviy-gdiz jkodjin ocvi ocz jgy bzojko hjypgz. -jkokvmnz pnzn v hjmz yzxgvmvodqz notgz ja xjhhviy-gdiz kvmndib: tjp xmzvoz vi dinovixz ja JkodjiKvmnzm, kjkpgvoz do rdoc jkodjin, -viy kvmnz ocz xjhhviy gdiz. jkokvmnz vggjrn pnzmn oj nkzxdat jkodjin di ocz xjiqziodjivg BIP/KJNDS ntiovs, viy vyydodjivggt bzizmvozn -pnvbz viy czgk hznnvbzn ajm tjp. - Optparse is a more convenient, flexible, and powerful library for parsing command-line options than the old getopt module. optparse uses a more declarative style of command-line parsing: you create an instance of OptionParser, populate it with options, and parse the command line. optparse allows users to specify options in the conventional GNU/POSIX syntax, and additionally generates usage and help messages for you. - -Tuyufwxj nx f rtwj htsajsnjsy, kqjcngqj, fsi utbjwkzq qngwfwd ktw ufwxnsl htrrfsi-qnsj tuyntsx ymfs ymj tqi ljytuy rtizqj. -tuyufwxj zxjx f rtwj ijhqfwfynaj xydqj tk htrrfsi-qnsj ufwxnsl: dtz hwjfyj fs nsxyfshj tk TuyntsUfwxjw, utuzqfyj ny bnym tuyntsx, -fsi ufwxj ymj htrrfsi qnsj. tuyufwxj fqqtbx zxjwx yt xujhnkd tuyntsx ns ymj htsajsyntsfq LSZ/UTXNC xdsyfc, fsi fiinyntsfqqd ljsjwfyjx -zxflj fsi mjqu rjxxfljx ktw dtz. - -Yzdzkbco sc k wybo myxfoxsoxd, pvohslvo, kxn zygobpev vslbkbi pyb zkbcsxq mywwkxn-vsxo yzdsyxc drkx dro yvn qodyzd wynevo. -yzdzkbco ecoc k wybo nomvkbkdsfo cdivo yp mywwkxn-vsxo zkbcsxq: iye mbokdo kx sxcdkxmo yp YzdsyxZkbcob, zyzevkdo sd gsdr yzdsyxc, -kxn zkbco dro mywwkxn vsxo. yzdzkbco kvvygc ecobc dy czomspi yzdsyxc sx dro myxfoxdsyxkv QXE/ZYCSH cixdkh, kxn knnsdsyxkvvi qoxobkdoc -eckqo kxn rovz wocckqoc pyb iye. - -Deiepght xh p bdgt rdcktcxtci, uatmxqat, pcs edltguja axqgpgn udg epghxcv rdbbpcs-axct deixdch iwpc iwt das vtidei bdsjat. -deiepght jhth p bdgt strapgpixkt hinat du rdbbpcs-axct epghxcv: ndj rgtpit pc xchipcrt du DeixdcEpghtg, edejapit xi lxiw deixdch, -pcs epght iwt rdbbpcs axct. deiepght paadlh jhtgh id hetrxun deixdch xc iwt rdcktcixdcpa VCJ/EDHXM hncipm, pcs pssxixdcpaan vtctgpith -jhpvt pcs wtae bthhpvth udg ndj. - -Ijnjulmy cm u gily wihpyhcyhn, zfyrcvfy, uhx jiqylzof fcvluls zil julmcha wigguhx-fchy ijncihm nbuh nby ifx aynijn gixofy. -ijnjulmy omym u gily xywfuluncpy mnsfy iz wigguhx-fchy julmcha: sio wlyuny uh chmnuhwy iz IjncihJulmyl, jijofuny cn qcnb ijncihm, -uhx julmy nby wigguhx fchy. ijnjulmy uffiqm omylm ni mjywczs ijncihm ch nby wihpyhncihuf AHO/JIMCR mshnur, uhx uxxcncihuffs ayhylunym -omuay uhx byfj gymmuaym zil sio. - -Nosozqrd hr z lnqd bnmudmhdms, ekdwhakd, zmc onvdqetk khaqzqx enq ozqrhmf bnllzmc-khmd noshnmr sgzm sgd nkc fdsnos lnctkd. -nosozqrd trdr z lnqd cdbkzqzshud rsxkd ne bnllzmc-khmd ozqrhmf: xnt bqdzsd zm hmrszmbd ne NoshnmOzqrdq, onotkzsd hs vhsg noshnmr, -zmc ozqrd sgd bnllzmc khmd. nosozqrd zkknvr trdqr sn rodbhex noshnmr hm sgd bnmudmshnmzk FMT/ONRHW rxmszw, zmc zcchshnmzkkx fdmdqzsdr -trzfd zmc gdko ldrrzfdr enq xnt. - -Stxtevwi mw e qsvi gsrzirmirx, jpibmfpi, erh tsaivjyp pmfvevc jsv tevwmrk gsqqerh-pmri stxmsrw xler xli sph kixstx qshypi. -stxtevwi ywiw e qsvi higpevexmzi wxcpi sj gsqqerh-pmri tevwmrk: csy gviexi er mrwxergi sj StxmsrTevwiv, tstypexi mx amxl stxmsrw, -erh tevwi xli gsqqerh pmri. stxtevwi eppsaw ywivw xs wtigmjc stxmsrw mr xli gsrzirxmsrep KRY/TSWMB wcrxeb, erh ehhmxmsreppc kirivexiw -yweki erh lipt qiwwekiw jsv csy. - -Xycyjabn rb j vxan lxwenwrnwc, oungrkun, jwm yxfnaodu urkajah oxa yjabrwp lxvvjwm-urwn xycrxwb cqjw cqn xum pncxyc vxmdun. -xycyjabn dbnb j vxan mnlujajcren bchun xo lxvvjwm-urwn yjabrwp: hxd lanjcn jw rwbcjwln xo XycrxwYjabna, yxydujcn rc frcq xycrxwb, -jwm yjabn cqn lxvvjwm urwn. xycyjabn juuxfb dbnab cx bynlroh xycrxwb rw cqn lxwenwcrxwju PWD/YXBRG bhwcjg, jwm jmmrcrxwjuuh pnwnajcnb -dbjpn jwm qnuy vnbbjpnb oxa hxd. - -Cdhdofgs wg o acfs qcbjsbwsbh, tzslwpzs, obr dcksftiz zwpfofm tcf dofgwbu qcaaobr-zwbs cdhwcbg hvob hvs czr ushcdh acrizs. -cdhdofgs igsg o acfs rsqzofohwjs ghmzs ct qcaaobr-zwbs dofgwbu: mci qfsohs ob wbghobqs ct CdhwcbDofgsf, dcdizohs wh kwhv cdhwcbg, -obr dofgs hvs qcaaobr zwbs. cdhdofgs ozzckg igsfg hc gdsqwtm cdhwcbg wb hvs qcbjsbhwcboz UBI/DCGWL gmbhol, obr orrwhwcbozzm usbsfohsg -igous obr vszd asggousg tcf mci. - -Himitklx bl t fhkx vhgoxgbxgm, yexqbuex, tgw ihpxkyne ebuktkr yhk itklbgz vhfftgw-ebgx himbhgl matg max hew zxmhim fhwnex. -himitklx nlxl t fhkx wxvetktmbox lmrex hy vhfftgw-ebgx itklbgz: rhn vkxtmx tg bglmtgvx hy HimbhgItklxk, ihinetmx bm pbma himbhgl, -tgw itklx max vhfftgw ebgx. himitklx teehpl nlxkl mh lixvbyr himbhgl bg max vhgoxgmbhgte ZGN/IHLBQ lrgmtq, tgw twwbmbhgteer zxgxktmxl -nltzx tgw axei fxlltzxl yhk rhn. - -Mnrnypqc gq y kmpc amltclgclr, djcvgzjc, ylb nmucpdsj jgzpypw dmp nypqgle amkkylb-jglc mnrgmlq rfyl rfc mjb ecrmnr kmbsjc. -mnrnypqc sqcq y kmpc bcajypyrgtc qrwjc md amkkylb-jglc nypqgle: wms apcyrc yl glqrylac md MnrgmlNypqcp, nmnsjyrc gr ugrf mnrgmlq, -ylb nypqc rfc amkkylb jglc. mnrnypqc yjjmuq sqcpq rm qncagdw mnrgmlq gl rfc amltclrgmlyj ELS/NMQGV qwlryv, ylb ybbgrgmlyjjw eclcpyrcq -sqyec ylb fcjn kcqqyecq dmp wms. - -Rswsduvh lv d pruh frqyhqlhqw, iohaleoh, dqg srzhuixo oleudub iru sduvlqj frppdqg-olqh rswlrqv wkdq wkh rog jhwrsw prgxoh. -rswsduvh xvhv d pruh ghfodudwlyh vwboh ri frppdqg-olqh sduvlqj: brx fuhdwh dq lqvwdqfh ri RswlrqSduvhu, srsxodwh lw zlwk rswlrqv, -dqg sduvh wkh frppdqg olqh. rswsduvh doorzv xvhuv wr vshflib rswlrqv lq wkh frqyhqwlrqdo JQX/SRVLA vbqwda, dqg dgglwlrqdoob jhqhudwhv -xvdjh dqg khos phvvdjhv iru brx. - -Wxbxizam qa i uwzm kwvdmvqmvb, ntmfqjtm, ivl xwemznct tqjzizg nwz xizaqvo kwuuivl-tqvm wxbqwva bpiv bpm wtl ombwxb uwlctm. -wxbxizam cama i uwzm lmktizibqdm abgtm wn kwuuivl-tqvm xizaqvo: gwc kzmibm iv qvabivkm wn WxbqwvXizamz, xwxctibm qb eqbp wxbqwva, -ivl xizam bpm kwuuivl tqvm. wxbxizam ittwea camza bw axmkqng wxbqwva qv bpm kwvdmvbqwvit OVC/XWAQF agvbif, ivl illqbqwvittg omvmzibma -caiom ivl pmtx umaaioma nwz gwc. - -Bcgcnefr vf n zber pbairavrag, syrkvoyr, naq cbjreshy yvoenel sbe cnefvat pbzznaq-yvar bcgvbaf guna gur byq trgbcg zbqhyr. -bcgcnefr hfrf n zber qrpynengvir fglyr bs pbzznaq-yvar cnefvat: lbh perngr na vafgnapr bs BcgvbaCnefre, cbchyngr vg jvgu bcgvbaf, -naq cnefr gur pbzznaq yvar. bcgcnefr nyybjf hfref gb fcrpvsl bcgvbaf va gur pbairagvbany TAH/CBFVK flagnk, naq nqqvgvbanyyl trarengrf -hfntr naq uryc zrffntrf sbe lbh. - -Ghlhsjkw ak s egjw ugfnwfawfl, xdwpatdw, sfv hgowjxmd datjsjq xgj hsjkafy ugeesfv-dafw ghlagfk lzsf lzw gdv ywlghl egvmdw. -ghlhsjkw mkwk s egjw vwudsjslanw klqdw gx ugeesfv-dafw hsjkafy: qgm ujwslw sf afklsfuw gx GhlagfHsjkwj, hghmdslw al oalz ghlagfk, -sfv hsjkw lzw ugeesfv dafw. ghlhsjkw sddgok mkwjk lg khwuaxq ghlagfk af lzw ugfnwflagfsd YFM/HGKAP kqflsp, sfv svvalagfsddq ywfwjslwk -mksyw sfv zwdh ewkksywk xgj qgm. - -Lmqmxopb fp x jlob zlksbkfbkq, cibufyib, xka mltbocri ifyoxov clo mxopfkd zljjxka-ifkb lmqflkp qexk qeb lia dbqlmq jlarib. -lmqmxopb rpbp x jlob abzixoxqfsb pqvib lc zljjxka-ifkb mxopfkd: vlr zobxqb xk fkpqxkzb lc LmqflkMxopbo, mlmrixqb fq tfqe lmqflkp, -xka mxopb qeb zljjxka ifkb. lmqmxopb xiiltp rpbop ql pmbzfcv lmqflkp fk qeb zlksbkqflkxi DKR/MLPFU pvkqxu, xka xaafqflkxiiv dbkboxqbp -rpxdb xka ebim jbppxdbp clo vlr. - -Qrvrctug ku c oqtg eqpxgpkgpv, hngzkdng, cpf rqygthwn nkdtcta hqt rctukpi eqoocpf-nkpg qrvkqpu vjcp vjg qnf igvqrv oqfwng. -qrvrctug wugu c oqtg fgenctcvkxg uvang qh eqoocpf-nkpg rctukpi: aqw etgcvg cp kpuvcpeg qh QrvkqpRctugt, rqrwncvg kv ykvj qrvkqpu, -cpf rctug vjg eqoocpf nkpg. qrvrctug cnnqyu wugtu vq urgekha qrvkqpu kp vjg eqpxgpvkqpcn IPW/RQUKZ uapvcz, cpf cffkvkqpcnna igpgtcvgu -wucig cpf jgnr oguucigu hqt aqw. - -Vwawhyzl pz h tvyl jvucluplua, mslepisl, huk wvdlymbs spiyhyf mvy whyzpun jvtthuk-spul vwapvuz aohu aol vsk nlavwa tvkbsl. -vwawhyzl bzlz h tvyl kljshyhapcl zafsl vm jvtthuk-spul whyzpun: fvb jylhal hu puzahujl vm VwapvuWhyzly, wvwbshal pa dpao vwapvuz, -huk whyzl aol jvtthuk spul. vwawhyzl hssvdz bzlyz av zwljpmf vwapvuz pu aol jvucluapvuhs NUB/WVZPE zfuahe, huk hkkpapvuhssf nlulyhalz -bzhnl huk olsw tlzzhnlz mvy fvb. - -Abfbmdeq ue m yadq oazhqzuqzf, rxqjunxq, mzp baiqdrgx xundmdk rad bmdeuzs oayymzp-xuzq abfuaze ftmz ftq axp sqfabf yapgxq. -abfbmdeq geqe m yadq pqoxmdmfuhq efkxq ar oayymzp-xuzq bmdeuzs: kag odqmfq mz uzefmzoq ar AbfuazBmdeqd, babgxmfq uf iuft abfuaze, -mzp bmdeq ftq oayymzp xuzq. abfbmdeq mxxaie geqde fa ebqourk abfuaze uz ftq oazhqzfuazmx SZG/BAEUJ ekzfmj, mzp mppufuazmxxk sqzqdmfqe -gemsq mzp tqxb yqeemsqe rad kag. - -Fgkgrijv zj r dfiv tfemvezvek, wcvozscv, reu gfnviwlc czsirip wfi grijzex tfddreu-czev fgkzfej kyre kyv fcu xvkfgk dfulcv. -fgkgrijv ljvj r dfiv uvtcrirkzmv jkpcv fw tfddreu-czev grijzex: pfl tivrkv re zejkretv fw FgkzfeGrijvi, gfglcrkv zk nzky fgkzfej, -reu grijv kyv tfddreu czev. fgkgrijv rccfnj ljvij kf jgvtzwp fgkzfej ze kyv tfemvekzferc XEL/GFJZO jpekro, reu ruuzkzferccp xvevirkvj -ljrxv reu yvcg dvjjrxvj wfi pfl. - -Klplwnoa eo w ikna ykjrajeajp, bhatexha, wjz lksanbqh hexnwnu bkn lwnoejc ykiiwjz-heja klpekjo pdwj pda khz capklp ikzqha. -klplwnoa qoao w ikna zayhwnwpera opuha kb ykiiwjz-heja lwnoejc: ukq ynawpa wj ejopwjya kb KlpekjLwnoan, lklqhwpa ep sepd klpekjo, -wjz lwnoa pda ykiiwjz heja. klplwnoa whhkso qoano pk olayebu klpekjo ej pda ykjrajpekjwh CJQ/LKOET oujpwt, wjz wzzepekjwhhu cajanwpao -qowca wjz dahl iaoowcao bkn ukq. - -Pquqbstf jt b npsf dpowfojfou, gmfyjcmf, boe qpxfsgvm mjcsbsz gps qbstjoh dpnnboe-mjof pqujpot uibo uif pme hfupqu npevmf. -pquqbstf vtft b npsf efdmbsbujwf tuzmf pg dpnnboe-mjof qbstjoh: zpv dsfbuf bo jotubodf pg PqujpoQbstfs, qpqvmbuf ju xjui pqujpot, -boe qbstf uif dpnnboe mjof. pquqbstf bmmpxt vtfst up tqfdjgz pqujpot jo uif dpowfoujpobm HOV/QPTJY tzouby, boe beejujpobmmz hfofsbuft -vtbhf boe ifmq nfttbhft gps zpv. - -Uvzvgxyk oy g suxk iutbktoktz, lrkdohrk, gtj vuckxlar rohxgxe lux vgxyotm iussgtj-rotk uvzouty zngt znk urj mkzuvz sujark. -uvzvgxyk ayky g suxk jkirgxgzobk yzerk ul iussgtj-rotk vgxyotm: eua ixkgzk gt otyzgtik ul UvzoutVgxykx, vuvargzk oz cozn uvzouty, -gtj vgxyk znk iussgtj rotk. uvzvgxyk grrucy aykxy zu yvkiole uvzouty ot znk iutbktzoutgr MTA/VUYOD yetzgd, gtj gjjozoutgrre mktkxgzky -aygmk gtj nkrv skyygmky lux eua. - -Daoaturh vr t jduh ndgihgvhgo, emhcvqmh, tgk adfhuelm mvqutuz edu aturvgb ndjjtgk-mvgh daovdgr oytg oyh dmk bhodao jdklmh. -daoaturh lrhr t jduh khnmtutovih rozmh de ndjjtgk-mvgh aturvgb: zdl nuhtoh tg vgrotgnh de DaovdgAturhu, adalmtoh vo fvoy daovdgr, -tgk aturh oyh ndjjtgk mvgh. daoaturh tmmdfr lrhur od rahnvez daovdgr vg oyh ndgihgovdgtm BGL/ADRVC rzgotc, tgk tkkvovdgtmmz bhghutohr -lrtbh tgk yhma jhrrtbhr edu zdl. - -Olzlefcs gc e uofs yortsrgsrz, pxsngbxs, erv loqsfpwx xgbfefk pof lefcgrm youuerv-xgrs olzgorc zjer zjs oxv mszolz uovwxs. -olzlefcs wcsc e uofs vsyxefezgts czkxs op youuerv-xgrs lefcgrm: kow yfsezs er grczerys op OlzgorLefcsf, lolwxezs gz qgzj olzgorc, -erv lefcs zjs youuerv xgrs. olzlefcs exxoqc wcsfc zo clsygpk olzgorc gr zjs yortsrzgorex MRW/LOCGN ckrzen, erv evvgzgorexxk msrsfezsc -wcems erv jsxl usccemsc pof kow. - -Zwkwpqnd rn p fzqd jzcedcrdck, aidyrmid, pcg wzbdqahi irmqpqv azq wpqnrcx jzffpcg-ircd zwkrzcn kupc kud zig xdkzwk fzghid. -zwkwpqnd hndn p fzqd gdjipqpkred nkvid za jzffpcg-ircd wpqnrcx: vzh jqdpkd pc rcnkpcjd za ZwkrzcWpqndq, wzwhipkd rk brku zwkrzcn, -pcg wpqnd kud jzffpcg ircd. zwkwpqnd piizbn hndqn kz nwdjrav zwkrzcn rc kud jzcedckrzcpi XCH/WZNRY nvckpy, pcg pggrkrzcpiiv xdcdqpkdn -hnpxd pcg udiw fdnnpxdn azq vzh. - -Khvhabyo cy a qkbo uknponconv, ltojcxto, anr hkmoblst tcxbabg lkb habycni ukqqanr-tcno khvckny vfan vfo ktr iovkhv qkrsto. -khvhabyo syoy a qkbo routabavcpo yvgto kl ukqqanr-tcno habycni: gks uboavo an cnyvanuo kl KhvcknHabyob, hkhstavo cv mcvf khvckny, -anr habyo vfo ukqqanr tcno. khvhabyo attkmy syoby vk yhouclg khvckny cn vfo uknponvcknat INS/HKYCJ ygnvaj, anr arrcvcknattg ionobavoy -syaio anr foth qoyyaioy lkb gks. - -Vsgslmjz nj l bvmz fvyazynzyg, wezuniez, lyc svxzmwde enimlmr wvm slmjnyt fvbblyc-enyz vsgnvyj gqly gqz vec tzgvsg bvcdez. -vsgslmjz djzj l bvmz czfelmlgnaz jgrez vw fvbblyc-enyz slmjnyt: rvd fmzlgz ly nyjglyfz vw VsgnvySlmjzm, svsdelgz ng xngq vsgnvyj, -lyc slmjz gqz fvbblyc enyz. vsgslmjz leevxj djzmj gv jszfnwr vsgnvyj ny gqz fvyazygnvyle TYD/SVJNU jryglu, lyc lccngnvyleer tzyzmlgzj -djltz lyc qzes bzjjltzj wvm rvd. - -Gdrdwxuk yu w mgxk qgjlkjykjr, hpkfytpk, wjn dgikxhop pytxwxc hgx dwxuyje qgmmwjn-pyjk gdrygju rbwj rbk gpn ekrgdr mgnopk. -gdrdwxuk ouku w mgxk nkqpwxwrylk urcpk gh qgmmwjn-pyjk dwxuyje: cgo qxkwrk wj yjurwjqk gh GdrygjDwxukx, dgdopwrk yr iyrb gdrygju, -wjn dwxuk rbk qgmmwjn pyjk. gdrdwxuk wppgiu oukxu rg udkqyhc gdrygju yj rbk qgjlkjrygjwp EJO/DGUYF ucjrwf, wjn wnnyrygjwppc ekjkxwrku -ouwek wjn bkpd mkuuweku hgx cgo. - -Rocohifv jf h xriv bruwvujvuc, savqjeav, huy ortvisza ajeihin sri ohifjup brxxhuy-ajuv rocjruf cmhu cmv ray pvcroc xryzav. -rocohifv zfvf h xriv yvbahihcjwv fcnav rs brxxhuy-ajuv ohifjup: nrz bivhcv hu jufchubv rs RocjruOhifvi, orozahcv jc tjcm rocjruf, -huy ohifv cmv brxxhuy ajuv. rocohifv haartf zfvif cr fovbjsn rocjruf ju cmv bruwvucjruha PUZ/ORFJQ fnuchq, huy hyyjcjruhaan pvuvihcvf -zfhpv huy mvao xvffhpvf sri nrz. - -Cznzstqg uq s ictg mcfhgfugfn, dlgbuplg, sfj zcegtdkl luptsty dct zstqufa mciisfj-lufg cznucfq nxsf nxg clj agnczn icjklg. -cznzstqg kqgq s ictg jgmlstsnuhg qnylg cd mciisfj-lufg zstqufa: yck mtgsng sf ufqnsfmg cd CznucfZstqgt, zczklsng un eunx cznucfq, -sfj zstqg nxg mciisfj lufg. cznzstqg sllceq kqgtq nc qzgmudy cznucfq uf nxg mcfhgfnucfsl AFK/ZCQUB qyfnsb, sfj sjjunucfslly agfgtsngq -kqsag sfj xglz igqqsagq dct yck. - -Nkykdebr fb d tner xnqsrqfrqy, owrmfawr, dqu knpreovw wfaedej one kdebfql xnttdqu-wfqr nkyfnqb yidq yir nwu lrynky tnuvwr. -nkykdebr vbrb d tner urxwdedyfsr byjwr no xnttdqu-wfqr kdebfql: jnv xerdyr dq fqbydqxr no NkyfnqKdebre, knkvwdyr fy pfyi nkyfnqb, -dqu kdebr yir xnttdqu wfqr. nkykdebr dwwnpb vbreb yn bkrxfoj nkyfnqb fq yir xnqsrqyfnqdw LQV/KNBFM bjqydm, dqu duufyfnqdwwj lrqredyrb -vbdlr dqu irwk trbbdlrb one jnv. - -Yvjvopmc qm o eypc iybdcbqcbj, zhcxqlhc, obf vyacpzgh hqlpopu zyp vopmqbw iyeeobf-hqbc yvjqybm jtob jtc yhf wcjyvj eyfghc. -yvjvopmc gmcm o eypc fcihopojqdc mjuhc yz iyeeobf-hqbc vopmqbw: uyg ipcojc ob qbmjobic yz YvjqybVopmcp, vyvghojc qj aqjt yvjqybm, -obf vopmc jtc iyeeobf hqbc. yvjvopmc ohhyam gmcpm jy mvciqzu yvjqybm qb jtc iybdcbjqyboh WBG/VYMQX mubjox, obf offqjqybohhu wcbcpojcm -gmowc obf tchv ecmmowcm zyp uyg. - -Jgugzaxn bx z pjan tjmonmbnmu, ksnibwsn, zmq gjlnakrs sbwazaf kja gzaxbmh tjppzmq-sbmn jgubjmx uezm uen jsq hnujgu pjqrsn. -jgugzaxn rxnx z pjan qntszazubon xufsn jk tjppzmq-sbmn gzaxbmh: fjr tanzun zm bmxuzmtn jk JgubjmGzaxna, gjgrszun bu lbue jgubjmx, -zmq gzaxn uen tjppzmq sbmn. jgugzaxn zssjlx rxnax uj xgntbkf jgubjmx bm uen tjmonmubjmzs HMR/GJXBI xfmuzi, zmq zqqbubjmzssf hnmnazunx -rxzhn zmq ensg pnxxzhnx kja fjr. - -Urfrkliy mi k auly euxzyxmyxf, vdytmhdy, kxb ruwylvcd dmhlklq vul rklimxs euaakxb-dmxy urfmuxi fpkx fpy udb syfurf aubcdy. -urfrkliy ciyi k auly byedklkfmzy ifqdy uv euaakxb-dmxy rklimxs: quc elykfy kx mxifkxey uv UrfmuxRkliyl, rurcdkfy mf wmfp urfmuxi, -kxb rkliy fpy euaakxb dmxy. urfrkliy kdduwi ciyli fu iryemvq urfmuxi mx fpy euxzyxfmuxkd SXC/RUIMT iqxfkt, kxb kbbmfmuxkddq syxylkfyi -ciksy kxb pydr ayiiksyi vul quc. - -Fcqcvwtj xt v lfwj pfikjixjiq, gojexsoj, vim cfhjwgno oxswvwb gfw cvwtxid pfllvim-oxij fcqxfit qavi qaj fom djqfcq lfmnoj. -fcqcvwtj ntjt v lfwj mjpovwvqxkj tqboj fg pfllvim-oxij cvwtxid: bfn pwjvqj vi xitqvipj fg FcqxfiCvwtjw, cfcnovqj xq hxqa fcqxfit, -vim cvwtj qaj pfllvim oxij. fcqcvwtj voofht ntjwt qf tcjpxgb fcqxfit xi qaj pfikjiqxfivo DIN/CFTXE tbiqve, vim vmmxqxfivoob djijwvqjt -ntvdj vim ajoc ljttvdjt gfw bfn. - -Qnbngheu ie g wqhu aqtvutiutb, rzupidzu, gtx nqsuhryz zidhghm rqh ngheito aqwwgtx-zitu qnbiqte blgt blu qzx oubqnb wqxyzu. -qnbngheu yeue g wqhu xuazghgbivu ebmzu qr aqwwgtx-zitu ngheito: mqy ahugbu gt itebgtau qr QnbiqtNgheuh, nqnyzgbu ib sibl qnbiqte, -gtx ngheu blu aqwwgtx zitu. qnbngheu gzzqse yeuhe bq enuairm qnbiqte it blu aqtvutbiqtgz OTY/NQEIP emtbgp, gtx gxxibiqtgzzm outuhgbue -yegou gtx luzn wueegoue rqh mqy. - -Bymyrspf tp r hbsf lbegfetfem, ckfatokf, rei ybdfscjk ktosrsx cbs yrsptez lbhhrei-ktef bymtbep mwre mwf bki zfmbym hbijkf. -bymyrspf jpfp r hbsf iflkrsrmtgf pmxkf bc lbhhrei-ktef yrsptez: xbj lsfrmf re tepmrelf bc BymtbeYrspfs, ybyjkrmf tm dtmw bymtbep, -rei yrspf mwf lbhhrei ktef. bymyrspf rkkbdp jpfsp mb pyfltcx bymtbep te mwf lbegfemtberk ZEJ/YBPTA pxemra, rei riitmtberkkx zfefsrmfp -jprzf rei wfky hfpprzfp cbs xbj. - -Mjxjcdaq ea c smdq wmprqpeqpx, nvqlezvq, cpt jmoqdnuv vezdcdi nmd jcdaepk wmsscpt-vepq mjxempa xhcp xhq mvt kqxmjx smtuvq. -mjxjcdaq uaqa c smdq tqwvcdcxerq axivq mn wmsscpt-vepq jcdaepk: imu wdqcxq cp epaxcpwq mn MjxempJcdaqd, jmjuvcxq ex oexh mjxempa, -cpt jcdaq xhq wmsscpt vepq. mjxjcdaq cvvmoa uaqda xm ajqweni mjxempa ep xhq wmprqpxempcv KPU/JMAEL aipxcl, cpt cttexempcvvi kqpqdcxqa -uackq cpt hqvj sqaackqa nmd imu. - -Xuiunolb pl n dxob hxacbapbai, ygbwpkgb, nae uxzboyfg gpkonot yxo unolpav hxddnae-gpab xuipxal isna isb xge vbixui dxefgb. -xuiunolb flbl n dxob ebhgnonipcb litgb xy hxddnae-gpab unolpav: txf hobnib na palinahb xy XuipxaUnolbo, uxufgnib pi zpis xuipxal, -nae unolb isb hxddnae gpab. xuiunolb nggxzl flbol ix lubhpyt xuipxal pa isb hxacbaipxang VAF/UXLPW ltainw, nae neepipxanggt vbabonibl -flnvb nae sbgu dbllnvbl yxo txf. - -Iftfyzwm aw y oizm silnmlamlt, jrmhavrm, ylp fikmzjqr ravzyze jiz fyzwalg siooylp-ralm iftailw tdyl tdm irp gmtift oipqrm. -iftfyzwm qwmw y oizm pmsryzytanm wterm ij siooylp-ralm fyzwalg: eiq szmytm yl alwtylsm ij IftailFyzwmz, fifqrytm at katd iftailw, -ylp fyzwm tdm siooylp ralm. iftfyzwm yrrikw qwmzw ti wfmsaje iftailw al tdm silnmltailyr GLQ/FIWAH weltyh, ylp yppatailyrre gmlmzytmw -qwygm ylp dmrf omwwygmw jiz eiq. - -Tqeqjkhx lh j ztkx dtwyxwlxwe, ucxslgcx, jwa qtvxkubc clgkjkp utk qjkhlwr dtzzjwa-clwx tqeltwh eojw eox tca rxetqe ztabcx. -tqeqjkhx bhxh j ztkx axdcjkjelyx hepcx tu dtzzjwa-clwx qjkhlwr: ptb dkxjex jw lwhejwdx tu TqeltwQjkhxk, qtqbcjex le vleo tqeltwh, -jwa qjkhx eox dtzzjwa clwx. tqeqjkhx jcctvh bhxkh et hqxdlup tqeltwh lw eox dtwyxweltwjc RWB/QTHLS hpwejs, jwa jaaleltwjccp rxwxkjexh -bhjrx jwa oxcq zxhhjrxh utk ptb. - -Ebpbuvsi ws u kevi oehjihwihp, fnidwrni, uhl begivfmn nwrvuva fev buvswhc oekkuhl-nwhi ebpwehs pzuh pzi enl cipebp kelmni. -ebpbuvsi msis u kevi lionuvupwji spani ef oekkuhl-nwhi buvswhc: aem oviupi uh whspuhoi ef EbpwehBuvsiv, bebmnupi wp gwpz ebpwehs, -uhl buvsi pzi oekkuhl nwhi. ebpbuvsi unnegs msivs pe sbiowfa ebpwehs wh pzi oehjihpwehun CHM/BESWD sahpud, uhl ullwpwehunna cihivupis -msuci uhl zinb kissucis fev aem. - -Pmamfgdt hd f vpgt zpsutshtsa, qytohcyt, fsw mprtgqxy yhcgfgl qpg mfgdhsn zpvvfsw-yhst pmahpsd akfs akt pyw ntapma vpwxyt. -pmamfgdt xdtd f vpgt wtzyfgfahut dalyt pq zpvvfsw-yhst mfgdhsn: lpx zgtfat fs hsdafszt pq PmahpsMfgdtg, mpmxyfat ha rhak pmahpsd, -fsw mfgdt akt zpvvfsw yhst. pmamfgdt fyyprd xdtgd ap dmtzhql pmahpsd hs akt zpsutsahpsfy NSX/MPDHO dlsafo, fsw fwwhahpsfyyl ntstgfatd -xdfnt fsw ktym vtddfntd qpg lpx. - -Axlxqroe so q gare kadfedsedl, bjezsnje, qdh xacerbij jsnrqrw bar xqrosdy kaggqdh-jsde axlsado lvqd lve ajh yelaxl gahije. -axlxqroe ioeo q gare hekjqrqlsfe olwje ab kaggqdh-jsde xqrosdy: wai kreqle qd sdolqdke ab AxlsadXqroer, xaxijqle sl cslv axlsado, -qdh xqroe lve kaggqdh jsde. axlxqroe qjjaco ioero la oxeksbw axlsado sd lve kadfedlsadqj YDI/XAOSZ owdlqz, qdh qhhslsadqjjw yederqleo -ioqye qdh vejx geooqyeo bar wai. - -Liwibczp dz b rlcp vloqpodpow, mupkdyup, bos ilnpcmtu udycbch mlc ibczdoj vlrrbos-udop liwdloz wgbo wgp lus jpwliw rlstup. -liwibczp tzpz b rlcp spvubcbwdqp zwhup lm vlrrbos-udop ibczdoj: hlt vcpbwp bo dozwbovp lm LiwdloIbczpc, ilitubwp dw ndwg liwdloz, -bos ibczp wgp vlrrbos udop. liwibczp buulnz tzpcz wl zipvdmh liwdloz do wgp vloqpowdlobu JOT/ILZDK zhowbk, bos bssdwdlobuuh jpopcbwpz -tzbjp bos gpui rpzzbjpz mlc hlt. - -Wthtmnka ok m cwna gwzbazoazh, xfavojfa, mzd twyanxef fojnmns xwn tmnkozu gwccmzd-foza wthowzk hrmz hra wfd uahwth cwdefa. -wthtmnka ekak m cwna dagfmnmhoba khsfa wx gwccmzd-foza tmnkozu: swe gnamha mz ozkhmzga wx WthowzTmnkan, twtefmha oh yohr wthowzk, -mzd tmnka hra gwccmzd foza. wthtmnka mffwyk ekank hw ktagoxs wthowzk oz hra gwzbazhowzmf UZE/TWKOV kszhmv, mzd mddohowzmffs uazanmhak -ekmua mzd raft cakkmuak xwn swe. - -Hesexyvl zv x nhyl rhkmlkzlks, iqlgzuql, xko ehjlyipq qzuyxyd ihy exyvzkf rhnnxko-qzkl heszhkv scxk scl hqo flshes nhopql. -hesexyvl pvlv x nhyl olrqxyxszml vsdql hi rhnnxko-qzkl exyvzkf: dhp rylxsl xk zkvsxkrl hi HeszhkExyvly, ehepqxsl zs jzsc heszhkv, -xko exyvl scl rhnnxko qzkl. hesexyvl xqqhjv pvlyv sh velrzid heszhkv zk scl rhkmlkszhkxq FKP/EHVZG vdksxg, xko xoozszhkxqqd flklyxslv -pvxfl xko clqe nlvvxflv ihy dhp. - -Spdpijgw kg i ysjw csvxwvkwvd, tbwrkfbw, ivz psuwjtab bkfjijo tsj pijgkvq csyyivz-bkvw spdksvg dniv dnw sbz qwdspd yszabw. -spdpijgw agwg i ysjw zwcbijidkxw gdobw st csyyivz-bkvw pijgkvq: osa cjwidw iv kvgdivcw st SpdksvPijgwj, pspabidw kd ukdn spdksvg, -ivz pijgw dnw csyyivz bkvw. spdpijgw ibbsug agwjg ds gpwckto spdksvg kv dnw csvxwvdksvib QVA/PSGKR govdir, ivz izzkdksvibbo qwvwjidwg -agiqw ivz nwbp ywggiqwg tsj osa. - -Laiajetr zt j hler nlwmrwzrwi, gsrqzysr, jwc albregxs szyejef gle ajetzwv nlhhjwc-szwr laizlwt ikjw ikr lsc vrilai hlcxsr. -laiajetr xtrt j hler crnsjejizmr tifsr lg nlhhjwc-szwr ajetzwv: flx nerjir jw zwtijwnr lg LaizlwAjetre, alaxsjir zi bzik laizlwt, -jwc ajetr ikr nlhhjwc szwr. laiajetr jsslbt xtret il tarnzgf laizlwt zw ikr nlwmrwizlwjs VWX/ALTZQ tfwijq, jwc jcczizlwjssf vrwrejirt -xtjvr jwc krsa hrttjvrt gle flx. - -Ixfxgbqo wq g eibo kitjotwotf, dponwvpo, gtz xiyobdup pwvbgbc dib xgbqwts kieegtz-pwto ixfwitq fhgt fho ipz sofixf eizupo. -ixfxgbqo uqoq g eibo zokpgbgfwjo qfcpo id kieegtz-pwto xgbqwts: ciu kbogfo gt wtqfgtko id IxfwitXgbqob, xixupgfo wf ywfh ixfwitq, -gtz xgbqo fho kieegtz pwto. ixfxgbqo gppiyq uqobq fi qxokwdc ixfwitq wt fho kitjotfwitgp STU/XIQWN qctfgn, gtz gzzwfwitgppc sotobgfoq -uqgso gtz hopx eoqqgsoq dib ciu. - -Fucudynl tn d bfyl hfqglqtlqc, amlktsml, dqw ufvlyarm mtsydyz afy udyntqp hfbbdqw-mtql fuctfqn cedq cel fmw plcfuc bfwrml. -fucudynl rnln d bfyl wlhmdydctgl nczml fa hfbbdqw-mtql udyntqp: zfr hyldcl dq tqncdqhl fa FuctfqUdynly, ufurmdcl tc vtce fuctfqn, -dqw udynl cel hfbbdqw mtql. fucudynl dmmfvn rnlyn cf nulhtaz fuctfqn tq cel hfqglqctfqdm PQR/UFNTK nzqcdk, dqw dwwtctfqdmmz plqlydcln -rndpl dqw elmu blnndpln afy zfr. - -Crzravki qk a ycvi ecndinqinz, xjihqpji, ant rcsivxoj jqpvavw xcv ravkqnm ecyyant-jqni crzqcnk zban zbi cjt mizcrz yctoji. -crzravki okik a ycvi tiejavazqdi kzwji cx ecyyant-jqni ravkqnm: wco eviazi an qnkzanei cx CrzqcnRavkiv, rcrojazi qz sqzb crzqcnk, -ant ravki zbi ecyyant jqni. crzravki ajjcsk okivk zc krieqxw crzqcnk qn zbi ecndinzqcnaj MNO/RCKQH kwnzah, ant attqzqcnajjw minivazik -okami ant bijr yikkamik xcv wco. - -Zowoxshf nh x vzsf bzkafknfkw, ugfenmgf, xkq ozpfsulg gnmsxst uzs oxshnkj bzvvxkq-gnkf zownzkh wyxk wyf zgq jfwzow vzqlgf. -zowoxshf lhfh x vzsf qfbgxsxwnaf hwtgf zu bzvvxkq-gnkf oxshnkj: tzl bsfxwf xk nkhwxkbf zu ZownzkOxshfs, ozolgxwf nw pnwy zownzkh, -xkq oxshf wyf bzvvxkq gnkf. zowoxshf xggzph lhfsh wz hofbnut zownzkh nk wyf bzkafkwnzkxg JKL/OZHNE htkwxe, xkq xqqnwnzkxggt jfkfsxwfh -lhxjf xkq yfgo vfhhxjfh uzs tzl. - -Wltlupec ke u swpc ywhxchkcht, rdcbkjdc, uhn lwmcprid dkjpupq rwp lupekhg ywssuhn-dkhc wltkwhe tvuh tvc wdn gctwlt swnidc. -wltlupec iece u swpc ncyduputkxc etqdc wr ywssuhn-dkhc lupekhg: qwi ypcutc uh khetuhyc wr WltkwhLupecp, lwlidutc kt mktv wltkwhe, -uhn lupec tvc ywssuhn dkhc. wltlupec uddwme iecpe tw elcykrq wltkwhe kh tvc ywhxchtkwhud GHI/LWEKB eqhtub, uhn unnktkwhuddq gchcputce -ieugc uhn vcdl sceeugce rwp qwi. - -Tiqirmbz hb r ptmz vteuzehzeq, oazyhgaz, rek itjzmofa ahgmrmn otm irmbhed vtpprek-ahez tiqhteb qsre qsz tak dzqtiq ptkfaz. -tiqirmbz fbzb r ptmz kzvarmrqhuz bqnaz to vtpprek-ahez irmbhed: ntf vmzrqz re hebqrevz to TiqhteIrmbzm, itifarqz hq jhqs tiqhteb, -rek irmbz qsz vtpprek ahez. tiqirmbz raatjb fbzmb qt bizvhon tiqhteb he qsz vteuzeqhtera DEF/ITBHY bneqry, rek rkkhqhteraan dzezmrqzb -fbrdz rek szai pzbbrdzb otm ntf. - -Qfnfojyw ey o mqjw sqbrwbewbn, lxwvedxw, obh fqgwjlcx xedjojk lqj fojyeba sqmmobh-xebw qfneqby npob npw qxh awnqfn mqhcxw. -qfnfojyw cywy o mqjw hwsxojonerw ynkxw ql sqmmobh-xebw fojyeba: kqc sjwonw ob ebynobsw ql QfneqbFojywj, fqfcxonw en genp qfneqby, -obh fojyw npw sqmmobh xebw. qfnfojyw oxxqgy cywjy nq yfwselk qfneqby eb npw sqbrwbneqbox ABC/FQYEV ykbnov, obh ohheneqboxxk awbwjonwy -cyoaw obh pwxf mwyyoawy lqj kqc. - -Nckclgvt bv l jngt pnyotybtyk, iutsbaut, lye cndtgizu ubaglgh ing clgvbyx pnjjlye-ubyt nckbnyv kmly kmt nue xtknck jnezut. -nckclgvt zvtv l jngt etpulglkbot vkhut ni pnjjlye-ubyt clgvbyx: hnz pgtlkt ly byvklypt ni NckbnyClgvtg, cnczulkt bk dbkm nckbnyv, -lye clgvt kmt pnjjlye ubyt. nckclgvt luundv zvtgv kn vctpbih nckbnyv by kmt pnyotykbnylu XYZ/CNVBS vhykls, lye leebkbnyluuh xtytglktv -zvlxt lye mtuc jtvvlxtv ing hnz. - -Kzhzidsq ys i gkdq mkvlqvyqvh, frqpyxrq, ivb zkaqdfwr ryxdide fkd zidsyvu mkggivb-ryvq kzhykvs hjiv hjq krb uqhkzh gkbwrq. -kzhzidsq wsqs i gkdq bqmridihylq sherq kf mkggivb-ryvq zidsyvu: ekw mdqihq iv yvshivmq kf KzhykvZidsqd, zkzwrihq yh ayhj kzhykvs, -ivb zidsq hjq mkggivb ryvq. kzhzidsq irrkas wsqds hk szqmyfe kzhykvs yv hjq mkvlqvhykvir UVW/ZKSYP sevhip, ivb ibbyhykvirre uqvqdihqs -wsiuq ivb jqrz gqssiuqs fkd ekw. - -Hwewfapn vp f dhan jhsinsvnse, conmvuon, fsy whxnacto ovuafab cha wfapvsr jhddfsy-ovsn hwevhsp egfs egn hoy rnehwe dhyton. -hwewfapn tpnp f dhan ynjofafevin pebon hc jhddfsy-ovsn wfapvsr: bht janfen fs vspefsjn hc HwevhsWfapna, whwtofen ve xveg hwevhsp, -fsy wfapn egn jhddfsy ovsn. hwewfapn foohxp tpnap eh pwnjvcb hwevhsp vs egn jhsinsevhsfo RST/WHPVM pbsefm, fsy fyyvevhsfoob rnsnafenp -tpfrn fsy gnow dnppfrnp cha bht. - -Etbtcxmk sm c aexk gepfkpskpb, zlkjsrlk, cpv teukxzql lsrxcxy zex tcxmspo geaacpv-lspk etbsepm bdcp bdk elv okbetb aevqlk. -etbtcxmk qmkm c aexk vkglcxcbsfk mbylk ez geaacpv-lspk tcxmspo: yeq gxkcbk cp spmbcpgk ez EtbsepTcxmkx, tetqlcbk sb usbd etbsepm, -cpv tcxmk bdk geaacpv lspk. etbtcxmk clleum qmkxm be mtkgszy etbsepm sp bdk gepfkpbsepcl OPQ/TEMSJ mypbcj, cpv cvvsbsepclly okpkxcbkm -qmcok cpv dklt akmmcokm zex yeq. - -Bqyqzujh pj z xbuh dbmchmphmy, wihgpoih, zms qbrhuwni ipouzuv wbu qzujpml dbxxzms-ipmh bqypbmj yazm yah bis lhybqy xbsnih. -bqyqzujh njhj z xbuh shdizuzypch jyvih bw dbxxzms-ipmh qzujpml: vbn duhzyh zm pmjyzmdh bw BqypbmQzujhu, qbqnizyh py rpya bqypbmj, -zms qzujh yah dbxxzms ipmh. bqyqzujh ziibrj njhuj yb jqhdpwv bqypbmj pm yah dbmchmypbmzi LMN/QBJPG jvmyzg, zms zsspypbmziiv lhmhuzyhj -njzlh zms ahiq xhjjzlhj wbu vbn. - -Ynvnwrge mg w uyre ayjzejmejv, tfedmlfe, wjp nyoertkf fmlrwrs tyr nwrgmji ayuuwjp-fmje ynvmyjg vxwj vxe yfp ievynv uypkfe. -ynvnwrge kgeg w uyre peafwrwvmze gvsfe yt ayuuwjp-fmje nwrgmji: syk arewve wj mjgvwjae yt YnvmyjNwrger, nynkfwve mv omvx ynvmyjg, -wjp nwrge vxe ayuuwjp fmje. ynvnwrge wffyog kgerg vy gneamts ynvmyjg mj vxe ayjzejvmyjwf IJK/NYGMD gsjvwd, wjp wppmvmyjwffs iejerwveg -kgwie wjp xefn ueggwieg tyr syk. - -Vksktodb jd t rvob xvgwbgjbgs, qcbajicb, tgm kvlboqhc cjiotop qvo ktodjgf xvrrtgm-cjgb vksjvgd sutg sub vcm fbsvks rvmhcb. -vksktodb hdbd t rvob mbxctotsjwb dspcb vq xvrrtgm-cjgb ktodjgf: pvh xobtsb tg jgdstgxb vq VksjvgKtodbo, kvkhctsb js ljsu vksjvgd, -tgm ktodb sub xvrrtgm cjgb. vksktodb tccvld hdbod sv dkbxjqp vksjvgd jg sub xvgwbgsjvgtc FGH/KVDJA dpgsta, tgm tmmjsjvgtccp fbgbotsbd -hdtfb tgm ubck rbddtfbd qvo pvh. - -Shphqlay ga q osly usdtydgydp, nzyxgfzy, qdj hsiylnez zgflqlm nsl hqlagdc usooqdj-zgdy shpgsda prqd pry szj cypshp osjezy. -shphqlay eaya q osly jyuzqlqpgty apmzy sn usooqdj-zgdy hqlagdc: mse ulyqpy qd gdapqduy sn ShpgsdHqlayl, hshezqpy gp igpr shpgsda, -qdj hqlay pry usooqdj zgdy. shphqlay qzzsia eayla ps ahyugnm shpgsda gd pry usdtydpgsdqz CDE/HSAGX amdpqx, qdj qjjgpgsdqzzm cydylqpya -eaqcy qdj ryzh oyaaqcya nsl mse. - -Pemenixv dx n lpiv rpaqvadvam, kwvudcwv, nag epfvikbw wdcinij kpi enixdaz rpllnag-wdav pemdpax mona mov pwg zvmpem lpgbwv. -pemenixv bxvx n lpiv gvrwninmdqv xmjwv pk rpllnag-wdav enixdaz: jpb rivnmv na daxmnarv pk PemdpaEnixvi, epebwnmv dm fdmo pemdpax, -nag enixv mov rpllnag wdav. pemenixv nwwpfx bxvix mp xevrdkj pemdpax da mov rpaqvamdpanw ZAB/EPXDU xjamnu, nag nggdmdpanwwj zvavinmvx -bxnzv nag ovwe lvxxnzvx kpi jpb. - -Mbjbkfus au k imfs omxnsxasxj, htsrazts, kxd bmcsfhyt tazfkfg hmf bkfuaxw omiikxd-taxs mbjamxu jlkx jls mtd wsjmbj imdyts. -mbjbkfus yusu k imfs dsotkfkjans ujgts mh omiikxd-taxs bkfuaxw: gmy ofskjs kx axujkxos mh MbjamxBkfusf, bmbytkjs aj cajl mbjamxu, -kxd bkfus jls omiikxd taxs. mbjbkfus kttmcu yusfu jm ubsoahg mbjamxu ax jls omxnsxjamxkt WXY/BMUAR ugxjkr, kxd kddajamxkttg wsxsfkjsu -yukws kxd lstb isuukwsu hmf gmy. - -Jygyhcrp xr h fjcp ljukpuxpug, eqpoxwqp, hua yjzpcevq qxwchcd ejc yhcrxut ljffhua-qxup jygxjur gihu gip jqa tpgjyg fjavqp. -jygyhcrp vrpr h fjcp aplqhchgxkp rgdqp je ljffhua-qxup yhcrxut: djv lcphgp hu xurghulp je JygxjuYhcrpc, yjyvqhgp xg zxgi jygxjur, -hua yhcrp gip ljffhua qxup. jygyhcrp hqqjzr vrpcr gj ryplxed jygxjur xu gip ljukpugxjuhq TUV/YJRXO rdugho, hua haaxgxjuhqqd tpupchgpr -vrhtp hua ipqy fprrhtpr ejc djv. - -Gvdvezom uo e cgzm igrhmrumrd, bnmlutnm, erx vgwmzbsn nutzeza bgz vezourq igccerx-nurm gvdugro dfer dfm gnx qmdgvd cgxsnm. -gvdvezom somo e cgzm xminezeduhm odanm gb igccerx-nurm vezourq: ags izmedm er uroderim gb GvdugrVezomz, vgvsnedm ud wudf gvdugro, -erx vezom dfm igccerx nurm. gvdvezom enngwo somzo dg ovmiuba gvdugro ur dfm igrhmrdugren QRS/VGOUL oardel, erx exxudugrenna qmrmzedmo -soeqm erx fmnv cmooeqmo bgz ags. - -Dsasbwlj rl b zdwj fdoejorjoa, ykjirqkj, bou sdtjwypk krqwbwx ydw sbwlron fdzzbou-kroj dsardol acbo acj dku njadsa zdupkj. -dsasbwlj pljl b zdwj ujfkbwbarej laxkj dy fdzzbou-kroj sbwlron: xdp fwjbaj bo rolabofj dy DsardoSbwljw, sdspkbaj ra trac dsardol, -bou sbwlj acj fdzzbou kroj. dsasbwlj bkkdtl pljwl ad lsjfryx dsardol ro acj fdoejoardobk NOP/SDLRI lxoabi, bou buurardobkkx njojwbajl -plbnj bou cjks zjllbnjl ydw xdp. - -Apxpytig oi y watg calbgloglx, vhgfonhg, ylr paqgtvmh hontytu vat pytiolk cawwylr-holg apxoali xzyl xzg ahr kgxapx warmhg. -apxpytig migi y watg rgchytyxobg ixuhg av cawwylr-holg pytiolk: uam ctgyxg yl olixylcg av ApxoalPytigt, papmhyxg ox qoxz apxoali, -ylr pytig xzg cawwylr holg. apxpytig yhhaqi migti xa ipgcovu apxoali ol xzg calbglxoalyh KLM/PAIOF iulxyf, ylr yrroxoalyhhu kglgtyxgi -miykg ylr zghp wgiiykgi vat uam. - -Xmumvqfd lf v txqd zxiydildiu, sedclked, vio mxndqsje elkqvqr sxq mvqflih zxttvio-elid xmulxif uwvi uwd xeo hduxmu txojed. -xmumvqfd jfdf v txqd odzevqvulyd fured xs zxttvio-elid mvqflih: rxj zqdvud vi lifuvizd xs XmulxiMvqfdq, mxmjevud lu nluw xmulxif, -vio mvqfd uwd zxttvio elid. xmumvqfd veexnf jfdqf ux fmdzlsr xmulxif li uwd zxiydiulxive HIJ/MXFLC friuvc, vio voolulxiveer hdidqvudf -jfvhd vio wdem tdffvhdf sxq rxj. - -Ujrjsnca ic s quna wufvafiafr, pbazihba, sfl jukanpgb bihnsno pun jsncife wuqqsfl-bifa ujriufc rtsf rta ubl earujr qulgba. -ujrjsnca gcac s quna lawbsnsriva croba up wuqqsfl-bifa jsncife: oug wnasra sf ifcrsfwa up UjriufJsncan, jujgbsra ir kirt ujriufc, -sfl jsnca rta wuqqsfl bifa. ujrjsnca sbbukc gcanc ru cjawipo ujriufc if rta wufvafriufsb EFG/JUCIZ cofrsz, sfl slliriufsbbo eafansrac -gcsea sfl tabj qaccseac pun oug. - -Rgogpkzx fz p nrkx trcsxcfxco, myxwfeyx, pci grhxkmdy yfekpkl mrk gpkzfcb trnnpci-yfcx rgofrcz oqpc oqx ryi bxorgo nridyx. -rgogpkzx dzxz p nrkx ixtypkpofsx zolyx rm trnnpci-yfcx gpkzfcb: lrd tkxpox pc fczopctx rm RgofrcGpkzxk, grgdypox fo hfoq rgofrcz, -pci gpkzx oqx trnnpci yfcx. rgogpkzx pyyrhz dzxkz or zgxtfml rgofrcz fc oqx trcsxcofrcpy BCD/GRZFW zlcopw, pci piifofrcpyyl bxcxkpoxz -dzpbx pci qxyg nxzzpbxz mrk lrd. - -Odldmhwu cw m kohu qozpuzcuzl, jvutcbvu, mzf doeuhjav vcbhmhi joh dmhwczy qokkmzf-vczu odlcozw lnmz lnu ovf yulodl kofavu. -odldmhwu awuw m kohu fuqvmhmlcpu wlivu oj qokkmzf-vczu dmhwczy: ioa qhumlu mz czwlmzqu oj OdlcozDmhwuh, dodavmlu cl ecln odlcozw, -mzf dmhwu lnu qokkmzf vczu. odldmhwu mvvoew awuhw lo wduqcji odlcozw cz lnu qozpuzlcozmv YZA/DOWCT wizlmt, mzf mffclcozmvvi yuzuhmluw -awmyu mzf nuvd kuwwmyuw joh ioa. - -Jaqafizv lz f bjiv njsyvslvsq, mkvglwkv, fse ajpvimhk klwifix mji afizlsd njbbfse-klsv jaqljsz qufs quv jke dvqjaq bjehkv. -jaqafizv hzvz f bjiv evnkfifqlyv zqxkv jm njbbfse-klsv afizlsd: xjh nivfqv fs lszqfsnv jm JaqljsAfizvi, ajahkfqv lq plqu jaqljsz, -fse afizv quv njbbfse klsv. jaqafizv fkkjpz hzviz qj zavnlmx jaqljsz ls quv njsyvsqljsfk DSH/AJZLG zxsqfg, fse feelqljsfkkx dvsvifqvz -hzfdv fse uvka bvzzfdvz mji xjh. - -Qhxhmpgc sg m iqpc uqzfczsczx, trcnsdrc, mzl hqwcptor rsdpmpe tqp hmpgszk uqiimzl-rszc qhxsqzg xbmz xbc qrl kcxqhx iqlorc. -qhxhmpgc ogcg m iqpc lcurmpmxsfc gxerc qt uqiimzl-rszc hmpgszk: eqo upcmxc mz szgxmzuc qt QhxsqzHmpgcp, hqhormxc sx wsxb qhxsqzg, -mzl hmpgc xbc uqiimzl rszc. qhxhmpgc mrrqwg ogcpg xq ghcuste qhxsqzg sz xbc uqzfczxsqzmr KZO/HQGSN gezxmn, mzl mllsxsqzmrre kczcpmxcg -ogmkc mzl bcrh icggmkcg tqp eqo. - -Xoeotwnj zn t pxwj bxgmjgzjge, ayjuzkyj, tgs oxdjwavy yzkwtwl axw otwnzgr bxpptgs-yzgj xoezxgn eitg eij xys rjexoe pxsvyj. -xoeotwnj vnjn t pxwj sjbytwtezmj nelyj xa bxpptgs-yzgj otwnzgr: lxv bwjtej tg zgnetgbj xa XoezxgOtwnjw, oxovytej ze dzei xoezxgn, -tgs otwnj eij bxpptgs yzgj. xoeotwnj tyyxdn vnjwn ex nojbzal xoezxgn zg eij bxgmjgezxgty RGV/OXNZU nlgetu, tgs tsszezxgtyyl rjgjwtejn -vntrj tgs ijyo pjnntrjn axw lxv. - -Evlvaduq gu a wedq ientqngqnl, hfqbgrfq, anz vekqdhcf fgrdads hed vadugny iewwanz-fgnq evlgenu lpan lpq efz yqlevl wezcfq. -evlvaduq cuqu a wedq zqifadalgtq ulsfq eh iewwanz-fgnq vadugny: sec idqalq an gnulaniq eh EvlgenVaduqd, vevcfalq gl kglp evlgenu, -anz vaduq lpq iewwanz fgnq. evlvaduq affeku cuqdu le uvqighs evlgenu gn lpq ientqnlgenaf YNC/VEUGB usnlab, anz azzglgenaffs yqnqdalqu -cuayq anz pqfv wquuayqu hed sec. - -Lcschkbx nb h dlkx pluaxunxus, omxinymx, hug clrxkojm mnykhkz olk chkbnuf plddhug-mnux lcsnlub swhu swx lmg fxslcs dlgjmx. -lcschkbx jbxb h dlkx gxpmhkhsnax bszmx lo plddhug-mnux chkbnuf: zlj pkxhsx hu nubshupx lo LcsnluChkbxk, clcjmhsx ns rnsw lcsnlub, -hug chkbx swx plddhug mnux. lcschkbx hmmlrb jbxkb sl bcxpnoz lcsnlub nu swx pluaxusnluhm FUJ/CLBNI bzushi, hug hggnsnluhmmz fxuxkhsxb -jbhfx hug wxmc dxbbhfxb olk zlj. - -Sjzjorie ui o ksre wsbhebuebz, vtepufte, obn jsyervqt tufrorg vsr joriubm wskkobn-tube sjzusbi zdob zde stn mezsjz ksnqte. -sjzjorie qiei o ksre newtorozuhe izgte sv wskkobn-tube joriubm: gsq wreoze ob ubizobwe sv SjzusbJorier, jsjqtoze uz yuzd sjzusbi, -obn jorie zde wskkobn tube. sjzjorie ottsyi qieri zs ijewuvg sjzusbi ub zde wsbhebzusbot MBQ/JSIUP igbzop, obn onnuzusbottg meberozei -qiome obn detj keiiomei vsr gsq. - -Zqgqvypl bp v rzyl dzioliblig, calwbmal, viu qzflycxa abmyvyn czy qvypbit dzrrviu-abil zqgbzip gkvi gkl zau tlgzqg rzuxal. -zqgqvypl xplp v rzyl uldavyvgbol pgnal zc dzrrviu-abil qvypbit: nzx dylvgl vi bipgvidl zc ZqgbziQvyply, qzqxavgl bg fbgk zqgbzip, -viu qvypl gkl dzrrviu abil. zqgqvypl vaazfp xplyp gz pqldbcn zqgbzip bi gkl dzioligbziva TIX/QZPBW pnigvw, viu vuubgbzivaan tlilyvglp -xpvtl viu klaq rlppvtlp czy nzx. - -Gxnxcfws iw c ygfs kgpvspispn, jhsdiths, cpb xgmsfjeh hitfcfu jgf xcfwipa kgyycpb-hips gxnigpw nrcp nrs ghb asngxn ygbehs. -gxnxcfws ewsw c ygfs bskhcfcnivs wnuhs gj kgyycpb-hips xcfwipa: uge kfscns cp ipwncpks gj GxnigpXcfwsf, xgxehcns in minr gxnigpw, -cpb xcfws nrs kgyycpb hips. gxnxcfws chhgmw ewsfw ng wxskiju gxnigpw ip nrs kgpvspnigpch APE/XGWID wupncd, cpb cbbinigpchhu aspsfcnsw -ewcas cpb rshx yswwcasw jgf uge. - -Neuejmdz pd j fnmz rnwczwpzwu, qozkpaoz, jwi entzmqlo opamjmb qnm ejmdpwh rnffjwi-opwz neupnwd uyjw uyz noi hzuneu fniloz. -neuejmdz ldzd j fnmz izrojmjupcz duboz nq rnffjwi-opwz ejmdpwh: bnl rmzjuz jw pwdujwrz nq NeupnwEjmdzm, enelojuz pu tpuy neupnwd, -jwi ejmdz uyz rnffjwi opwz. neuejmdz joontd ldzmd un dezrpqb neupnwd pw uyz rnwczwupnwjo HWL/ENDPK dbwujk, jwi jiipupnwjoob hzwzmjuzd -ldjhz jwi yzoe fzddjhzd qnm bnl. - -Ulblqtkg wk q mutg yudjgdwgdb, xvgrwhvg, qdp luagtxsv vwhtqti xut lqtkwdo yummqdp-vwdg ulbwudk bfqd bfg uvp ogbulb mupsvg. -ulblqtkg skgk q mutg pgyvqtqbwjg kbivg ux yummqdp-vwdg lqtkwdo: ius ytgqbg qd wdkbqdyg ux UlbwudLqtkgt, lulsvqbg wb awbf ulbwudk, -qdp lqtkg bfg yummqdp vwdg. ulblqtkg qvvuak skgtk bu klgywxi ulbwudk wd bfg yudjgdbwudqv ODS/LUKWR kidbqr, qdp qppwbwudqvvi ogdgtqbgk -skqog qdp fgvl mgkkqogk xut ius. - -Bsisxarn dr x tban fbkqnkdnki, ecnydocn, xkw sbhnaezc cdoaxap eba sxardkv fbttxkw-cdkn bsidbkr imxk imn bcw vnibsi tbwzcn. -bsisxarn zrnr x tban wnfcxaxidqn ripcn be fbttxkw-cdkn sxardkv: pbz fanxin xk dkrixkfn be BsidbkSxarna, sbszcxin di hdim bsidbkr, -xkw sxarn imn fbttxkw cdkn. bsisxarn xccbhr zrnar ib rsnfdep bsidbkr dk imn fbkqnkidbkxc VKZ/SBRDY rpkixy, xkw xwwdidbkxccp vnknaxinr -zrxvn xkw mncs tnrrxvnr eba pbz. - -Izpzehyu ky e aihu mirxurkurp, ljufkvju, erd ziouhlgj jkvhehw lih zehykrc miaaerd-jkru izpkiry pter ptu ijd cupizp aidgju. -izpzehyu gyuy e aihu dumjehepkxu ypwju il miaaerd-jkru zehykrc: wig mhuepu er krypermu il IzpkirZehyuh, zizgjepu kp okpt izpkiry, -erd zehyu ptu miaaerd jkru. izpzehyu ejjioy gyuhy pi yzumklw izpkiry kr ptu mirxurpkirej CRG/ZIYKF ywrpef, erd eddkpkirejjw curuhepuy -gyecu erd tujz auyyecuy lih wig. - -Pgwglofb rf l hpob tpyebyrbyw, sqbmrcqb, lyk gpvbosnq qrcolod spo glofryj tphhlyk-qryb pgwrpyf waly wab pqk jbwpgw hpknqb. -pgwglofb nfbf l hpob kbtqlolwreb fwdqb ps tphhlyk-qryb glofryj: dpn toblwb ly ryfwlytb ps PgwrpyGlofbo, gpgnqlwb rw vrwa pgwrpyf, -lyk glofb wab tphhlyk qryb. pgwglofb lqqpvf nfbof wp fgbtrsd pgwrpyf ry wab tpyebywrpylq JYN/GPFRM fdywlm, lyk lkkrwrpylqqd jbybolwbf -nfljb lyk abqg hbffljbf spo dpn. - -Wndnsvmi ym s owvi awflifyifd, zxityjxi, sfr nwcivzux xyjvsvk zwv nsvmyfq awoosfr-xyfi wndywfm dhsf dhi wxr qidwnd owruxi. -wndnsvmi umim s owvi riaxsvsdyli mdkxi wz awoosfr-xyfi nsvmyfq: kwu avisdi sf yfmdsfai wz WndywfNsvmiv, nwnuxsdi yd cydh wndywfm, -sfr nsvmi dhi awoosfr xyfi. wndnsvmi sxxwcm umivm dw mniayzk wndywfm yf dhi awflifdywfsx QFU/NWMYT mkfdst, sfr srrydywfsxxk qifivsdim -umsqi sfr hixn oimmsqim zwv kwu. - -Dukuzctp ft z vdcp hdmspmfpmk, gepafqep, zmy udjpcgbe efqczcr gdc uzctfmx hdvvzmy-efmp dukfdmt kozm kop dey xpkduk vdybep. -dukuzctp btpt z vdcp yphezczkfsp tkrep dg hdvvzmy-efmp uzctfmx: rdb hcpzkp zm fmtkzmhp dg DukfdmUzctpc, udubezkp fk jfko dukfdmt, -zmy uzctp kop hdvvzmy efmp. dukuzctp zeedjt btpct kd tuphfgr dukfdmt fm kop hdmspmkfdmze XMB/UDTFA trmkza, zmy zyyfkfdmzeer xpmpczkpt -btzxp zmy opeu vpttzxpt gdc rdb. - -Kbrbgjaw ma g ckjw oktzwtmwtr, nlwhmxlw, gtf bkqwjnil lmxjgjy nkj bgjamte okccgtf-lmtw kbrmkta rvgt rvw klf ewrkbr ckfilw. -kbrbgjaw iawa g ckjw fwolgjgrmzw arylw kn okccgtf-lmtw bgjamte: yki ojwgrw gt mtargtow kn KbrmktBgjawj, bkbilgrw mr qmrv kbrmkta, -gtf bgjaw rvw okccgtf lmtw. kbrbgjaw gllkqa iawja rk abwomny kbrmkta mt rvw oktzwtrmktgl ETI/BKAMH aytrgh, gtf gffmrmktglly ewtwjgrwa -iagew gtf vwlb cwaagewa nkj yki. - -Riyinqhd th n jrqd vragdatday, usdotesd, nam irxdqups steqnqf urq inqhtal vrjjnam-stad riytrah ycna ycd rsm ldyriy jrmpsd. -riyinqhd phdh n jrqd mdvsnqnytgd hyfsd ru vrjjnam-stad inqhtal: frp vqdnyd na tahynavd ru RiytraInqhdq, iripsnyd ty xtyc riytrah, -nam inqhd ycd vrjjnam stad. riyinqhd nssrxh phdqh yr hidvtuf riytrah ta ycd vragdaytrans LAP/IRHTO hfayno, nam nmmtytranssf ldadqnydh -phnld nam cdsi jdhhnldh urq frp. - -Ypfpuxok ao u qyxk cyhnkhakhf, bzkvalzk, uht pyekxbwz zalxuxm byx puxoahs cyqquht-zahk ypfayho fjuh fjk yzt skfypf qytwzk. -ypfpuxok woko u qyxk tkczuxufank ofmzk yb cyqquht-zahk puxoahs: myw cxkufk uh ahofuhck yb YpfayhPuxokx, pypwzufk af eafj ypfayho, -uht puxok fjk cyqquht zahk. ypfpuxok uzzyeo wokxo fy opkcabm ypfayho ah fjk cyhnkhfayhuz SHW/PYOAV omhfuv, uht uttafayhuzzm skhkxufko -wousk uht jkzp qkoousko byx myw. - -Fwmwbevr hv b xfer jfourohrom, igrchsgr, boa wflreidg ghsebet ife wbevhoz jfxxboa-ghor fwmhfov mqbo mqr fga zrmfwm xfadgr. -fwmwbevr dvrv b xfer arjgbebmhur vmtgr fi jfxxboa-ghor wbevhoz: tfd jerbmr bo hovmbojr fi FwmhfoWbevre, wfwdgbmr hm lhmq fwmhfov, -boa wbevr mqr jfxxboa ghor. fwmwbevr bggflv dvrev mf vwrjhit fwmhfov ho mqr jfouromhfobg ZOD/WFVHC vtombc, boa baahmhfobggt zrorebmrv -dvbzr boa qrgw xrvvbzrv ife tfd. - -Mdtdilcy oc i emly qmvbyvoyvt, pnyjozny, ivh dmsylpkn nozlila pml dilcovg qmeeivh-novy mdtomvc txiv txy mnh gytmdt emhkny. -mdtdilcy kcyc i emly hyqnilitoby ctany mp qmeeivh-novy dilcovg: amk qlyity iv ovctivqy mp MdtomvDilcyl, dmdknity ot sotx mdtomvc, -ivh dilcy txy qmeeivh novy. mdtdilcy innmsc kcylc tm cdyqopa mdtomvc ov txy qmvbyvtomvin GVK/DMCOJ cavtij, ivh ihhotomvinna gyvylityc -kcigy ivh xynd eyccigyc pml amk. - -Tkakpsjf vj p ltsf xtcifcvfca, wufqvguf, pco ktzfswru uvgspsh wts kpsjvcn xtllpco-uvcf tkavtcj aepc aef tuo nfatka ltoruf. -tkakpsjf rjfj p ltsf ofxupspavif jahuf tw xtllpco-uvcf kpsjvcn: htr xsfpaf pc vcjapcxf tw TkavtcKpsjfs, ktkrupaf va zvae tkavtcj, -pco kpsjf aef xtllpco uvcf. tkakpsjf puutzj rjfsj at jkfxvwh tkavtcj vc aef xtcifcavtcpu NCR/KTJVQ jhcapq, pco poovavtcpuuh nfcfspafj -rjpnf pco efuk lfjjpnfj wts htr. - -Arhrwzqm cq w sazm eajpmjcmjh, dbmxcnbm, wjv ragmzdyb bcnzwzo daz rwzqcju easswjv-bcjm arhcajq hlwj hlm abv umharh savybm. -arhrwzqm yqmq w sazm vmebwzwhcpm qhobm ad easswjv-bcjm rwzqcju: oay ezmwhm wj cjqhwjem ad ArhcajRwzqmz, rarybwhm ch gchl arhcajq, -wjv rwzqm hlm easswjv bcjm. arhrwzqm wbbagq yqmzq ha qrmecdo arhcajq cj hlm eajpmjhcajwb UJY/RAQCX qojhwx, wjv wvvchcajwbbo umjmzwhmq -yqwum wjv lmbr smqqwumq daz oay. - -Hyoydgxt jx d zhgt lhqwtqjtqo, kitejuit, dqc yhntgkfi ijugdgv khg ydgxjqb lhzzdqc-ijqt hyojhqx osdq ost hic btohyo zhcfit. -hyoydgxt fxtx d zhgt ctlidgdojwt xovit hk lhzzdqc-ijqt ydgxjqb: vhf lgtdot dq jqxodqlt hk HyojhqYdgxtg, yhyfidot jo njos hyojhqx, -dqc ydgxt ost lhzzdqc ijqt. hyoydgxt diihnx fxtgx oh xytljkv hyojhqx jq ost lhqwtqojhqdi BQF/YHXJE xvqode, dqc dccjojhqdiiv btqtgdotx -fxdbt dqc stiy ztxxdbtx khg vhf. - -Ofvfknea qe k gona soxdaxqaxv, rpalqbpa, kxj fouanrmp pqbnknc ron fkneqxi soggkxj-pqxa ofvqoxe vzkx vza opj iavofv gojmpa. -ofvfknea meae k gona jaspknkvqda evcpa or soggkxj-pqxa fkneqxi: com snakva kx qxevkxsa or OfvqoxFknean, fofmpkva qv uqvz ofvqoxe, -kxj fknea vza soggkxj pqxa. ofvfknea kppoue meane vo efasqrc ofvqoxe qx vza soxdaxvqoxkp IXM/FOEQL ecxvkl, kxj kjjqvqoxkppc iaxankvae -mekia kxj zapf gaeekiae ron com. - -Vmcmrulh xl r nvuh zvekhexhec, ywhsxiwh, req mvbhuytw wxiuruj yvu mrulxep zvnnreq-wxeh vmcxvel cgre cgh vwq phcvmc nvqtwh. -vmcmrulh tlhl r nvuh qhzwrurcxkh lcjwh vy zvnnreq-wxeh mrulxep: jvt zuhrch re xelcrezh vy VmcxveMrulhu, mvmtwrch xc bxcg vmcxvel, -req mrulh cgh zvnnreq wxeh. vmcmrulh rwwvbl tlhul cv lmhzxyj vmcxvel xe cgh zvekhecxverw PET/MVLXS ljecrs, req rqqxcxverwwj phehurchl -tlrph req ghwm nhllrphl yvu jvt. - -Ctjtybso es y ucbo gclroleolj, fdozepdo, ylx tciobfad depbybq fcb tybselw gcuuylx-delo ctjecls jnyl jno cdx wojctj ucxado. -ctjtybso asos y ucbo xogdybyjero sjqdo cf gcuuylx-delo tybselw: qca gboyjo yl elsjylgo cf CtjeclTybsob, tctadyjo ej iejn ctjecls, -ylx tybso jno gcuuylx delo. ctjtybso yddcis asobs jc stogefq ctjecls el jno gclroljeclyd WLA/TCSEZ sqljyz, ylx yxxejeclyddq wolobyjos -asywo ylx nodt uossywos fcb qca. - -Rakavsbf pb v zrsf nricfipfik, oqfupeqf, viw arlfsotq qpesvsd ors avsbpix nrzzviw-qpif rakprib kgvi kgf rqw xfkrak zrwtqf. -rakavsbf tbfb v zrsf wfnqvsvkpcf bkdqf ro nrzzviw-qpif avsbpix: drt nsfvkf vi pibkvinf ro RakpriAvsbfs, aratqvkf pk lpkg rakprib, -viw avsbf kgf nrzzviw qpif. rakavsbf vqqrlb tbfsb kr bafnpod rakprib pi kgf nricfikprivq XIT/ARBPU bdikvu, viw vwwpkprivqqd xfifsvkfb -tbvxf viw gfqa zfbbvxfb ors drt. - -Ktdtoluy iu o skly gkbvybiybd, hjynixjy, obp tkeylhmj jixlolw hkl toluibq gkssobp-jiby ktdikbu dzob dzy kjp qydktd skpmjy. -ktdtoluy muyu o skly pygjolodivy udwjy kh gkssobp-jiby toluibq: wkm glyody ob ibudobgy kh KtdikbToluyl, tktmjody id eidz ktdikbu, -obp toluy dzy gkssobp jiby. ktdtoluy ojjkeu muylu dk utygihw ktdikbu ib dzy gkbvybdikboj QBM/TKUIN uwbdon, obp oppidikbojjw qybylodyu -muoqy obp zyjt syuuoqyu hkl wkm. - -Dmwmhenr bn h lder zduorubruw, acrgbqcr, hui mdxreafc cbqehep ade mhenbuj zdllhui-cbur dmwbdun wshu wsr dci jrwdmw ldifcr. -dmwmhenr fnrn h lder irzchehwbor nwpcr da zdllhui-cbur mhenbuj: pdf zerhwr hu bunwhuzr da DmwbduMhenre, mdmfchwr bw xbws dmwbdun, -hui mhenr wsr zdllhui cbur. dmwmhenr hccdxn fnren wd nmrzbap dmwbdun bu wsr zduoruwbduhc JUF/MDNBG npuwhg, hui hiibwbduhccp jrurehwrn -fnhjr hui srcm lrnnhjrn ade pdf. - -Wfpfaxgk ug a ewxk swnhknuknp, tvkzujvk, anb fwqkxtyv vujxaxi twx faxgunc sweeanb-vunk wfpuwng plan plk wvb ckpwfp ewbyvk. -wfpfaxgk ygkg a ewxk bksvaxapuhk gpivk wt sweeanb-vunk faxgunc: iwy sxkapk an ungpansk wt WfpuwnFaxgkx, fwfyvapk up qupl wfpuwng, -anb faxgk plk sweeanb vunk. wfpfaxgk avvwqg ygkxg pw gfksuti wfpuwng un plk swnhknpuwnav CNY/FWGUZ ginpaz, anb abbupuwnavvi cknkxapkg -ygack anb lkvf ekggackg twx iwy. - -Pyiytqzd nz t xpqd lpgadgndgi, modsncod, tgu ypjdqmro oncqtqb mpq ytqzngv lpxxtgu-ongd pyinpgz ietg ied pou vdipyi xpurod. -pyiytqzd rzdz t xpqd udlotqtinad zibod pm lpxxtgu-ongd ytqzngv: bpr lqdtid tg ngzitgld pm PyinpgYtqzdq, ypyrotid ni jnie pyinpgz, -tgu ytqzd ied lpxxtgu ongd. pyiytqzd toopjz rzdqz ip zydlnmb pyinpgz ng ied lpgadginpgto VGR/YPZNS zbgits, tgu tuuninpgtoob vdgdqtidz -rztvd tgu edoy xdzztvdz mpq bpr. - -Irbrmjsw gs m qijw eiztwzgwzb, fhwlgvhw, mzn ricwjfkh hgvjmju fij rmjsgzo eiqqmzn-hgzw irbgizs bxmz bxw ihn owbirb qinkhw. -irbrmjsw ksws m qijw nwehmjmbgtw sbuhw if eiqqmzn-hgzw rmjsgzo: uik ejwmbw mz gzsbmzew if IrbgizRmjswj, rirkhmbw gb cgbx irbgizs, -mzn rmjsw bxw eiqqmzn hgzw. irbrmjsw mhhics kswjs bi srwegfu irbgizs gz bxw eiztwzbgizmh OZK/RISGL suzbml, mzn mnngbgizmhhu owzwjmbws -ksmow mzn xwhr qwssmows fij uik. - -Bkukfclp zl f jbcp xbsmpszpsu, yapezoap, fsg kbvpcyda azocfcn ybc kfclzsh xbjjfsg-azsp bkuzbsl uqfs uqp bag hpubku jbgdap. -bkukfclp dlpl f jbcp gpxafcfuzmp lunap by xbjjfsg-azsp kfclzsh: nbd xcpfup fs zslufsxp by BkuzbsKfclpc, kbkdafup zu vzuq bkuzbsl, -fsg kfclp uqp xbjjfsg azsp. bkukfclp faabvl dlpcl ub lkpxzyn bkuzbsl zs uqp xbsmpsuzbsfa HSD/KBLZE lnsufe, fsg fggzuzbsfaan hpspcfupl -dlfhp fsg qpak jpllfhpl ybc nbd. - -Udndyvei se y cuvi qulfilsiln, rtixshti, ylz duoivrwt tshvyvg ruv dyvesla quccylz-tsli udnsule njyl nji utz ainudn cuzwti. -udndyvei weie y cuvi ziqtyvynsfi engti ur quccylz-tsli dyvesla: guw qviyni yl slenylqi ur UdnsulDyveiv, dudwtyni sn osnj udnsule, -ylz dyvei nji quccylz tsli. udndyvei yttuoe weive nu ediqsrg udnsule sl nji qulfilnsulyt ALW/DUESX eglnyx, ylz yzzsnsulyttg ailivynie -weyai ylz jitd cieeyaie ruv guw. - -Nwgwroxb lx r vnob jneybelbeg, kmbqlamb, res wnhbokpm mlaoroz kno wroxlet jnvvres-mleb nwglnex gcre gcb nms tbgnwg vnspmb. -nwgwroxb pxbx r vnob sbjmrorglyb xgzmb nk jnvvres-mleb wroxlet: znp jobrgb re lexgrejb nk NwglneWroxbo, wnwpmrgb lg hlgc nwglnex, -res wroxb gcb jnvvres mleb. nwgwroxb rmmnhx pxbox gn xwbjlkz nwglnex le gcb jneybeglnerm TEP/WNXLQ xzegrq, res rsslglnermmz tbeborgbx -pxrtb res cbmw vbxxrtbx kno znp. - -Gpzpkhqu eq k oghu cgxruxeuxz, dfujetfu, kxl pgauhdif fethkhs dgh pkhqexm cgookxl-fexu gpzegxq zvkx zvu gfl muzgpz oglifu. -gpzpkhqu iquq k oghu lucfkhkzeru qzsfu gd cgookxl-fexu pkhqexm: sgi chukzu kx exqzkxcu gd GpzegxPkhquh, pgpifkzu ez aezv gpzegxq, -kxl pkhqu zvu cgookxl fexu. gpzpkhqu kffgaq iquhq zg qpuceds gpzegxq ex zvu cgxruxzegxkf MXI/PGQEJ qsxzkj, kxl kllezegxkffs muxuhkzuq -iqkmu kxl vufp ouqqkmuq dgh sgi. - -Zisidajn xj d hzan vzqknqxnqs, wyncxmyn, dqe iztnawby yxmadal wza idajxqf vzhhdqe-yxqn zisxzqj sodq son zye fnszis hzebyn. -zisidajn bjnj d hzan envydadsxkn jslyn zw vzhhdqe-yxqn idajxqf: lzb vandsn dq xqjsdqvn zw ZisxzqIdajna, izibydsn xs txso zisxzqj, -dqe idajn son vzhhdqe yxqn. zisidajn dyyztj bjnaj sz jinvxwl zisxzqj xq son vzqknqsxzqdy FQB/IZJXC jlqsdc, dqe deexsxzqdyyl fnqnadsnj -bjdfn dqe onyi hnjjdfnj wza lzb. - -Sblbwtcg qc w astg osjdgjqgjl, prgvqfrg, wjx bsmgtpur rqftwte pst bwtcqjy osaawjx-rqjg sblqsjc lhwj lhg srx yglsbl asxurg. -sblbwtcg ucgc w astg xgorwtwlqdg clerg sp osaawjx-rqjg bwtcqjy: esu otgwlg wj qjclwjog sp SblqsjBwtcgt, bsburwlg ql mqlh sblqsjc, -wjx bwtcg lhg osaawjx rqjg. sblbwtcg wrrsmc ucgtc ls cbgoqpe sblqsjc qj lhg osjdgjlqsjwr YJU/BSCQV cejlwv, wjx wxxqlqsjwrre ygjgtwlgc -ucwyg wjx hgrb agccwygc pst esu. - -Lueupmvz jv p tlmz hlcwzcjzce, ikzojykz, pcq ulfzmink kjympmx ilm upmvjcr hlttpcq-kjcz luejlcv eapc eaz lkq rzelue tlqnkz. -lueupmvz nvzv p tlmz qzhkpmpejwz vexkz li hlttpcq-kjcz upmvjcr: xln hmzpez pc jcvepchz li LuejlcUpmvzm, ulunkpez je fjea luejlcv, -pcq upmvz eaz hlttpcq kjcz. lueupmvz pkklfv nvzmv el vuzhjix luejlcv jc eaz hlcwzcejlcpk RCN/ULVJO vxcepo, pcq pqqjejlcpkkx rzczmpezv -nvprz pcq azku tzvvprzv ilm xln. - -Enxnifos co i mefs aevpsvcsvx, bdshcrds, ivj neysfbgd dcrfifq bef nifocvk aemmivj-dcvs enxcevo xtiv xts edj ksxenx mejgds. -enxnifos goso i mefs jsadifixcps oxqds eb aemmivj-dcvs nifocvk: qeg afsixs iv cvoxivas eb EnxcevNifosf, nengdixs cx ycxt enxcevo, -ivj nifos xts aemmivj dcvs. enxnifos iddeyo gosfo xe onsacbq enxcevo cv xts aevpsvxcevid KVG/NEOCH oqvxih, ivj ijjcxceviddq ksvsfixso -goiks ivj tsdn msooikso bef qeg. - -Xgqgbyhl vh b fxyl txoilovloq, uwlavkwl, boc gxrlyuzw wvkybyj uxy gbyhvod txffboc-wvol xgqvxoh qmbo qml xwc dlqxgq fxczwl. -xgqgbyhl zhlh b fxyl cltwbybqvil hqjwl xu txffboc-wvol gbyhvod: jxz tylbql bo vohqbotl xu XgqvxoGbyhly, gxgzwbql vq rvqm xgqvxoh, -boc gbyhl qml txffboc wvol. xgqgbyhl bwwxrh zhlyh qx hgltvuj xgqvxoh vo qml txoiloqvxobw DOZ/GXHVA hjoqba, boc bccvqvxobwwj dlolybqlh -zhbdl boc mlwg flhhbdlh uxy jxz. - -Qzjzurae oa u yqre mqhbehoehj, npetodpe, uhv zqkernsp podrurc nqr zuraohw mqyyuhv-pohe qzjoqha jfuh jfe qpv wejqzj yqvspe. -qzjzurae saea u yqre vempurujobe ajcpe qn mqyyuhv-pohe zuraohw: cqs mreuje uh ohajuhme qn QzjoqhZuraer, zqzspuje oj kojf qzjoqha, -uhv zurae jfe mqyyuhv pohe. qzjzurae uppqka saera jq azemonc qzjoqha oh jfe mqhbehjoqhup WHS/ZQAOT achjut, uhv uvvojoqhuppc weherujea -sauwe uhv fepz yeaauwea nqr cqs. - -Jscsnktx ht n rjkx fjauxahxac, gixmhwix, nao sjdxkgli ihwknkv gjk snkthap fjrrnao-ihax jschjat cyna cyx jio pxcjsc rjolix. -jscsnktx ltxt n rjkx oxfinknchux tcvix jg fjrrnao-ihax snkthap: vjl fkxncx na hatcnafx jg JschjaSnktxk, sjslincx hc dhcy jschjat, -nao snktx cyx fjrrnao ihax. jscsnktx niijdt ltxkt cj tsxfhgv jschjat ha cyx fjauxachjani PAL/SJTHM tvacnm, nao noohchjaniiv pxaxkncxt -ltnpx nao yxis rxttnpxt gjk vjl. - -Clvlgdmq am g kcdq yctnqtaqtv, zbqfapbq, gth lcwqdzeb bapdgdo zcd lgdmati yckkgth-batq clvactm vrgt vrq cbh iqvclv kchebq. -clvlgdmq emqm g kcdq hqybgdgvanq mvobq cz yckkgth-batq lgdmati: oce ydqgvq gt atmvgtyq cz ClvactLgdmqd, lclebgvq av wavr clvactm, -gth lgdmq vrq yckkgth batq. clvlgdmq gbbcwm emqdm vc mlqyazo clvactm at vrq yctnqtvactgb ITE/LCMAF motvgf, gth ghhavactgbbo iqtqdgvqm -emgiq gth rqbl kqmmgiqm zcd oce. - -Veoezwfj tf z dvwj rvmgjmtjmo, sujytiuj, zma evpjwsxu utiwzwh svw ezwftmb rvddzma-utmj veotvmf okzm okj vua bjoveo dvaxuj. -veoezwfj xfjf z dvwj ajruzwzotgj fohuj vs rvddzma-utmj ezwftmb: hvx rwjzoj zm tmfozmrj vs VeotvmEzwfjw, evexuzoj to ptok veotvmf, -zma ezwfj okj rvddzma utmj. veoezwfj zuuvpf xfjwf ov fejrtsh veotvmf tm okj rvmgjmotvmzu BMX/EVFTY fhmozy, zma zaatotvmzuuh bjmjwzojf -xfzbj zma kjue djffzbjf svw hvx. - -Oxhxspyc my s wopc kofzcfmcfh, lncrmbnc, sft xoicplqn nmbpspa lop xspymfu kowwsft-nmfc oxhmofy hdsf hdc ont uchoxh wotqnc. -oxhxspyc qycy s wopc tcknspshmzc yhanc ol kowwsft-nmfc xspymfu: aoq kpcshc sf mfyhsfkc ol OxhmofXspycp, xoxqnshc mh imhd oxhmofy, -sft xspyc hdc kowwsft nmfc. oxhxspyc snnoiy qycpy ho yxckmla oxhmofy mf hdc kofzcfhmofsn UFQ/XOYMR yafhsr, sft sttmhmofsnna ucfcpshcy -qysuc sft dcnx wcyysucy lop aoq. - -Hqaqlirv fr l phiv dhysvyfvya, egvkfugv, lym qhbviejg gfuilit ehi qlirfyn dhpplym-gfyv hqafhyr awly awv hgm nvahqa phmjgv. -hqaqlirv jrvr l phiv mvdglilafsv ratgv he dhpplym-gfyv qlirfyn: thj divlav ly fyralydv he HqafhyQlirvi, qhqjglav fa bfaw hqafhyr, -lym qlirv awv dhpplym gfyv. hqaqlirv lgghbr jrvir ah rqvdfet hqafhyr fy awv dhysvyafhylg NYJ/QHRFK rtyalk, lym lmmfafhylggt nvyvilavr -jrlnv lym wvgq pvrrlnvr ehi thj. - -Ajtjebko yk e iabo warloryort, xzodynzo, erf jauobxcz zynbebm xab jebkyrg waiierf-zyro ajtyark tper tpo azf gotajt iafczo. -ajtjebko ckok e iabo fowzebetylo ktmzo ax waiierf-zyro jebkyrg: mac wboeto er yrkterwo ax AjtyarJebkob, jajczeto yt uytp ajtyark, -erf jebko tpo waiierf zyro. ajtjebko ezzauk ckobk ta kjowyxm ajtyark yr tpo warlortyarez GRC/JAKYD kmrted, erf effytyarezzm gorobetok -ckego erf pozj iokkegok xab mac. - -Tcmcxudh rd x btuh ptkehkrhkm, qshwrgsh, xky ctnhuqvs srguxuf qtu cxudrkz ptbbxky-srkh tcmrtkd mixk mih tsy zhmtcm btyvsh. -tcmcxudh vdhd x btuh yhpsxuxmreh dmfsh tq ptbbxky-srkh cxudrkz: ftv puhxmh xk rkdmxkph tq TcmrtkCxudhu, ctcvsxmh rm nrmi tcmrtkd, -xky cxudh mih ptbbxky srkh. tcmcxudh xsstnd vdhud mt dchprqf tcmrtkd rk mih ptkehkmrtkxs ZKV/CTDRW dfkmxw, xky xyyrmrtkxssf zhkhuxmhd -vdxzh xky ihsc bhddxzhd qtu ftv. - -Mvfvqnwa kw q umna imdxadkadf, jlapkzla, qdr vmganjol lkznqny jmn vqnwkds imuuqdr-lkda mvfkmdw fbqd fba mlr safmvf umrola. -mvfvqnwa owaw q umna railqnqfkxa wfyla mj imuuqdr-lkda vqnwkds: ymo inaqfa qd kdwfqdia mj MvfkmdVqnwan, vmvolqfa kf gkfb mvfkmdw, -qdr vqnwa fba imuuqdr lkda. mvfvqnwa qllmgw owanw fm wvaikjy mvfkmdw kd fba imdxadfkmdql SDO/VMWKP wydfqp, qdr qrrkfkmdqlly sadanqfaw -owqsa qdr balv uawwqsaw jmn ymo. - -Foyojgpt dp j nfgt bfwqtwdtwy, cetidset, jwk ofztgche edsgjgr cfg ojgpdwl bfnnjwk-edwt foydfwp yujw yut fek ltyfoy nfkhet. -foyojgpt hptp j nfgt ktbejgjydqt pyret fc bfnnjwk-edwt ojgpdwl: rfh bgtjyt jw dwpyjwbt fc FoydfwOjgptg, ofohejyt dy zdyu foydfwp, -jwk ojgpt yut bfnnjwk edwt. foyojgpt jeefzp hptgp yf potbdcr foydfwp dw yut bfwqtwydfwje LWH/OFPDI prwyji, jwk jkkdydfwjeer ltwtgjytp -hpjlt jwk uteo ntppjltp cfg rfh. - -Yhrhczim wi c gyzm uypjmpwmpr, vxmbwlxm, cpd hysmzvax xwlzczk vyz hcziwpe uyggcpd-xwpm yhrwypi rncp rnm yxd emryhr gydaxm. -yhrhczim aimi c gyzm dmuxczcrwjm irkxm yv uyggcpd-xwpm hcziwpe: kya uzmcrm cp wpircpum yv YhrwypHczimz, hyhaxcrm wr swrn yhrwypi, -cpd hczim rnm uyggcpd xwpm. yhrhczim cxxysi aimzi ry ihmuwvk yhrwypi wp rnm uypjmprwypcx EPA/HYIWB ikprcb, cpd cddwrwypcxxk empmzcrmi -aicem cpd nmxh gmiicemi vyz kya. - -Pasarwhj bh r tpwj npeojebjes, uijkbcij, rey apzjwudi ibcwrwv upw arwhbef npttrey-ibej pasbpeh sqre sqj piy fjspas tpydij. -pasarwhj dhjh r tpwj yjnirwrsboj hsvij pu npttrey-ibej arwhbef: vpd nwjrsj re behsrenj pu PasbpeArwhjw, apadirsj bs zbsq pasbpeh, -rey arwhj sqj npttrey ibej. pasarwhj riipzh dhjwh sp hajnbuv pasbpeh be sqj npeojesbperi FED/APHBK hvesrk, rey ryybsbperiiv fjejwrsjh -dhrfj rey qjia tjhhrfjh upw vpd. - -Sdvduzkm ek u wszm qshrmhemhv, xlmneflm, uhb dscmzxgl lefzuzy xsz duzkehi qswwuhb-lehm sdveshk vtuh vtm slb imvsdv wsbglm. -sdvduzkm gkmk u wszm bmqluzuverm kvylm sx qswwuhb-lehm duzkehi: ysg qzmuvm uh ehkvuhqm sx SdveshDuzkmz, dsdgluvm ev cevt sdveshk, -uhb duzkm vtm qswwuhb lehm. sdvduzkm ullsck gkmzk vs kdmqexy sdveshk eh vtm qshrmhveshul IHG/DSKEN kyhvun, uhb ubbeveshully imhmzuvmk -gkuim uhb tmld wmkkuimk xsz ysg. - -Vgygxcnp hn x zvcp tvkupkhpky, aopqhiop, xke gvfpcajo ohicxcb avc gxcnhkl tvzzxke-ohkp vgyhvkn ywxk ywp voe lpyvgy zvejop. -vgygxcnp jnpn x zvcp eptoxcxyhup nybop va tvzzxke-ohkp gxcnhkl: bvj tcpxyp xk hknyxktp va VgyhvkGxcnpc, gvgjoxyp hy fhyw vgyhvkn, -xke gxcnp ywp tvzzxke ohkp. vgygxcnp xoovfn jnpcn yv ngpthab vgyhvkn hk ywp tvkupkyhvkxo LKJ/GVNHQ nbkyxq, xke xeehyhvkxoob lpkpcxypn -jnxlp xke wpog zpnnxlpn avc bvj. - -Yjbjafqs kq a cyfs wynxsnksnb, drstklrs, anh jyisfdmr rklfafe dyf jafqkno wyccanh-rkns yjbkynq bzan bzs yrh osbyjb cyhmrs. -yjbjafqs mqsq a cyfs hswrafabkxs qbers yd wyccanh-rkns jafqkno: eym wfsabs an knqbanws yd YjbkynJafqsf, jyjmrabs kb ikbz yjbkynq, -anh jafqs bzs wyccanh rkns. yjbjafqs arryiq mqsfq by qjswkde yjbkynq kn bzs wynxsnbkynar ONM/JYQKT qenbat, anh ahhkbkynarre osnsfabsq -mqaos anh zsrj csqqaosq dyf eym. - -Bmemditv nt d fbiv zbqavqnvqe, guvwnouv, dqk mblvigpu unoidih gbi mditnqr zbffdqk-unqv bmenbqt ecdq ecv buk rvebme fbkpuv. -bmemditv ptvt d fbiv kvzudidenav tehuv bg zbffdqk-unqv mditnqr: hbp zivdev dq nqtedqzv bg BmenbqMditvi, mbmpudev ne lnec bmenbqt, -dqk mditv ecv zbffdqk unqv. bmemditv duublt ptvit eb tmvzngh bmenbqt nq ecv zbqavqenbqdu RQP/MBTNW thqedw, dqk dkknenbqduuh rvqvidevt -ptdrv dqk cvum fvttdrvt gbi hbp. - -Ephpglwy qw g iely cetdytqyth, jxyzqrxy, gtn peoyljsx xqrlglk jel pglwqtu ceiigtn-xqty ephqetw hfgt hfy exn uyheph iensxy. -ephpglwy swyw g iely nycxglghqdy whkxy ej ceiigtn-xqty pglwqtu: kes clyghy gt qtwhgtcy ej EphqetPglwyl, pepsxghy qh oqhf ephqetw, -gtn pglwy hfy ceiigtn xqty. ephpglwy gxxeow swylw he wpycqjk ephqetw qt hfy cetdythqetgx UTS/PEWQZ wkthgz, gtn gnnqhqetgxxk uytylghyw -swguy gtn fyxp iywwguyw jel kes. - -Hsksjozb tz j lhob fhwgbwtbwk, mabctuab, jwq shrbomva atuojon mho sjoztwx fhlljwq-atwb hskthwz kijw kib haq xbkhsk lhqvab. -hsksjozb vzbz j lhob qbfajojktgb zknab hm fhlljwq-atwb sjoztwx: nhv fobjkb jw twzkjwfb hm HskthwSjozbo, shsvajkb tk rtki hskthwz, -jwq sjozb kib fhlljwq atwb. hsksjozb jaahrz vzboz kh zsbftmn hskthwz tw kib fhwgbwkthwja XWV/SHZTC znwkjc, jwq jqqtkthwjaan xbwbojkbz -vzjxb jwq ibas lbzzjxbz mho nhv. - -Kvnvmrce wc m okre ikzjezwezn, pdefwxde, mzt vkuerpyd dwxrmrq pkr vmrcwza ikoomzt-dwze kvnwkzc nlmz nle kdt aenkvn oktyde. -kvnvmrce ycec m okre teidmrmnwje cnqde kp ikoomzt-dwze vmrcwza: qky iremne mz wzcnmzie kp KvnwkzVmrcer, vkvydmne wn uwnl kvnwkzc, -mzt vmrce nle ikoomzt dwze. kvnvmrce mddkuc ycerc nk cveiwpq kvnwkzc wz nle ikzjeznwkzmd AZY/VKCWF cqznmf, mzt mttwnwkzmddq aezermnec -ycmae mzt ledv oeccmaec pkr qky. - -Nyqypufh zf p rnuh lncmhczhcq, sghizagh, pcw ynxhusbg gzauput snu ypufzcd lnrrpcw-gzch nyqzncf qopc qoh ngw dhqnyq rnwbgh. -nyqypufh bfhf p rnuh whlgpupqzmh fqtgh ns lnrrpcw-gzch ypufzcd: tnb luhpqh pc zcfqpclh ns NyqzncYpufhu, ynybgpqh zq xzqo nyqzncf, -pcw ypufh qoh lnrrpcw gzch. nyqypufh pggnxf bfhuf qn fyhlzst nyqzncf zc qoh lncmhcqzncpg DCB/YNFZI ftcqpi, pcw pwwzqzncpggt dhchupqhf -bfpdh pcw ohgy rhffpdhf snu tnb. - -Qbtbsxik ci s uqxk oqfpkfckft, vjklcdjk, sfz bqakxvej jcdxsxw vqx bsxicfg oquusfz-jcfk qbtcqfi trsf trk qjz gktqbt uqzejk. -qbtbsxik eiki s uqxk zkojsxstcpk itwjk qv oquusfz-jcfk bsxicfg: wqe oxkstk sf cfitsfok qv QbtcqfBsxikx, bqbejstk ct actr qbtcqfi, -sfz bsxik trk oquusfz jcfk. qbtbsxik sjjqai eikxi tq ibkocvw qbtcqfi cf trk oqfpkftcqfsj GFE/BQICL iwftsl, sfz szzctcqfsjjw gkfkxstki -eisgk sfz rkjb ukiisgki vqx wqe. - -Tewevaln fl v xtan rtisnifniw, ymnofgmn, vic etdnayhm mfgavaz yta evalfij rtxxvic-mfin tewftil wuvi wun tmc jnwtew xtchmn. -tewevaln hlnl v xtan cnrmvavwfsn lwzmn ty rtxxvic-mfin evalfij: zth ranvwn vi filwvirn ty TewftiEvalna, etehmvwn fw dfwu tewftil, -vic evaln wun rtxxvic mfin. tewevaln vmmtdl hlnal wt lenrfyz tewftil fi wun rtisniwftivm JIH/ETLFO lziwvo, vic vccfwftivmmz jninavwnl -hlvjn vic unme xnllvjnl yta zth. - -Whzhydoq io y awdq uwlvqliqlz, bpqrijpq, ylf hwgqdbkp pijdydc bwd hydoilm uwaaylf-pilq whziwlo zxyl zxq wpf mqzwhz awfkpq. -whzhydoq koqo y awdq fqupydyzivq ozcpq wb uwaaylf-pilq hydoilm: cwk udqyzq yl ilozyluq wb WhziwlHydoqd, hwhkpyzq iz gizx whziwlo, -ylf hydoq zxq uwaaylf pilq. whzhydoq yppwgo koqdo zw ohquibc whziwlo il zxq uwlvqlziwlyp MLK/HWOIR oclzyr, ylf yffiziwlyppc mqlqdyzqo -koymq ylf xqph aqooymqo bwd cwk. - -Zkckbgrt lr b dzgt xzoytoltoc, estulmst, boi kzjtgens slmgbgf ezg kbgrlop xzddboi-slot zkclzor cabo cat zsi ptczkc dzinst. -zkckbgrt nrtr b dzgt itxsbgbclyt rcfst ze xzddboi-slot kbgrlop: fzn xgtbct bo lorcboxt ze ZkclzoKbgrtg, kzknsbct lc jlca zkclzor, -boi kbgrt cat xzddboi slot. zkckbgrt bsszjr nrtgr cz rktxlef zkclzor lo cat xzoytoclzobs PON/KZRLU rfocbu, boi biilclzobssf ptotgbctr -nrbpt boi atsk dtrrbptr ezg fzn. - -Cnfnejuw ou e gcjw acrbwrowrf, hvwxopvw, erl ncmwjhqv vopjeji hcj nejuors acggerl-vorw cnfocru fder fdw cvl swfcnf gclqvw. -cnfnejuw quwu e gcjw lwavejefobw ufivw ch acggerl-vorw nejuors: icq ajwefw er oruferaw ch CnfocrNejuwj, ncnqvefw of mofd cnfocru, -erl nejuw fdw acggerl vorw. cnfnejuw evvcmu quwju fc unwaohi cnfocru or fdw acrbwrfocrev SRQ/NCUOX uirfex, erl ellofocrevvi swrwjefwu -quesw erl dwvn gwuueswu hcj icq. - -Fqiqhmxz rx h jfmz dfuezurzui, kyzarsyz, huo qfpzmkty yrsmhml kfm qhmxruv dfjjhuo-yruz fqirfux ighu igz fyo vzifqi jfotyz. -fqiqhmxz txzx h jfmz ozdyhmhirez xilyz fk dfjjhuo-yruz qhmxruv: lft dmzhiz hu ruxihudz fk FqirfuQhmxzm, qfqtyhiz ri prig fqirfux, -huo qhmxz igz dfjjhuo yruz. fqiqhmxz hyyfpx txzmx if xqzdrkl fqirfux ru igz dfuezuirfuhy VUT/QFXRA xluiha, huo hoorirfuhyyl vzuzmhizx -txhvz huo gzyq jzxxhvzx kfm lft. - -Itltkpac ua k mipc gixhcxucxl, nbcduvbc, kxr tiscpnwb buvpkpo nip tkpauxy gimmkxr-buxc itluixa ljkx ljc ibr yclitl mirwbc. -itltkpac waca k mipc rcgbkpkluhc alobc in gimmkxr-buxc tkpauxy: oiw gpcklc kx uxalkxgc in ItluixTkpacp, titwbklc ul sulj itluixa, -kxr tkpac ljc gimmkxr buxc. itltkpac kbbisa wacpa li atcguno itluixa ux ljc gixhcxluixkb YXW/TIAUD aoxlkd, kxr krruluixkbbo ycxcpklca -wakyc kxr jcbt mcaakyca nip oiw. - -Lwownsdf xd n plsf jlakfaxfao, qefgxyef, nau wlvfsqze exysnsr qls wnsdxab jlppnau-exaf lwoxlad omna omf leu bfolwo pluzef. -lwownsdf zdfd n plsf ufjensnoxkf doref lq jlppnau-exaf wnsdxab: rlz jsfnof na xadonajf lq LwoxlaWnsdfs, wlwzenof xo vxom lwoxlad, -nau wnsdf omf jlppnau exaf. lwownsdf neelvd zdfsd ol dwfjxqr lwoxlad xa omf jlakfaoxlane BAZ/WLDXG draong, nau nuuxoxlaneer bfafsnofd -zdnbf nau mfew pfddnbfd qls rlz. - -Ozrzqvgi ag q sovi modnidaidr, thijabhi, qdx zoyivtch habvqvu tov zqvgade mossqdx-hadi ozraodg rpqd rpi ohx eirozr soxchi. -ozrzqvgi cgig q sovi ximhqvqrani gruhi ot mossqdx-hadi zqvgade: uoc mviqri qd adgrqdmi ot OzraodZqvgiv, zozchqri ar yarp ozraodg, -qdx zqvgi rpi mossqdx hadi. ozrzqvgi qhhoyg cgivg ro gzimatu ozraodg ad rpi modnidraodqh EDC/ZOGAJ gudrqj, qdx qxxaraodqhhu eidivqrig -cgqei qdx pihz siggqeig tov uoc. - -Rcuctyjl dj t vryl prgqlgdlgu, wklmdekl, tga crblywfk kdeytyx wry ctyjdgh prvvtga-kdgl rcudrgj ustg usl rka hlurcu vrafkl. -rcuctyjl fjlj t vryl alpktytudql juxkl rw prvvtga-kdgl ctyjdgh: xrf pyltul tg dgjutgpl rw RcudrgCtyjly, crcfktul du bdus rcudrgj, -tga ctyjl usl prvvtga kdgl. rcuctyjl tkkrbj fjlyj ur jclpdwx rcudrgj dg usl prgqlgudrgtk HGF/CRJDM jxgutm, tga taadudrgtkkx hlglytulj -fjthl tga slkc vljjthlj wry xrf. - -Ufxfwbmo gm w yubo sujtojgojx, znopghno, wjd fueobzin nghbwba zub fwbmgjk suyywjd-ngjo ufxgujm xvwj xvo und koxufx yudino. -ufxfwbmo imom w yubo dosnwbwxgto mxano uz suyywjd-ngjo fwbmgjk: aui sbowxo wj gjmxwjso uz UfxgujFwbmob, fufinwxo gx egxv ufxgujm, -wjd fwbmo xvo suyywjd ngjo. ufxfwbmo wnnuem imobm xu mfosgza ufxgujm gj xvo sujtojxgujwn KJI/FUMGP majxwp, wjd wddgxgujwnna kojobwxom -imwko wjd vonf yommwkom zub aui. - -Xiaizepr jp z bxer vxmwrmjrma, cqrsjkqr, zmg ixhreclq qjkezed cxe izepjmn vxbbzmg-qjmr xiajxmp ayzm ayr xqg nraxia bxglqr. -xiaizepr lprp z bxer grvqzezajwr padqr xc vxbbzmg-qjmr izepjmn: dxl verzar zm jmpazmvr xc XiajxmIzepre, ixilqzar ja hjay xiajxmp, -zmg izepr ayr vxbbzmg qjmr. xiaizepr zqqxhp lprep ax pirvjcd xiajxmp jm ayr vxmwrmajxmzq NML/IXPJS pdmazs, zmg zggjajxmzqqd nrmrezarp -lpznr zmg yrqi brppznrp cxe dxl. - -Aldlchsu ms c eahu yapzupmupd, ftuvmntu, cpj lakuhfot tmnhchg fah lchsmpq yaeecpj-tmpu aldmaps dbcp dbu atj qudald eajotu. -aldlchsu osus c eahu juytchcdmzu sdgtu af yaeecpj-tmpu lchsmpq: gao yhucdu cp mpsdcpyu af AldmapLchsuh, lalotcdu md kmdb aldmaps, -cpj lchsu dbu yaeecpj tmpu. aldlchsu cttaks osuhs da sluymfg aldmaps mp dbu yapzupdmapct QPO/LASMV sgpdcv, cpj cjjmdmapcttg qupuhcdus -oscqu cpj butl eusscqus fah gao. - -Dogofkvx pv f hdkx bdscxspxsg, iwxypqwx, fsm odnxkirw wpqkfkj idk ofkvpst bdhhfsm-wpsx dogpdsv gefs gex dwm txgdog hdmrwx. -dogofkvx rvxv f hdkx mxbwfkfgpcx vgjwx di bdhhfsm-wpsx ofkvpst: jdr bkxfgx fs psvgfsbx di DogpdsOfkvxk, odorwfgx pg npge dogpdsv, -fsm ofkvx gex bdhhfsm wpsx. dogofkvx fwwdnv rvxkv gd voxbpij dogpdsv ps gex bdscxsgpdsfw TSR/ODVPY vjsgfy, fsm fmmpgpdsfwwj txsxkfgxv -rvftx fsm exwo hxvvftxv idk jdr. - -Grjrinya sy i kgna egvfavsavj, lzabstza, ivp rgqanluz zstninm lgn rinysvw egkkivp-zsva grjsgvy jhiv jha gzp wajgrj kgpuza. -grjrinya uyay i kgna paezinijsfa yjmza gl egkkivp-zsva rinysvw: mgu enaija iv svyjivea gl GrjsgvRinyan, rgruzija sj qsjh grjsgvy, -ivp rinya jha egkkivp zsva. grjrinya izzgqy uyany jg yraeslm grjsgvy sv jha egvfavjsgviz WVU/RGYSB ymvjib, ivp ippsjsgvizzm wavanijay -uyiwa ivp hazr kayyiway lgn mgu. - -Jumulqbd vb l njqd hjyidyvdym, ocdevwcd, lys ujtdqoxc cvwqlqp ojq ulqbvyz hjnnlys-cvyd jumvjyb mkly mkd jcs zdmjum njsxcd. -jumulqbd xbdb l njqd sdhclqlmvid bmpcd jo hjnnlys-cvyd ulqbvyz: pjx hqdlmd ly vybmlyhd jo JumvjyUlqbdq, ujuxclmd vm tvmk jumvjyb, -lys ulqbd mkd hjnnlys cvyd. jumulqbd lccjtb xbdqb mj budhvop jumvjyb vy mkd hjyidymvjylc ZYX/UJBVE bpymle, lys lssvmvjylccp zdydqlmdb -xblzd lys kdcu ndbblzdb ojq pjx. - -Mxpxoteg ye o qmtg kmblgbygbp, rfghyzfg, obv xmwgtraf fyztots rmt xoteybc kmqqobv-fybg mxpymbe pnob png mfv cgpmxp qmvafg. -mxpxoteg aege o qmtg vgkfotopylg epsfg mr kmqqobv-fybg xoteybc: sma ktgopg ob ybepobkg mr MxpymbXotegt, xmxafopg yp wypn mxpymbe, -obv xoteg png kmqqobv fybg. mxpxoteg offmwe aegte pm exgkyrs mxpymbe yb png kmblgbpymbof CBA/XMEYH esbpoh, obv ovvypymboffs cgbgtopge -aeocg obv ngfx qgeeocge rmt sma. - -Xamahgjt fj h rxgt nxustuftum, wotyfkot, huq axvtgwpo ofkghgb wxg ahgjfuz nxrrhuq-ofut xamfxuj mchu mct xoq ztmxam rxqpot. -xamahgjt pjtj h rxgt qtnohghmfst jmbot xw nxrrhuq-ofut ahgjfuz: bxp ngthmt hu fujmhunt xw XamfxuAhgjtg, axapohmt fm vfmc xamfxuj, -huq ahgjt mct nxrrhuq ofut. xamahgjt hooxvj pjtgj mx jatnfwb xamfxuj fu mct nxustumfxuho ZUP/AXJFY jbumhy, huq hqqfmfxuhoob ztutghmtj -pjhzt huq ctoa rtjjhztj wxg bxp. - -Mpbpwvyi uy w gmvi cmjhijuijb, ldinuzdi, wjf pmkivled duzvwvq lmv pwvyujo cmggwjf-duji mpbumjy brwj bri mdf oibmpb gmfedi. -mpbpwvyi eyiy w gmvi ficdwvwbuhi ybqdi ml cmggwjf-duji pwvyujo: qme cviwbi wj ujybwjci ml MpbumjPwvyiv, pmpedwbi ub kubr mpbumjy, -wjf pwvyi bri cmggwjf duji. mpbpwvyi wddmky eyivy bm ypiculq mpbumjy uj bri cmjhijbumjwd OJE/PMYUN yqjbwn, wjf wffubumjwddq oijivwbiy -eywoi wjf ridp giyywoiy lmv qme. - -Beqelknx jn l vbkx rbywxyjxyq, asxcjosx, lyu ebzxkats sjoklkf abk elknjyd rbvvlyu-sjyx beqjbyn qgly qgx bsu dxqbeq vbutsx. -beqelknx tnxn l vbkx uxrslklqjwx nqfsx ba rbvvlyu-sjyx elknjyd: fbt rkxlqx ly jynqlyrx ba BeqjbyElknxk, ebetslqx jq zjqg beqjbyn, -lyu elknx qgx rbvvlyu sjyx. beqelknx lssbzn tnxkn qb nexrjaf beqjbyn jy qgx rbywxyqjbyls DYT/EBNJC nfyqlc, lyu luujqjbylssf dxyxklqxn -tnldx lyu gxse vxnnldxn abk fbt. - -Qtftazcm yc a kqzm gqnlmnymnf, phmrydhm, anj tqomzpih hydzazu pqz tazcyns gqkkanj-hynm qtfyqnc fvan fvm qhj smfqtf kqjihm. -qtftazcm icmc a kqzm jmghazafylm cfuhm qp gqkkanj-hynm tazcyns: uqi gzmafm an yncfangm qp QtfyqnTazcmz, tqtihafm yf oyfv qtfyqnc, -anj tazcm fvm gqkkanj hynm. qtftazcm ahhqoc icmzc fq ctmgypu qtfyqnc yn fvm gqnlmnfyqnah SNI/TQCYR cunfar, anj ajjyfyqnahhu smnmzafmc -icasm anj vmht kmccasmc pqz uqi. - -Fiuiporb nr p zfob vfcabcnbcu, ewbgnswb, pcy ifdboexw wnsopoj efo ipornch vfzzpcy-wncb fiunfcr ukpc ukb fwy hbufiu zfyxwb. -fiuiporb xrbr p zfob ybvwpopunab rujwb fe vfzzpcy-wncb ipornch: jfx vobpub pc ncrupcvb fe FiunfcIporbo, ifixwpub nu dnuk fiunfcr, -pcy iporb ukb vfzzpcy wncb. fiuiporb pwwfdr xrbor uf ribvnej fiunfcr nc ukb vfcabcunfcpw HCX/IFRNG rjcupg, pcy pyynunfcpwwj hbcbopubr -xrphb pcy kbwi zbrrphbr efo jfx. - -Uxjxedgq cg e oudq kurpqrcqrj, tlqvchlq, ern xusqdtml lchdedy tud xedgcrw kuooern-lcrq uxjcurg jzer jzq uln wqjuxj ounmlq. -uxjxedgq mgqg e oudq nqkledejcpq gjylq ut kuooern-lcrq xedgcrw: yum kdqejq er crgjerkq ut UxjcurXedgqd, xuxmlejq cj scjz uxjcurg, -ern xedgq jzq kuooern lcrq. uxjxedgq ellusg mgqdg ju gxqkcty uxjcurg cr jzq kurpqrjcurel WRM/XUGCV gyrjev, ern enncjcurelly wqrqdejqg -mgewq ern zqlx oqggewqg tud yum. - -Jmymtsvf rv t djsf zjgefgrfgy, iafkrwaf, tgc mjhfsiba arwstsn ijs mtsvrgl zjddtgc-argf jmyrjgv yotg yof jac lfyjmy djcbaf. -jmymtsvf bvfv t djsf cfzatstyref vynaf ji zjddtgc-argf mtsvrgl: njb zsftyf tg rgvytgzf ji JmyrjgMtsvfs, mjmbatyf ry hryo jmyrjgv, -tgc mtsvf yof zjddtgc argf. jmymtsvf taajhv bvfsv yj vmfzrin jmyrjgv rg yof zjgefgyrjgta LGB/MJVRK vngytk, tgc tccryrjgtaan lfgfstyfv -bvtlf tgc ofam dfvvtlfv ijs njb. - -Ybnbihku gk i syhu oyvtuvguvn, xpuzglpu, ivr bywuhxqp pglhihc xyh bihkgva oyssivr-pgvu ybngyvk ndiv ndu ypr aunybn syrqpu. -ybnbihku qkuk i syhu ruopihingtu kncpu yx oyssivr-pgvu bihkgva: cyq ohuinu iv gvknivou yx YbngyvBihkuh, bybqpinu gn wgnd ybngyvk, -ivr bihku ndu oyssivr pgvu. ybnbihku ippywk qkuhk ny kbuogxc ybngyvk gv ndu oyvtuvngyvip AVQ/BYKGZ kcvniz, ivr irrgngyvippc auvuhinuk -qkiau ivr dupb sukkiauk xyh cyq. - -Nqcqxwzj vz x hnwj dnkijkvjkc, mejovaej, xkg qnljwmfe evawxwr mnw qxwzvkp dnhhxkg-evkj nqcvnkz csxk csj neg pjcnqc hngfej. -nqcqxwzj fzjz x hnwj gjdexwxcvij zcrej nm dnhhxkg-evkj qxwzvkp: rnf dwjxcj xk vkzcxkdj nm NqcvnkQxwzjw, qnqfexcj vc lvcs nqcvnkz, -xkg qxwzj csj dnhhxkg evkj. nqcqxwzj xeenlz fzjwz cn zqjdvmr nqcvnkz vk csj dnkijkcvnkxe PKF/QNZVO zrkcxo, xkg xggvcvnkxeer pjkjwxcjz -fzxpj xkg sjeq hjzzxpjz mnw rnf. - -Cfrfmloy ko m wcly sczxyzkyzr, btydkpty, mzv fcaylbut tkplmlg bcl fmlokze scwwmzv-tkzy cfrkczo rhmz rhy ctv eyrcfr wcvuty. -cfrfmloy uoyo m wcly vystmlmrkxy orgty cb scwwmzv-tkzy fmlokze: gcu slymry mz kzormzsy cb CfrkczFmloyl, fcfutmry kr akrh cfrkczo, -mzv fmloy rhy scwwmzv tkzy. cfrfmloy mttcao uoylo rc ofyskbg cfrkczo kz rhy sczxyzrkczmt EZU/FCOKD ogzrmd, mzv mvvkrkczmttg eyzylmryo -uomey mzv hytf wyoomeyo bcl gcu. - -Rugubadn zd b lran hromnoznog, qinszein, bok urpnaqji izeabav qra ubadzot hrllbok-izon rugzrod gwbo gwn rik tngrug lrkjin. -rugubadn jdnd b lran knhibabgzmn dgvin rq hrllbok-izon ubadzot: vrj hanbgn bo zodgbohn rq RugzroUbadna, urujibgn zg pzgw rugzrod, -bok ubadn gwn hrllbok izon. rugubadn biirpd jdnad gr dunhzqv rugzrod zo gwn hromnogzrobi TOJ/URDZS dvogbs, bok bkkzgzrobiiv tnonabgnd -jdbtn bok wniu lnddbtnd qra vrj. - -Gjvjqpsc os q agpc wgdbcdocdv, fxchotxc, qdz jgecpfyx xotpqpk fgp jqpsodi wgaaqdz-xodc gjvogds vlqd vlc gxz icvgjv agzyxc. -gjvjqpsc yscs q agpc zcwxqpqvobc svkxc gf wgaaqdz-xodc jqpsodi: kgy wpcqvc qd odsvqdwc gf GjvogdJqpscp, jgjyxqvc ov eovl gjvogds, -qdz jqpsc vlc wgaaqdz xodc. gjvjqpsc qxxges yscps vg sjcwofk gjvogds od vlc wgdbcdvogdqx IDY/JGSOH skdvqh, qdz qzzovogdqxxk icdcpqvcs -ysqic qdz lcxj acssqics fgp kgy. - -Vykyfehr dh f pver lvsqrsdrsk, umrwdimr, fso yvtreunm mdiefez uve yfehdsx lvppfso-mdsr vykdvsh kafs kar vmo xrkvyk pvonmr. -vykyfehr nhrh f pver orlmfefkdqr hkzmr vu lvppfso-mdsr yfehdsx: zvn lerfkr fs dshkfslr vu VykdvsYfehre, yvynmfkr dk tdka vykdvsh, -fso yfehr kar lvppfso mdsr. vykyfehr fmmvth nhreh kv hyrlduz vykdvsh ds kar lvsqrskdvsfm XSN/YVHDW hzskfw, fso foodkdvsfmmz xrsrefkrh -nhfxr fso army prhhfxrh uve zvn. - -Knznutwg sw u ektg akhfghsghz, jbglsxbg, uhd nkigtjcb bsxtuto jkt nutwshm akeeuhd-bshg knzskhw zpuh zpg kbd mgzknz ekdcbg. -knznutwg cwgw u ektg dgabutuzsfg wzobg kj akeeuhd-bshg nutwshm: okc atguzg uh shwzuhag kj KnzskhNutwgt, nkncbuzg sz iszp knzskhw, -uhd nutwg zpg akeeuhd bshg. knznutwg ubbkiw cwgtw zk wngasjo knzskhw sh zpg akhfghzskhub MHC/NKWSL wohzul, uhd uddszskhubbo mghgtuzgw -cwumg uhd pgbn egwwumgw jkt okc. - -Zcocjilv hl j tziv pzwuvwhvwo, yqvahmqv, jws czxviyrq qhmijid yzi cjilhwb pzttjws-qhwv zcohzwl oejw oev zqs bvozco tzsrqv. -zcocjilv rlvl j tziv svpqjijohuv lodqv zy pzttjws-qhwv cjilhwb: dzr pivjov jw hwlojwpv zy ZcohzwCjilvi, czcrqjov ho xhoe zcohzwl, -jws cjilv oev pzttjws qhwv. zcocjilv jqqzxl rlvil oz lcvphyd zcohzwl hw oev pzwuvwohzwjq BWR/CZLHA ldwoja, jws jsshohzwjqqd bvwvijovl -rljbv jws evqc tvlljbvl yzi dzr. - -Ordryxak wa y ioxk eoljklwkld, nfkpwbfk, ylh romkxngf fwbxyxs nox ryxawlq eoiiylh-fwlk ordwola dtyl dtk ofh qkdord iohgfk. -ordryxak gaka y ioxk hkefyxydwjk adsfk on eoiiylh-fwlk ryxawlq: sog exkydk yl wladylek on OrdwolRyxakx, rorgfydk wd mwdt ordwola, -ylh ryxak dtk eoiiylh fwlk. ordryxak yffoma gakxa do arkewns ordwola wl dtk eoljkldwolyf QLG/ROAWP asldyp, ylh yhhwdwolyffs qklkxydka -gayqk ylh tkfr ikaayqka nox sog. - -Dgsgnmpz lp n xdmz tdayzalzas, cuzelquz, naw gdbzmcvu ulqmnmh cdm gnmplaf tdxxnaw-ulaz dgsldap sina siz duw fzsdgs xdwvuz. -dgsgnmpz vpzp n xdmz wztunmnslyz pshuz dc tdxxnaw-ulaz gnmplaf: hdv tmznsz na lapsnatz dc DgsldaGnmpzm, gdgvunsz ls blsi dgsldap, -naw gnmpz siz tdxxnaw ulaz. dgsgnmpz nuudbp vpzmp sd pgztlch dgsldap la siz tdayzasldanu FAV/GDPLE phasne, naw nwwlsldanuuh fzazmnszp -vpnfz naw izug xzppnfzp cdm hdv. - -Svhvcbeo ae c msbo ispnopaoph, rjotafjo, cpl vsqobrkj jafbcbw rsb vcbeapu ismmcpl-japo svhaspe hxcp hxo sjl uohsvh mslkjo. -svhvcbeo keoe c msbo loijcbchano ehwjo sr ismmcpl-japo vcbeapu: wsk ibocho cp apehcpio sr SvhaspVcbeob, vsvkjcho ah qahx svhaspe, -cpl vcbeo hxo ismmcpl japo. svhvcbeo cjjsqe keobe hs evoiarw svhaspe ap hxo ispnophaspcj UPK/VSEAT ewphct, cpl cllahaspcjjw uopobchoe -kecuo cpl xojv moeecuoe rsb wsk. - -Hkwkrqtd pt r bhqd xhecdepdew, gydipuyd, rea khfdqgzy ypuqrql ghq krqtpej xhbbrea-yped hkwphet wmre wmd hya jdwhkw bhazyd. -hkwkrqtd ztdt r bhqd adxyrqrwpcd twlyd hg xhbbrea-yped krqtpej: lhz xqdrwd re petwrexd hg HkwpheKrqtdq, khkzyrwd pw fpwm hkwphet, -rea krqtd wmd xhbbrea yped. hkwkrqtd ryyhft ztdqt wh tkdxpgl hkwphet pe wmd xhecdewphery JEZ/KHTPI tlewri, rea raapwpheryyl jdedqrwdt -ztrjd rea mdyk bdttrjdt ghq lhz. - -Wzlzgfis ei g qwfs mwtrstestl, vnsxejns, gtp zwusfvon nejfgfa vwf zgfiety mwqqgtp-nets wzlewti lbgt lbs wnp yslwzl qwpons. -wzlzgfis oisi g qwfs psmngfglers ilans wv mwqqgtp-nets zgfiety: awo mfsgls gt etilgtms wv WzlewtZgfisf, zwzongls el uelb wzlewti, -gtp zgfis lbs mwqqgtp nets. wzlzgfis gnnwui oisfi lw izsmeva wzlewti et lbs mwtrstlewtgn YTO/ZWIEX iatlgx, gtp gppelewtgnna ystsfglsi -oigys gtp bsnz qsiigysi vwf awo. - -Loaovuxh tx v fluh blighithia, kchmtych, vie oljhukdc ctyuvup klu ovuxtin blffvie-ctih loatlix aqvi aqh lce nhaloa fledch. -loaovuxh dxhx v fluh ehbcvuvatgh xapch lk blffvie-ctih ovuxtin: pld buhvah vi tixavibh lk LoatliOvuxhu, olodcvah ta jtaq loatlix, -vie ovuxh aqh blffvie ctih. loaovuxh vccljx dxhux al xohbtkp loatlix ti aqh blighiatlivc NID/OLXTM xpiavm, vie veetatlivccp nhihuvahx -dxvnh vie qhco fhxxvnhx klu pld. - -Adpdkjmw im k uajw qaxvwxiwxp, zrwbinrw, kxt daywjzsr rinjkje zaj dkjmixc qauukxt-rixw adpiaxm pfkx pfw art cwpadp uatsrw. -adpdkjmw smwm k uajw twqrkjkpivw mperw az qauukxt-rixw dkjmixc: eas qjwkpw kx ixmpkxqw az AdpiaxDkjmwj, dadsrkpw ip yipf adpiaxm, -kxt dkjmw pfw qauukxt rixw. adpdkjmw krraym smwjm pa mdwqize adpiaxm ix pfw qaxvwxpiaxkr CXS/DAMIB mexpkb, kxt kttipiaxkrre cwxwjkpwm -smkcw kxt fwrd uwmmkcwm zaj eas. - -Pseszybl xb z jpyl fpmklmxlme, oglqxcgl, zmi spnlyohg gxcyzyt opy szybxmr fpjjzmi-gxml psexpmb euzm eul pgi rlepse jpihgl. -pseszybl hblb z jpyl ilfgzyzexkl betgl po fpjjzmi-gxml szybxmr: tph fylzel zm xmbezmfl po PsexpmSzybly, spshgzel xe nxeu psexpmb, -zmi szybl eul fpjjzmi gxml. pseszybl zggpnb hblyb ep bslfxot psexpmb xm eul fpmklmexpmzg RMH/SPBXQ btmezq, zmi ziixexpmzggt rlmlyzelb -hbzrl zmi ulgs jlbbzrlb opy tph. - -Ehthonqa mq o yena uebzabmabt, dvafmrva, obx hecandwv vmrnoni den honqmbg ueyyobx-vmba ehtmebq tjob tja evx gateht yexwva. -ehthonqa wqaq o yena xauvonotmza qtiva ed ueyyobx-vmba honqmbg: iew unaota ob mbqtobua ed EhtmebHonqan, hehwvota mt cmtj ehtmebq, -obx honqa tja ueyyobx vmba. ehthonqa ovvecq wqanq te qhaumdi ehtmebq mb tja uebzabtmebov GBW/HEQMF qibtof, obx oxxmtmebovvi gabanotaq -wqoga obx javh yaqqogaq den iew. - -Twiwdcfp bf d ntcp jtqopqbpqi, skpubgkp, dqm wtrpcslk kbgcdcx stc wdcfbqv jtnndqm-kbqp twibtqf iydq iyp tkm vpitwi ntmlkp. -twiwdcfp lfpf d ntcp mpjkdcdibop fixkp ts jtnndqm-kbqp wdcfbqv: xtl jcpdip dq bqfidqjp ts TwibtqWdcfpc, wtwlkdip bi rbiy twibtqf, -dqm wdcfp iyp jtnndqm kbqp. twiwdcfp dkktrf lfpcf it fwpjbsx twibtqf bq iyp jtqopqibtqdk VQL/WTFBU fxqidu, dqm dmmbibtqdkkx vpqpcdipf -lfdvp dqm ypkw npffdvpf stc xtl. - -Ilxlsrue qu s cire yifdefqefx, hzejqvze, sfb ligerhaz zqvrsrm hir lsruqfk yiccsfb-zqfe ilxqifu xnsf xne izb kexilx cibaze. -ilxlsrue aueu s cire beyzsrsxqde uxmze ih yiccsfb-zqfe lsruqfk: mia yresxe sf qfuxsfye ih IlxqifLsruer, lilazsxe qx gqxn ilxqifu, -sfb lsrue xne yiccsfb zqfe. ilxlsrue szzigu aueru xi uleyqhm ilxqifu qf xne yifdefxqifsz KFA/LIUQJ umfxsj, sfb sbbqxqifszzm kefersxeu -auske sfb nezl ceuuskeu hir mia. - -Bawapyxl hx p dbyl nbculchlcw, kelshoel, pcm abtlykve ehoypyr kby apyxhcj nbddpcm-ehcl bawhbcx wipc wil bem jlwbaw dbmvel. -bawapyxl vxlx p dbyl mlnepypwhul xwrel bk nbddpcm-ehcl apyxhcj: rbv nylpwl pc hcxwpcnl bk BawhbcApyxly, abavepwl hw thwi bawhbcx, -pcm apyxl wil nbddpcm ehcl. bawapyxl peebtx vxlyx wb xalnhkr bawhbcx hc wil nbculcwhbcpe JCV/ABXHS xrcwps, pcm pmmhwhbcpeer jlclypwlx -vxpjl pcm ilea dlxxpjlx kby rbv. - -Wvrvktsg cs k ywtg iwxpgxcgxr, fzgncjzg, kxh vwogtfqz zcjtktm fwt vktscxe iwyykxh-zcxg wvrcwxs rdkx rdg wzh egrwvr ywhqzg. -wvrvktsg qsgs k ywtg hgizktkrcpg srmzg wf iwyykxh-zcxg vktscxe: mwq itgkrg kx cxsrkxig wf WvrcwxVktsgt, vwvqzkrg cr ocrd wvrcwxs, -kxh vktsg rdg iwyykxh zcxg. wvrvktsg kzzwos qsgts rw svgicfm wvrcwxs cx rdg iwxpgxrcwxkz EXQ/VWSCN smxrkn, kxh khhcrcwxkzzm egxgtkrgs -qskeg kxh dgzv ygsskegs fwt mwq. - -Rqmqfonb xn f trob drskbsxbsm, aubixeub, fsc qrjboalu uxeofoh aro qfonxsz drttfsc-uxsb rqmxrsn myfs myb ruc zbmrqm trclub. -rqmqfonb lnbn f trob cbdufofmxkb nmhub ra drttfsc-uxsb qfonxsz: hrl dobfmb fs xsnmfsdb ra RqmxrsQfonbo, qrqlufmb xm jxmy rqmxrsn, -fsc qfonb myb drttfsc uxsb. rqmqfonb fuurjn lnbon mr nqbdxah rqmxrsn xs myb drskbsmxrsfu ZSL/QRNXI nhsmfi, fsc fccxmxrsfuuh zbsbofmbn -lnfzb fsc ybuq tbnnfzbn aro hrl. - -Mlhlajiw si a omjw ymnfwnswnh, vpwdszpw, anx lmewjvgp pszjajc vmj lajisnu ymooanx-psnw mlhsmni htan htw mpx uwhmlh omxgpw. -mlhlajiw giwi a omjw xwypajahsfw ihcpw mv ymooanx-psnw lajisnu: cmg yjwahw an snihanyw mv MlhsmnLajiwj, lmlgpahw sh esht mlhsmni, -anx lajiw htw ymooanx psnw. mlhlajiw appmei giwji hm ilwysvc mlhsmni sn htw ymnfwnhsmnap UNG/LMISD icnhad, anx axxshsmnappc uwnwjahwi -giauw anx twpl owiiauwi vmj cmg. - -Hgcgvedr nd v jher thiarinric, qkrynukr, vis ghzreqbk knuevex qhe gvednip thjjvis-knir hgcnhid covi cor hks prchgc jhsbkr. -hgcgvedr bdrd v jher srtkvevcnar dcxkr hq thjjvis-knir gvednip: xhb tervcr vi nidcvitr hq HgcnhiGvedre, ghgbkvcr nc znco hgcnhid, -vis gvedr cor thjjvis knir. hgcgvedr vkkhzd bdred ch dgrtnqx hgcnhid ni cor thiaricnhivk PIB/GHDNY dxicvy, vis vssncnhivkkx prirevcrd -bdvpr vis orkg jrddvprd qhe xhb. - -Cbxbqzym iy q eczm ocdvmdimdx, lfmtipfm, qdn bcumzlwf fipzqzs lcz bqzyidk oceeqdn-fidm cbxicdy xjqd xjm cfn kmxcbx ecnwfm. -cbxbqzym wymy q eczm nmofqzqxivm yxsfm cl oceeqdn-fidm bqzyidk: scw ozmqxm qd idyxqdom cl CbxicdBqzymz, bcbwfqxm ix uixj cbxicdy, -qdn bqzym xjm oceeqdn fidm. cbxbqzym qffcuy wymzy xc ybmoils cbxicdy id xjm ocdvmdxicdqf KDW/BCYIT ysdxqt, qdn qnnixicdqffs kmdmzqxmy -wyqkm qdn jmfb emyyqkmy lcz scw. - -Xwswluth dt l zxuh jxyqhydhys, gahodkah, lyi wxphugra adkulun gxu wlutdyf jxzzlyi-adyh xwsdxyt sely seh xai fhsxws zxirah. -xwswluth rtht l zxuh ihjalulsdqh tsnah xg jxzzlyi-adyh wlutdyf: nxr juhlsh ly dytslyjh xg XwsdxyWluthu, wxwralsh ds pdse xwsdxyt, -lyi wluth seh jxzzlyi adyh. xwswluth laaxpt rthut sx twhjdgn xwsdxyt dy seh jxyqhysdxyla FYR/WXTDO tnyslo, lyi liidsdxylaan fhyhulsht -rtlfh lyi ehaw zhttlfht gxu nxr. - -Srnrgpoc yo g uspc estlctyctn, bvcjyfvc, gtd rskcpbmv vyfpgpi bsp rgpoyta esuugtd-vytc srnysto nzgt nzc svd acnsrn usdmvc. -srnrgpoc moco g uspc dcevgpgnylc onivc sb esuugtd-vytc rgpoyta: ism epcgnc gt ytongtec sb SrnystRgpocp, rsrmvgnc yn kynz srnysto, -gtd rgpoc nzc esuugtd vytc. srnrgpoc gvvsko mocpo ns orceybi srnysto yt nzc estlctnystgv ATM/RSOYJ oitngj, gtd gddynystgvvi actcpgnco -mogac gtd zcvr ucoogaco bsp ism. - -Nmimbkjx tj b pnkx znogxotxoi, wqxetaqx, boy mnfxkwhq qtakbkd wnk mbkjtov znppboy-qtox nmitnoj iubo iux nqy vxinmi pnyhqx. -nmimbkjx hjxj b pnkx yxzqbkbitgx jidqx nw znppboy-qtox mbkjtov: dnh zkxbix bo tojibozx nw NmitnoMbkjxk, mnmhqbix ti ftiu nmitnoj, -boy mbkjx iux znppboy qtox. nmimbkjx bqqnfj hjxkj in jmxztwd nmitnoj to iux znogxoitnobq VOH/MNJTE jdoibe, boy byytitnobqqd vxoxkbixj -hjbvx boy uxqm pxjjbvxj wnk dnh. - -Ihdhwfes oe w kifs uijbsjosjd, rlszovls, wjt hiasfrcl lovfwfy rif hwfeojq uikkwjt-lojs ihdoije dpwj dps ilt qsdihd kitcls. -ihdhwfes cese w kifs tsulwfwdobs edyls ir uikkwjt-lojs hwfeojq: yic ufswds wj ojedwjus ir IhdoijHwfesf, hihclwds od aodp ihdoije, -wjt hwfes dps uikkwjt lojs. ihdhwfes wlliae cesfe di ehsuory ihdoije oj dps uijbsjdoijwl QJC/HIEOZ eyjdwz, wjt wttodoijwlly qsjsfwdse -cewqs wjt pslh kseewqse rif yic. - -Dcycrazn jz r fdan pdewnejney, mgnujqgn, reo cdvnamxg gjqarat mda crazjel pdffreo-gjen dcyjdez ykre ykn dgo lnydcy fdoxgn. -dcycrazn xznz r fdan onpgraryjwn zytgn dm pdffreo-gjen crazjel: tdx panryn re jezyrepn dm DcyjdeCrazna, cdcxgryn jy vjyk dcyjdez, -reo crazn ykn pdffreo gjen. dcycrazn rggdvz xznaz yd zcnpjmt dcyjdez je ykn pdewneyjderg LEX/CDZJU zteyru, reo roojyjderggt lnenarynz -xzrln reo kngc fnzzrlnz mda tdx. - -Yxtxmvui eu m ayvi kyzrizeizt, hbipelbi, mzj xyqivhsb belvmvo hyv xmvuezg kyaamzj-bezi yxteyzu tfmz tfi ybj gityxt ayjsbi. -yxtxmvui suiu m ayvi jikbmvmteri utobi yh kyaamzj-bezi xmvuezg: oys kvimti mz ezutmzki yh YxteyzXmvuiv, xyxsbmti et qetf yxteyzu, -mzj xmvui tfi kyaamzj bezi. yxtxmvui mbbyqu suivu ty uxikeho yxteyzu ez tfi kyzrizteyzmb GZS/XYUEP uoztmp, mzj mjjeteyzmbbo gizivmtiu -sumgi mzj fibx aiuumgiu hyv oys. - -Tsoshqpd zp h vtqd ftumduzduo, cwdkzgwd, hue stldqcnw wzgqhqj ctq shqpzub ftvvhue-wzud tsoztup oahu oad twe bdotso vtenwd. -tsoshqpd npdp h vtqd edfwhqhozmd pojwd tc ftvvhue-wzud shqpzub: jtn fqdhod hu zupohufd tc TsoztuShqpdq, stsnwhod zo lzoa tsoztup, -hue shqpd oad ftvvhue wzud. tsoshqpd hwwtlp npdqp ot psdfzcj tsoztup zu oad ftumduoztuhw BUN/STPZK pjuohk, hue heezoztuhwwj bdudqhodp -nphbd hue adws vdpphbdp ctq jtn. - -Onjnclky uk c qoly aophypuypj, xryfubry, cpz nogylxir rublcle xol nclkupw aoqqcpz-rupy onjuopk jvcp jvy orz wyjonj qoziry. -onjnclky ikyk c qoly zyarclcjuhy kjery ox aoqqcpz-rupy nclkupw: eoi alycjy cp upkjcpay ox OnjuopNclkyl, nonircjy uj gujv onjuopk, -cpz nclky jvy aoqqcpz rupy. onjnclky crrogk ikylk jo knyauxe onjuopk up jvy aophypjuopcr WPI/NOKUF kepjcf, cpz czzujuopcrre wypylcjyk -ikcwy cpz vyrn qykkcwyk xol eoi. - -Jieixgft pf x ljgt vjkctkptke, smtapwmt, xku ijbtgsdm mpwgxgz sjg ixgfpkr vjllxku-mpkt jiepjkf eqxk eqt jmu rtejie ljudmt. -jieixgft dftf x ljgt utvmxgxepct fezmt js vjllxku-mpkt ixgfpkr: zjd vgtxet xk pkfexkvt js JiepjkIxgftg, ijidmxet pe bpeq jiepjkf, -xku ixgft eqt vjllxku mpkt. jieixgft xmmjbf dftgf ej fitvpsz jiepjkf pk eqt vjkctkepjkxm RKD/IJFPA fzkexa, xku xuupepjkxmmz rtktgxetf -dfxrt xku qtmi ltffxrtf sjg zjd. - -Edzdsbao ka s gebo qefxofkofz, nhovkrho, sfp dewobnyh hkrbsbu neb dsbakfm qeggsfp-hkfo edzkefa zlsf zlo ehp mozedz gepyho. -edzdsbao yaoa s gebo poqhsbszkxo azuho en qeggsfp-hkfo dsbakfm: uey qboszo sf kfazsfqo en EdzkefDsbaob, dedyhszo kz wkzl edzkefa, -sfp dsbao zlo qeggsfp hkfo. edzdsbao shhewa yaoba ze adoqknu edzkefa kf zlo qefxofzkefsh MFY/DEAKV aufzsv, sfp sppkzkefshhu mofobszoa -yasmo sfp lohd goaasmoa neb uey. - -Zyuynwvj fv n bzwj lzasjafjau, icjqfmcj, nak yzrjwitc cfmwnwp izw ynwvfah lzbbnak-cfaj zyufzav ugna ugj zck hjuzyu bzktcj. -zyuynwvj tvjv n bzwj kjlcnwnufsj vupcj zi lzbbnak-cfaj ynwvfah: pzt lwjnuj na favunalj zi ZyufzaYnwvjw, yzytcnuj fu rfug zyufzav, -nak ynwvj ugj lzbbnak cfaj. zyuynwvj ncczrv tvjwv uz vyjlfip zyufzav fa ugj lzasjaufzanc HAT/YZVFQ vpaunq, nak nkkfufzanccp hjajwnujv -tvnhj nak gjcy bjvvnhjv izw pzt. - -Utptirqe aq i wure guvnevaevp, dxelahxe, ivf tumerdox xahrirk dur tirqavc guwwivf-xave utpauvq pbiv pbe uxf ceputp wufoxe. -utptirqe oqeq i wure fegxiripane qpkxe ud guwwivf-xave tirqavc: kuo greipe iv avqpivge ud UtpauvTirqer, tutoxipe ap mapb utpauvq, -ivf tirqe pbe guwwivf xave. utptirqe ixxumq oqerq pu qtegadk utpauvq av pbe guvnevpauvix CVO/TUQAL qkvpil, ivf iffapauvixxk ceveripeq -oqice ivf bext weqqiceq dur kuo. - -Pokodmlz vl d rpmz bpqizqvzqk, yszgvcsz, dqa ophzmyjs svcmdmf ypm odmlvqx bprrdqa-svqz pokvpql kwdq kwz psa xzkpok rpajsz. -pokodmlz jlzl d rpmz azbsdmdkviz lkfsz py bprrdqa-svqz odmlvqx: fpj bmzdkz dq vqlkdqbz py PokvpqOdmlzm, opojsdkz vk hvkw pokvpql, -dqa odmlz kwz bprrdqa svqz. pokodmlz dssphl jlzml kp lozbvyf pokvpql vq kwz bpqizqkvpqds XQJ/OPLVG lfqkdg, dqa daavkvpqdssf xzqzmdkzl -jldxz dqa wzso rzlldxzl ypm fpj. - -Kjfjyhgu qg y mkhu wkldulqulf, tnubqxnu, ylv jkcuhten nqxhyha tkh jyhgqls wkmmylv-nqlu kjfqklg fryl fru knv sufkjf mkvenu. -kjfjyhgu egug y mkhu vuwnyhyfqdu gfanu kt wkmmylv-nqlu jyhgqls: ake whuyfu yl qlgfylwu kt KjfqklJyhguh, jkjenyfu qf cqfr kjfqklg, -ylv jyhgu fru wkmmylv nqlu. kjfjyhgu ynnkcg eguhg fk gjuwqta kjfqklg ql fru wkldulfqklyn SLE/JKGQB galfyb, ylv yvvqfqklynna suluhyfug -egysu ylv runj muggysug tkh ake. - -Feaetcbp lb t hfcp rfgypglpga, oipwlsip, tgq efxpcozi ilsctcv ofc etcblgn rfhhtgq-ilgp fealfgb amtg amp fiq npafea hfqzip. -feaetcbp zbpb t hfcp qpritctalyp bavip fo rfhhtgq-ilgp etcblgn: vfz rcptap tg lgbatgrp fo FealfgEtcbpc, efezitap la xlam fealfgb, -tgq etcbp amp rfhhtgq ilgp. feaetcbp tiifxb zbpcb af beprlov fealfgb lg amp rfgypgalfgti NGZ/EFBLW bvgatw, tgq tqqlalfgtiiv npgpctapb -zbtnp tgq mpie hpbbtnpb ofc vfz. - -Azvzoxwk gw o caxk mabtkbgkbv, jdkrgndk, obl zaskxjud dgnxoxq jax zoxwgbi maccobl-dgbk azvgabw vhob vhk adl ikvazv caludk. -azvzoxwk uwkw o caxk lkmdoxovgtk wvqdk aj maccobl-dgbk zoxwgbi: qau mxkovk ob gbwvobmk aj AzvgabZoxwkx, zazudovk gv sgvh azvgabw, -obl zoxwk vhk maccobl dgbk. azvzoxwk oddasw uwkxw va wzkmgjq azvgabw gb vhk mabtkbvgabod IBU/ZAWGR wqbvor, obl ollgvgaboddq ikbkxovkw -uwoik obl hkdz ckwwoikw jax qau. - -Vuqujsrf br j xvsf hvwofwbfwq, eyfmbiyf, jwg uvnfsepy ybisjsl evs ujsrbwd hvxxjwg-ybwf vuqbvwr qcjw qcf vyg dfqvuq xvgpyf. -vuqujsrf prfr j xvsf gfhyjsjqbof rqlyf ve hvxxjwg-ybwf ujsrbwd: lvp hsfjqf jw bwrqjwhf ve VuqbvwUjsrfs, uvupyjqf bq nbqc vuqbvwr, -jwg ujsrf qcf hvxxjwg ybwf. vuqujsrf jyyvnr prfsr qv rufhbel vuqbvwr bw qcf hvwofwqbvwjy DWP/UVRBM rlwqjm, jwg jggbqbvwjyyl dfwfsjqfr -prjdf jwg cfyu xfrrjdfr evs lvp. - -Qplpenma wm e sqna cqrjarwarl, ztahwdta, erb pqianzkt twdneng zqn penmwry cqsserb-twra qplwqrm lxer lxa qtb yalqpl sqbkta. -qplpenma kmam e sqna bactenelwja mlgta qz cqsserb-twra penmwry: gqk cnaela er wrmlerca qz QplwqrPenman, pqpktela wl iwlx qplwqrm, -erb penma lxa cqsserb twra. qplpenma ettqim kmanm lq mpacwzg qplwqrm wr lxa cqrjarlwqret YRK/PQMWH mgrleh, erb ebbwlwqrettg yaranelam -kmeya erb xatp sammeyam zqn gqk. - -Lkgkzihv rh z nliv xlmevmrvmg, uovcryov, zmw kldviufo oryizib uli kzihrmt xlnnzmw-ormv lkgrlmh gszm gsv low tvglkg nlwfov. -lkgkzihv fhvh z nliv wvxozizgrev hgbov lu xlnnzmw-ormv kzihrmt: blf xivzgv zm rmhgzmxv lu LkgrlmKzihvi, klkfozgv rg drgs lkgrlmh, -zmw kzihv gsv xlnnzmw ormv. lkgkzihv zooldh fhvih gl hkvxrub lkgrlmh rm gsv xlmevmgrlmzo TMF/KLHRC hbmgzc, zmw zwwrgrlmzoob tvmvizgvh -fhztv zmw svok nvhhztvh uli blf. - -Gfbfudcq mc u igdq sghzqhmqhb, pjqxmtjq, uhr fgyqdpaj jmtdudw pgd fudcmho sgiiuhr-jmhq gfbmghc bnuh bnq gjr oqbgfb igrajq. -gfbfudcq acqc u igdq rqsjudubmzq cbwjq gp sgiiuhr-jmhq fudcmho: wga sdqubq uh mhcbuhsq gp GfbmghFudcqd, fgfajubq mb ymbn gfbmghc, -uhr fudcq bnq sgiiuhr jmhq. gfbfudcq ujjgyc acqdc bg cfqsmpw gfbmghc mh bnq sghzqhbmghuj OHA/FGCMX cwhbux, uhr urrmbmghujjw oqhqdubqc -acuoq uhr nqjf iqccuoqc pgd wga. - -Tacazovb dv z ftob ntmqbmdbmc, iybedgyb, zmu atxboijy ydgozol ito azovdmp ntffzmu-ydmb tacdtmv cwzm cwb tyu pbctac ftujyb. -tacazovb jvbv z ftob ubnyzozcdqb vclyb ti ntffzmu-ydmb azovdmp: ltj nobzcb zm dmvczmnb ti TacdtmAzovbo, atajyzcb dc xdcw tacdtmv, -zmu azovb cwb ntffzmu ydmb. tacazovb zyytxv jvbov ct vabndil tacdtmv dm cwb ntmqbmcdtmzy PMJ/ATVDE vlmcze, zmu zuudcdtmzyyl pbmbozcbv -jvzpb zmu wbya fbvvzpbv ito ltj. - -Cjljixek me i ocxk wcvzkvmkvl, rhknmphk, ivd jcgkxrsh hmpxixu rcx jixemvy wcooivd-hmvk cjlmcve lfiv lfk chd yklcjl ocdshk. -cjljixek seke i ocxk dkwhixilmzk eluhk cr wcooivd-hmvk jixemvy: ucs wxkilk iv mvelivwk cr CjlmcvJixekx, jcjshilk ml gmlf cjlmcve, -ivd jixek lfk wcooivd hmvk. cjljixek ihhcge sekxe lc ejkwmru cjlmcve mv lfk wcvzkvlmcvih YVS/JCEMN euvlin, ivd iddmlmcvihhu ykvkxilke -seiyk ivd fkhj okeeiyke rcx ucs. - -Lsusrgnt vn r xlgt fleitevteu, aqtwvyqt, rem slptgabq qvygrgd alg srgnveh flxxrem-qvet lsuvlen uore uot lqm htulsu xlmbqt. -lsusrgnt bntn r xlgt mtfqrgruvit nudqt la flxxrem-qvet srgnveh: dlb fgtrut re venureft la LsuvleSrgntg, slsbqrut vu pvuo lsuvlen, -rem srgnt uot flxxrem qvet. lsusrgnt rqqlpn bntgn ul nstfvad lsuvlen ve uot fleiteuvlerq HEB/SLNVW ndeurw, rem rmmvuvlerqqd htetgrutn -bnrht rem otqs xtnnrhtn alg dlb. - -Ubdbapwc ew a gupc ounrcnecnd, jzcfehzc, anv buycpjkz zehpapm jup bapwenq ougganv-zenc ubdeunw dxan dxc uzv qcdubd guvkzc. -ubdbapwc kwcw a gupc vcozapaderc wdmzc uj ougganv-zenc bapwenq: muk opcadc an enwdanoc uj UbdeunBapwcp, bubkzadc ed yedx ubdeunw, -anv bapwc dxc ougganv zenc. ubdbapwc azzuyw kwcpw du wbcoejm ubdeunw en dxc ounrcndeunaz QNK/BUWEF wmndaf, anv avvedeunazzm qcncpadcw -kwaqc anv xczb gcwwaqcw jup muk. - -Dkmkjyfl nf j pdyl xdwalwnlwm, silonqil, jwe kdhlysti inqyjyv sdy kjyfnwz xdppjwe-inwl dkmndwf mgjw mgl die zlmdkm pdetil. -dkmkjyfl tflf j pdyl elxijyjmnal fmvil ds xdppjwe-inwl kjyfnwz: vdt xyljml jw nwfmjwxl ds DkmndwKjyfly, kdktijml nm hnmg dkmndwf, -jwe kjyfl mgl xdppjwe inwl. dkmkjyfl jiidhf tflyf md fklxnsv dkmndwf nw mgl xdwalwmndwji ZWT/KDFNO fvwmjo, jwe jeenmndwjiiv zlwlyjmlf -tfjzl jwe glik plffjzlf sdy vdt. - -Mtvtshou wo s ymhu gmfjufwufv, bruxwzru, sfn tmquhbcr rwzhshe bmh tshowfi gmyysfn-rwfu mtvwmfo vpsf vpu mrn iuvmtv ymncru. -mtvtshou couo s ymhu nugrshsvwju overu mb gmyysfn-rwfu tshowfi: emc ghusvu sf wfovsfgu mb MtvwmfTshouh, tmtcrsvu wv qwvp mtvwmfo, -sfn tshou vpu gmyysfn rwfu. mtvtshou srrmqo couho vm otugwbe mtvwmfo wf vpu gmfjufvwmfsr IFC/TMOWX oefvsx, sfn snnwvwmfsrre iufuhsvuo -cosiu sfn purt yuoosiuo bmh emc. - -Vcecbqxd fx b hvqd pvosdofdoe, kadgfiad, bow cvzdqkla afiqbqn kvq cbqxfor pvhhbow-afod vcefvox eybo eyd vaw rdevce hvwlad. -vcecbqxd lxdx b hvqd wdpabqbefsd xenad vk pvhhbow-afod cbqxfor: nvl pqdbed bo foxebopd vk VcefvoCbqxdq, cvclabed fe zfey vcefvox, -bow cbqxd eyd pvhhbow afod. vcecbqxd baavzx lxdqx ev xcdpfkn vcefvox fo eyd pvosdoefvoba ROL/CVXFG xnoebg, bow bwwfefvobaan rdodqbedx -lxbrd bow ydac hdxxbrdx kvq nvl. - -Elnlkzgm og k qezm yexbmxomxn, tjmporjm, kxf leimztuj jorzkzw tez lkzgoxa yeqqkxf-joxm elnoexg nhkx nhm ejf amneln qefujm. -elnlkzgm ugmg k qezm fmyjkzknobm gnwjm et yeqqkxf-joxm lkzgoxa: weu yzmknm kx oxgnkxym et ElnoexLkzgmz, lelujknm on ionh elnoexg, -kxf lkzgm nhm yeqqkxf joxm. elnlkzgm kjjeig ugmzg ne glmyotw elnoexg ox nhm yexbmxnoexkj AXU/LEGOP gwxnkp, kxf kffonoexkjjw amxmzknmg -ugkam kxf hmjl qmggkamg tez weu. - -Nuwutipv xp t zniv hngkvgxvgw, csvyxasv, tgo unrvicds sxaitif cni utipxgj hnzztgo-sxgv nuwxngp wqtg wqv nso jvwnuw znodsv. -nuwutipv dpvp t zniv ovhstitwxkv pwfsv nc hnzztgo-sxgv utipxgj: fnd hivtwv tg xgpwtghv nc NuwxngUtipvi, unudstwv xw rxwq nuwxngp, -tgo utipv wqv hnzztgo sxgv. nuwutipv tssnrp dpvip wn puvhxcf nuwxngp xg wqv hngkvgwxngts JGD/UNPXY pfgwty, tgo tooxwxngtssf jvgvitwvp -dptjv tgo qvsu zvpptjvp cni fnd. - -Wdfdcrye gy c iwre qwptepgepf, lbehgjbe, cpx dwaerlmb bgjrcro lwr dcrygps qwiicpx-bgpe wdfgwpy fzcp fze wbx sefwdf iwxmbe. -wdfdcrye myey c iwre xeqbcrcfgte yfobe wl qwiicpx-bgpe dcrygps: owm qrecfe cp gpyfcpqe wl WdfgwpDcryer, dwdmbcfe gf agfz wdfgwpy, -cpx dcrye fze qwiicpx bgpe. wdfdcrye cbbway myery fw ydeqglo wdfgwpy gp fze qwptepfgwpcb SPM/DWYGH yopfch, cpx cxxgfgwpcbbo sepercfey -mycse cpx zebd ieyycsey lwr owm. - -Fmomlahn ph l rfan zfycnypnyo, uknqpskn, lyg mfjnauvk kpsalax ufa mlahpyb zfrrlyg-kpyn fmopfyh oily oin fkg bnofmo rfgvkn. -fmomlahn vhnh l rfan gnzklalopcn hoxkn fu zfrrlyg-kpyn mlahpyb: xfv zanlon ly pyholyzn fu FmopfyMlahna, mfmvklon po jpoi fmopfyh, -lyg mlahn oin zfrrlyg kpyn. fmomlahn lkkfjh vhnah of hmnzpux fmopfyh py oin zfycnyopfylk BYV/MFHPQ hxyolq, lyg lggpopfylkkx bnynalonh -vhlbn lyg inkm rnhhlbnh ufa xfv. - -Ovxvujqw yq u aojw iohlwhywhx, dtwzybtw, uhp voswjdet tybjujg doj vujqyhk ioaauhp-tyhw ovxyohq xruh xrw otp kwxovx aopetw. -ovxvujqw eqwq u aojw pwitujuxylw qxgtw od ioaauhp-tyhw vujqyhk: goe ijwuxw uh yhqxuhiw od OvxyohVujqwj, vovetuxw yx syxr ovxyohq, -uhp vujqw xrw ioaauhp tyhw. ovxvujqw uttosq eqwjq xo qvwiydg ovxyohq yh xrw iohlwhxyohut KHE/VOQYZ qghxuz, uhp uppyxyohuttg kwhwjuxwq -equkw uhp rwtv awqqukwq doj goe. - -Xegedszf hz d jxsf rxqufqhfqg, mcfihkcf, dqy exbfsmnc chksdsp mxs edszhqt rxjjdqy-chqf xeghxqz gadq gaf xcy tfgxeg jxyncf. -xegedszf nzfz d jxsf yfrcdsdghuf zgpcf xm rxjjdqy-chqf edszhqt: pxn rsfdgf dq hqzgdqrf xm XeghxqEdszfs, exencdgf hg bhga xeghxqz, -dqy edszf gaf rxjjdqy chqf. xegedszf dccxbz nzfsz gx zefrhmp xeghxqz hq gaf rxqufqghxqdc TQN/EXZHI zpqgdi, dqy dyyhghxqdccp tfqfsdgfz -nzdtf dqy afce jfzzdtfz mxs pxn. - -Gnpnmbio qi m sgbo agzdozqozp, vlorqtlo, mzh ngkobvwl lqtbmby vgb nmbiqzc agssmzh-lqzo gnpqgzi pjmz pjo glh copgnp sghwlo. -gnpnmbio wioi m sgbo hoalmbmpqdo ipylo gv agssmzh-lqzo nmbiqzc: ygw abompo mz qzipmzao gv GnpqgzNmbiob, ngnwlmpo qp kqpj gnpqgzi, -mzh nmbio pjo agssmzh lqzo. gnpnmbio mllgki wiobi pg inoaqvy gnpqgzi qz pjo agzdozpqgzml CZW/NGIQR iyzpmr, mzh mhhqpqgzmlly cozobmpoi -wimco mzh joln soiimcoi vgb ygw. - -Pwywvkrx zr v bpkx jpimxizxiy, euxazcux, viq wptxkefu uzckvkh epk wvkrzil jpbbviq-uzix pwyzpir ysvi ysx puq lxypwy bpqfux. -pwywvkrx frxr v bpkx qxjuvkvyzmx ryhux pe jpbbviq-uzix wvkrzil: hpf jkxvyx vi ziryvijx pe PwyzpiWvkrxk, wpwfuvyx zy tzys pwyzpir, -viq wvkrx ysx jpbbviq uzix. pwywvkrx vuuptr frxkr yp rwxjzeh pwyzpir zi ysx jpimxiyzpivu LIF/WPRZA rhiyva, viq vqqzyzpivuuh lxixkvyxr -frvlx viq sxuw bxrrvlxr epk hpf. - -Yfhfetag ia e kytg syrvgrigrh, ndgjildg, erz fycgtnod diltetq nyt fetairu sykkerz-dirg yfhiyra hber hbg ydz ughyfh kyzodg. -yfhfetag oaga e kytg zgsdetehivg ahqdg yn sykkerz-dirg fetairu: qyo stgehg er irahersg yn YfhiyrFetagt, fyfodehg ih cihb yfhiyra, -erz fetag hbg sykkerz dirg. yfhfetag eddyca oagta hy afgsinq yfhiyra ir hbg syrvgrhiyred URO/FYAIJ aqrhej, erz ezzihiyreddq ugrgtehga -oaeug erz bgdf kgaaeuga nyt qyo. - -Hoqoncjp rj n thcp bhaeparpaq, wmpsrump, nai ohlpcwxm mrucncz whc oncjrad bhttnai-mrap hoqrhaj qkna qkp hmi dpqhoq thixmp. -hoqoncjp xjpj n thcp ipbmncnqrep jqzmp hw bhttnai-mrap oncjrad: zhx bcpnqp na rajqnabp hw HoqrhaOncjpc, ohoxmnqp rq lrqk hoqrhaj, -nai oncjp qkp bhttnai mrap. hoqoncjp nmmhlj xjpcj qh jopbrwz hoqrhaj ra qkp bhaepaqrhanm DAX/OHJRS jzaqns, nai niirqrhanmmz dpapcnqpj -xjndp nai kpmo tpjjndpj whc zhx. - -Qxzxwlsy as w cqly kqjnyjayjz, fvybadvy, wjr xquylfgv vadlwli fql xwlsajm kqccwjr-vajy qxzaqjs ztwj zty qvr myzqxz cqrgvy. -qxzxwlsy gsys w cqly rykvwlwzany szivy qf kqccwjr-vajy xwlsajm: iqg klywzy wj ajszwjky qf QxzaqjXwlsyl, xqxgvwzy az uazt qxzaqjs, -wjr xwlsy zty kqccwjr vajy. qxzxwlsy wvvqus gsyls zq sxykafi qxzaqjs aj zty kqjnyjzaqjwv MJG/XQSAB sijzwb, wjr wrrazaqjwvvi myjylwzys -gswmy wjr tyvx cysswmys fql iqg. - -Zgigfubh jb f lzuh tzswhsjhsi, oehkjmeh, fsa gzdhuope ejmufur ozu gfubjsv tzllfsa-ejsh zgijzsb icfs ich zea vhizgi lzapeh. -zgigfubh pbhb f lzuh ahtefufijwh bireh zo tzllfsa-ejsh gfubjsv: rzp tuhfih fs jsbifsth zo ZgijzsGfubhu, gzgpefih ji djic zgijzsb, -fsa gfubh ich tzllfsa ejsh. zgigfubh feezdb pbhub iz bghtjor zgijzsb js ich tzswhsijzsfe VSP/GZBJK brsifk, fsa faajijzsfeer vhshufihb -pbfvh fsa cheg lhbbfvhb ozu rzp. - -Iprpodkq sk o uidq cibfqbsqbr, xnqtsvnq, obj pimqdxyn nsvdoda xid podksbe ciuuobj-nsbq iprsibk rlob rlq inj eqripr uijynq. -iprpodkq ykqk o uidq jqcnodorsfq kranq ix ciuuobj-nsbq podksbe: aiy cdqorq ob sbkrobcq ix IprsibPodkqd, pipynorq sr msrl iprsibk, -obj podkq rlq ciuuobj nsbq. iprpodkq onnimk ykqdk ri kpqcsxa iprsibk sb rlq cibfqbrsibon EBY/PIKST kabrot, obj ojjsrsibonna eqbqdorqk -ykoeq obj lqnp uqkkoeqk xid aiy. - -Ryayxmtz bt x drmz lrkozkbzka, gwzcbewz, xks yrvzmghw wbemxmj grm yxmtbkn lrddxks-wbkz ryabrkt auxk auz rws nzarya drshwz. -ryayxmtz htzt x drmz szlwxmxaboz tajwz rg lrddxks-wbkz yxmtbkn: jrh lmzxaz xk bktaxklz rg RyabrkYxmtzm, yryhwxaz ba vbau ryabrkt, -xks yxmtz auz lrddxks wbkz. ryayxmtz xwwrvt htzmt ar tyzlbgj ryabrkt bk auz lrkozkabrkxw NKH/YRTBC tjkaxc, xks xssbabrkxwwj nzkzmxazt -htxnz xks uzwy dzttxnzt grm jrh. - -Ahjhgvci kc g mavi uatxitkitj, pfilknfi, gtb haeivpqf fknvgvs pav hgvcktw uammgtb-fkti ahjkatc jdgt jdi afb wijahj mabqfi. -ahjhgvci qcic g mavi biufgvgjkxi cjsfi ap uammgtb-fkti hgvcktw: saq uvigji gt ktcjgtui ap AhjkatHgvciv, hahqfgji kj ekjd ahjkatc, -gtb hgvci jdi uammgtb fkti. ahjhgvci gffaec qcivc ja chiukps ahjkatc kt jdi uatxitjkatgf WTQ/HACKL cstjgl, gtb gbbkjkatgffs witivgjic -qcgwi gtb difh miccgwic pav saq. - -Jqsqpelr tl p vjer djcgrctrcs, yorutwor, pck qjnreyzo otwepeb yje qpeltcf djvvpck-otcr jqstjcl smpc smr jok frsjqs vjkzor. -jqsqpelr zlrl p vjer krdopepstgr lsbor jy djvvpck-otcr qpeltcf: bjz derpsr pc tclspcdr jy JqstjcQpelre, qjqzopsr ts ntsm jqstjcl, -pck qpelr smr djvvpck otcr. jqsqpelr poojnl zlrel sj lqrdtyb jqstjcl tc smr djcgrcstjcpo FCZ/QJLTU lbcspu, pck pkktstjcpoob frcrepsrl -zlpfr pck mroq vrllpfrl yje bjz. - -Szbzynua cu y esna mslpalcalb, hxadcfxa, ylt zswanhix xcfnynk hsn zynuclo mseeylt-xcla szbcslu bvyl bva sxt oabszb estixa. -szbzynua iuau y esna tamxynybcpa ubkxa sh mseeylt-xcla zynuclo: ksi mnayba yl clubylma sh SzbcslZynuan, zszixyba cb wcbv szbcslu, -ylt zynua bva mseeylt xcla. szbzynua yxxswu iuanu bs uzamchk szbcslu cl bva mslpalbcslyx OLI/ZSUCD uklbyd, ylt yttcbcslyxxk oalanybau -iuyoa ylt vaxz eauuyoau hsn ksi. - -Bikihwdj ld h nbwj vbuyjuljuk, qgjmlogj, huc ibfjwqrg glowhwt qbw ihwdlux vbnnhuc-gluj biklbud kehu kej bgc xjkbik nbcrgj. -bikihwdj rdjd h nbwj cjvghwhklyj dktgj bq vbnnhuc-gluj ihwdlux: tbr vwjhkj hu ludkhuvj bq BiklbuIhwdjw, ibirghkj lk flke biklbud, -huc ihwdj kej vbnnhuc gluj. bikihwdj hggbfd rdjwd kb dijvlqt biklbud lu kej vbuyjuklbuhg XUR/IBDLM dtukhm, huc hcclklbuhggt xjujwhkjd -rdhxj huc ejgi njddhxjd qbw tbr. - -Krtrqfms um q wkfs ekdhsdusdt, zpsvuxps, qdl rkosfzap puxfqfc zkf rqfmudg ekwwqdl-puds krtukdm tnqd tns kpl gstkrt wklaps. -krtrqfms amsm q wkfs lsepqfqtuhs mtcps kz ekwwqdl-puds rqfmudg: cka efsqts qd udmtqdes kz KrtukdRqfmsf, rkrapqts ut outn krtukdm, -qdl rqfms tns ekwwqdl puds. krtrqfms qppkom amsfm tk mrseuzc krtukdm ud tns ekdhsdtukdqp GDA/RKMUV mcdtqv, qdl qllutukdqppc gsdsfqtsm -amqgs qdl nspr wsmmqgsm zkf cka. - -Fagaxqld jl x pfqd nfkwdkjdkg, yudmjsud, xki afrdqybu ujsqxqh yfq axqljkt nfppxki-ujkd fagjfkl goxk god fui tdgfag pfibud. -fagaxqld bldl x pfqd idnuxqxgjwd lghud fy nfppxki-ujkd axqljkt: hfb nqdxgd xk jklgxknd fy FagjfkAxqldq, afabuxgd jg rjgo fagjfkl, -xki axqld god nfppxki ujkd. fagaxqld xuufrl bldql gf ladnjyh fagjfkl jk god nfkwdkgjfkxu TKB/AFLJM lhkgxm, xki xiijgjfkxuuh tdkdqxgdl -blxtd xki odua pdllxtdl yfq hfb. - -Gbhbyrme km y qgre oglxelkelh, zvenktve, ylj bgserzcv vktryri zgr byrmklu ogqqylj-vkle gbhkglm hpyl hpe gvj uehgbh qgjcve. -gbhbyrme cmem y qgre jeovyryhkxe mhive gz ogqqylj-vkle byrmklu: igc oreyhe yl klmhyloe gz GbhkglByrmer, bgbcvyhe kh skhp gbhkglm, -ylj byrme hpe ogqqylj vkle. gbhbyrme yvvgsm cmerm hg mbeokzi gbhkglm kl hpe oglxelhkglyv ULC/BGMKN milhyn, ylj yjjkhkglyvvi ueleryhem -cmyue ylj pevb qemmyuem zgr igc. - -Hciczsnf ln z rhsf phmyfmlfmi, awfoluwf, zmk chtfsadw wluszsj ahs czsnlmv phrrzmk-wlmf hcilhmn iqzm iqf hwk vfihci rhkdwf. -hciczsnf dnfn z rhsf kfpwzszilyf nijwf ha phrrzmk-wlmf czsnlmv: jhd psfzif zm lmnizmpf ha HcilhmCzsnfs, chcdwzif li tliq hcilhmn, -zmk czsnf iqf phrrzmk wlmf. hciczsnf zwwhtn dnfsn ih ncfplaj hcilhmn lm iqf phmyfmilhmzw VMD/CHNLO njmizo, zmk zkklilhmzwwj vfmfszifn -dnzvf zmk qfwc rfnnzvfn ahs jhd. - -Idjdatog mo a sitg qinzgnmgnj, bxgpmvxg, anl diugtbex xmvtatk bit datomnw qissanl-xmng idjmino jran jrg ixl wgjidj silexg. -idjdatog eogo a sitg lgqxatajmzg ojkxg ib qissanl-xmng datomnw: kie qtgajg an mnojanqg ib IdjminDatogt, didexajg mj umjr idjmino, -anl datog jrg qissanl xmng. idjdatog axxiuo eogto ji odgqmbk idjmino mn jrg qinzgnjminax WNE/DIOMP oknjap, anl allmjminaxxk wgngtajgo -eoawg anl rgxd sgooawgo bit kie. - -Jekebuph np b tjuh rjoahonhok, cyhqnwyh, bom ejvhucfy ynwubul cju ebupnox rjttbom-ynoh jeknjop ksbo ksh jym xhkjek tjmfyh. -jekebuph fphp b tjuh mhrybubknah pklyh jc rjttbom-ynoh ebupnox: ljf ruhbkh bo nopkborh jc JeknjoEbuphu, ejefybkh nk vnks jeknjop, -bom ebuph ksh rjttbom ynoh. jekebuph byyjvp fphup kj pehrncl jeknjop no ksh rjoahoknjoby XOF/EJPNQ plokbq, bom bmmnknjobyyl xhohubkhp -fpbxh bom shye thppbxhp cju ljf. - -Kflfcvqi oq c ukvi skpbipoipl, dziroxzi, cpn fkwivdgz zoxvcvm dkv fcvqopy skuucpn-zopi kflokpq ltcp lti kzn yilkfl ukngzi. -kflfcvqi gqiq c ukvi niszcvclobi qlmzi kd skuucpn-zopi fcvqopy: mkg svicli cp opqlcpsi kd KflokpFcvqiv, fkfgzcli ol wolt kflokpq, -cpn fcvqi lti skuucpn zopi. kflfcvqi czzkwq gqivq lk qfisodm kflokpq op lti skpbiplokpcz YPG/FKQOR qmplcr, cpn cnnolokpczzm yipivcliq -gqcyi cpn tizf uiqqcyiq dkv mkg. - -Lgmgdwrj pr d vlwj tlqcjqpjqm, eajspyaj, dqo glxjweha apywdwn elw gdwrpqz tlvvdqo-apqj lgmplqr mudq muj lao zjmlgm vlohaj. -lgmgdwrj hrjr d vlwj ojtadwdmpcj rmnaj le tlvvdqo-apqj gdwrpqz: nlh twjdmj dq pqrmdqtj le LgmplqGdwrjw, glghadmj pm xpmu lgmplqr, -dqo gdwrj muj tlvvdqo apqj. lgmgdwrj daalxr hrjwr ml rgjtpen lgmplqr pq muj tlqcjqmplqda ZQH/GLRPS rnqmds, dqo doopmplqdaan zjqjwdmjr -hrdzj dqo ujag vjrrdzjr elw nlh. - -Mhnhexsk qs e wmxk umrdkrqkrn, fbktqzbk, erp hmykxfib bqzxexo fmx hexsqra umwwerp-bqrk mhnqmrs nver nvk mbp aknmhn wmpibk. -mhnhexsk isks e wmxk pkubexenqdk snobk mf umwwerp-bqrk hexsqra: omi uxkenk er qrsneruk mf MhnqmrHexskx, hmhibenk qn yqnv mhnqmrs, -erp hexsk nvk umwwerp bqrk. mhnhexsk ebbmys iskxs nm shkuqfo mhnqmrs qr nvk umrdkrnqmreb ARI/HMSQT sornet, erp eppqnqmrebbo akrkxenks -iseak erp vkbh wksseaks fmx omi. - -Nioifytl rt f xnyl vnselsrlso, gcluracl, fsq inzlygjc crayfyp gny ifytrsb vnxxfsq-crsl niornst owfs owl ncq blonio xnqjcl. -nioifytl jtlt f xnyl qlvcfyforel topcl ng vnxxfsq-crsl ifytrsb: pnj vylfol fs rstofsvl ng NiornsIfytly, inijcfol ro zrow niornst, -fsq ifytl owl vnxxfsq crsl. nioifytl fccnzt jtlyt on tilvrgp niornst rs owl vnselsornsfc BSJ/INTRU tpsofu, fsq fqqrornsfccp blslyfolt -jtfbl fsq wlci xlttfblt gny pnj. - -Ojpjgzum su g yozm wotfmtsmtp, hdmvsbdm, gtr joamzhkd dsbzgzq hoz jgzustc woyygtr-dstm ojpsotu pxgt pxm odr cmpojp yorkdm. -ojpjgzum kumu g yozm rmwdgzgpsfm upqdm oh woyygtr-dstm jgzustc: qok wzmgpm gt stupgtwm oh OjpsotJgzumz, jojkdgpm sp aspx ojpsotu, -gtr jgzum pxm woyygtr dstm. ojpjgzum gddoau kumzu po ujmwshq ojpsotu st pxm wotfmtpsotgd CTK/JOUSV uqtpgv, gtr grrspsotgddq cmtmzgpmu -kugcm gtr xmdj ymuugcmu hoz qok. - -Pkqkhavn tv h zpan xpugnutnuq, ienwtcen, hus kpbnaile etcahar ipa khavtud xpzzhus-etun pkqtpuv qyhu qyn pes dnqpkq zpslen. -pkqkhavn lvnv h zpan snxehahqtgn vqren pi xpzzhus-etun khavtud: rpl xanhqn hu tuvqhuxn pi PkqtpuKhavna, kpklehqn tq btqy pkqtpuv, -hus khavn qyn xpzzhus etun. pkqkhavn heepbv lvnav qp vknxtir pkqtpuv tu qyn xpugnuqtpuhe DUL/KPVTW vruqhw, hus hsstqtpuheer dnunahqnv -lvhdn hus ynek znvvhdnv ipa rpl. - -Qlrlibwo uw i aqbo yqvhovuovr, jfoxudfo, ivt lqcobjmf fudbibs jqb libwuve yqaaivt-fuvo qlruqvw rziv rzo qft eorqlr aqtmfo. -qlrlibwo mwow i aqbo toyfibiruho wrsfo qj yqaaivt-fuvo libwuve: sqm yboiro iv uvwrivyo qj QlruqvLibwob, lqlmfiro ur curz qlruqvw, -ivt libwo rzo yqaaivt fuvo. qlrlibwo iffqcw mwobw rq wloyujs qlruqvw uv rzo yqvhovruqvif EVM/LQWUX wsvrix, ivt itturuqviffs eovobirow -mwieo ivt zofl aowwieow jqb sqm. - -Rmsmjcxp vx j brcp zrwipwvpws, kgpyvegp, jwu mrdpckng gvecjct krc mjcxvwf zrbbjwu-gvwp rmsvrwx sajw sap rgu fpsrms brungp. -rmsmjcxp nxpx j brcp upzgjcjsvip xstgp rk zrbbjwu-gvwp mjcxvwf: trn zcpjsp jw vwxsjwzp rk RmsvrwMjcxpc, mrmngjsp vs dvsa rmsvrwx, -jwu mjcxp sap zrbbjwu gvwp. rmsmjcxp jggrdx nxpcx sr xmpzvkt rmsvrwx vw sap zrwipwsvrwjg FWN/MRXVY xtwsjy, jwu juuvsvrwjggt fpwpcjspx -nxjfp jwu apgm bpxxjfpx krc trn. - -Sntnkdyq wy k csdq asxjqxwqxt, lhqzwfhq, kxv nseqdloh hwfdkdu lsd nkdywxg ascckxv-hwxq sntwsxy tbkx tbq shv gqtsnt csvohq. -sntnkdyq oyqy k csdq vqahkdktwjq ytuhq sl ascckxv-hwxq nkdywxg: uso adqktq kx wxytkxaq sl SntwsxNkdyqd, nsnohktq wt ewtb sntwsxy, -kxv nkdyq tbq ascckxv hwxq. sntnkdyq khhsey oyqdy ts ynqawlu sntwsxy wx tbq asxjqxtwsxkh GXO/NSYWZ yuxtkz, kxv kvvwtwsxkhhu gqxqdktqy -oykgq kxv bqhn cqyykgqy lsd uso. - -Touolezr xz l dter btykryxryu, miraxgir, lyw otfrempi ixgelev mte olezxyh btddlyw-ixyr touxtyz ucly ucr tiw hrutou dtwpir. -touolezr pzrz l dter wrbileluxkr zuvir tm btddlyw-ixyr olezxyh: vtp berlur ly xyzulybr tm TouxtyOlezre, otopilur xu fxuc touxtyz, -lyw olezr ucr btddlyw ixyr. touolezr liitfz pzrez ut zorbxmv touxtyz xy ucr btykryuxtyli HYP/OTZXA zvyula, lyw lwwxuxtyliiv hryrelurz -pzlhr lyw crio drzzlhrz mte vtp. - -Upvpmfas ya m eufs cuzlszyszv, njsbyhjs, mzx pugsfnqj jyhfmfw nuf pmfayzi cueemzx-jyzs upvyuza vdmz vds ujx isvupv euxqjs. -upvpmfas qasa m eufs xscjmfmvyls avwjs un cueemzx-jyzs pmfayzi: wuq cfsmvs mz yzavmzcs un UpvyuzPmfasf, pupqjmvs yv gyvd upvyuza, -mzx pmfas vds cueemzx jyzs. upvpmfas mjjuga qasfa vu apscynw upvyuza yz vds cuzlszvyuzmj IZQ/PUAYB awzvmb, mzx mxxyvyuzmjjw iszsfmvsa -qamis mzx dsjp esaamisa nuf wuq. - -Vqwqngbt zb n fvgt dvamtaztaw, oktczikt, nay qvhtgork kzigngx ovg qngbzaj dvffnay-kzat vqwzvab wena wet vky jtwvqw fvyrkt. -vqwqngbt rbtb n fvgt ytdkngnwzmt bwxkt vo dvffnay-kzat qngbzaj: xvr dgtnwt na zabwnadt vo VqwzvaQngbtg, qvqrknwt zw hzwe vqwzvab, -nay qngbt wet dvffnay kzat. vqwqngbt nkkvhb rbtgb wv bqtdzox vqwzvab za wet dvamtawzvank JAR/QVBZC bxawnc, nay nyyzwzvankkx jtatgnwtb -rbnjt nay etkq ftbbnjtb ovg xvr. - -Wrxrohcu ac o gwhu ewbnubaubx, pludajlu, obz rwiuhpsl lajhohy pwh rohcabk ewggobz-labu wrxawbc xfob xfu wlz kuxwrx gwzslu. -wrxrohcu scuc o gwhu zuelohoxanu cxylu wp ewggobz-labu rohcabk: yws ehuoxu ob abcxobeu wp WrxawbRohcuh, rwrsloxu ax iaxf wrxawbc, -obz rohcu xfu ewggobz labu. wrxrohcu ollwic scuhc xw crueapy wrxawbc ab xfu ewbnubxawbol KBS/RWCAD cybxod, obz ozzaxawbolly kubuhoxuc -scoku obz fulr guccokuc pwh yws. - -Xsyspidv bd p hxiv fxcovcbvcy, qmvebkmv, pca sxjviqtm mbkipiz qxi spidbcl fxhhpca-mbcv xsybxcd ygpc ygv xma lvyxsy hxatmv. -xsyspidv tdvd p hxiv avfmpipybov dyzmv xq fxhhpca-mbcv spidbcl: zxt fivpyv pc bcdypcfv xq XsybxcSpidvi, sxstmpyv by jbyg xsybxcd, -pca spidv ygv fxhhpca mbcv. xsyspidv pmmxjd tdvid yx dsvfbqz xsybxcd bc ygv fxcovcybxcpm LCT/SXDBE dzcype, pca paabybxcpmmz lvcvipyvd -tdplv pca gvms hvddplvd qxi zxt. - -Ytztqjew ce q iyjw gydpwdcwdz, rnwfclnw, qdb tykwjrun ncljqja ryj tqjecdm gyiiqdb-ncdw ytzcyde zhqd zhw ynb mwzytz iybunw. -ytztqjew uewe q iyjw bwgnqjqzcpw ezanw yr gyiiqdb-ncdw tqjecdm: ayu gjwqzw qd cdezqdgw yr YtzcydTqjewj, tytunqzw cz kczh ytzcyde, -qdb tqjew zhw gyiiqdb ncdw. ytztqjew qnnyke uewje zy etwgcra ytzcyde cd zhw gydpwdzcydqn MDU/TYECF eadzqf, qdb qbbczcydqnna mwdwjqzwe -ueqmw qdb hwnt iweeqmwe ryj ayu. - -Zuaurkfx df r jzkx hzeqxedxea, soxgdmox, rec uzlxksvo odmkrkb szk urkfden hzjjrec-odex zuadzef aire aix zoc nxazua jzcvox. -zuaurkfx vfxf r jzkx cxhorkradqx fabox zs hzjjrec-odex urkfden: bzv hkxrax re defarehx zs ZuadzeUrkfxk, uzuvorax da ldai zuadzef, -rec urkfx aix hzjjrec odex. zuaurkfx roozlf vfxkf az fuxhdsb zuadzef de aix hzeqxeadzero NEV/UZFDG fbearg, rec rccdadzeroob nxexkraxf -vfrnx rec ixou jxffrnxf szk bzv. - -Avbvslgy eg s kaly iafryfeyfb, tpyhenpy, sfd vamyltwp penlslc tal vslgefo iakksfd-pefy avbeafg bjsf bjy apd oybavb kadwpy. -avbvslgy wgyg s kaly dyipslsbery gbcpy at iakksfd-pefy vslgefo: caw ilysby sf efgbsfiy at AvbeafVslgyl, vavwpsby eb mebj avbeafg, -sfd vslgy bjy iakksfd pefy. avbvslgy sppamg wgylg ba gvyietc avbeafg ef bjy iafryfbeafsp OFW/VAGEH gcfbsh, sfd sddebeafsppc oyfylsbyg -wgsoy sfd jypv kyggsoyg tal caw. - -Bwcwtmhz fh t lbmz jbgszgfzgc, uqzifoqz, tge wbnzmuxq qfomtmd ubm wtmhfgp jblltge-qfgz bwcfbgh cktg ckz bqe pzcbwc lbexqz. -bwcwtmhz xhzh t lbmz ezjqtmtcfsz hcdqz bu jblltge-qfgz wtmhfgp: dbx jmztcz tg fghctgjz bu BwcfbgWtmhzm, wbwxqtcz fc nfck bwcfbgh, -tge wtmhz ckz jblltge qfgz. bwcwtmhz tqqbnh xhzmh cb hwzjfud bwcfbgh fg ckz jbgszgcfbgtq PGX/WBHFI hdgcti, tge teefcfbgtqqd pzgzmtczh -xhtpz tge kzqw lzhhtpzh ubm dbx. - -Cxdxunia gi u mcna kchtahgahd, vrajgpra, uhf xcoanvyr rgpnune vcn xunighq kcmmuhf-rgha cxdgchi dluh dla crf qadcxd mcfyra. -cxdxunia yiai u mcna fakrunudgta idera cv kcmmuhf-rgha xunighq: ecy knauda uh ghiduhka cv CxdgchXunian, xcxyruda gd ogdl cxdgchi, -uhf xunia dla kcmmuhf rgha. cxdxunia urrcoi yiani dc ixakgve cxdgchi gh dla kchtahdgchur QHY/XCIGJ iehduj, uhf uffgdgchurre qahanudai -yiuqa uhf larx maiiuqai vcn ecy. - -Dyeyvojb hj v ndob ldiubihbie, wsbkhqsb, vig ydpbowzs shqovof wdo yvojhir ldnnvig-shib dyehdij emvi emb dsg rbedye ndgzsb. -dyeyvojb zjbj v ndob gblsvovehub jefsb dw ldnnvig-shib yvojhir: fdz lobveb vi hijevilb dw DyehdiYvojbo, ydyzsveb he phem dyehdij, -vig yvojb emb ldnnvig shib. dyeyvojb vssdpj zjboj ed jyblhwf dyehdij hi emb ldiubiehdivs RIZ/YDJHK jfievk, vig vgghehdivssf rbibovebj -zjvrb vig mbsy nbjjvrbj wdo fdz. - -Ezfzwpkc ik w oepc mejvcjicjf, xtclirtc, wjh zeqcpxat tirpwpg xep zwpkijs meoowjh-tijc ezfiejk fnwj fnc eth scfezf oehatc. -ezfzwpkc akck w oepc hcmtwpwfivc kfgtc ex meoowjh-tijc zwpkijs: gea mpcwfc wj ijkfwjmc ex EzfiejZwpkcp, zezatwfc if qifn ezfiejk, -wjh zwpkc fnc meoowjh tijc. ezfzwpkc wtteqk akcpk fe kzcmixg ezfiejk ij fnc mejvcjfiejwt SJA/ZEKIL kgjfwl, wjh whhifiejwttg scjcpwfck -akwsc wjh nctz ockkwsck xep gea. - diff --git a/afiniczny/test_afine.py b/afiniczny/test_afine.py new file mode 100755 index 0000000..a77a04e --- /dev/null +++ b/afiniczny/test_afine.py @@ -0,0 +1,27 @@ +import unittest +import afine + +class TestAfiniczneSzyfrowanie(unittest.TestCase): + + def setup(self): + pass + + def test_szyfruj_litere(self): + self.assertEqual('b', afine.zaszyfruj_litere('a', 1, 1)) + + def test_bledne_szyfrowanie_litery(self): + self.assertNotEqual('b', afine.zaszyfruj_litere('a', 5, 5)) + + def test_szyfruj_tekst(self): + self.assertEqual("bcd", afine.zaszyfruj_tekst("abc", 1, 1)) + + def test_nwd(self): + self.assertEqual(1, nwd(1, 26)) + self.assertEqual(1, nwd(3, 26)) + self.assertEqual(1, nwd(5, 26)) + + + + +if __name__ == "__main__": + unittest.main() \ No newline at end of file
sbogutyn/krypto
59011a5898b7f2924a386334c592839ade20c9ac
dodanie tekstu z tablicy
diff --git a/afiniczny/listing.txt b/afiniczny/listing.txt new file mode 100755 index 0000000..59d0228 --- /dev/null +++ b/afiniczny/listing.txt @@ -0,0 +1,108 @@ +kryptoanaliza z tekstem jawnym +wyniki = set([(9, 25), (11, 23), (23, 11), (7, 1), (25, 9), (19, 15), (1, 7), (21, 13), (15, 19), (5, 3), (17, 17), (3, 5)]) & set([(17, 5), (11, 17), (23, 19), (9, 21), (21, 23), (19, 1), (7, 25), (25, 15), (15, 9), (3, 7), (1, 11), (5, 3)]) +wyniki = set([(5, 3)]) & set([(3, 15), (17, 9), (19, 23), (15, 21), (21, 11), (1, 1), (25, 13), (7, 17), (9, 5), (23, 25), (11, 19), (5, 3)]) +wyniki = set([(5, 3)]) & set([(17, 5), (11, 17), (23, 19), (9, 21), (21, 23), (19, 1), (7, 25), (25, 15), (15, 9), (3, 7), (1, 11), (5, 3)]) +wyniki = set([(5, 3)]) & set([(7, 3), (1, 3), (3, 3), (15, 3), (9, 3), (11, 3), (21, 3), (23, 3), (17, 3), (19, 3), (25, 3), (5, 3)]) +wyniki = set([(5, 3)]) & set([(9, 13), (7, 21), (19, 25), (11, 5), (17, 7), (3, 11), (23, 9), (1, 19), (25, 1), (21, 17), (15, 15), (5, 3)]) +wyniki = set([(5, 3)]) & set([(25, 7), (15, 5), (3, 13), (21, 1), (1, 23), (9, 9), (17, 21), (23, 17), (7, 19), (11, 25), (19, 11), (5, 3)]) +wyniki = set([(5, 3)]) & set([(9, 13), (7, 21), (19, 25), (11, 5), (17, 7), (3, 11), (23, 9), (1, 19), (25, 1), (21, 17), (15, 15), (5, 3)]) +e +x +set([(5, 3)]) + 43408 function calls in 0.724 CPU seconds + + Ordered by: standard name + + ncalls tottime percall cumtime percall filename:lineno(function) + 108 0.001 0.000 0.001 0.000 :0(add) + 45 0.000 0.000 0.000 0.000 :0(append) + 2 0.000 0.000 0.000 0.000 :0(close) + 1 0.000 0.000 0.000 0.000 :0(copy) + 24 0.000 0.000 0.000 0.000 :0(endswith) + 1 0.005 0.005 0.724 0.724 :0(execfile) + 8 0.001 0.000 0.001 0.000 :0(filter) + 12 0.000 0.000 0.000 0.000 :0(find) + 26 0.000 0.000 0.000 0.000 :0(get) + 3 0.000 0.000 0.000 0.000 :0(hasattr) + 2496 0.022 0.000 0.022 0.000 :0(index) + 10 0.000 0.000 0.000 0.000 :0(isinstance) + 1 0.000 0.000 0.000 0.000 :0(items) + 2 0.000 0.000 0.000 0.000 :0(join) + 44 0.000 0.000 0.000 0.000 :0(len) + 5 0.000 0.000 0.000 0.000 :0(lower) + 2 0.000 0.000 0.000 0.000 :0(open) + 2 0.000 0.000 0.000 0.000 :0(pop) + 108 0.001 0.000 0.001 0.000 :0(range) + 2 0.000 0.000 0.000 0.000 :0(read) + 8 0.000 0.000 0.000 0.000 :0(replace) + 4 0.000 0.000 0.000 0.000 :0(reverse) + 104 0.001 0.000 0.001 0.000 :0(setattr) + 1 0.000 0.000 0.000 0.000 :0(setprofile) + 8 0.000 0.000 0.000 0.000 :0(split) + 25 0.000 0.000 0.000 0.000 :0(startswith) + 8 0.000 0.000 0.000 0.000 :0(stat) + 1 0.000 0.000 0.000 0.000 :0(strip) + 2 0.000 0.000 0.000 0.000 :0(translate) + 1 0.000 0.000 0.724 0.724 <string>:1(<module>) + 3 0.001 0.000 0.001 0.000 UserDict.py:18(__getitem__) + 8 0.000 0.000 0.001 0.000 UserDict.py:58(get) + 8 0.000 0.000 0.000 0.000 UserDict.py:70(__contains__) + 2 0.000 0.000 0.000 0.000 __init__.py:49(normalize_encoding) + 1 0.028 0.028 0.719 0.719 afine.py:2(<module>) + 2496 0.283 0.000 0.553 0.000 afine.py:22(znajdz_odwrotnosc) + 34944 0.270 0.000 0.270 0.000 afine.py:28(sprawdz_odwrotnosc) + 2496 0.103 0.000 0.678 0.000 afine.py:34(odszyfruj_litere) + 208 0.003 0.000 0.003 0.000 afine.py:64(nwd) + 2 0.000 0.000 0.000 0.000 afine.py:73(odczytaj_plik) + 8 0.000 0.000 0.000 0.000 genericpath.py:15(exists) + 4 0.000 0.000 0.001 0.000 gettext.py:130(_expand_lang) + 2 0.002 0.001 0.004 0.002 gettext.py:421(find) + 2 0.000 0.000 0.004 0.002 gettext.py:461(translation) + 2 0.000 0.000 0.004 0.002 gettext.py:527(dgettext) + 2 0.000 0.000 0.004 0.002 gettext.py:565(gettext) + 4 0.000 0.000 0.000 0.000 locale.py:334(normalize) + 8 0.000 0.000 0.004 0.001 optparse.py:1007(add_option) + 1 0.000 0.000 0.006 0.006 optparse.py:1185(__init__) + 1 0.000 0.000 0.000 0.000 optparse.py:1237(_create_option_list) + 1 0.000 0.000 0.004 0.004 optparse.py:1242(_add_help_option) + 1 0.000 0.000 0.001 0.001 optparse.py:1247(_add_version_option) + 1 0.000 0.000 0.005 0.005 optparse.py:1252(_populate_option_list) + 1 0.000 0.000 0.000 0.000 optparse.py:1262(_init_parsing_state) + 1 0.000 0.000 0.000 0.000 optparse.py:1271(set_usage) + 1 0.000 0.000 0.000 0.000 optparse.py:1307(_get_all_options) + 1 0.000 0.000 0.000 0.000 optparse.py:1313(get_default_values) + 1 0.000 0.000 0.000 0.000 optparse.py:1356(_get_args) + 1 0.000 0.000 0.000 0.000 optparse.py:1362(parse_args) + 1 0.000 0.000 0.000 0.000 optparse.py:1401(check_values) + 1 0.000 0.000 0.000 0.000 optparse.py:1414(_process_args) + 2 0.000 0.000 0.000 0.000 optparse.py:1511(_process_short_opts) + 1 0.000 0.000 0.000 0.000 optparse.py:200(__init__) + 1 0.000 0.000 0.000 0.000 optparse.py:224(set_parser) + 1 0.000 0.000 0.000 0.000 optparse.py:365(__init__) + 8 0.001 0.000 0.004 0.001 optparse.py:560(__init__) + 8 0.000 0.000 0.001 0.000 optparse.py:579(_check_opt_strings) + 8 0.000 0.000 0.000 0.000 optparse.py:588(_set_opt_strings) + 8 0.000 0.000 0.001 0.000 optparse.py:609(_set_attrs) + 8 0.000 0.000 0.000 0.000 optparse.py:629(_check_action) + 8 0.000 0.000 0.000 0.000 optparse.py:635(_check_type) + 8 0.000 0.000 0.000 0.000 optparse.py:665(_check_choice) + 8 0.001 0.000 0.001 0.000 optparse.py:678(_check_dest) + 8 0.000 0.000 0.000 0.000 optparse.py:693(_check_const) + 8 0.000 0.000 0.000 0.000 optparse.py:699(_check_nargs) + 8 0.000 0.000 0.000 0.000 optparse.py:708(_check_callback) + 2 0.000 0.000 0.000 0.000 optparse.py:752(takes_value) + 2 0.000 0.000 0.000 0.000 optparse.py:771(convert_value) + 2 0.000 0.000 0.000 0.000 optparse.py:778(process) + 2 0.000 0.000 0.000 0.000 optparse.py:790(take_action) + 8 0.000 0.000 0.000 0.000 optparse.py:832(isbasestring) + 1 0.000 0.000 0.000 0.000 optparse.py:837(__init__) + 1 0.001 0.001 0.001 0.001 optparse.py:932(__init__) + 1 0.000 0.000 0.000 0.000 optparse.py:943(_create_option_mappings) + 1 0.000 0.000 0.000 0.000 optparse.py:959(set_conflict_handler) + 1 0.000 0.000 0.000 0.000 optparse.py:964(set_description) + 8 0.000 0.000 0.000 0.000 optparse.py:980(_check_conflict) + 8 0.000 0.000 0.000 0.000 posixpath.py:59(join) + 1 0.000 0.000 0.724 0.724 profile:0(execfile('./afine.py')) + 0 0.000 0.000 profile:0(profiler) + + diff --git a/vigenera/zajecia.txt b/vigenera/zajecia.txt new file mode 100755 index 0000000..8f3e37e --- /dev/null +++ b/vigenera/zajecia.txt @@ -0,0 +1,17 @@ +k = kluczyk|kluczyk|kluczyk +m = tekstdo|zaszyfr|owania + + +M[a] = c[a + k] +M[b] = c[b + k] +M[c] = c[c + k] + +C = Mk +C[l] = M[l-k] + +E(k, m)[i] = m[i] + k[i mod N] + +dla i szukamy k[i] + +c[j] dla j = i mod N +c[j] = m[j] + k[i]/k
sbogutyn/krypto
d1cdb2b8f44f9e79c38586aa83e62e9f64642569
poprawiona kryptoanaliza za pomcą kryptogramu.
diff --git a/afine.py b/afine.py index a081aaf..a39a84e 100755 --- a/afine.py +++ b/afine.py @@ -1,239 +1,214 @@ #!/usr/bin/env python from string import ascii_lowercase, ascii_uppercase, letters, maketrans from optparse import OptionParser # szyfruje pojedyncza litera afinicznym (cezar to afiniczny z a = 1) def zaszyfruj_litere(litera,a,b): if (litera >= 'a' and litera <= 'z'): kod = list(ascii_lowercase).index(litera) nowy_kod = (kod * a + b) % 26 return list(ascii_lowercase)[nowy_kod] elif (litera >= 'A' and litera <= 'Z'): kod = list(ascii_uppercase).index(litera) nowy_kod = (kod * a + b) % 26 return list(ascii_uppercase)[nowy_kod] else: return litera; def zaszyfruj_alfabet(a, b): szyfr = lambda x : zaszyfruj_litere(x, a, b); return ''.join(map(szyfr, list(letters))) -def nznajdz_odwrotnosc(a, modn): - print "szukam odwrotnosci", a - # znalesc takie b, ze - # a * b % modn = 1 - u = 1; w = a; - x = 0; z = modn; - while (w != 0): - if w < z: - tmp = u - u = x - x = tmp - tmp = w - w = z - z = tmp - q = w / z - u = u - q * x - w = w - q * z - if z == 1: - if x < 0: - x = x + modn - return x - else: - return -1 - def znajdz_odwrotnosc(a, modn): for i in xrange(modn): if sprawdz_odwrotnosc(a, i, modn): return i return -1 def sprawdz_odwrotnosc(a, b, modn): if ((a * b) % modn) == 1: return True else: return False def odszyfruj_litere(litera, a, b): odw_a = znajdz_odwrotnosc(a, 26) if odw_a != -1: if (litera >= 'A' and litera <= 'Z'): kod = list(ascii_uppercase).index(litera) nowy_kod = (odw_a * (kod - b)) % 26 return list(ascii_uppercase)[nowy_kod] elif (litera >= 'a' and litera <= 'z'): kod = list(ascii_lowercase).index(litera) nowy_kod = (odw_a * (kod - b)) % 26 return list(ascii_lowercase)[nowy_kod] else: return litera def odszyfruj_alfabet(alfabet, a, b): odszyfruj = lambda x : odszyfruj_litere(x, a, b) return ''.join(map(odszyfruj, list(alfabet))) def tlumacz_tekst(tekst, alfabet1, alfabet2): transtab = maketrans(alfabet1, alfabet2) return tekst.translate(transtab) def zaszyfruj_tekst(tekst, a, b): zaszyfrowany_alfabet = zaszyfruj_alfabet(a, b) return tlumacz_tekst(tekst,letters, zaszyfrowany_alfabet) def odszyfruj_tekst(tekst, a, b): zaszyfrowany_alfabet = zaszyfruj_alfabet(a, b) return tlumacz_tekst(tekst, zaszyfrowany_alfabet, letters) def nwd(a, b): x = a y = b while (y != 0): c = x % y x = y y = c return x def odczytaj_plik(nazwa_pliku): plik = open(nazwa_pliku, "r") tresc = plik.read() plik.close() return tresc def zapisz_do_pliku(nazwa_pliku, tresc): plik = open(nazwa_pliku, "w+") plik.write(tresc) plik.close() def wczytaj_klucz(nazwa_pliku): tresc = odczytaj_plik(nazwa_pliku) wartosci = tresc.split(',') if len(wartosci) == 1: return (int(wartosci[0])) elif len(wartosci) == 2: return (int(wartosci[0]), int(wartosci[1])) if __name__ == "__main__": PLIK_PLAIN="plain.txt" PLIK_CRYPTO="crypto.txt" PLIK_DECRYPT="decrypt.txt" PLIK_EXTRA="extra.txt" PLIK_KEY="key.txt" parser = OptionParser(usage="Program szyfrujacy i deszyfrujacy.", version="%prog 1.0") parser.add_option("-c", "--cezar", action="store_true", dest="cezar_flag", default=False, help="uzyj szyfru cezara") parser.add_option("-a", "--afiniczny", action="store_true", dest="afiniczny_flag", default=False, help="uzyj szyfru afinicznego") parser.add_option("-d", "--deszyfrowanie", action="store_true", dest="deszyfruj_flag", default=False, help="deszyfrowanie pliku crypto.txt") parser.add_option("-e", "--szyfrowanie", action="store_true", dest="szyfruj_flag", default=False, help="szyfrowanie pliku plain.txt") parser.add_option("-j", "--jawny", action="store_true", dest="jawny_flag", default=False, help="kryptoanaliza z tekstem jawnym") parser.add_option("-k", "--krypto", action="store_true", dest="krypto_flag", default=False, help="kryptoanaliza tylko za pomoca kryptogramu") (options, args) = parser.parse_args() if len(args) != 0: parser.error("zla liczba argumentow") if options.afiniczny_flag: if options.szyfruj_flag: print "Szyfrowanie afinicznym" klucze = wczytaj_klucz(PLIK_KEY) tekst = odczytaj_plik(PLIK_PLAIN) zapisz_do_pliku(PLIK_CRYPTO, zaszyfruj_tekst(tekst, klucze[0], klucze[1])) elif options.deszyfruj_flag: print "Deszyfrowanie afinicznym" klucze = wczytaj_klucz(PLIK_KEY) zaszyfrowany_tekst = odczytaj_plik(PLIK_CRYPTO) zapisz_do_pliku(PLIK_DECRYPT, odszyfruj_tekst(zaszyfrowany_tekst, klucze[0], klucze[1])) elif options.jawny_flag: print "kryptoanaliza z tekstem jawnym" - pomoc = odczytaj_plik(PLIK_EXTRA) + pomoc = odczytaj_plik(PLIK_EXTRA).strip() zaszyfrowany_tekst = odczytaj_plik(PLIK_CRYPTO) if (len(pomoc) < len(zaszyfrowany_tekst)): dlugosc = len(pomoc) else: dlugosc = len(zaszyfrowany_tekst) wyniki = set() for i in xrange(dlugosc): wynik = set() - print "next" for a in range(26): if nwd (a, 26) == 1: for b in range(26): if odszyfruj_litere(zaszyfrowany_tekst[i], a ,b) == pomoc[i]: wynik.add( (a, b) ) if len(wyniki) == 0: for i in wynik: wyniki.add(i) else: print "wyniki = ", wyniki, " & ", wynik - wyniki = wyniki & wyniki + wyniki = wyniki & wynik print pomoc[dlugosc - 1] print zaszyfrowany_tekst[dlugosc - 1] print wyniki elif options.krypto_flag: zaszyfrowany_tekst = odczytaj_plik(PLIK_CRYPTO) tekst = "" for a in range(26): if nwd(a, 26) == 1: for b in range(26): tekst += odszyfruj_tekst(zaszyfrowany_tekst, a, b) + "\n" zapisz_do_pliku(PLIK_DECRYPT, tekst) print "kryptoanaliza za pomoca kryptogramu" elif options.cezar_flag: print "cezar!" if options.szyfruj_flag: print "szyfrowanie" elif options.deszyfruj_flag: print "deszyfrowanie" elif options.jawny_flag: print "kryptoanaliza z tekstem jawnym" elif options.krypto_flag: print "kryptoanaliza za pomoca kryptogramu" else: print "Klucze: ", wczytaj_klucz(PLIK_KEY) print zaszyfruj_litere('A', 1, 1) print zaszyfruj_litere('B', 2, 1) print zaszyfruj_litere('Z', 1, 1) print zaszyfruj_alfabet(1,1) for i in range(1, 25): if nwd(i, 26) == 1: print "a = ", i print "Zaszyfrowany: ", zaszyfruj_tekst("ala ma kota", i, 1) print "Odszyfrowany: ", odszyfruj_tekst(zaszyfruj_tekst("ala ma kota", i, 1), i, 1) try: print odszyfruj_alfabet(zaszyfruj_alfabet(26, 3), 26, 3) except TypeError: print "NWD(a, 26) != 1" try: for i in xrange(26): print "Odwrotnosc: ", i , " to: ", znajdz_odwrotnosc(i ,26) except TypeError: print "brak odwrotnosci" diff --git a/crypto.txt b/crypto.txt old mode 100644 new mode 100755 diff --git a/decrypt.txt b/decrypt.txt old mode 100644 new mode 100755 diff --git a/extra.txt b/extra.txt old mode 100644 new mode 100755 diff --git a/key.txt b/key.txt old mode 100644 new mode 100755 diff --git a/plain.txt b/plain.txt old mode 100644 new mode 100755
sbogutyn/krypto
93e0bef9388f6923ba7bbf22f14d31d4b2390e07
pierwsza wrzutka
diff --git a/afine.py b/afine.py new file mode 100755 index 0000000..a081aaf --- /dev/null +++ b/afine.py @@ -0,0 +1,239 @@ +#!/usr/bin/env python +from string import ascii_lowercase, ascii_uppercase, letters, maketrans +from optparse import OptionParser + +# szyfruje pojedyncza litera afinicznym (cezar to afiniczny z a = 1) +def zaszyfruj_litere(litera,a,b): + if (litera >= 'a' and litera <= 'z'): + kod = list(ascii_lowercase).index(litera) + nowy_kod = (kod * a + b) % 26 + return list(ascii_lowercase)[nowy_kod] + elif (litera >= 'A' and litera <= 'Z'): + kod = list(ascii_uppercase).index(litera) + nowy_kod = (kod * a + b) % 26 + return list(ascii_uppercase)[nowy_kod] + else: + return litera; + +def zaszyfruj_alfabet(a, b): + szyfr = lambda x : zaszyfruj_litere(x, a, b); + return ''.join(map(szyfr, list(letters))) + +def nznajdz_odwrotnosc(a, modn): + print "szukam odwrotnosci", a + # znalesc takie b, ze + # a * b % modn = 1 + u = 1; w = a; + x = 0; z = modn; + while (w != 0): + if w < z: + tmp = u + u = x + x = tmp + tmp = w + w = z + z = tmp + q = w / z + u = u - q * x + w = w - q * z + if z == 1: + if x < 0: + x = x + modn + return x + else: + return -1 + +def znajdz_odwrotnosc(a, modn): + for i in xrange(modn): + if sprawdz_odwrotnosc(a, i, modn): + return i + return -1 + +def sprawdz_odwrotnosc(a, b, modn): + if ((a * b) % modn) == 1: + return True + else: + return False + +def odszyfruj_litere(litera, a, b): + odw_a = znajdz_odwrotnosc(a, 26) + if odw_a != -1: + if (litera >= 'A' and litera <= 'Z'): + kod = list(ascii_uppercase).index(litera) + nowy_kod = (odw_a * (kod - b)) % 26 + return list(ascii_uppercase)[nowy_kod] + elif (litera >= 'a' and litera <= 'z'): + kod = list(ascii_lowercase).index(litera) + nowy_kod = (odw_a * (kod - b)) % 26 + return list(ascii_lowercase)[nowy_kod] + else: + return litera + +def odszyfruj_alfabet(alfabet, a, b): + odszyfruj = lambda x : odszyfruj_litere(x, a, b) + return ''.join(map(odszyfruj, list(alfabet))) + +def tlumacz_tekst(tekst, alfabet1, alfabet2): + transtab = maketrans(alfabet1, alfabet2) + return tekst.translate(transtab) + +def zaszyfruj_tekst(tekst, a, b): + zaszyfrowany_alfabet = zaszyfruj_alfabet(a, b) + return tlumacz_tekst(tekst,letters, zaszyfrowany_alfabet) + +def odszyfruj_tekst(tekst, a, b): + zaszyfrowany_alfabet = zaszyfruj_alfabet(a, b) + return tlumacz_tekst(tekst, zaszyfrowany_alfabet, letters) + +def nwd(a, b): + x = a + y = b + while (y != 0): + c = x % y + x = y + y = c + return x + +def odczytaj_plik(nazwa_pliku): + plik = open(nazwa_pliku, "r") + tresc = plik.read() + plik.close() + return tresc + +def zapisz_do_pliku(nazwa_pliku, tresc): + plik = open(nazwa_pliku, "w+") + plik.write(tresc) + plik.close() + +def wczytaj_klucz(nazwa_pliku): + tresc = odczytaj_plik(nazwa_pliku) + wartosci = tresc.split(',') + if len(wartosci) == 1: + return (int(wartosci[0])) + elif len(wartosci) == 2: + return (int(wartosci[0]), int(wartosci[1])) + +if __name__ == "__main__": + PLIK_PLAIN="plain.txt" + PLIK_CRYPTO="crypto.txt" + PLIK_DECRYPT="decrypt.txt" + PLIK_EXTRA="extra.txt" + PLIK_KEY="key.txt" + + parser = OptionParser(usage="Program szyfrujacy i deszyfrujacy.", + version="%prog 1.0") + parser.add_option("-c", "--cezar", + action="store_true", + dest="cezar_flag", + default=False, + help="uzyj szyfru cezara") + parser.add_option("-a", "--afiniczny", + action="store_true", + dest="afiniczny_flag", + default=False, + help="uzyj szyfru afinicznego") + parser.add_option("-d", "--deszyfrowanie", + action="store_true", + dest="deszyfruj_flag", + default=False, + help="deszyfrowanie pliku crypto.txt") + parser.add_option("-e", "--szyfrowanie", + action="store_true", + dest="szyfruj_flag", + default=False, + help="szyfrowanie pliku plain.txt") + parser.add_option("-j", "--jawny", + action="store_true", + dest="jawny_flag", + default=False, + help="kryptoanaliza z tekstem jawnym") + parser.add_option("-k", "--krypto", + action="store_true", + dest="krypto_flag", + default=False, + help="kryptoanaliza tylko za pomoca kryptogramu") + (options, args) = parser.parse_args() + if len(args) != 0: + parser.error("zla liczba argumentow") + + if options.afiniczny_flag: + if options.szyfruj_flag: + print "Szyfrowanie afinicznym" + klucze = wczytaj_klucz(PLIK_KEY) + tekst = odczytaj_plik(PLIK_PLAIN) + zapisz_do_pliku(PLIK_CRYPTO, zaszyfruj_tekst(tekst, klucze[0], klucze[1])) + elif options.deszyfruj_flag: + print "Deszyfrowanie afinicznym" + klucze = wczytaj_klucz(PLIK_KEY) + zaszyfrowany_tekst = odczytaj_plik(PLIK_CRYPTO) + zapisz_do_pliku(PLIK_DECRYPT, odszyfruj_tekst(zaszyfrowany_tekst, klucze[0], klucze[1])) + elif options.jawny_flag: + print "kryptoanaliza z tekstem jawnym" + pomoc = odczytaj_plik(PLIK_EXTRA) + zaszyfrowany_tekst = odczytaj_plik(PLIK_CRYPTO) + if (len(pomoc) < len(zaszyfrowany_tekst)): + dlugosc = len(pomoc) + else: + dlugosc = len(zaszyfrowany_tekst) + wyniki = set() + for i in xrange(dlugosc): + wynik = set() + print "next" + for a in range(26): + if nwd (a, 26) == 1: + for b in range(26): + if odszyfruj_litere(zaszyfrowany_tekst[i], a ,b) == pomoc[i]: + wynik.add( (a, b) ) + if len(wyniki) == 0: + for i in wynik: + wyniki.add(i) + else: + print "wyniki = ", wyniki, " & ", wynik + wyniki = wyniki & wyniki + print pomoc[dlugosc - 1] + print zaszyfrowany_tekst[dlugosc - 1] + print wyniki + + + + elif options.krypto_flag: + zaszyfrowany_tekst = odczytaj_plik(PLIK_CRYPTO) + tekst = "" + for a in range(26): + if nwd(a, 26) == 1: + for b in range(26): + tekst += odszyfruj_tekst(zaszyfrowany_tekst, a, b) + "\n" + zapisz_do_pliku(PLIK_DECRYPT, tekst) + + print "kryptoanaliza za pomoca kryptogramu" + + elif options.cezar_flag: + print "cezar!" + if options.szyfruj_flag: + print "szyfrowanie" + elif options.deszyfruj_flag: + print "deszyfrowanie" + elif options.jawny_flag: + print "kryptoanaliza z tekstem jawnym" + elif options.krypto_flag: + print "kryptoanaliza za pomoca kryptogramu" + else: + print "Klucze: ", wczytaj_klucz(PLIK_KEY) + print zaszyfruj_litere('A', 1, 1) + print zaszyfruj_litere('B', 2, 1) + print zaszyfruj_litere('Z', 1, 1) + print zaszyfruj_alfabet(1,1) + for i in range(1, 25): + if nwd(i, 26) == 1: + print "a = ", i + print "Zaszyfrowany: ", zaszyfruj_tekst("ala ma kota", i, 1) + print "Odszyfrowany: ", odszyfruj_tekst(zaszyfruj_tekst("ala ma kota", i, 1), i, 1) + try: + print odszyfruj_alfabet(zaszyfruj_alfabet(26, 3), 26, 3) + except TypeError: + print "NWD(a, 26) != 1" + try: + for i in xrange(26): + print "Odwrotnosc: ", i , " to: ", znajdz_odwrotnosc(i ,26) + except TypeError: + print "brak odwrotnosci" diff --git a/crypto.txt b/crypto.txt new file mode 100644 index 0000000..0f2224d --- /dev/null +++ b/crypto.txt @@ -0,0 +1,4 @@ +Vauadkpx rp d lvkx nvqexqrxqu, cgxorigx, dqs avjxkczg grikdkt cvk adkprqh nvlldqs-grqx vaurvqp umdq umx vgs hxuvau lvszgx. +vauadkpx zpxp d lvkx sxngdkdurex putgx vc nvlldqs-grqx adkprqh: tvz nkxdux dq rqpudqnx vc VaurvqAdkpxk, avazgdux ru jrum vaurvqp, +dqs adkpx umx nvlldqs grqx. vauadkpx dggvjp zpxkp uv paxnrct vaurvqp rq umx nvqexqurvqdg HQZ/AVPRO ptqudo, dqs dssrurvqdggt hxqxkduxp +zpdhx dqs mxga lxppdhxp cvk tvz. diff --git a/decrypt.txt b/decrypt.txt new file mode 100644 index 0000000..4dad810 --- /dev/null +++ b/decrypt.txt @@ -0,0 +1,1560 @@ +Vauadkpx rp d lvkx nvqexqrxqu, cgxorigx, dqs avjxkczg grikdkt cvk adkprqh nvlldqs-grqx vaurvqp umdq umx vgs hxuvau lvszgx. +vauadkpx zpxp d lvkx sxngdkdurex putgx vc nvlldqs-grqx adkprqh: tvz nkxdux dq rqpudqnx vc VaurvqAdkpxk, avazgdux ru jrum vaurvqp, +dqs adkpx umx nvlldqs grqx. vauadkpx dggvjp zpxkp uv paxnrct vaurvqp rq umx nvqexqurvqdg HQZ/AVPRO ptqudo, dqs dssrurvqdggt hxqxkduxp +zpdhx dqs mxga lxppdhxp cvk tvz. + +Uztzcjow qo c kujw mupdwpqwpt, bfwnqhfw, cpr zuiwjbyf fqhjcjs buj zcjoqpg mukkcpr-fqpw uztqupo tlcp tlw ufr gwtuzt kuryfw. +uztzcjow yowo c kujw rwmfcjctqdw otsfw ub mukkcpr-fqpw zcjoqpg: suy mjwctw cp qpotcpmw ub UztqupZcjowj, zuzyfctw qt iqtl uztqupo, +cpr zcjow tlw mukkcpr fqpw. uztzcjow cffuio yowjo tu ozwmqbs uztqupo qp tlw mupdwptqupcf GPY/ZUOQN osptcn, cpr crrqtqupcffs gwpwjctwo +yocgw cpr lwfz kwoocgwo buj suy. + +Tysybinv pn b jtiv ltocvopvos, aevmpgev, boq ythviaxe epgibir ati ybinpof ltjjboq-epov tyspton skbo skv teq fvstys jtqxev. +tysybinv xnvn b jtiv qvlebibspcv nsrev ta ltjjboq-epov ybinpof: rtx livbsv bo ponsbolv ta TysptoYbinvi, ytyxebsv ps hpsk tyspton, +boq ybinv skv ltjjboq epov. tysybinv beethn xnvin st nyvlpar tyspton po skv ltocvosptobe FOX/YTNPM nrosbm, boq bqqpsptobeer fvovibsvn +xnbfv boq kvey jvnnbfvn ati rtx. + +Sxrxahmu om a ishu ksnbunounr, zdulofdu, anp xsguhzwd dofhahq zsh xahmone ksiianp-donu sxrosnm rjan rju sdp eursxr ispwdu. +sxrxahmu wmum a ishu pukdaharobu mrqdu sz ksiianp-donu xahmone: qsw khuaru an onmranku sz SxrosnXahmuh, xsxwdaru or gorj sxrosnm, +anp xahmu rju ksiianp donu. sxrxahmu addsgm wmuhm rs mxukozq sxrosnm on rju ksnbunrosnad ENW/XSMOL mqnral, anp apporosnaddq eunuharum +wmaeu anp judx iummaeum zsh qsw. + +Rwqwzglt nl z hrgt jrmatmntmq, yctknect, zmo wrftgyvc cnegzgp yrg wzglnmd jrhhzmo-cnmt rwqnrml qizm qit rco dtqrwq hrovct. +rwqwzglt vltl z hrgt otjczgzqnat lqpct ry jrhhzmo-cnmt wzglnmd: prv jgtzqt zm nmlqzmjt ry RwqnrmWzgltg, wrwvczqt nq fnqi rwqnrml, +zmo wzglt qit jrhhzmo cnmt. rwqwzglt zccrfl vltgl qr lwtjnyp rwqnrml nm qit jrmatmqnrmzc DMV/WRLNK lpmqzk, zmo zoonqnrmzccp dtmtgzqtl +vlzdt zmo itcw htllzdtl yrg prv. + +Qvpvyfks mk y gqfs iqlzslmslp, xbsjmdbs, yln vqesfxub bmdfyfo xqf vyfkmlc iqggyln-bmls qvpmqlk phyl phs qbn cspqvp gqnubs. +qvpvyfks uksk y gqfs nsibyfypmzs kpobs qx iqggyln-bmls vyfkmlc: oqu ifsyps yl mlkpylis qx QvpmqlVyfksf, vqvubyps mp emph qvpmqlk, +yln vyfks phs iqggyln bmls. qvpvyfks ybbqek uksfk pq kvsimxo qvpmqlk ml phs iqlzslpmqlyb CLU/VQKMJ kolpyj, yln ynnmpmqlybbo cslsfypsk +ukycs yln hsbv gskkycsk xqf oqu. + +Puouxejr lj x fper hpkyrklrko, warilcar, xkm updrewta alcexen wpe uxejlkb hpffxkm-alkr puolpkj ogxk ogr pam bropuo fpmtar. +puouxejr tjrj x fper mrhaxexolyr jonar pw hpffxkm-alkr uxejlkb: npt herxor xk lkjoxkhr pw PuolpkUxejre, uputaxor lo dlog puolpkj, +xkm uxejr ogr hpffxkm alkr. puouxejr xaapdj tjrej op jurhlwn puolpkj lk ogr hpkyrkolpkxa BKT/UPJLI jnkoxi, xkm xmmlolpkxaan brkrexorj +tjxbr xkm grau frjjxbrj wpe npt. + +Otntwdiq ki w eodq gojxqjkqjn, vzqhkbzq, wjl tocqdvsz zkbdwdm vod twdikja goeewjl-zkjq otnkoji nfwj nfq ozl aqnotn eolszq. +otntwdiq siqi w eodq lqgzwdwnkxq inmzq ov goeewjl-zkjq twdikja: mos gdqwnq wj kjinwjgq ov OtnkojTwdiqd, totszwnq kn cknf otnkoji, +wjl twdiq nfq goeewjl zkjq. otntwdiq wzzoci siqdi no itqgkvm otnkoji kj nfq gojxqjnkojwz AJS/TOIKH imjnwh, wjl wllknkojwzzm aqjqdwnqi +siwaq wjl fqzt eqiiwaqi vod mos. + +Nsmsvchp jh v dncp fniwpijpim, uypgjayp, vik snbpcury yjacvcl unc svchjiz fnddvik-yjip nsmjnih mevi mep nyk zpmnsm dnkryp. +nsmsvchp rhph v dncp kpfyvcvmjwp hmlyp nu fnddvik-yjip svchjiz: lnr fcpvmp vi jihmvifp nu NsmjniSvchpc, snsryvmp jm bjme nsmjnih, +vik svchp mep fnddvik yjip. nsmsvchp vyynbh rhpch mn hspfjul nsmjnih ji mep fniwpimjnivy ZIR/SNHJG hlimvg, vik vkkjmjnivyyl zpipcvmph +rhvzp vik epys dphhvzph unc lnr. + +Mrlrubgo ig u cmbo emhvohiohl, txofizxo, uhj rmaobtqx xizbubk tmb rubgihy emccuhj-xiho mrlimhg lduh ldo mxj yolmrl cmjqxo. +mrlrubgo qgog u cmbo joexubulivo glkxo mt emccuhj-xiho rubgihy: kmq eboulo uh ihgluheo mt MrlimhRubgob, rmrqxulo il aild mrlimhg, +uhj rubgo ldo emccuhj xiho. mrlrubgo uxxmag qgobg lm groeitk mrlimhg ih ldo emhvohlimhux YHQ/RMGIF gkhluf, uhj ujjilimhuxxk yohobulog +qguyo uhj doxr cogguyog tmb kmq. + +Lqkqtafn hf t blan dlgunghngk, swnehywn, tgi qlznaspw whyataj sla qtafhgx dlbbtgi-whgn lqkhlgf kctg kcn lwi xnklqk blipwn. +lqkqtafn pfnf t blan indwtatkhun fkjwn ls dlbbtgi-whgn qtafhgx: jlp dantkn tg hgfktgdn ls LqkhlgQtafna, qlqpwtkn hk zhkc lqkhlgf, +tgi qtafn kcn dlbbtgi whgn. lqkqtafn twwlzf pfnaf kl fqndhsj lqkhlgf hg kcn dlgungkhlgtw XGP/QLFHE fjgkte, tgi tiihkhlgtwwj xngnatknf +pftxn tgi cnwq bnfftxnf sla jlp. + +Kpjpszem ge s akzm ckftmfgmfj, rvmdgxvm, sfh pkymzrov vgxzszi rkz pszegfw ckaasfh-vgfm kpjgkfe jbsf jbm kvh wmjkpj akhovm. +kpjpszem oeme s akzm hmcvszsjgtm ejivm kr ckaasfh-vgfm pszegfw: iko czmsjm sf gfejsfcm kr KpjgkfPszemz, pkpovsjm gj ygjb kpjgkfe, +sfh pszem jbm ckaasfh vgfm. kpjpszem svvkye oemze jk epmcgri kpjgkfe gf jbm ckftmfjgkfsv WFO/PKEGD eifjsd, sfh shhgjgkfsvvi wmfmzsjme +oeswm sfh bmvp ameeswme rkz iko. + +Joiorydl fd r zjyl bjesleflei, qulcfwul, reg ojxlyqnu ufwyryh qjy orydfev bjzzreg-ufel joifjed iare ial jug vlijoi zjgnul. +joiorydl ndld r zjyl glburyrifsl dihul jq bjzzreg-ufel orydfev: hjn bylril re fedirebl jq JoifjeOrydly, ojonuril fi xfia joifjed, +reg orydl ial bjzzreg ufel. joiorydl ruujxd ndlyd ij dolbfqh joifjed fe ial bjesleifjeru VEN/OJDFC dheirc, reg rggfifjeruuh vlelyrild +ndrvl reg aluo zlddrvld qjy hjn. + +Inhnqxck ec q yixk aidrkdekdh, ptkbevtk, qdf niwkxpmt tevxqxg pix nqxcedu aiyyqdf-tedk inheidc hzqd hzk itf ukhinh yifmtk. +inhnqxck mckc q yixk fkatqxqherk chgtk ip aiyyqdf-tedk nqxcedu: gim axkqhk qd edchqdak ip InheidNqxckx, ninmtqhk eh wehz inheidc, +qdf nqxck hzk aiyyqdf tedk. inhnqxck qttiwc mckxc hi cnkaepg inheidc ed hzk aidrkdheidqt UDM/NICEB cgdhqb, qdf qffeheidqttg ukdkxqhkc +mcquk qdf zktn ykccqukc pix gim. + +Hmgmpwbj db p xhwj zhcqjcdjcg, osjadusj, pce mhvjwols sduwpwf ohw mpwbdct zhxxpce-sdcj hmgdhcb gypc gyj hse tjghmg xhelsj. +hmgmpwbj lbjb p xhwj ejzspwpgdqj bgfsj ho zhxxpce-sdcj mpwbdct: fhl zwjpgj pc dcbgpczj ho HmgdhcMpwbjw, mhmlspgj dg vdgy hmgdhcb, +pce mpwbj gyj zhxxpce sdcj. hmgmpwbj psshvb lbjwb gh bmjzdof hmgdhcb dc gyj zhcqjcgdhcps TCL/MHBDA bfcgpa, pce peedgdhcpssf tjcjwpgjb +lbptj pce yjsm xjbbptjb ohw fhl. + +Glflovai ca o wgvi ygbpibcibf, nrizctri, obd lguivnkr rctvove ngv lovacbs ygwwobd-rcbi glfcgba fxob fxi grd sifglf wgdkri. +glflovai kaia o wgvi diyrovofcpi aferi gn ygwwobd-rcbi lovacbs: egk yviofi ob cbafobyi gn GlfcgbLovaiv, lglkrofi cf ucfx glfcgba, +obd lovai fxi ygwwobd rcbi. glflovai orrgua kaiva fg aliycne glfcgba cb fxi ygbpibfcgbor SBK/LGACZ aebfoz, obd oddcfcgborre sibivofia +kaosi obd xirl wiaaosia ngv egk. + +Fkeknuzh bz n vfuh xfaohabhae, mqhybsqh, nac kfthumjq qbsunud mfu knuzbar xfvvnac-qbah fkebfaz ewna ewh fqc rhefke vfcjqh. +fkeknuzh jzhz n vfuh chxqnuneboh zedqh fm xfvvnac-qbah knuzbar: dfj xuhneh na bazenaxh fm FkebfaKnuzhu, kfkjqneh be tbew fkebfaz, +nac knuzh ewh xfvvnac qbah. fkeknuzh nqqftz jzhuz ef zkhxbmd fkebfaz ba ewh xfaohaebfanq RAJ/KFZBY zdaeny, nac nccbebfanqqd rhahunehz +jznrh nac whqk vhzznrhz mfu dfj. + +Ejdjmtyg ay m uetg wezngzagzd, lpgxarpg, mzb jesgtlip partmtc let jmtyazq weuumzb-pazg ejdaezy dvmz dvg epb qgdejd uebipg. +ejdjmtyg iygy m uetg bgwpmtmdang ydcpg el weuumzb-pazg jmtyazq: cei wtgmdg mz azydmzwg el EjdaezJmtygt, jejipmdg ad sadv ejdaezy, +mzb jmtyg dvg weuumzb pazg. ejdjmtyg mppesy iygty de yjgwalc ejdaezy az dvg wezngzdaezmp QZI/JEYAX yczdmx, mzb mbbadaezmppc qgzgtmdgy +iymqg mzb vgpj ugyymqgy let cei. + +Dicilsxf zx l tdsf vdymfyzfyc, kofwzqof, lya idrfskho ozqslsb kds ilsxzyp vdttlya-ozyf diczdyx culy cuf doa pfcdic tdahof. +dicilsxf hxfx l tdsf afvolslczmf xcbof dk vdttlya-ozyf ilsxzyp: bdh vsflcf ly zyxclyvf dk DiczdyIlsxfs, idiholcf zc rzcu diczdyx, +lya ilsxf cuf vdttlya ozyf. dicilsxf loodrx hxfsx cd xifvzkb diczdyx zy cuf vdymfyczdylo PYH/IDXZW xbyclw, lya laazczdyloob pfyfslcfx +hxlpf lya ufoi tfxxlpfx kds bdh. + +Chbhkrwe yw k scre ucxlexyexb, jnevypne, kxz hcqerjgn nyprkra jcr hkrwyxo ucsskxz-nyxe chbycxw btkx bte cnz oebchb sczgne. +chbhkrwe gwew k scre zeunkrkbyle wbane cj ucsskxz-nyxe hkrwyxo: acg urekbe kx yxwbkxue cj ChbycxHkrwer, hchgnkbe yb qybt chbycxw, +kxz hkrwe bte ucsskxz nyxe. chbhkrwe knncqw gwerw bc wheuyja chbycxw yx bte ucxlexbycxkn OXG/HCWYV waxbkv, kxz kzzybycxknna oexerkbew +gwkoe kxz tenh sewwkoew jcr acg. + +Bgagjqvd xv j rbqd tbwkdwxdwa, imduxomd, jwy gbpdqifm mxoqjqz ibq gjqvxwn tbrrjwy-mxwd bgaxbwv asjw asd bmy ndabga rbyfmd. +bgagjqvd fvdv j rbqd ydtmjqjaxkd vazmd bi tbrrjwy-mxwd gjqvxwn: zbf tqdjad jw xwvajwtd bi BgaxbwGjqvdq, gbgfmjad xa pxas bgaxbwv, +jwy gjqvd asd tbrrjwy mxwd. bgagjqvd jmmbpv fvdqv ab vgdtxiz bgaxbwv xw asd tbwkdwaxbwjm NWF/GBVXU vzwaju, jwy jyyxaxbwjmmz ndwdqjadv +fvjnd jwy sdmg rdvvjndv ibq zbf. + +Afzfipuc wu i qapc savjcvwcvz, hlctwnlc, ivx faocphel lwnpipy hap fipuwvm saqqivx-lwvc afzwavu zriv zrc alx mczafz qaxelc. +afzfipuc eucu i qapc xcslipizwjc uzylc ah saqqivx-lwvc fipuwvm: yae spcizc iv wvuzivsc ah AfzwavFipucp, fafelizc wz owzr afzwavu, +ivx fipuc zrc saqqivx lwvc. afzfipuc illaou eucpu za ufcswhy afzwavu wv zrc savjcvzwavil MVE/FAUWT uyvzit, ivx ixxwzwavilly mcvcpizcu +euimc ivx rclf qcuuimcu hap yae. + +Zeyehotb vt h pzob rzuibuvbuy, gkbsvmkb, huw eznbogdk kvmohox gzo ehotvul rzpphuw-kvub zeyvzut yqhu yqb zkw lbyzey pzwdkb. +zeyehotb dtbt h pzob wbrkhohyvib tyxkb zg rzpphuw-kvub ehotvul: xzd robhyb hu vutyhurb zg ZeyvzuEhotbo, ezedkhyb vy nvyq zeyvzut, +huw ehotb yqb rzpphuw kvub. zeyehotb hkkznt dtbot yz tebrvgx zeyvzut vu yqb rzuibuyvzuhk LUD/EZTVS txuyhs, huw hwwvyvzuhkkx lbubohybt +dthlb huw qbke pbtthlbt gzo xzd. + +Ydxdgnsa us g oyna qythatuatx, fjarulja, gtv dymanfcj julngnw fyn dgnsutk qyoogtv-juta ydxuyts xpgt xpa yjv kaxydx oyvcja. +ydxdgnsa csas g oyna vaqjgngxuha sxwja yf qyoogtv-juta dgnsutk: wyc qnagxa gt utsxgtqa yf YdxuytDgnsan, dydcjgxa ux muxp ydxuyts, +gtv dgnsa xpa qyoogtv juta. ydxdgnsa gjjyms csans xy sdaqufw ydxuyts ut xpa qythatxuytgj KTC/DYSUR swtxgr, gtv gvvuxuytgjjw katangxas +csgka gtv pajd oassgkas fyn wyc. + +Xcwcfmrz tr f nxmz pxsgzstzsw, eizqtkiz, fsu cxlzmebi itkmfmv exm cfmrtsj pxnnfsu-itsz xcwtxsr wofs woz xiu jzwxcw nxubiz. +xcwcfmrz brzr f nxmz uzpifmfwtgz rwviz xe pxnnfsu-itsz cfmrtsj: vxb pmzfwz fs tsrwfspz xe XcwtxsCfmrzm, cxcbifwz tw ltwo xcwtxsr, +fsu cfmrz woz pxnnfsu itsz. xcwcfmrz fiixlr brzmr wx rczptev xcwtxsr ts woz pxsgzswtxsfi JSB/CXRTQ rvswfq, fsu fuutwtxsfiiv jzszmfwzr +brfjz fsu ozic nzrrfjzr exm vxb. + +Wbvbelqy sq e mwly owrfyrsyrv, dhypsjhy, ert bwkyldah hsjlelu dwl belqsri owmmert-hsry wbvswrq vner vny wht iyvwbv mwtahy. +wbvbelqy aqyq e mwly tyohelevsfy qvuhy wd owmmert-hsry belqsri: uwa olyevy er srqveroy wd WbvswrBelqyl, bwbahevy sv ksvn wbvswrq, +ert belqy vny owmmert hsry. wbvbelqy ehhwkq aqylq vw qbyosdu wbvswrq sr vny owrfyrvswreh IRA/BWQSP qurvep, ert ettsvswrehhu iyrylevyq +aqeiy ert nyhb myqqeiyq dwl uwa. + +Hayabmfz xf b vhmz nhokzoxzoy, sczwxucz, bog ahdzmsrc cxumbmp shm abmfxol nhvvbog-cxoz hayxhof yebo yez hcg lzyhay vhgrcz. +hayabmfz rfzf b vhmz gzncbmbyxkz fypcz hs nhvvbog-cxoz abmfxol: phr nmzbyz bo xofybonz hs HayxhoAbmfzm, aharcbyz xy dxye hayxhof, +bog abmfz yez nhvvbog cxoz. hayabmfz bcchdf rfzmf yh faznxsp hayxhof xo yez nhokzoyxhobc LOR/AHFXW fpoybw, bog bggxyxhobccp lzozmbyzf +rfblz bog ezca vzffblzf shm phr. + +Yrprsdwq ow s mydq eyfbqfoqfp, jtqnoltq, sfx ryuqdjit toldsdg jyd rsdwofc eymmsfx-tofq yrpoyfw pvsf pvq ytx cqpyrp myxitq. +yrprsdwq iwqw s mydq xqetsdspobq wpgtq yj eymmsfx-tofq rsdwofc: gyi edqspq sf ofwpsfeq yj YrpoyfRsdwqd, ryritspq op uopv yrpoyfw, +sfx rsdwq pvq eymmsfx tofq. yrprsdwq sttyuw iwqdw py wrqeojg yrpoyfw of pvq eyfbqfpoyfst CFI/RYWON wgfpsn, sfx sxxopoyfsttg cqfqdspqw +iwscq sfx vqtr mqwwscqw jyd gyi. + +Pigijunh fn j dpuh vpwshwfhwg, akhefckh, jwo iplhuazk kfcujux apu ijunfwt vpddjwo-kfwh pigfpwn gmjw gmh pko thgpig dpozkh. +pigijunh znhn j dpuh ohvkjujgfsh ngxkh pa vpddjwo-kfwh ijunfwt: xpz vuhjgh jw fwngjwvh pa PigfpwIjunhu, ipizkjgh fg lfgm pigfpwn, +jwo ijunh gmh vpddjwo kfwh. pigijunh jkkpln znhun gp nihvfax pigfpwn fw gmh vpwshwgfpwjk TWZ/IPNFE nxwgje, jwo joofgfpwjkkx thwhujghn +znjth jwo mhki dhnnjthn apu xpz. + +Gzxzaley we a ugly mgnjynwynx, rbyvwtby, anf zgcylrqb bwtlalo rgl zalewnk mguuanf-bwny gzxwgne xdan xdy gbf kyxgzx ugfqby. +gzxzaley qeye a ugly fymbalaxwjy exoby gr mguuanf-bwny zalewnk: ogq mlyaxy an wnexanmy gr GzxwgnZaleyl, zgzqbaxy wx cwxd gzxwgne, +anf zaley xdy mguuanf bwny. gzxzaley abbgce qeyle xg ezymwro gzxwgne wn xdy mgnjynxwgnab KNQ/ZGEWV eonxav, anf affwxwgnabbo kynylaxye +qeaky anf dybz uyeeakye rgl ogq. + +Xqoqrcvp nv r lxcp dxeapenpeo, ispmnksp, rew qxtpcihs snkcrcf ixc qrcvneb dxllrew-snep xqonxev oure oup xsw bpoxqo lxwhsp. +xqoqrcvp hvpv r lxcp wpdsrcronap vofsp xi dxllrew-snep qrcvneb: fxh dcprop re nevoredp xi XqonxeQrcvpc, qxqhsrop no tnou xqonxev, +rew qrcvp oup dxllrew snep. xqoqrcvp rssxtv hvpcv ox vqpdnif xqonxev ne oup dxeapeonxers BEH/QXVNM vfeorm, rew rwwnonxerssf bpepcropv +hvrbp rew upsq lpvvrbpv ixc fxh. + +Ohfhitmg em i cotg uovrgvegvf, zjgdebjg, ivn hokgtzyj jebtitw zot hitmevs uoccivn-jevg ohfeovm fliv flg ojn sgfohf conyjg. +ohfhitmg ymgm i cotg ngujitiferg mfwjg oz uoccivn-jevg hitmevs: woy utgifg iv evmfivug oz OhfeovHitmgt, hohyjifg ef kefl ohfeovm, +ivn hitmg flg uoccivn jevg. ohfhitmg ijjokm ymgtm fo mhguezw ohfeovm ev flg uovrgvfeovij SVY/HOMED mwvfid, ivn innefeovijjw sgvgtifgm +ymisg ivn lgjh cgmmisgm zot woy. + +Fywyzkdx vd z tfkx lfmixmvxmw, qaxuvsax, zme yfbxkqpa avskzkn qfk yzkdvmj lfttzme-avmx fywvfmd wczm wcx fae jxwfyw tfepax. +fywyzkdx pdxd z tfkx exlazkzwvix dwnax fq lfttzme-avmx yzkdvmj: nfp lkxzwx zm vmdwzmlx fq FywvfmYzkdxk, yfypazwx vw bvwc fywvfmd, +zme yzkdx wcx lfttzme avmx. fywyzkdx zaafbd pdxkd wf dyxlvqn fywvfmd vm wcx lfmixmwvfmza JMP/YFDVU dnmwzu, zme zeevwvfmzaan jxmxkzwxd +pdzjx zme cxay txddzjxd qfk nfp. + +Wpnpqbuo mu q kwbo cwdzodmodn, hrolmjro, qdv pwsobhgr rmjbqbe hwb pqbumda cwkkqdv-rmdo wpnmwdu ntqd nto wrv aonwpn kwvgro. +wpnpqbuo guou q kwbo vocrqbqnmzo unero wh cwkkqdv-rmdo pqbumda: ewg cboqno qd mdunqdco wh WpnmwdPqbuob, pwpgrqno mn smnt wpnmwdu, +qdv pqbuo nto cwkkqdv rmdo. wpnpqbuo qrrwsu guobu nw upocmhe wpnmwdu md nto cwdzodnmwdqr ADG/PWUML uednql, qdv qvvmnmwdqrre aodobqnou +guqao qdv torp kouuqaou hwb ewg. + +Ngeghslf dl h bnsf tnuqfudfue, yifcdaif, hum gnjfsyxi idashsv yns ghsldur tnbbhum-iduf ngednul ekhu ekf nim rfenge bnmxif. +ngeghslf xlfl h bnsf mftihshedqf levif ny tnbbhum-iduf ghsldur: vnx tsfhef hu dulehutf ny NgednuGhslfs, gngxihef de jdek ngednul, +hum ghslf ekf tnbbhum iduf. ngeghslf hiinjl xlfsl en lgftdyv ngednul du ekf tnuqfuednuhi RUX/GNLDC lvuehc, hum hmmdednuhiiv rfufshefl +xlhrf hum kfig bfllhrfl yns vnx. + +Exvxyjcw uc y sejw kelhwluwlv, pzwturzw, yld xeawjpoz zurjyjm pej xyjculi kessyld-zulw exvuelc vbyl vbw ezd iwvexv sedozw. +exvxyjcw ocwc y sejw dwkzyjyvuhw cvmzw ep kessyld-zulw xyjculi: meo kjwyvw yl ulcvylkw ep ExvuelXyjcwj, xexozyvw uv auvb exvuelc, +yld xyjcw vbw kessyld zulw. exvxyjcw yzzeac ocwjc ve cxwkupm exvuelc ul vbw kelhwlvuelyz ILO/XECUT cmlvyt, yld ydduvuelyzzm iwlwjyvwc +ocyiw yld bwzx swccyiwc pej meo. + +Vomopatn lt p jvan bvcynclncm, gqnkliqn, pcu ovrnagfq qliapad gva opatlcz bvjjpcu-qlcn vomlvct mspc msn vqu znmvom jvufqn. +vomopatn ftnt p jvan unbqpapmlyn tmdqn vg bvjjpcu-qlcn opatlcz: dvf banpmn pc lctmpcbn vg VomlvcOpatna, ovofqpmn lm rlms vomlvct, +pcu opatn msn bvjjpcu qlcn. vomopatn pqqvrt ftnat mv tonblgd vomlvct lc msn bvcyncmlvcpq ZCF/OVTLK tdcmpk, pcu puulmlvcpqqd zncnapmnt +ftpzn pcu snqo jnttpznt gva dvf. + +Mfdfgrke ck g amre smtpetcetd, xhebczhe, gtl fmierxwh hczrgru xmr fgrkctq smaagtl-hcte mfdcmtk djgt dje mhl qedmfd amlwhe. +mfdfgrke wkek g amre leshgrgdcpe kduhe mx smaagtl-hcte fgrkctq: umw sregde gt ctkdgtse mx MfdcmtFgrker, fmfwhgde cd icdj mfdcmtk, +gtl fgrke dje smaagtl hcte. mfdfgrke ghhmik wkerk dm kfescxu mfdcmtk ct dje smtpetdcmtgh QTW/FMKCB kutdgb, gtl gllcdcmtghhu qetergdek +wkgqe gtl jehf aekkgqek xmr umw. + +Dwuwxibv tb x rdiv jdkgvktvku, oyvstqyv, xkc wdzviony ytqixil odi wxibtkh jdrrxkc-ytkv dwutdkb uaxk uav dyc hvudwu rdcnyv. +dwuwxibv nbvb x rdiv cvjyxixutgv bulyv do jdrrxkc-ytkv wxibtkh: ldn jivxuv xk tkbuxkjv do DwutdkWxibvi, wdwnyxuv tu ztua dwutdkb, +xkc wxibv uav jdrrxkc ytkv. dwuwxibv xyydzb nbvib ud bwvjtol dwutdkb tk uav jdkgvkutdkxy HKN/WDBTS blkuxs, xkc xcctutdkxyyl hvkvixuvb +nbxhv xkc avyw rvbbxhvb odi ldn. + +Unlnozsm ks o iuzm aubxmbkmbl, fpmjkhpm, obt nuqmzfep pkhzozc fuz nozskby auiiobt-pkbm unlkubs lrob lrm upt ymlunl iutepm. +unlnozsm esms o iuzm tmapozolkxm slcpm uf auiiobt-pkbm nozskby: cue azmolm ob kbslobam uf UnlkubNozsmz, nunepolm kl qklr unlkubs, +obt nozsm lrm auiiobt pkbm. unlnozsm oppuqs esmzs lu snmakfc unlkubs kb lrm aubxmblkubop YBE/NUSKJ scbloj, obt ottklkuboppc ymbmzolms +esoym obt rmpn imssoyms fuz cue. + +Lecefqjd bj f zlqd rlsodsbdsc, wgdabygd, fsk elhdqwvg gbyqfqt wlq efqjbsp rlzzfsk-gbsd lecblsj cifs cid lgk pdclec zlkvgd. +lecefqjd vjdj f zlqd kdrgfqfcbod jctgd lw rlzzfsk-gbsd efqjbsp: tlv rqdfcd fs bsjcfsrd lw LecblsEfqjdq, elevgfcd bc hbci lecblsj, +fsk efqjd cid rlzzfsk gbsd. lecefqjd fgglhj vjdqj cl jedrbwt lecblsj bs cid rlsodscblsfg PSV/ELJBA jtscfa, fsk fkkbcblsfggt pdsdqfcdj +vjfpd fsk idge zdjjfpdj wlq tlv. + +Cvtvwhau sa w qchu icjfujsujt, nxurspxu, wjb vcyuhnmx xsphwhk nch vwhasjg icqqwjb-xsju cvtscja tzwj tzu cxb gutcvt qcbmxu. +cvtvwhau maua w qchu buixwhwtsfu atkxu cn icqqwjb-xsju vwhasjg: kcm ihuwtu wj sjatwjiu cn CvtscjVwhauh, vcvmxwtu st ystz cvtscja, +wjb vwhau tzu icqqwjb xsju. cvtvwhau wxxcya mauha tc avuisnk cvtscja sj tzu icjfujtscjwx GJM/VCASR akjtwr, wjb wbbstscjwxxk gujuhwtua +mawgu wjb zuxv quaawgua nch kcm. + +Tmkmnyrl jr n htyl ztawlajlak, eolijgol, nas mtplyedo ojgynyb ety mnyrjax zthhnas-ojal tmkjtar kqna kql tos xlktmk htsdol. +tmkmnyrl drlr n htyl slzonynkjwl rkbol te zthhnas-ojal mnyrjax: btd zylnkl na jarknazl te TmkjtaMnyrly, mtmdonkl jk pjkq tmkjtar, +nas mnyrl kql zthhnas ojal. tmkmnyrl nootpr drlyr kt rmlzjeb tmkjtar ja kql ztawlakjtano XAD/MTRJI rbakni, nas nssjkjtanoob xlalynklr +drnxl nas qlom hlrrnxlr ety btd. + +Kdbdepic ai e ykpc qkrncracrb, vfczaxfc, erj dkgcpvuf faxpeps vkp depiaro qkyyerj-farc kdbakri bher bhc kfj ocbkdb ykjufc. +kdbdepic uici e ykpc jcqfepebanc ibsfc kv qkyyerj-farc depiaro: sku qpcebc er ariberqc kv KdbakrDepicp, dkdufebc ab gabh kdbakri, +erj depic bhc qkyyerj farc. kdbdepic effkgi uicpi bk idcqavs kdbakri ar bhc qkrncrbakref ORU/DKIAZ isrbez, erj ejjabakreffs ocrcpebci +uieoc erj hcfd yciieoci vkp sku. + +Busuvgzt rz v pbgt hbietirtis, mwtqrowt, via ubxtgmlw wrogvgj mbg uvgzrif hbppvia-writ busrbiz syvi syt bwa ftsbus pbalwt. +busuvgzt lztz v pbgt athwvgvsret zsjwt bm hbppvia-writ uvgzrif: jbl hgtvst vi rizsviht bm BusrbiUvgztg, ubulwvst rs xrsy busrbiz, +via uvgzt syt hbppvia writ. busuvgzt vwwbxz lztgz sb zuthrmj busrbiz ri syt hbietisrbivw FIL/UBZRQ zjisvq, via vaarsrbivwwj ftitgvstz +lzvft via ytwu ptzzvftz mbg jbl. + +Sljlmxqk iq m gsxk yszvkzikzj, dnkhifnk, mzr lsokxdcn nifxmxa dsx lmxqizw ysggmzr-nizk sljiszq jpmz jpk snr wkjslj gsrcnk. +sljlmxqk cqkq m gsxk rkynmxmjivk qjank sd ysggmzr-nizk lmxqizw: asc yxkmjk mz izqjmzyk sd SljiszLmxqkx, lslcnmjk ij oijp sljiszq, +mzr lmxqk jpk ysggmzr nizk. sljlmxqk mnnsoq cqkxq js qlkyida sljiszq iz jpk yszvkzjiszmn WZC/LSQIH qazjmh, mzr mrrijiszmnna wkzkxmjkq +cqmwk mzr pknl gkqqmwkq dsx asc. + +Jcacdohb zh d xjob pjqmbqzbqa, uebyzweb, dqi cjfboute ezwodor ujo cdohzqn pjxxdqi-ezqb jcazjqh agdq agb jei nbajca xjiteb. +jcacdohb thbh d xjob ibpedodazmb hareb ju pjxxdqi-ezqb cdohzqn: rjt pobdab dq zqhadqpb ju JcazjqCdohbo, cjctedab za fzag jcazjqh, +dqi cdohb agb pjxxdqi ezqb. jcacdohb deejfh thboh aj hcbpzur jcazjqh zq agb pjqmbqazjqde NQT/CJHZY hrqady, dqi diizazjqdeer nbqbodabh +thdnb dqi gbec xbhhdnbh ujo rjt. + +Atrtufys qy u oafs gahdshqshr, lvspqnvs, uhz tawsflkv vqnfufi laf tufyqhe gaoouhz-vqhs atrqahy rxuh rxs avz esratr oazkvs. +atrtufys kysy u oafs zsgvufurqds yrivs al gaoouhz-vqhs tufyqhe: iak gfsurs uh qhyruhgs al AtrqahTufysf, tatkvurs qr wqrx atrqahy, +uhz tufys rxs gaoouhz vqhs. atrtufys uvvawy kysfy ra ytsgqli atrqahy qh rxs gahdshrqahuv EHK/TAYQP yihrup, uhz uzzqrqahuvvi eshsfursy +kyues uhz xsvt osyyuesy laf iak. + +Rkiklwpj hp l frwj xryujyhjyi, cmjghemj, lyq krnjwcbm mhewlwz crw klwphyv xrfflyq-mhyj rkihryp ioly ioj rmq vjirki frqbmj. +rkiklwpj bpjp l frwj qjxmlwlihuj pizmj rc xrfflyq-mhyj klwphyv: zrb xwjlij ly hypilyxj rc RkihryKlwpjw, krkbmlij hi nhio rkihryp, +lyq klwpj ioj xrfflyq mhyj. rkiklwpj lmmrnp bpjwp ir pkjxhcz rkihryp hy ioj xryujyihrylm VYB/KRPHG pzyilg, lyq lqqhihrylmmz vjyjwlijp +bplvj lyq ojmk fjpplvjp crw zrb. + +Ibzbcnga yg c wina oiplapyapz, tdaxyvda, cph bieantsd dyvncnq tin bcngypm oiwwcph-dypa ibzyipg zfcp zfa idh mazibz wihsda. +ibzbcnga sgag c wina haodcnczyla gzqda it oiwwcph-dypa bcngypm: qis onacza cp ypgzcpoa it IbzyipBcngan, bibsdcza yz eyzf ibzyipg, +cph bcnga zfa oiwwcph dypa. ibzbcnga cddieg sgang zi gbaoytq ibzyipg yp zfa oiplapzyipcd MPS/BIGYX gqpzcx, cph chhyzyipcddq mapanczag +sgcma cph fadb waggcmag tin qis. + +Zsqstexr px t nzer fzgcrgprgq, kuropmur, tgy szvrekju upmeteh kze stexpgd fznntgy-upgr zsqpzgx qwtg qwr zuy drqzsq nzyjur. +zsqstexr jxrx t nzer yrfutetqpcr xqhur zk fznntgy-upgr stexpgd: hzj fertqr tg pgxqtgfr zk ZsqpzgStexre, szsjutqr pq vpqw zsqpzgx, +tgy stexr qwr fznntgy upgr. zsqstexr tuuzvx jxrex qz xsrfpkh zsqpzgx pg qwr fzgcrgqpzgtu DGJ/SZXPO xhgqto, tgy tyypqpzgtuuh drgretqrx +jxtdr tgy wrus nrxxtdrx kze hzj. + +Qjhjkvoi go k eqvi wqxtixgixh, blifgdli, kxp jqmivbal lgdvkvy bqv jkvogxu wqeekxp-lgxi qjhgqxo hnkx hni qlp uihqjh eqpali. +qjhjkvoi aoio k eqvi piwlkvkhgti ohyli qb wqeekxp-lgxi jkvogxu: yqa wvikhi kx gxohkxwi qb QjhgqxJkvoiv, jqjalkhi gh mghn qjhgqxo, +kxp jkvoi hni wqeekxp lgxi. qjhjkvoi kllqmo aoivo hq ojiwgby qjhgqxo gx hni wqxtixhgqxkl UXA/JQOGF oyxhkf, kxp kppghgqxklly uixivkhio +aokui kxp nilj eiookuio bqv yqa. + +Zaealcdp td l xzcp nzygpytpye, qwpitmwp, lyo azhpcqfw wtmclcj qzc alcdtyr nzxxlyo-wtyp zaetzyd esly esp zwo rpezae xzofwp. +zaealcdp fdpd l xzcp opnwlcletgp dejwp zq nzxxlyo-wtyp alcdtyr: jzf ncplep ly tydelynp zq ZaetzyAlcdpc, azafwlep te htes zaetzyd, +lyo alcdp esp nzxxlyo wtyp. zaealcdp lwwzhd fdpcd ez dapntqj zaetzyd ty esp nzygpyetzylw RYF/AZDTI djyeli, lyo lootetzylwwj rpypclepd +fdlrp lyo spwa xpddlrpd qzc jzf. + +Efjfqhiu yi q cehu sedludyudj, vbunyrbu, qdt femuhvkb byrhqho veh fqhiydw seccqdt-bydu efjyedi jxqd jxu ebt wujefj cetkbu. +efjfqhiu kiui q cehu tusbqhqjylu ijobu ev seccqdt-bydu fqhiydw: oek shuqju qd ydijqdsu ev EfjyedFqhiuh, fefkbqju yj myjx efjyedi, +qdt fqhiu jxu seccqdt bydu. efjfqhiu qbbemi kiuhi je ifusyvo efjyedi yd jxu sedludjyedqb WDK/FEIYN iodjqn, qdt qttyjyedqbbo wuduhqjui +kiqwu qdt xubf cuiiqwui veh oek. + +Jkokvmnz dn v hjmz xjiqzidzio, agzsdwgz, viy kjrzmapg gdwmvmt ajm kvmndib xjhhviy-gdiz jkodjin ocvi ocz jgy bzojko hjypgz. +jkokvmnz pnzn v hjmz yzxgvmvodqz notgz ja xjhhviy-gdiz kvmndib: tjp xmzvoz vi dinovixz ja JkodjiKvmnzm, kjkpgvoz do rdoc jkodjin, +viy kvmnz ocz xjhhviy gdiz. jkokvmnz vggjrn pnzmn oj nkzxdat jkodjin di ocz xjiqziodjivg BIP/KJNDS ntiovs, viy vyydodjivggt bzizmvozn +pnvbz viy czgk hznnvbzn ajm tjp. + +Optparse is a more convenient, flexible, and powerful library for parsing command-line options than the old getopt module. +optparse uses a more declarative style of command-line parsing: you create an instance of OptionParser, populate it with options, +and parse the command line. optparse allows users to specify options in the conventional GNU/POSIX syntax, and additionally generates +usage and help messages for you. + +Tuyufwxj nx f rtwj htsajsnjsy, kqjcngqj, fsi utbjwkzq qngwfwd ktw ufwxnsl htrrfsi-qnsj tuyntsx ymfs ymj tqi ljytuy rtizqj. +tuyufwxj zxjx f rtwj ijhqfwfynaj xydqj tk htrrfsi-qnsj ufwxnsl: dtz hwjfyj fs nsxyfshj tk TuyntsUfwxjw, utuzqfyj ny bnym tuyntsx, +fsi ufwxj ymj htrrfsi qnsj. tuyufwxj fqqtbx zxjwx yt xujhnkd tuyntsx ns ymj htsajsyntsfq LSZ/UTXNC xdsyfc, fsi fiinyntsfqqd ljsjwfyjx +zxflj fsi mjqu rjxxfljx ktw dtz. + +Yzdzkbco sc k wybo myxfoxsoxd, pvohslvo, kxn zygobpev vslbkbi pyb zkbcsxq mywwkxn-vsxo yzdsyxc drkx dro yvn qodyzd wynevo. +yzdzkbco ecoc k wybo nomvkbkdsfo cdivo yp mywwkxn-vsxo zkbcsxq: iye mbokdo kx sxcdkxmo yp YzdsyxZkbcob, zyzevkdo sd gsdr yzdsyxc, +kxn zkbco dro mywwkxn vsxo. yzdzkbco kvvygc ecobc dy czomspi yzdsyxc sx dro myxfoxdsyxkv QXE/ZYCSH cixdkh, kxn knnsdsyxkvvi qoxobkdoc +eckqo kxn rovz wocckqoc pyb iye. + +Deiepght xh p bdgt rdcktcxtci, uatmxqat, pcs edltguja axqgpgn udg epghxcv rdbbpcs-axct deixdch iwpc iwt das vtidei bdsjat. +deiepght jhth p bdgt strapgpixkt hinat du rdbbpcs-axct epghxcv: ndj rgtpit pc xchipcrt du DeixdcEpghtg, edejapit xi lxiw deixdch, +pcs epght iwt rdbbpcs axct. deiepght paadlh jhtgh id hetrxun deixdch xc iwt rdcktcixdcpa VCJ/EDHXM hncipm, pcs pssxixdcpaan vtctgpith +jhpvt pcs wtae bthhpvth udg ndj. + +Ijnjulmy cm u gily wihpyhcyhn, zfyrcvfy, uhx jiqylzof fcvluls zil julmcha wigguhx-fchy ijncihm nbuh nby ifx aynijn gixofy. +ijnjulmy omym u gily xywfuluncpy mnsfy iz wigguhx-fchy julmcha: sio wlyuny uh chmnuhwy iz IjncihJulmyl, jijofuny cn qcnb ijncihm, +uhx julmy nby wigguhx fchy. ijnjulmy uffiqm omylm ni mjywczs ijncihm ch nby wihpyhncihuf AHO/JIMCR mshnur, uhx uxxcncihuffs ayhylunym +omuay uhx byfj gymmuaym zil sio. + +Nosozqrd hr z lnqd bnmudmhdms, ekdwhakd, zmc onvdqetk khaqzqx enq ozqrhmf bnllzmc-khmd noshnmr sgzm sgd nkc fdsnos lnctkd. +nosozqrd trdr z lnqd cdbkzqzshud rsxkd ne bnllzmc-khmd ozqrhmf: xnt bqdzsd zm hmrszmbd ne NoshnmOzqrdq, onotkzsd hs vhsg noshnmr, +zmc ozqrd sgd bnllzmc khmd. nosozqrd zkknvr trdqr sn rodbhex noshnmr hm sgd bnmudmshnmzk FMT/ONRHW rxmszw, zmc zcchshnmzkkx fdmdqzsdr +trzfd zmc gdko ldrrzfdr enq xnt. + +Stxtevwi mw e qsvi gsrzirmirx, jpibmfpi, erh tsaivjyp pmfvevc jsv tevwmrk gsqqerh-pmri stxmsrw xler xli sph kixstx qshypi. +stxtevwi ywiw e qsvi higpevexmzi wxcpi sj gsqqerh-pmri tevwmrk: csy gviexi er mrwxergi sj StxmsrTevwiv, tstypexi mx amxl stxmsrw, +erh tevwi xli gsqqerh pmri. stxtevwi eppsaw ywivw xs wtigmjc stxmsrw mr xli gsrzirxmsrep KRY/TSWMB wcrxeb, erh ehhmxmsreppc kirivexiw +yweki erh lipt qiwwekiw jsv csy. + +Xycyjabn rb j vxan lxwenwrnwc, oungrkun, jwm yxfnaodu urkajah oxa yjabrwp lxvvjwm-urwn xycrxwb cqjw cqn xum pncxyc vxmdun. +xycyjabn dbnb j vxan mnlujajcren bchun xo lxvvjwm-urwn yjabrwp: hxd lanjcn jw rwbcjwln xo XycrxwYjabna, yxydujcn rc frcq xycrxwb, +jwm yjabn cqn lxvvjwm urwn. xycyjabn juuxfb dbnab cx bynlroh xycrxwb rw cqn lxwenwcrxwju PWD/YXBRG bhwcjg, jwm jmmrcrxwjuuh pnwnajcnb +dbjpn jwm qnuy vnbbjpnb oxa hxd. + +Cdhdofgs wg o acfs qcbjsbwsbh, tzslwpzs, obr dcksftiz zwpfofm tcf dofgwbu qcaaobr-zwbs cdhwcbg hvob hvs czr ushcdh acrizs. +cdhdofgs igsg o acfs rsqzofohwjs ghmzs ct qcaaobr-zwbs dofgwbu: mci qfsohs ob wbghobqs ct CdhwcbDofgsf, dcdizohs wh kwhv cdhwcbg, +obr dofgs hvs qcaaobr zwbs. cdhdofgs ozzckg igsfg hc gdsqwtm cdhwcbg wb hvs qcbjsbhwcboz UBI/DCGWL gmbhol, obr orrwhwcbozzm usbsfohsg +igous obr vszd asggousg tcf mci. + +Himitklx bl t fhkx vhgoxgbxgm, yexqbuex, tgw ihpxkyne ebuktkr yhk itklbgz vhfftgw-ebgx himbhgl matg max hew zxmhim fhwnex. +himitklx nlxl t fhkx wxvetktmbox lmrex hy vhfftgw-ebgx itklbgz: rhn vkxtmx tg bglmtgvx hy HimbhgItklxk, ihinetmx bm pbma himbhgl, +tgw itklx max vhfftgw ebgx. himitklx teehpl nlxkl mh lixvbyr himbhgl bg max vhgoxgmbhgte ZGN/IHLBQ lrgmtq, tgw twwbmbhgteer zxgxktmxl +nltzx tgw axei fxlltzxl yhk rhn. + +Mnrnypqc gq y kmpc amltclgclr, djcvgzjc, ylb nmucpdsj jgzpypw dmp nypqgle amkkylb-jglc mnrgmlq rfyl rfc mjb ecrmnr kmbsjc. +mnrnypqc sqcq y kmpc bcajypyrgtc qrwjc md amkkylb-jglc nypqgle: wms apcyrc yl glqrylac md MnrgmlNypqcp, nmnsjyrc gr ugrf mnrgmlq, +ylb nypqc rfc amkkylb jglc. mnrnypqc yjjmuq sqcpq rm qncagdw mnrgmlq gl rfc amltclrgmlyj ELS/NMQGV qwlryv, ylb ybbgrgmlyjjw eclcpyrcq +sqyec ylb fcjn kcqqyecq dmp wms. + +Rswsduvh lv d pruh frqyhqlhqw, iohaleoh, dqg srzhuixo oleudub iru sduvlqj frppdqg-olqh rswlrqv wkdq wkh rog jhwrsw prgxoh. +rswsduvh xvhv d pruh ghfodudwlyh vwboh ri frppdqg-olqh sduvlqj: brx fuhdwh dq lqvwdqfh ri RswlrqSduvhu, srsxodwh lw zlwk rswlrqv, +dqg sduvh wkh frppdqg olqh. rswsduvh doorzv xvhuv wr vshflib rswlrqv lq wkh frqyhqwlrqdo JQX/SRVLA vbqwda, dqg dgglwlrqdoob jhqhudwhv +xvdjh dqg khos phvvdjhv iru brx. + +Wxbxizam qa i uwzm kwvdmvqmvb, ntmfqjtm, ivl xwemznct tqjzizg nwz xizaqvo kwuuivl-tqvm wxbqwva bpiv bpm wtl ombwxb uwlctm. +wxbxizam cama i uwzm lmktizibqdm abgtm wn kwuuivl-tqvm xizaqvo: gwc kzmibm iv qvabivkm wn WxbqwvXizamz, xwxctibm qb eqbp wxbqwva, +ivl xizam bpm kwuuivl tqvm. wxbxizam ittwea camza bw axmkqng wxbqwva qv bpm kwvdmvbqwvit OVC/XWAQF agvbif, ivl illqbqwvittg omvmzibma +caiom ivl pmtx umaaioma nwz gwc. + +Bcgcnefr vf n zber pbairavrag, syrkvoyr, naq cbjreshy yvoenel sbe cnefvat pbzznaq-yvar bcgvbaf guna gur byq trgbcg zbqhyr. +bcgcnefr hfrf n zber qrpynengvir fglyr bs pbzznaq-yvar cnefvat: lbh perngr na vafgnapr bs BcgvbaCnefre, cbchyngr vg jvgu bcgvbaf, +naq cnefr gur pbzznaq yvar. bcgcnefr nyybjf hfref gb fcrpvsl bcgvbaf va gur pbairagvbany TAH/CBFVK flagnk, naq nqqvgvbanyyl trarengrf +hfntr naq uryc zrffntrf sbe lbh. + +Ghlhsjkw ak s egjw ugfnwfawfl, xdwpatdw, sfv hgowjxmd datjsjq xgj hsjkafy ugeesfv-dafw ghlagfk lzsf lzw gdv ywlghl egvmdw. +ghlhsjkw mkwk s egjw vwudsjslanw klqdw gx ugeesfv-dafw hsjkafy: qgm ujwslw sf afklsfuw gx GhlagfHsjkwj, hghmdslw al oalz ghlagfk, +sfv hsjkw lzw ugeesfv dafw. ghlhsjkw sddgok mkwjk lg khwuaxq ghlagfk af lzw ugfnwflagfsd YFM/HGKAP kqflsp, sfv svvalagfsddq ywfwjslwk +mksyw sfv zwdh ewkksywk xgj qgm. + +Lmqmxopb fp x jlob zlksbkfbkq, cibufyib, xka mltbocri ifyoxov clo mxopfkd zljjxka-ifkb lmqflkp qexk qeb lia dbqlmq jlarib. +lmqmxopb rpbp x jlob abzixoxqfsb pqvib lc zljjxka-ifkb mxopfkd: vlr zobxqb xk fkpqxkzb lc LmqflkMxopbo, mlmrixqb fq tfqe lmqflkp, +xka mxopb qeb zljjxka ifkb. lmqmxopb xiiltp rpbop ql pmbzfcv lmqflkp fk qeb zlksbkqflkxi DKR/MLPFU pvkqxu, xka xaafqflkxiiv dbkboxqbp +rpxdb xka ebim jbppxdbp clo vlr. + +Qrvrctug ku c oqtg eqpxgpkgpv, hngzkdng, cpf rqygthwn nkdtcta hqt rctukpi eqoocpf-nkpg qrvkqpu vjcp vjg qnf igvqrv oqfwng. +qrvrctug wugu c oqtg fgenctcvkxg uvang qh eqoocpf-nkpg rctukpi: aqw etgcvg cp kpuvcpeg qh QrvkqpRctugt, rqrwncvg kv ykvj qrvkqpu, +cpf rctug vjg eqoocpf nkpg. qrvrctug cnnqyu wugtu vq urgekha qrvkqpu kp vjg eqpxgpvkqpcn IPW/RQUKZ uapvcz, cpf cffkvkqpcnna igpgtcvgu +wucig cpf jgnr oguucigu hqt aqw. + +Vwawhyzl pz h tvyl jvucluplua, mslepisl, huk wvdlymbs spiyhyf mvy whyzpun jvtthuk-spul vwapvuz aohu aol vsk nlavwa tvkbsl. +vwawhyzl bzlz h tvyl kljshyhapcl zafsl vm jvtthuk-spul whyzpun: fvb jylhal hu puzahujl vm VwapvuWhyzly, wvwbshal pa dpao vwapvuz, +huk whyzl aol jvtthuk spul. vwawhyzl hssvdz bzlyz av zwljpmf vwapvuz pu aol jvucluapvuhs NUB/WVZPE zfuahe, huk hkkpapvuhssf nlulyhalz +bzhnl huk olsw tlzzhnlz mvy fvb. + +Abfbmdeq ue m yadq oazhqzuqzf, rxqjunxq, mzp baiqdrgx xundmdk rad bmdeuzs oayymzp-xuzq abfuaze ftmz ftq axp sqfabf yapgxq. +abfbmdeq geqe m yadq pqoxmdmfuhq efkxq ar oayymzp-xuzq bmdeuzs: kag odqmfq mz uzefmzoq ar AbfuazBmdeqd, babgxmfq uf iuft abfuaze, +mzp bmdeq ftq oayymzp xuzq. abfbmdeq mxxaie geqde fa ebqourk abfuaze uz ftq oazhqzfuazmx SZG/BAEUJ ekzfmj, mzp mppufuazmxxk sqzqdmfqe +gemsq mzp tqxb yqeemsqe rad kag. + +Fgkgrijv zj r dfiv tfemvezvek, wcvozscv, reu gfnviwlc czsirip wfi grijzex tfddreu-czev fgkzfej kyre kyv fcu xvkfgk dfulcv. +fgkgrijv ljvj r dfiv uvtcrirkzmv jkpcv fw tfddreu-czev grijzex: pfl tivrkv re zejkretv fw FgkzfeGrijvi, gfglcrkv zk nzky fgkzfej, +reu grijv kyv tfddreu czev. fgkgrijv rccfnj ljvij kf jgvtzwp fgkzfej ze kyv tfemvekzferc XEL/GFJZO jpekro, reu ruuzkzferccp xvevirkvj +ljrxv reu yvcg dvjjrxvj wfi pfl. + +Klplwnoa eo w ikna ykjrajeajp, bhatexha, wjz lksanbqh hexnwnu bkn lwnoejc ykiiwjz-heja klpekjo pdwj pda khz capklp ikzqha. +klplwnoa qoao w ikna zayhwnwpera opuha kb ykiiwjz-heja lwnoejc: ukq ynawpa wj ejopwjya kb KlpekjLwnoan, lklqhwpa ep sepd klpekjo, +wjz lwnoa pda ykiiwjz heja. klplwnoa whhkso qoano pk olayebu klpekjo ej pda ykjrajpekjwh CJQ/LKOET oujpwt, wjz wzzepekjwhhu cajanwpao +qowca wjz dahl iaoowcao bkn ukq. + +Pquqbstf jt b npsf dpowfojfou, gmfyjcmf, boe qpxfsgvm mjcsbsz gps qbstjoh dpnnboe-mjof pqujpot uibo uif pme hfupqu npevmf. +pquqbstf vtft b npsf efdmbsbujwf tuzmf pg dpnnboe-mjof qbstjoh: zpv dsfbuf bo jotubodf pg PqujpoQbstfs, qpqvmbuf ju xjui pqujpot, +boe qbstf uif dpnnboe mjof. pquqbstf bmmpxt vtfst up tqfdjgz pqujpot jo uif dpowfoujpobm HOV/QPTJY tzouby, boe beejujpobmmz hfofsbuft +vtbhf boe ifmq nfttbhft gps zpv. + +Uvzvgxyk oy g suxk iutbktoktz, lrkdohrk, gtj vuckxlar rohxgxe lux vgxyotm iussgtj-rotk uvzouty zngt znk urj mkzuvz sujark. +uvzvgxyk ayky g suxk jkirgxgzobk yzerk ul iussgtj-rotk vgxyotm: eua ixkgzk gt otyzgtik ul UvzoutVgxykx, vuvargzk oz cozn uvzouty, +gtj vgxyk znk iussgtj rotk. uvzvgxyk grrucy aykxy zu yvkiole uvzouty ot znk iutbktzoutgr MTA/VUYOD yetzgd, gtj gjjozoutgrre mktkxgzky +aygmk gtj nkrv skyygmky lux eua. + +Daoaturh vr t jduh ndgihgvhgo, emhcvqmh, tgk adfhuelm mvqutuz edu aturvgb ndjjtgk-mvgh daovdgr oytg oyh dmk bhodao jdklmh. +daoaturh lrhr t jduh khnmtutovih rozmh de ndjjtgk-mvgh aturvgb: zdl nuhtoh tg vgrotgnh de DaovdgAturhu, adalmtoh vo fvoy daovdgr, +tgk aturh oyh ndjjtgk mvgh. daoaturh tmmdfr lrhur od rahnvez daovdgr vg oyh ndgihgovdgtm BGL/ADRVC rzgotc, tgk tkkvovdgtmmz bhghutohr +lrtbh tgk yhma jhrrtbhr edu zdl. + +Olzlefcs gc e uofs yortsrgsrz, pxsngbxs, erv loqsfpwx xgbfefk pof lefcgrm youuerv-xgrs olzgorc zjer zjs oxv mszolz uovwxs. +olzlefcs wcsc e uofs vsyxefezgts czkxs op youuerv-xgrs lefcgrm: kow yfsezs er grczerys op OlzgorLefcsf, lolwxezs gz qgzj olzgorc, +erv lefcs zjs youuerv xgrs. olzlefcs exxoqc wcsfc zo clsygpk olzgorc gr zjs yortsrzgorex MRW/LOCGN ckrzen, erv evvgzgorexxk msrsfezsc +wcems erv jsxl usccemsc pof kow. + +Zwkwpqnd rn p fzqd jzcedcrdck, aidyrmid, pcg wzbdqahi irmqpqv azq wpqnrcx jzffpcg-ircd zwkrzcn kupc kud zig xdkzwk fzghid. +zwkwpqnd hndn p fzqd gdjipqpkred nkvid za jzffpcg-ircd wpqnrcx: vzh jqdpkd pc rcnkpcjd za ZwkrzcWpqndq, wzwhipkd rk brku zwkrzcn, +pcg wpqnd kud jzffpcg ircd. zwkwpqnd piizbn hndqn kz nwdjrav zwkrzcn rc kud jzcedckrzcpi XCH/WZNRY nvckpy, pcg pggrkrzcpiiv xdcdqpkdn +hnpxd pcg udiw fdnnpxdn azq vzh. + +Khvhabyo cy a qkbo uknponconv, ltojcxto, anr hkmoblst tcxbabg lkb habycni ukqqanr-tcno khvckny vfan vfo ktr iovkhv qkrsto. +khvhabyo syoy a qkbo routabavcpo yvgto kl ukqqanr-tcno habycni: gks uboavo an cnyvanuo kl KhvcknHabyob, hkhstavo cv mcvf khvckny, +anr habyo vfo ukqqanr tcno. khvhabyo attkmy syoby vk yhouclg khvckny cn vfo uknponvcknat INS/HKYCJ ygnvaj, anr arrcvcknattg ionobavoy +syaio anr foth qoyyaioy lkb gks. + +Vsgslmjz nj l bvmz fvyazynzyg, wezuniez, lyc svxzmwde enimlmr wvm slmjnyt fvbblyc-enyz vsgnvyj gqly gqz vec tzgvsg bvcdez. +vsgslmjz djzj l bvmz czfelmlgnaz jgrez vw fvbblyc-enyz slmjnyt: rvd fmzlgz ly nyjglyfz vw VsgnvySlmjzm, svsdelgz ng xngq vsgnvyj, +lyc slmjz gqz fvbblyc enyz. vsgslmjz leevxj djzmj gv jszfnwr vsgnvyj ny gqz fvyazygnvyle TYD/SVJNU jryglu, lyc lccngnvyleer tzyzmlgzj +djltz lyc qzes bzjjltzj wvm rvd. + +Gdrdwxuk yu w mgxk qgjlkjykjr, hpkfytpk, wjn dgikxhop pytxwxc hgx dwxuyje qgmmwjn-pyjk gdrygju rbwj rbk gpn ekrgdr mgnopk. +gdrdwxuk ouku w mgxk nkqpwxwrylk urcpk gh qgmmwjn-pyjk dwxuyje: cgo qxkwrk wj yjurwjqk gh GdrygjDwxukx, dgdopwrk yr iyrb gdrygju, +wjn dwxuk rbk qgmmwjn pyjk. gdrdwxuk wppgiu oukxu rg udkqyhc gdrygju yj rbk qgjlkjrygjwp EJO/DGUYF ucjrwf, wjn wnnyrygjwppc ekjkxwrku +ouwek wjn bkpd mkuuweku hgx cgo. + +Rocohifv jf h xriv bruwvujvuc, savqjeav, huy ortvisza ajeihin sri ohifjup brxxhuy-ajuv rocjruf cmhu cmv ray pvcroc xryzav. +rocohifv zfvf h xriv yvbahihcjwv fcnav rs brxxhuy-ajuv ohifjup: nrz bivhcv hu jufchubv rs RocjruOhifvi, orozahcv jc tjcm rocjruf, +huy ohifv cmv brxxhuy ajuv. rocohifv haartf zfvif cr fovbjsn rocjruf ju cmv bruwvucjruha PUZ/ORFJQ fnuchq, huy hyyjcjruhaan pvuvihcvf +zfhpv huy mvao xvffhpvf sri nrz. + +Cznzstqg uq s ictg mcfhgfugfn, dlgbuplg, sfj zcegtdkl luptsty dct zstqufa mciisfj-lufg cznucfq nxsf nxg clj agnczn icjklg. +cznzstqg kqgq s ictg jgmlstsnuhg qnylg cd mciisfj-lufg zstqufa: yck mtgsng sf ufqnsfmg cd CznucfZstqgt, zczklsng un eunx cznucfq, +sfj zstqg nxg mciisfj lufg. cznzstqg sllceq kqgtq nc qzgmudy cznucfq uf nxg mcfhgfnucfsl AFK/ZCQUB qyfnsb, sfj sjjunucfslly agfgtsngq +kqsag sfj xglz igqqsagq dct yck. + +Nkykdebr fb d tner xnqsrqfrqy, owrmfawr, dqu knpreovw wfaedej one kdebfql xnttdqu-wfqr nkyfnqb yidq yir nwu lrynky tnuvwr. +nkykdebr vbrb d tner urxwdedyfsr byjwr no xnttdqu-wfqr kdebfql: jnv xerdyr dq fqbydqxr no NkyfnqKdebre, knkvwdyr fy pfyi nkyfnqb, +dqu kdebr yir xnttdqu wfqr. nkykdebr dwwnpb vbreb yn bkrxfoj nkyfnqb fq yir xnqsrqyfnqdw LQV/KNBFM bjqydm, dqu duufyfnqdwwj lrqredyrb +vbdlr dqu irwk trbbdlrb one jnv. + +Yvjvopmc qm o eypc iybdcbqcbj, zhcxqlhc, obf vyacpzgh hqlpopu zyp vopmqbw iyeeobf-hqbc yvjqybm jtob jtc yhf wcjyvj eyfghc. +yvjvopmc gmcm o eypc fcihopojqdc mjuhc yz iyeeobf-hqbc vopmqbw: uyg ipcojc ob qbmjobic yz YvjqybVopmcp, vyvghojc qj aqjt yvjqybm, +obf vopmc jtc iyeeobf hqbc. yvjvopmc ohhyam gmcpm jy mvciqzu yvjqybm qb jtc iybdcbjqyboh WBG/VYMQX mubjox, obf offqjqybohhu wcbcpojcm +gmowc obf tchv ecmmowcm zyp uyg. + +Jgugzaxn bx z pjan tjmonmbnmu, ksnibwsn, zmq gjlnakrs sbwazaf kja gzaxbmh tjppzmq-sbmn jgubjmx uezm uen jsq hnujgu pjqrsn. +jgugzaxn rxnx z pjan qntszazubon xufsn jk tjppzmq-sbmn gzaxbmh: fjr tanzun zm bmxuzmtn jk JgubjmGzaxna, gjgrszun bu lbue jgubjmx, +zmq gzaxn uen tjppzmq sbmn. jgugzaxn zssjlx rxnax uj xgntbkf jgubjmx bm uen tjmonmubjmzs HMR/GJXBI xfmuzi, zmq zqqbubjmzssf hnmnazunx +rxzhn zmq ensg pnxxzhnx kja fjr. + +Urfrkliy mi k auly euxzyxmyxf, vdytmhdy, kxb ruwylvcd dmhlklq vul rklimxs euaakxb-dmxy urfmuxi fpkx fpy udb syfurf aubcdy. +urfrkliy ciyi k auly byedklkfmzy ifqdy uv euaakxb-dmxy rklimxs: quc elykfy kx mxifkxey uv UrfmuxRkliyl, rurcdkfy mf wmfp urfmuxi, +kxb rkliy fpy euaakxb dmxy. urfrkliy kdduwi ciyli fu iryemvq urfmuxi mx fpy euxzyxfmuxkd SXC/RUIMT iqxfkt, kxb kbbmfmuxkddq syxylkfyi +ciksy kxb pydr ayiiksyi vul quc. + +Fcqcvwtj xt v lfwj pfikjixjiq, gojexsoj, vim cfhjwgno oxswvwb gfw cvwtxid pfllvim-oxij fcqxfit qavi qaj fom djqfcq lfmnoj. +fcqcvwtj ntjt v lfwj mjpovwvqxkj tqboj fg pfllvim-oxij cvwtxid: bfn pwjvqj vi xitqvipj fg FcqxfiCvwtjw, cfcnovqj xq hxqa fcqxfit, +vim cvwtj qaj pfllvim oxij. fcqcvwtj voofht ntjwt qf tcjpxgb fcqxfit xi qaj pfikjiqxfivo DIN/CFTXE tbiqve, vim vmmxqxfivoob djijwvqjt +ntvdj vim ajoc ljttvdjt gfw bfn. + +Qnbngheu ie g wqhu aqtvutiutb, rzupidzu, gtx nqsuhryz zidhghm rqh ngheito aqwwgtx-zitu qnbiqte blgt blu qzx oubqnb wqxyzu. +qnbngheu yeue g wqhu xuazghgbivu ebmzu qr aqwwgtx-zitu ngheito: mqy ahugbu gt itebgtau qr QnbiqtNgheuh, nqnyzgbu ib sibl qnbiqte, +gtx ngheu blu aqwwgtx zitu. qnbngheu gzzqse yeuhe bq enuairm qnbiqte it blu aqtvutbiqtgz OTY/NQEIP emtbgp, gtx gxxibiqtgzzm outuhgbue +yegou gtx luzn wueegoue rqh mqy. + +Bymyrspf tp r hbsf lbegfetfem, ckfatokf, rei ybdfscjk ktosrsx cbs yrsptez lbhhrei-ktef bymtbep mwre mwf bki zfmbym hbijkf. +bymyrspf jpfp r hbsf iflkrsrmtgf pmxkf bc lbhhrei-ktef yrsptez: xbj lsfrmf re tepmrelf bc BymtbeYrspfs, ybyjkrmf tm dtmw bymtbep, +rei yrspf mwf lbhhrei ktef. bymyrspf rkkbdp jpfsp mb pyfltcx bymtbep te mwf lbegfemtberk ZEJ/YBPTA pxemra, rei riitmtberkkx zfefsrmfp +jprzf rei wfky hfpprzfp cbs xbj. + +Mjxjcdaq ea c smdq wmprqpeqpx, nvqlezvq, cpt jmoqdnuv vezdcdi nmd jcdaepk wmsscpt-vepq mjxempa xhcp xhq mvt kqxmjx smtuvq. +mjxjcdaq uaqa c smdq tqwvcdcxerq axivq mn wmsscpt-vepq jcdaepk: imu wdqcxq cp epaxcpwq mn MjxempJcdaqd, jmjuvcxq ex oexh mjxempa, +cpt jcdaq xhq wmsscpt vepq. mjxjcdaq cvvmoa uaqda xm ajqweni mjxempa ep xhq wmprqpxempcv KPU/JMAEL aipxcl, cpt cttexempcvvi kqpqdcxqa +uackq cpt hqvj sqaackqa nmd imu. + +Xuiunolb pl n dxob hxacbapbai, ygbwpkgb, nae uxzboyfg gpkonot yxo unolpav hxddnae-gpab xuipxal isna isb xge vbixui dxefgb. +xuiunolb flbl n dxob ebhgnonipcb litgb xy hxddnae-gpab unolpav: txf hobnib na palinahb xy XuipxaUnolbo, uxufgnib pi zpis xuipxal, +nae unolb isb hxddnae gpab. xuiunolb nggxzl flbol ix lubhpyt xuipxal pa isb hxacbaipxang VAF/UXLPW ltainw, nae neepipxanggt vbabonibl +flnvb nae sbgu dbllnvbl yxo txf. + +Iftfyzwm aw y oizm silnmlamlt, jrmhavrm, ylp fikmzjqr ravzyze jiz fyzwalg siooylp-ralm iftailw tdyl tdm irp gmtift oipqrm. +iftfyzwm qwmw y oizm pmsryzytanm wterm ij siooylp-ralm fyzwalg: eiq szmytm yl alwtylsm ij IftailFyzwmz, fifqrytm at katd iftailw, +ylp fyzwm tdm siooylp ralm. iftfyzwm yrrikw qwmzw ti wfmsaje iftailw al tdm silnmltailyr GLQ/FIWAH weltyh, ylp yppatailyrre gmlmzytmw +qwygm ylp dmrf omwwygmw jiz eiq. + +Tqeqjkhx lh j ztkx dtwyxwlxwe, ucxslgcx, jwa qtvxkubc clgkjkp utk qjkhlwr dtzzjwa-clwx tqeltwh eojw eox tca rxetqe ztabcx. +tqeqjkhx bhxh j ztkx axdcjkjelyx hepcx tu dtzzjwa-clwx qjkhlwr: ptb dkxjex jw lwhejwdx tu TqeltwQjkhxk, qtqbcjex le vleo tqeltwh, +jwa qjkhx eox dtzzjwa clwx. tqeqjkhx jcctvh bhxkh et hqxdlup tqeltwh lw eox dtwyxweltwjc RWB/QTHLS hpwejs, jwa jaaleltwjccp rxwxkjexh +bhjrx jwa oxcq zxhhjrxh utk ptb. + +Ebpbuvsi ws u kevi oehjihwihp, fnidwrni, uhl begivfmn nwrvuva fev buvswhc oekkuhl-nwhi ebpwehs pzuh pzi enl cipebp kelmni. +ebpbuvsi msis u kevi lionuvupwji spani ef oekkuhl-nwhi buvswhc: aem oviupi uh whspuhoi ef EbpwehBuvsiv, bebmnupi wp gwpz ebpwehs, +uhl buvsi pzi oekkuhl nwhi. ebpbuvsi unnegs msivs pe sbiowfa ebpwehs wh pzi oehjihpwehun CHM/BESWD sahpud, uhl ullwpwehunna cihivupis +msuci uhl zinb kissucis fev aem. + +Pmamfgdt hd f vpgt zpsutshtsa, qytohcyt, fsw mprtgqxy yhcgfgl qpg mfgdhsn zpvvfsw-yhst pmahpsd akfs akt pyw ntapma vpwxyt. +pmamfgdt xdtd f vpgt wtzyfgfahut dalyt pq zpvvfsw-yhst mfgdhsn: lpx zgtfat fs hsdafszt pq PmahpsMfgdtg, mpmxyfat ha rhak pmahpsd, +fsw mfgdt akt zpvvfsw yhst. pmamfgdt fyyprd xdtgd ap dmtzhql pmahpsd hs akt zpsutsahpsfy NSX/MPDHO dlsafo, fsw fwwhahpsfyyl ntstgfatd +xdfnt fsw ktym vtddfntd qpg lpx. + +Axlxqroe so q gare kadfedsedl, bjezsnje, qdh xacerbij jsnrqrw bar xqrosdy kaggqdh-jsde axlsado lvqd lve ajh yelaxl gahije. +axlxqroe ioeo q gare hekjqrqlsfe olwje ab kaggqdh-jsde xqrosdy: wai kreqle qd sdolqdke ab AxlsadXqroer, xaxijqle sl cslv axlsado, +qdh xqroe lve kaggqdh jsde. axlxqroe qjjaco ioero la oxeksbw axlsado sd lve kadfedlsadqj YDI/XAOSZ owdlqz, qdh qhhslsadqjjw yederqleo +ioqye qdh vejx geooqyeo bar wai. + +Liwibczp dz b rlcp vloqpodpow, mupkdyup, bos ilnpcmtu udycbch mlc ibczdoj vlrrbos-udop liwdloz wgbo wgp lus jpwliw rlstup. +liwibczp tzpz b rlcp spvubcbwdqp zwhup lm vlrrbos-udop ibczdoj: hlt vcpbwp bo dozwbovp lm LiwdloIbczpc, ilitubwp dw ndwg liwdloz, +bos ibczp wgp vlrrbos udop. liwibczp buulnz tzpcz wl zipvdmh liwdloz do wgp vloqpowdlobu JOT/ILZDK zhowbk, bos bssdwdlobuuh jpopcbwpz +tzbjp bos gpui rpzzbjpz mlc hlt. + +Wthtmnka ok m cwna gwzbazoazh, xfavojfa, mzd twyanxef fojnmns xwn tmnkozu gwccmzd-foza wthowzk hrmz hra wfd uahwth cwdefa. +wthtmnka ekak m cwna dagfmnmhoba khsfa wx gwccmzd-foza tmnkozu: swe gnamha mz ozkhmzga wx WthowzTmnkan, twtefmha oh yohr wthowzk, +mzd tmnka hra gwccmzd foza. wthtmnka mffwyk ekank hw ktagoxs wthowzk oz hra gwzbazhowzmf UZE/TWKOV kszhmv, mzd mddohowzmffs uazanmhak +ekmua mzd raft cakkmuak xwn swe. + +Hesexyvl zv x nhyl rhkmlkzlks, iqlgzuql, xko ehjlyipq qzuyxyd ihy exyvzkf rhnnxko-qzkl heszhkv scxk scl hqo flshes nhopql. +hesexyvl pvlv x nhyl olrqxyxszml vsdql hi rhnnxko-qzkl exyvzkf: dhp rylxsl xk zkvsxkrl hi HeszhkExyvly, ehepqxsl zs jzsc heszhkv, +xko exyvl scl rhnnxko qzkl. hesexyvl xqqhjv pvlyv sh velrzid heszhkv zk scl rhkmlkszhkxq FKP/EHVZG vdksxg, xko xoozszhkxqqd flklyxslv +pvxfl xko clqe nlvvxflv ihy dhp. + +Spdpijgw kg i ysjw csvxwvkwvd, tbwrkfbw, ivz psuwjtab bkfjijo tsj pijgkvq csyyivz-bkvw spdksvg dniv dnw sbz qwdspd yszabw. +spdpijgw agwg i ysjw zwcbijidkxw gdobw st csyyivz-bkvw pijgkvq: osa cjwidw iv kvgdivcw st SpdksvPijgwj, pspabidw kd ukdn spdksvg, +ivz pijgw dnw csyyivz bkvw. spdpijgw ibbsug agwjg ds gpwckto spdksvg kv dnw csvxwvdksvib QVA/PSGKR govdir, ivz izzkdksvibbo qwvwjidwg +agiqw ivz nwbp ywggiqwg tsj osa. + +Laiajetr zt j hler nlwmrwzrwi, gsrqzysr, jwc albregxs szyejef gle ajetzwv nlhhjwc-szwr laizlwt ikjw ikr lsc vrilai hlcxsr. +laiajetr xtrt j hler crnsjejizmr tifsr lg nlhhjwc-szwr ajetzwv: flx nerjir jw zwtijwnr lg LaizlwAjetre, alaxsjir zi bzik laizlwt, +jwc ajetr ikr nlhhjwc szwr. laiajetr jsslbt xtret il tarnzgf laizlwt zw ikr nlwmrwizlwjs VWX/ALTZQ tfwijq, jwc jcczizlwjssf vrwrejirt +xtjvr jwc krsa hrttjvrt gle flx. + +Ixfxgbqo wq g eibo kitjotwotf, dponwvpo, gtz xiyobdup pwvbgbc dib xgbqwts kieegtz-pwto ixfwitq fhgt fho ipz sofixf eizupo. +ixfxgbqo uqoq g eibo zokpgbgfwjo qfcpo id kieegtz-pwto xgbqwts: ciu kbogfo gt wtqfgtko id IxfwitXgbqob, xixupgfo wf ywfh ixfwitq, +gtz xgbqo fho kieegtz pwto. ixfxgbqo gppiyq uqobq fi qxokwdc ixfwitq wt fho kitjotfwitgp STU/XIQWN qctfgn, gtz gzzwfwitgppc sotobgfoq +uqgso gtz hopx eoqqgsoq dib ciu. + +Fucudynl tn d bfyl hfqglqtlqc, amlktsml, dqw ufvlyarm mtsydyz afy udyntqp hfbbdqw-mtql fuctfqn cedq cel fmw plcfuc bfwrml. +fucudynl rnln d bfyl wlhmdydctgl nczml fa hfbbdqw-mtql udyntqp: zfr hyldcl dq tqncdqhl fa FuctfqUdynly, ufurmdcl tc vtce fuctfqn, +dqw udynl cel hfbbdqw mtql. fucudynl dmmfvn rnlyn cf nulhtaz fuctfqn tq cel hfqglqctfqdm PQR/UFNTK nzqcdk, dqw dwwtctfqdmmz plqlydcln +rndpl dqw elmu blnndpln afy zfr. + +Crzravki qk a ycvi ecndinqinz, xjihqpji, ant rcsivxoj jqpvavw xcv ravkqnm ecyyant-jqni crzqcnk zban zbi cjt mizcrz yctoji. +crzravki okik a ycvi tiejavazqdi kzwji cx ecyyant-jqni ravkqnm: wco eviazi an qnkzanei cx CrzqcnRavkiv, rcrojazi qz sqzb crzqcnk, +ant ravki zbi ecyyant jqni. crzravki ajjcsk okivk zc krieqxw crzqcnk qn zbi ecndinzqcnaj MNO/RCKQH kwnzah, ant attqzqcnajjw minivazik +okami ant bijr yikkamik xcv wco. + +Zowoxshf nh x vzsf bzkafknfkw, ugfenmgf, xkq ozpfsulg gnmsxst uzs oxshnkj bzvvxkq-gnkf zownzkh wyxk wyf zgq jfwzow vzqlgf. +zowoxshf lhfh x vzsf qfbgxsxwnaf hwtgf zu bzvvxkq-gnkf oxshnkj: tzl bsfxwf xk nkhwxkbf zu ZownzkOxshfs, ozolgxwf nw pnwy zownzkh, +xkq oxshf wyf bzvvxkq gnkf. zowoxshf xggzph lhfsh wz hofbnut zownzkh nk wyf bzkafkwnzkxg JKL/OZHNE htkwxe, xkq xqqnwnzkxggt jfkfsxwfh +lhxjf xkq yfgo vfhhxjfh uzs tzl. + +Wltlupec ke u swpc ywhxchkcht, rdcbkjdc, uhn lwmcprid dkjpupq rwp lupekhg ywssuhn-dkhc wltkwhe tvuh tvc wdn gctwlt swnidc. +wltlupec iece u swpc ncyduputkxc etqdc wr ywssuhn-dkhc lupekhg: qwi ypcutc uh khetuhyc wr WltkwhLupecp, lwlidutc kt mktv wltkwhe, +uhn lupec tvc ywssuhn dkhc. wltlupec uddwme iecpe tw elcykrq wltkwhe kh tvc ywhxchtkwhud GHI/LWEKB eqhtub, uhn unnktkwhuddq gchcputce +ieugc uhn vcdl sceeugce rwp qwi. + +Tiqirmbz hb r ptmz vteuzehzeq, oazyhgaz, rek itjzmofa ahgmrmn otm irmbhed vtpprek-ahez tiqhteb qsre qsz tak dzqtiq ptkfaz. +tiqirmbz fbzb r ptmz kzvarmrqhuz bqnaz to vtpprek-ahez irmbhed: ntf vmzrqz re hebqrevz to TiqhteIrmbzm, itifarqz hq jhqs tiqhteb, +rek irmbz qsz vtpprek ahez. tiqirmbz raatjb fbzmb qt bizvhon tiqhteb he qsz vteuzeqhtera DEF/ITBHY bneqry, rek rkkhqhteraan dzezmrqzb +fbrdz rek szai pzbbrdzb otm ntf. + +Qfnfojyw ey o mqjw sqbrwbewbn, lxwvedxw, obh fqgwjlcx xedjojk lqj fojyeba sqmmobh-xebw qfneqby npob npw qxh awnqfn mqhcxw. +qfnfojyw cywy o mqjw hwsxojonerw ynkxw ql sqmmobh-xebw fojyeba: kqc sjwonw ob ebynobsw ql QfneqbFojywj, fqfcxonw en genp qfneqby, +obh fojyw npw sqmmobh xebw. qfnfojyw oxxqgy cywjy nq yfwselk qfneqby eb npw sqbrwbneqbox ABC/FQYEV ykbnov, obh ohheneqboxxk awbwjonwy +cyoaw obh pwxf mwyyoawy lqj kqc. + +Nckclgvt bv l jngt pnyotybtyk, iutsbaut, lye cndtgizu ubaglgh ing clgvbyx pnjjlye-ubyt nckbnyv kmly kmt nue xtknck jnezut. +nckclgvt zvtv l jngt etpulglkbot vkhut ni pnjjlye-ubyt clgvbyx: hnz pgtlkt ly byvklypt ni NckbnyClgvtg, cnczulkt bk dbkm nckbnyv, +lye clgvt kmt pnjjlye ubyt. nckclgvt luundv zvtgv kn vctpbih nckbnyv by kmt pnyotykbnylu XYZ/CNVBS vhykls, lye leebkbnyluuh xtytglktv +zvlxt lye mtuc jtvvlxtv ing hnz. + +Kzhzidsq ys i gkdq mkvlqvyqvh, frqpyxrq, ivb zkaqdfwr ryxdide fkd zidsyvu mkggivb-ryvq kzhykvs hjiv hjq krb uqhkzh gkbwrq. +kzhzidsq wsqs i gkdq bqmridihylq sherq kf mkggivb-ryvq zidsyvu: ekw mdqihq iv yvshivmq kf KzhykvZidsqd, zkzwrihq yh ayhj kzhykvs, +ivb zidsq hjq mkggivb ryvq. kzhzidsq irrkas wsqds hk szqmyfe kzhykvs yv hjq mkvlqvhykvir UVW/ZKSYP sevhip, ivb ibbyhykvirre uqvqdihqs +wsiuq ivb jqrz gqssiuqs fkd ekw. + +Hwewfapn vp f dhan jhsinsvnse, conmvuon, fsy whxnacto ovuafab cha wfapvsr jhddfsy-ovsn hwevhsp egfs egn hoy rnehwe dhyton. +hwewfapn tpnp f dhan ynjofafevin pebon hc jhddfsy-ovsn wfapvsr: bht janfen fs vspefsjn hc HwevhsWfapna, whwtofen ve xveg hwevhsp, +fsy wfapn egn jhddfsy ovsn. hwewfapn foohxp tpnap eh pwnjvcb hwevhsp vs egn jhsinsevhsfo RST/WHPVM pbsefm, fsy fyyvevhsfoob rnsnafenp +tpfrn fsy gnow dnppfrnp cha bht. + +Etbtcxmk sm c aexk gepfkpskpb, zlkjsrlk, cpv teukxzql lsrxcxy zex tcxmspo geaacpv-lspk etbsepm bdcp bdk elv okbetb aevqlk. +etbtcxmk qmkm c aexk vkglcxcbsfk mbylk ez geaacpv-lspk tcxmspo: yeq gxkcbk cp spmbcpgk ez EtbsepTcxmkx, tetqlcbk sb usbd etbsepm, +cpv tcxmk bdk geaacpv lspk. etbtcxmk clleum qmkxm be mtkgszy etbsepm sp bdk gepfkpbsepcl OPQ/TEMSJ mypbcj, cpv cvvsbsepclly okpkxcbkm +qmcok cpv dklt akmmcokm zex yeq. + +Bqyqzujh pj z xbuh dbmchmphmy, wihgpoih, zms qbrhuwni ipouzuv wbu qzujpml dbxxzms-ipmh bqypbmj yazm yah bis lhybqy xbsnih. +bqyqzujh njhj z xbuh shdizuzypch jyvih bw dbxxzms-ipmh qzujpml: vbn duhzyh zm pmjyzmdh bw BqypbmQzujhu, qbqnizyh py rpya bqypbmj, +zms qzujh yah dbxxzms ipmh. bqyqzujh ziibrj njhuj yb jqhdpwv bqypbmj pm yah dbmchmypbmzi LMN/QBJPG jvmyzg, zms zsspypbmziiv lhmhuzyhj +njzlh zms ahiq xhjjzlhj wbu vbn. + +Ynvnwrge mg w uyre ayjzejmejv, tfedmlfe, wjp nyoertkf fmlrwrs tyr nwrgmji ayuuwjp-fmje ynvmyjg vxwj vxe yfp ievynv uypkfe. +ynvnwrge kgeg w uyre peafwrwvmze gvsfe yt ayuuwjp-fmje nwrgmji: syk arewve wj mjgvwjae yt YnvmyjNwrger, nynkfwve mv omvx ynvmyjg, +wjp nwrge vxe ayuuwjp fmje. ynvnwrge wffyog kgerg vy gneamts ynvmyjg mj vxe ayjzejvmyjwf IJK/NYGMD gsjvwd, wjp wppmvmyjwffs iejerwveg +kgwie wjp xefn ueggwieg tyr syk. + +Vksktodb jd t rvob xvgwbgjbgs, qcbajicb, tgm kvlboqhc cjiotop qvo ktodjgf xvrrtgm-cjgb vksjvgd sutg sub vcm fbsvks rvmhcb. +vksktodb hdbd t rvob mbxctotsjwb dspcb vq xvrrtgm-cjgb ktodjgf: pvh xobtsb tg jgdstgxb vq VksjvgKtodbo, kvkhctsb js ljsu vksjvgd, +tgm ktodb sub xvrrtgm cjgb. vksktodb tccvld hdbod sv dkbxjqp vksjvgd jg sub xvgwbgsjvgtc FGH/KVDJA dpgsta, tgm tmmjsjvgtccp fbgbotsbd +hdtfb tgm ubck rbddtfbd qvo pvh. + +Shphqlay ga q osly usdtydgydp, nzyxgfzy, qdj hsiylnez zgflqlm nsl hqlagdc usooqdj-zgdy shpgsda prqd pry szj cypshp osjezy. +shphqlay eaya q osly jyuzqlqpgty apmzy sn usooqdj-zgdy hqlagdc: mse ulyqpy qd gdapqduy sn ShpgsdHqlayl, hshezqpy gp igpr shpgsda, +qdj hqlay pry usooqdj zgdy. shphqlay qzzsia eayla ps ahyugnm shpgsda gd pry usdtydpgsdqz CDE/HSAGX amdpqx, qdj qjjgpgsdqzzm cydylqpya +eaqcy qdj ryzh oyaaqcya nsl mse. + +Pemenixv dx n lpiv rpaqvadvam, kwvudcwv, nag epfvikbw wdcinij kpi enixdaz rpllnag-wdav pemdpax mona mov pwg zvmpem lpgbwv. +pemenixv bxvx n lpiv gvrwninmdqv xmjwv pk rpllnag-wdav enixdaz: jpb rivnmv na daxmnarv pk PemdpaEnixvi, epebwnmv dm fdmo pemdpax, +nag enixv mov rpllnag wdav. pemenixv nwwpfx bxvix mp xevrdkj pemdpax da mov rpaqvamdpanw ZAB/EPXDU xjamnu, nag nggdmdpanwwj zvavinmvx +bxnzv nag ovwe lvxxnzvx kpi jpb. + +Mbjbkfus au k imfs omxnsxasxj, htsrazts, kxd bmcsfhyt tazfkfg hmf bkfuaxw omiikxd-taxs mbjamxu jlkx jls mtd wsjmbj imdyts. +mbjbkfus yusu k imfs dsotkfkjans ujgts mh omiikxd-taxs bkfuaxw: gmy ofskjs kx axujkxos mh MbjamxBkfusf, bmbytkjs aj cajl mbjamxu, +kxd bkfus jls omiikxd taxs. mbjbkfus kttmcu yusfu jm ubsoahg mbjamxu ax jls omxnsxjamxkt WXY/BMUAR ugxjkr, kxd kddajamxkttg wsxsfkjsu +yukws kxd lstb isuukwsu hmf gmy. + +Jygyhcrp xr h fjcp ljukpuxpug, eqpoxwqp, hua yjzpcevq qxwchcd ejc yhcrxut ljffhua-qxup jygxjur gihu gip jqa tpgjyg fjavqp. +jygyhcrp vrpr h fjcp aplqhchgxkp rgdqp je ljffhua-qxup yhcrxut: djv lcphgp hu xurghulp je JygxjuYhcrpc, yjyvqhgp xg zxgi jygxjur, +hua yhcrp gip ljffhua qxup. jygyhcrp hqqjzr vrpcr gj ryplxed jygxjur xu gip ljukpugxjuhq TUV/YJRXO rdugho, hua haaxgxjuhqqd tpupchgpr +vrhtp hua ipqy fprrhtpr ejc djv. + +Gvdvezom uo e cgzm igrhmrumrd, bnmlutnm, erx vgwmzbsn nutzeza bgz vezourq igccerx-nurm gvdugro dfer dfm gnx qmdgvd cgxsnm. +gvdvezom somo e cgzm xminezeduhm odanm gb igccerx-nurm vezourq: ags izmedm er uroderim gb GvdugrVezomz, vgvsnedm ud wudf gvdugro, +erx vezom dfm igccerx nurm. gvdvezom enngwo somzo dg ovmiuba gvdugro ur dfm igrhmrdugren QRS/VGOUL oardel, erx exxudugrenna qmrmzedmo +soeqm erx fmnv cmooeqmo bgz ags. + +Dsasbwlj rl b zdwj fdoejorjoa, ykjirqkj, bou sdtjwypk krqwbwx ydw sbwlron fdzzbou-kroj dsardol acbo acj dku njadsa zdupkj. +dsasbwlj pljl b zdwj ujfkbwbarej laxkj dy fdzzbou-kroj sbwlron: xdp fwjbaj bo rolabofj dy DsardoSbwljw, sdspkbaj ra trac dsardol, +bou sbwlj acj fdzzbou kroj. dsasbwlj bkkdtl pljwl ad lsjfryx dsardol ro acj fdoejoardobk NOP/SDLRI lxoabi, bou buurardobkkx njojwbajl +plbnj bou cjks zjllbnjl ydw xdp. + +Apxpytig oi y watg calbgloglx, vhgfonhg, ylr paqgtvmh hontytu vat pytiolk cawwylr-holg apxoali xzyl xzg ahr kgxapx warmhg. +apxpytig migi y watg rgchytyxobg ixuhg av cawwylr-holg pytiolk: uam ctgyxg yl olixylcg av ApxoalPytigt, papmhyxg ox qoxz apxoali, +ylr pytig xzg cawwylr holg. apxpytig yhhaqi migti xa ipgcovu apxoali ol xzg calbglxoalyh KLM/PAIOF iulxyf, ylr yrroxoalyhhu kglgtyxgi +miykg ylr zghp wgiiykgi vat uam. + +Xmumvqfd lf v txqd zxiydildiu, sedclked, vio mxndqsje elkqvqr sxq mvqflih zxttvio-elid xmulxif uwvi uwd xeo hduxmu txojed. +xmumvqfd jfdf v txqd odzevqvulyd fured xs zxttvio-elid mvqflih: rxj zqdvud vi lifuvizd xs XmulxiMvqfdq, mxmjevud lu nluw xmulxif, +vio mvqfd uwd zxttvio elid. xmumvqfd veexnf jfdqf ux fmdzlsr xmulxif li uwd zxiydiulxive HIJ/MXFLC friuvc, vio voolulxiveer hdidqvudf +jfvhd vio wdem tdffvhdf sxq rxj. + +Ujrjsnca ic s quna wufvafiafr, pbazihba, sfl jukanpgb bihnsno pun jsncife wuqqsfl-bifa ujriufc rtsf rta ubl earujr qulgba. +ujrjsnca gcac s quna lawbsnsriva croba up wuqqsfl-bifa jsncife: oug wnasra sf ifcrsfwa up UjriufJsncan, jujgbsra ir kirt ujriufc, +sfl jsnca rta wuqqsfl bifa. ujrjsnca sbbukc gcanc ru cjawipo ujriufc if rta wufvafriufsb EFG/JUCIZ cofrsz, sfl slliriufsbbo eafansrac +gcsea sfl tabj qaccseac pun oug. + +Rgogpkzx fz p nrkx trcsxcfxco, myxwfeyx, pci grhxkmdy yfekpkl mrk gpkzfcb trnnpci-yfcx rgofrcz oqpc oqx ryi bxorgo nridyx. +rgogpkzx dzxz p nrkx ixtypkpofsx zolyx rm trnnpci-yfcx gpkzfcb: lrd tkxpox pc fczopctx rm RgofrcGpkzxk, grgdypox fo hfoq rgofrcz, +pci gpkzx oqx trnnpci yfcx. rgogpkzx pyyrhz dzxkz or zgxtfml rgofrcz fc oqx trcsxcofrcpy BCD/GRZFW zlcopw, pci piifofrcpyyl bxcxkpoxz +dzpbx pci qxyg nxzzpbxz mrk lrd. + +Odldmhwu cw m kohu qozpuzcuzl, jvutcbvu, mzf doeuhjav vcbhmhi joh dmhwczy qokkmzf-vczu odlcozw lnmz lnu ovf yulodl kofavu. +odldmhwu awuw m kohu fuqvmhmlcpu wlivu oj qokkmzf-vczu dmhwczy: ioa qhumlu mz czwlmzqu oj OdlcozDmhwuh, dodavmlu cl ecln odlcozw, +mzf dmhwu lnu qokkmzf vczu. odldmhwu mvvoew awuhw lo wduqcji odlcozw cz lnu qozpuzlcozmv YZA/DOWCT wizlmt, mzf mffclcozmvvi yuzuhmluw +awmyu mzf nuvd kuwwmyuw joh ioa. + +Jaqafizv lz f bjiv njsyvslvsq, mkvglwkv, fse ajpvimhk klwifix mji afizlsd njbbfse-klsv jaqljsz qufs quv jke dvqjaq bjehkv. +jaqafizv hzvz f bjiv evnkfifqlyv zqxkv jm njbbfse-klsv afizlsd: xjh nivfqv fs lszqfsnv jm JaqljsAfizvi, ajahkfqv lq plqu jaqljsz, +fse afizv quv njbbfse klsv. jaqafizv fkkjpz hzviz qj zavnlmx jaqljsz ls quv njsyvsqljsfk DSH/AJZLG zxsqfg, fse feelqljsfkkx dvsvifqvz +hzfdv fse uvka bvzzfdvz mji xjh. + +Qhxhmpgc sg m iqpc uqzfczsczx, trcnsdrc, mzl hqwcptor rsdpmpe tqp hmpgszk uqiimzl-rszc qhxsqzg xbmz xbc qrl kcxqhx iqlorc. +qhxhmpgc ogcg m iqpc lcurmpmxsfc gxerc qt uqiimzl-rszc hmpgszk: eqo upcmxc mz szgxmzuc qt QhxsqzHmpgcp, hqhormxc sx wsxb qhxsqzg, +mzl hmpgc xbc uqiimzl rszc. qhxhmpgc mrrqwg ogcpg xq ghcuste qhxsqzg sz xbc uqzfczxsqzmr KZO/HQGSN gezxmn, mzl mllsxsqzmrre kczcpmxcg +ogmkc mzl bcrh icggmkcg tqp eqo. + +Xoeotwnj zn t pxwj bxgmjgzjge, ayjuzkyj, tgs oxdjwavy yzkwtwl axw otwnzgr bxpptgs-yzgj xoezxgn eitg eij xys rjexoe pxsvyj. +xoeotwnj vnjn t pxwj sjbytwtezmj nelyj xa bxpptgs-yzgj otwnzgr: lxv bwjtej tg zgnetgbj xa XoezxgOtwnjw, oxovytej ze dzei xoezxgn, +tgs otwnj eij bxpptgs yzgj. xoeotwnj tyyxdn vnjwn ex nojbzal xoezxgn zg eij bxgmjgezxgty RGV/OXNZU nlgetu, tgs tsszezxgtyyl rjgjwtejn +vntrj tgs ijyo pjnntrjn axw lxv. + +Evlvaduq gu a wedq ientqngqnl, hfqbgrfq, anz vekqdhcf fgrdads hed vadugny iewwanz-fgnq evlgenu lpan lpq efz yqlevl wezcfq. +evlvaduq cuqu a wedq zqifadalgtq ulsfq eh iewwanz-fgnq vadugny: sec idqalq an gnulaniq eh EvlgenVaduqd, vevcfalq gl kglp evlgenu, +anz vaduq lpq iewwanz fgnq. evlvaduq affeku cuqdu le uvqighs evlgenu gn lpq ientqnlgenaf YNC/VEUGB usnlab, anz azzglgenaffs yqnqdalqu +cuayq anz pqfv wquuayqu hed sec. + +Lcschkbx nb h dlkx pluaxunxus, omxinymx, hug clrxkojm mnykhkz olk chkbnuf plddhug-mnux lcsnlub swhu swx lmg fxslcs dlgjmx. +lcschkbx jbxb h dlkx gxpmhkhsnax bszmx lo plddhug-mnux chkbnuf: zlj pkxhsx hu nubshupx lo LcsnluChkbxk, clcjmhsx ns rnsw lcsnlub, +hug chkbx swx plddhug mnux. lcschkbx hmmlrb jbxkb sl bcxpnoz lcsnlub nu swx pluaxusnluhm FUJ/CLBNI bzushi, hug hggnsnluhmmz fxuxkhsxb +jbhfx hug wxmc dxbbhfxb olk zlj. + +Sjzjorie ui o ksre wsbhebuebz, vtepufte, obn jsyervqt tufrorg vsr joriubm wskkobn-tube sjzusbi zdob zde stn mezsjz ksnqte. +sjzjorie qiei o ksre newtorozuhe izgte sv wskkobn-tube joriubm: gsq wreoze ob ubizobwe sv SjzusbJorier, jsjqtoze uz yuzd sjzusbi, +obn jorie zde wskkobn tube. sjzjorie ottsyi qieri zs ijewuvg sjzusbi ub zde wsbhebzusbot MBQ/JSIUP igbzop, obn onnuzusbottg meberozei +qiome obn detj keiiomei vsr gsq. + +Zqgqvypl bp v rzyl dzioliblig, calwbmal, viu qzflycxa abmyvyn czy qvypbit dzrrviu-abil zqgbzip gkvi gkl zau tlgzqg rzuxal. +zqgqvypl xplp v rzyl uldavyvgbol pgnal zc dzrrviu-abil qvypbit: nzx dylvgl vi bipgvidl zc ZqgbziQvyply, qzqxavgl bg fbgk zqgbzip, +viu qvypl gkl dzrrviu abil. zqgqvypl vaazfp xplyp gz pqldbcn zqgbzip bi gkl dzioligbziva TIX/QZPBW pnigvw, viu vuubgbzivaan tlilyvglp +xpvtl viu klaq rlppvtlp czy nzx. + +Gxnxcfws iw c ygfs kgpvspispn, jhsdiths, cpb xgmsfjeh hitfcfu jgf xcfwipa kgyycpb-hips gxnigpw nrcp nrs ghb asngxn ygbehs. +gxnxcfws ewsw c ygfs bskhcfcnivs wnuhs gj kgyycpb-hips xcfwipa: uge kfscns cp ipwncpks gj GxnigpXcfwsf, xgxehcns in minr gxnigpw, +cpb xcfws nrs kgyycpb hips. gxnxcfws chhgmw ewsfw ng wxskiju gxnigpw ip nrs kgpvspnigpch APE/XGWID wupncd, cpb cbbinigpchhu aspsfcnsw +ewcas cpb rshx yswwcasw jgf uge. + +Neuejmdz pd j fnmz rnwczwpzwu, qozkpaoz, jwi entzmqlo opamjmb qnm ejmdpwh rnffjwi-opwz neupnwd uyjw uyz noi hzuneu fniloz. +neuejmdz ldzd j fnmz izrojmjupcz duboz nq rnffjwi-opwz ejmdpwh: bnl rmzjuz jw pwdujwrz nq NeupnwEjmdzm, enelojuz pu tpuy neupnwd, +jwi ejmdz uyz rnffjwi opwz. neuejmdz joontd ldzmd un dezrpqb neupnwd pw uyz rnwczwupnwjo HWL/ENDPK dbwujk, jwi jiipupnwjoob hzwzmjuzd +ldjhz jwi yzoe fzddjhzd qnm bnl. + +Ulblqtkg wk q mutg yudjgdwgdb, xvgrwhvg, qdp luagtxsv vwhtqti xut lqtkwdo yummqdp-vwdg ulbwudk bfqd bfg uvp ogbulb mupsvg. +ulblqtkg skgk q mutg pgyvqtqbwjg kbivg ux yummqdp-vwdg lqtkwdo: ius ytgqbg qd wdkbqdyg ux UlbwudLqtkgt, lulsvqbg wb awbf ulbwudk, +qdp lqtkg bfg yummqdp vwdg. ulblqtkg qvvuak skgtk bu klgywxi ulbwudk wd bfg yudjgdbwudqv ODS/LUKWR kidbqr, qdp qppwbwudqvvi ogdgtqbgk +skqog qdp fgvl mgkkqogk xut ius. + +Bsisxarn dr x tban fbkqnkdnki, ecnydocn, xkw sbhnaezc cdoaxap eba sxardkv fbttxkw-cdkn bsidbkr imxk imn bcw vnibsi tbwzcn. +bsisxarn zrnr x tban wnfcxaxidqn ripcn be fbttxkw-cdkn sxardkv: pbz fanxin xk dkrixkfn be BsidbkSxarna, sbszcxin di hdim bsidbkr, +xkw sxarn imn fbttxkw cdkn. bsisxarn xccbhr zrnar ib rsnfdep bsidbkr dk imn fbkqnkidbkxc VKZ/SBRDY rpkixy, xkw xwwdidbkxccp vnknaxinr +zrxvn xkw mncs tnrrxvnr eba pbz. + +Izpzehyu ky e aihu mirxurkurp, ljufkvju, erd ziouhlgj jkvhehw lih zehykrc miaaerd-jkru izpkiry pter ptu ijd cupizp aidgju. +izpzehyu gyuy e aihu dumjehepkxu ypwju il miaaerd-jkru zehykrc: wig mhuepu er krypermu il IzpkirZehyuh, zizgjepu kp okpt izpkiry, +erd zehyu ptu miaaerd jkru. izpzehyu ejjioy gyuhy pi yzumklw izpkiry kr ptu mirxurpkirej CRG/ZIYKF ywrpef, erd eddkpkirejjw curuhepuy +gyecu erd tujz auyyecuy lih wig. + +Pgwglofb rf l hpob tpyebyrbyw, sqbmrcqb, lyk gpvbosnq qrcolod spo glofryj tphhlyk-qryb pgwrpyf waly wab pqk jbwpgw hpknqb. +pgwglofb nfbf l hpob kbtqlolwreb fwdqb ps tphhlyk-qryb glofryj: dpn toblwb ly ryfwlytb ps PgwrpyGlofbo, gpgnqlwb rw vrwa pgwrpyf, +lyk glofb wab tphhlyk qryb. pgwglofb lqqpvf nfbof wp fgbtrsd pgwrpyf ry wab tpyebywrpylq JYN/GPFRM fdywlm, lyk lkkrwrpylqqd jbybolwbf +nfljb lyk abqg hbffljbf spo dpn. + +Wndnsvmi ym s owvi awflifyifd, zxityjxi, sfr nwcivzux xyjvsvk zwv nsvmyfq awoosfr-xyfi wndywfm dhsf dhi wxr qidwnd owruxi. +wndnsvmi umim s owvi riaxsvsdyli mdkxi wz awoosfr-xyfi nsvmyfq: kwu avisdi sf yfmdsfai wz WndywfNsvmiv, nwnuxsdi yd cydh wndywfm, +sfr nsvmi dhi awoosfr xyfi. wndnsvmi sxxwcm umivm dw mniayzk wndywfm yf dhi awflifdywfsx QFU/NWMYT mkfdst, sfr srrydywfsxxk qifivsdim +umsqi sfr hixn oimmsqim zwv kwu. + +Dukuzctp ft z vdcp hdmspmfpmk, gepafqep, zmy udjpcgbe efqczcr gdc uzctfmx hdvvzmy-efmp dukfdmt kozm kop dey xpkduk vdybep. +dukuzctp btpt z vdcp yphezczkfsp tkrep dg hdvvzmy-efmp uzctfmx: rdb hcpzkp zm fmtkzmhp dg DukfdmUzctpc, udubezkp fk jfko dukfdmt, +zmy uzctp kop hdvvzmy efmp. dukuzctp zeedjt btpct kd tuphfgr dukfdmt fm kop hdmspmkfdmze XMB/UDTFA trmkza, zmy zyyfkfdmzeer xpmpczkpt +btzxp zmy opeu vpttzxpt gdc rdb. + +Kbrbgjaw ma g ckjw oktzwtmwtr, nlwhmxlw, gtf bkqwjnil lmxjgjy nkj bgjamte okccgtf-lmtw kbrmkta rvgt rvw klf ewrkbr ckfilw. +kbrbgjaw iawa g ckjw fwolgjgrmzw arylw kn okccgtf-lmtw bgjamte: yki ojwgrw gt mtargtow kn KbrmktBgjawj, bkbilgrw mr qmrv kbrmkta, +gtf bgjaw rvw okccgtf lmtw. kbrbgjaw gllkqa iawja rk abwomny kbrmkta mt rvw oktzwtrmktgl ETI/BKAMH aytrgh, gtf gffmrmktglly ewtwjgrwa +iagew gtf vwlb cwaagewa nkj yki. + +Riyinqhd th n jrqd vragdatday, usdotesd, nam irxdqups steqnqf urq inqhtal vrjjnam-stad riytrah ycna ycd rsm ldyriy jrmpsd. +riyinqhd phdh n jrqd mdvsnqnytgd hyfsd ru vrjjnam-stad inqhtal: frp vqdnyd na tahynavd ru RiytraInqhdq, iripsnyd ty xtyc riytrah, +nam inqhd ycd vrjjnam stad. riyinqhd nssrxh phdqh yr hidvtuf riytrah ta ycd vragdaytrans LAP/IRHTO hfayno, nam nmmtytranssf ldadqnydh +phnld nam cdsi jdhhnldh urq frp. + +Ypfpuxok ao u qyxk cyhnkhakhf, bzkvalzk, uht pyekxbwz zalxuxm byx puxoahs cyqquht-zahk ypfayho fjuh fjk yzt skfypf qytwzk. +ypfpuxok woko u qyxk tkczuxufank ofmzk yb cyqquht-zahk puxoahs: myw cxkufk uh ahofuhck yb YpfayhPuxokx, pypwzufk af eafj ypfayho, +uht puxok fjk cyqquht zahk. ypfpuxok uzzyeo wokxo fy opkcabm ypfayho ah fjk cyhnkhfayhuz SHW/PYOAV omhfuv, uht uttafayhuzzm skhkxufko +wousk uht jkzp qkoousko byx myw. + +Fwmwbevr hv b xfer jfourohrom, igrchsgr, boa wflreidg ghsebet ife wbevhoz jfxxboa-ghor fwmhfov mqbo mqr fga zrmfwm xfadgr. +fwmwbevr dvrv b xfer arjgbebmhur vmtgr fi jfxxboa-ghor wbevhoz: tfd jerbmr bo hovmbojr fi FwmhfoWbevre, wfwdgbmr hm lhmq fwmhfov, +boa wbevr mqr jfxxboa ghor. fwmwbevr bggflv dvrev mf vwrjhit fwmhfov ho mqr jfouromhfobg ZOD/WFVHC vtombc, boa baahmhfobggt zrorebmrv +dvbzr boa qrgw xrvvbzrv ife tfd. + +Mdtdilcy oc i emly qmvbyvoyvt, pnyjozny, ivh dmsylpkn nozlila pml dilcovg qmeeivh-novy mdtomvc txiv txy mnh gytmdt emhkny. +mdtdilcy kcyc i emly hyqnilitoby ctany mp qmeeivh-novy dilcovg: amk qlyity iv ovctivqy mp MdtomvDilcyl, dmdknity ot sotx mdtomvc, +ivh dilcy txy qmeeivh novy. mdtdilcy innmsc kcylc tm cdyqopa mdtomvc ov txy qmvbyvtomvin GVK/DMCOJ cavtij, ivh ihhotomvinna gyvylityc +kcigy ivh xynd eyccigyc pml amk. + +Tkakpsjf vj p ltsf xtcifcvfca, wufqvguf, pco ktzfswru uvgspsh wts kpsjvcn xtllpco-uvcf tkavtcj aepc aef tuo nfatka ltoruf. +tkakpsjf rjfj p ltsf ofxupspavif jahuf tw xtllpco-uvcf kpsjvcn: htr xsfpaf pc vcjapcxf tw TkavtcKpsjfs, ktkrupaf va zvae tkavtcj, +pco kpsjf aef xtllpco uvcf. tkakpsjf puutzj rjfsj at jkfxvwh tkavtcj vc aef xtcifcavtcpu NCR/KTJVQ jhcapq, pco poovavtcpuuh nfcfspafj +rjpnf pco efuk lfjjpnfj wts htr. + +Arhrwzqm cq w sazm eajpmjcmjh, dbmxcnbm, wjv ragmzdyb bcnzwzo daz rwzqcju easswjv-bcjm arhcajq hlwj hlm abv umharh savybm. +arhrwzqm yqmq w sazm vmebwzwhcpm qhobm ad easswjv-bcjm rwzqcju: oay ezmwhm wj cjqhwjem ad ArhcajRwzqmz, rarybwhm ch gchl arhcajq, +wjv rwzqm hlm easswjv bcjm. arhrwzqm wbbagq yqmzq ha qrmecdo arhcajq cj hlm eajpmjhcajwb UJY/RAQCX qojhwx, wjv wvvchcajwbbo umjmzwhmq +yqwum wjv lmbr smqqwumq daz oay. + +Hyoydgxt jx d zhgt lhqwtqjtqo, kitejuit, dqc yhntgkfi ijugdgv khg ydgxjqb lhzzdqc-ijqt hyojhqx osdq ost hic btohyo zhcfit. +hyoydgxt fxtx d zhgt ctlidgdojwt xovit hk lhzzdqc-ijqt ydgxjqb: vhf lgtdot dq jqxodqlt hk HyojhqYdgxtg, yhyfidot jo njos hyojhqx, +dqc ydgxt ost lhzzdqc ijqt. hyoydgxt diihnx fxtgx oh xytljkv hyojhqx jq ost lhqwtqojhqdi BQF/YHXJE xvqode, dqc dccjojhqdiiv btqtgdotx +fxdbt dqc stiy ztxxdbtx khg vhf. + +Ofvfknea qe k gona soxdaxqaxv, rpalqbpa, kxj fouanrmp pqbnknc ron fkneqxi soggkxj-pqxa ofvqoxe vzkx vza opj iavofv gojmpa. +ofvfknea meae k gona jaspknkvqda evcpa or soggkxj-pqxa fkneqxi: com snakva kx qxevkxsa or OfvqoxFknean, fofmpkva qv uqvz ofvqoxe, +kxj fknea vza soggkxj pqxa. ofvfknea kppoue meane vo efasqrc ofvqoxe qx vza soxdaxvqoxkp IXM/FOEQL ecxvkl, kxj kjjqvqoxkppc iaxankvae +mekia kxj zapf gaeekiae ron com. + +Vmcmrulh xl r nvuh zvekhexhec, ywhsxiwh, req mvbhuytw wxiuruj yvu mrulxep zvnnreq-wxeh vmcxvel cgre cgh vwq phcvmc nvqtwh. +vmcmrulh tlhl r nvuh qhzwrurcxkh lcjwh vy zvnnreq-wxeh mrulxep: jvt zuhrch re xelcrezh vy VmcxveMrulhu, mvmtwrch xc bxcg vmcxvel, +req mrulh cgh zvnnreq wxeh. vmcmrulh rwwvbl tlhul cv lmhzxyj vmcxvel xe cgh zvekhecxverw PET/MVLXS ljecrs, req rqqxcxverwwj phehurchl +tlrph req ghwm nhllrphl yvu jvt. + +Ctjtybso es y ucbo gclroleolj, fdozepdo, ylx tciobfad depbybq fcb tybselw gcuuylx-delo ctjecls jnyl jno cdx wojctj ucxado. +ctjtybso asos y ucbo xogdybyjero sjqdo cf gcuuylx-delo tybselw: qca gboyjo yl elsjylgo cf CtjeclTybsob, tctadyjo ej iejn ctjecls, +ylx tybso jno gcuuylx delo. ctjtybso yddcis asobs jc stogefq ctjecls el jno gclroljeclyd WLA/TCSEZ sqljyz, ylx yxxejeclyddq wolobyjos +asywo ylx nodt uossywos fcb qca. + +Rakavsbf pb v zrsf nricfipfik, oqfupeqf, viw arlfsotq qpesvsd ors avsbpix nrzzviw-qpif rakprib kgvi kgf rqw xfkrak zrwtqf. +rakavsbf tbfb v zrsf wfnqvsvkpcf bkdqf ro nrzzviw-qpif avsbpix: drt nsfvkf vi pibkvinf ro RakpriAvsbfs, aratqvkf pk lpkg rakprib, +viw avsbf kgf nrzzviw qpif. rakavsbf vqqrlb tbfsb kr bafnpod rakprib pi kgf nricfikprivq XIT/ARBPU bdikvu, viw vwwpkprivqqd xfifsvkfb +tbvxf viw gfqa zfbbvxfb ors drt. + +Ktdtoluy iu o skly gkbvybiybd, hjynixjy, obp tkeylhmj jixlolw hkl toluibq gkssobp-jiby ktdikbu dzob dzy kjp qydktd skpmjy. +ktdtoluy muyu o skly pygjolodivy udwjy kh gkssobp-jiby toluibq: wkm glyody ob ibudobgy kh KtdikbToluyl, tktmjody id eidz ktdikbu, +obp toluy dzy gkssobp jiby. ktdtoluy ojjkeu muylu dk utygihw ktdikbu ib dzy gkbvybdikboj QBM/TKUIN uwbdon, obp oppidikbojjw qybylodyu +muoqy obp zyjt syuuoqyu hkl wkm. + +Dmwmhenr bn h lder zduorubruw, acrgbqcr, hui mdxreafc cbqehep ade mhenbuj zdllhui-cbur dmwbdun wshu wsr dci jrwdmw ldifcr. +dmwmhenr fnrn h lder irzchehwbor nwpcr da zdllhui-cbur mhenbuj: pdf zerhwr hu bunwhuzr da DmwbduMhenre, mdmfchwr bw xbws dmwbdun, +hui mhenr wsr zdllhui cbur. dmwmhenr hccdxn fnren wd nmrzbap dmwbdun bu wsr zduoruwbduhc JUF/MDNBG npuwhg, hui hiibwbduhccp jrurehwrn +fnhjr hui srcm lrnnhjrn ade pdf. + +Wfpfaxgk ug a ewxk swnhknuknp, tvkzujvk, anb fwqkxtyv vujxaxi twx faxgunc sweeanb-vunk wfpuwng plan plk wvb ckpwfp ewbyvk. +wfpfaxgk ygkg a ewxk bksvaxapuhk gpivk wt sweeanb-vunk faxgunc: iwy sxkapk an ungpansk wt WfpuwnFaxgkx, fwfyvapk up qupl wfpuwng, +anb faxgk plk sweeanb vunk. wfpfaxgk avvwqg ygkxg pw gfksuti wfpuwng un plk swnhknpuwnav CNY/FWGUZ ginpaz, anb abbupuwnavvi cknkxapkg +ygack anb lkvf ekggackg twx iwy. + +Pyiytqzd nz t xpqd lpgadgndgi, modsncod, tgu ypjdqmro oncqtqb mpq ytqzngv lpxxtgu-ongd pyinpgz ietg ied pou vdipyi xpurod. +pyiytqzd rzdz t xpqd udlotqtinad zibod pm lpxxtgu-ongd ytqzngv: bpr lqdtid tg ngzitgld pm PyinpgYtqzdq, ypyrotid ni jnie pyinpgz, +tgu ytqzd ied lpxxtgu ongd. pyiytqzd toopjz rzdqz ip zydlnmb pyinpgz ng ied lpgadginpgto VGR/YPZNS zbgits, tgu tuuninpgtoob vdgdqtidz +rztvd tgu edoy xdzztvdz mpq bpr. + +Irbrmjsw gs m qijw eiztwzgwzb, fhwlgvhw, mzn ricwjfkh hgvjmju fij rmjsgzo eiqqmzn-hgzw irbgizs bxmz bxw ihn owbirb qinkhw. +irbrmjsw ksws m qijw nwehmjmbgtw sbuhw if eiqqmzn-hgzw rmjsgzo: uik ejwmbw mz gzsbmzew if IrbgizRmjswj, rirkhmbw gb cgbx irbgizs, +mzn rmjsw bxw eiqqmzn hgzw. irbrmjsw mhhics kswjs bi srwegfu irbgizs gz bxw eiztwzbgizmh OZK/RISGL suzbml, mzn mnngbgizmhhu owzwjmbws +ksmow mzn xwhr qwssmows fij uik. + +Bkukfclp zl f jbcp xbsmpszpsu, yapezoap, fsg kbvpcyda azocfcn ybc kfclzsh xbjjfsg-azsp bkuzbsl uqfs uqp bag hpubku jbgdap. +bkukfclp dlpl f jbcp gpxafcfuzmp lunap by xbjjfsg-azsp kfclzsh: nbd xcpfup fs zslufsxp by BkuzbsKfclpc, kbkdafup zu vzuq bkuzbsl, +fsg kfclp uqp xbjjfsg azsp. bkukfclp faabvl dlpcl ub lkpxzyn bkuzbsl zs uqp xbsmpsuzbsfa HSD/KBLZE lnsufe, fsg fggzuzbsfaan hpspcfupl +dlfhp fsg qpak jpllfhpl ybc nbd. + +Udndyvei se y cuvi qulfilsiln, rtixshti, ylz duoivrwt tshvyvg ruv dyvesla quccylz-tsli udnsule njyl nji utz ainudn cuzwti. +udndyvei weie y cuvi ziqtyvynsfi engti ur quccylz-tsli dyvesla: guw qviyni yl slenylqi ur UdnsulDyveiv, dudwtyni sn osnj udnsule, +ylz dyvei nji quccylz tsli. udndyvei yttuoe weive nu ediqsrg udnsule sl nji qulfilnsulyt ALW/DUESX eglnyx, ylz yzzsnsulyttg ailivynie +weyai ylz jitd cieeyaie ruv guw. + +Nwgwroxb lx r vnob jneybelbeg, kmbqlamb, res wnhbokpm mlaoroz kno wroxlet jnvvres-mleb nwglnex gcre gcb nms tbgnwg vnspmb. +nwgwroxb pxbx r vnob sbjmrorglyb xgzmb nk jnvvres-mleb wroxlet: znp jobrgb re lexgrejb nk NwglneWroxbo, wnwpmrgb lg hlgc nwglnex, +res wroxb gcb jnvvres mleb. nwgwroxb rmmnhx pxbox gn xwbjlkz nwglnex le gcb jneybeglnerm TEP/WNXLQ xzegrq, res rsslglnermmz tbeborgbx +pxrtb res cbmw vbxxrtbx kno znp. + +Gpzpkhqu eq k oghu cgxruxeuxz, dfujetfu, kxl pgauhdif fethkhs dgh pkhqexm cgookxl-fexu gpzegxq zvkx zvu gfl muzgpz oglifu. +gpzpkhqu iquq k oghu lucfkhkzeru qzsfu gd cgookxl-fexu pkhqexm: sgi chukzu kx exqzkxcu gd GpzegxPkhquh, pgpifkzu ez aezv gpzegxq, +kxl pkhqu zvu cgookxl fexu. gpzpkhqu kffgaq iquhq zg qpuceds gpzegxq ex zvu cgxruxzegxkf MXI/PGQEJ qsxzkj, kxl kllezegxkffs muxuhkzuq +iqkmu kxl vufp ouqqkmuq dgh sgi. + +Zisidajn xj d hzan vzqknqxnqs, wyncxmyn, dqe iztnawby yxmadal wza idajxqf vzhhdqe-yxqn zisxzqj sodq son zye fnszis hzebyn. +zisidajn bjnj d hzan envydadsxkn jslyn zw vzhhdqe-yxqn idajxqf: lzb vandsn dq xqjsdqvn zw ZisxzqIdajna, izibydsn xs txso zisxzqj, +dqe idajn son vzhhdqe yxqn. zisidajn dyyztj bjnaj sz jinvxwl zisxzqj xq son vzqknqsxzqdy FQB/IZJXC jlqsdc, dqe deexsxzqdyyl fnqnadsnj +bjdfn dqe onyi hnjjdfnj wza lzb. + +Sblbwtcg qc w astg osjdgjqgjl, prgvqfrg, wjx bsmgtpur rqftwte pst bwtcqjy osaawjx-rqjg sblqsjc lhwj lhg srx yglsbl asxurg. +sblbwtcg ucgc w astg xgorwtwlqdg clerg sp osaawjx-rqjg bwtcqjy: esu otgwlg wj qjclwjog sp SblqsjBwtcgt, bsburwlg ql mqlh sblqsjc, +wjx bwtcg lhg osaawjx rqjg. sblbwtcg wrrsmc ucgtc ls cbgoqpe sblqsjc qj lhg osjdgjlqsjwr YJU/BSCQV cejlwv, wjx wxxqlqsjwrre ygjgtwlgc +ucwyg wjx hgrb agccwygc pst esu. + +Lueupmvz jv p tlmz hlcwzcjzce, ikzojykz, pcq ulfzmink kjympmx ilm upmvjcr hlttpcq-kjcz luejlcv eapc eaz lkq rzelue tlqnkz. +lueupmvz nvzv p tlmz qzhkpmpejwz vexkz li hlttpcq-kjcz upmvjcr: xln hmzpez pc jcvepchz li LuejlcUpmvzm, ulunkpez je fjea luejlcv, +pcq upmvz eaz hlttpcq kjcz. lueupmvz pkklfv nvzmv el vuzhjix luejlcv jc eaz hlcwzcejlcpk RCN/ULVJO vxcepo, pcq pqqjejlcpkkx rzczmpezv +nvprz pcq azku tzvvprzv ilm xln. + +Enxnifos co i mefs aevpsvcsvx, bdshcrds, ivj neysfbgd dcrfifq bef nifocvk aemmivj-dcvs enxcevo xtiv xts edj ksxenx mejgds. +enxnifos goso i mefs jsadifixcps oxqds eb aemmivj-dcvs nifocvk: qeg afsixs iv cvoxivas eb EnxcevNifosf, nengdixs cx ycxt enxcevo, +ivj nifos xts aemmivj dcvs. enxnifos iddeyo gosfo xe onsacbq enxcevo cv xts aevpsvxcevid KVG/NEOCH oqvxih, ivj ijjcxceviddq ksvsfixso +goiks ivj tsdn msooikso bef qeg. + +Xgqgbyhl vh b fxyl txoilovloq, uwlavkwl, boc gxrlyuzw wvkybyj uxy gbyhvod txffboc-wvol xgqvxoh qmbo qml xwc dlqxgq fxczwl. +xgqgbyhl zhlh b fxyl cltwbybqvil hqjwl xu txffboc-wvol gbyhvod: jxz tylbql bo vohqbotl xu XgqvxoGbyhly, gxgzwbql vq rvqm xgqvxoh, +boc gbyhl qml txffboc wvol. xgqgbyhl bwwxrh zhlyh qx hgltvuj xgqvxoh vo qml txoiloqvxobw DOZ/GXHVA hjoqba, boc bccvqvxobwwj dlolybqlh +zhbdl boc mlwg flhhbdlh uxy jxz. + +Qzjzurae oa u yqre mqhbehoehj, npetodpe, uhv zqkernsp podrurc nqr zuraohw mqyyuhv-pohe qzjoqha jfuh jfe qpv wejqzj yqvspe. +qzjzurae saea u yqre vempurujobe ajcpe qn mqyyuhv-pohe zuraohw: cqs mreuje uh ohajuhme qn QzjoqhZuraer, zqzspuje oj kojf qzjoqha, +uhv zurae jfe mqyyuhv pohe. qzjzurae uppqka saera jq azemonc qzjoqha oh jfe mqhbehjoqhup WHS/ZQAOT achjut, uhv uvvojoqhuppc weherujea +sauwe uhv fepz yeaauwea nqr cqs. + +Jscsnktx ht n rjkx fjauxahxac, gixmhwix, nao sjdxkgli ihwknkv gjk snkthap fjrrnao-ihax jschjat cyna cyx jio pxcjsc rjolix. +jscsnktx ltxt n rjkx oxfinknchux tcvix jg fjrrnao-ihax snkthap: vjl fkxncx na hatcnafx jg JschjaSnktxk, sjslincx hc dhcy jschjat, +nao snktx cyx fjrrnao ihax. jscsnktx niijdt ltxkt cj tsxfhgv jschjat ha cyx fjauxachjani PAL/SJTHM tvacnm, nao noohchjaniiv pxaxkncxt +ltnpx nao yxis rxttnpxt gjk vjl. + +Clvlgdmq am g kcdq yctnqtaqtv, zbqfapbq, gth lcwqdzeb bapdgdo zcd lgdmati yckkgth-batq clvactm vrgt vrq cbh iqvclv kchebq. +clvlgdmq emqm g kcdq hqybgdgvanq mvobq cz yckkgth-batq lgdmati: oce ydqgvq gt atmvgtyq cz ClvactLgdmqd, lclebgvq av wavr clvactm, +gth lgdmq vrq yckkgth batq. clvlgdmq gbbcwm emqdm vc mlqyazo clvactm at vrq yctnqtvactgb ITE/LCMAF motvgf, gth ghhavactgbbo iqtqdgvqm +emgiq gth rqbl kqmmgiqm zcd oce. + +Veoezwfj tf z dvwj rvmgjmtjmo, sujytiuj, zma evpjwsxu utiwzwh svw ezwftmb rvddzma-utmj veotvmf okzm okj vua bjoveo dvaxuj. +veoezwfj xfjf z dvwj ajruzwzotgj fohuj vs rvddzma-utmj ezwftmb: hvx rwjzoj zm tmfozmrj vs VeotvmEzwfjw, evexuzoj to ptok veotvmf, +zma ezwfj okj rvddzma utmj. veoezwfj zuuvpf xfjwf ov fejrtsh veotvmf tm okj rvmgjmotvmzu BMX/EVFTY fhmozy, zma zaatotvmzuuh bjmjwzojf +xfzbj zma kjue djffzbjf svw hvx. + +Oxhxspyc my s wopc kofzcfmcfh, lncrmbnc, sft xoicplqn nmbpspa lop xspymfu kowwsft-nmfc oxhmofy hdsf hdc ont uchoxh wotqnc. +oxhxspyc qycy s wopc tcknspshmzc yhanc ol kowwsft-nmfc xspymfu: aoq kpcshc sf mfyhsfkc ol OxhmofXspycp, xoxqnshc mh imhd oxhmofy, +sft xspyc hdc kowwsft nmfc. oxhxspyc snnoiy qycpy ho yxckmla oxhmofy mf hdc kofzcfhmofsn UFQ/XOYMR yafhsr, sft sttmhmofsnna ucfcpshcy +qysuc sft dcnx wcyysucy lop aoq. + +Hqaqlirv fr l phiv dhysvyfvya, egvkfugv, lym qhbviejg gfuilit ehi qlirfyn dhpplym-gfyv hqafhyr awly awv hgm nvahqa phmjgv. +hqaqlirv jrvr l phiv mvdglilafsv ratgv he dhpplym-gfyv qlirfyn: thj divlav ly fyralydv he HqafhyQlirvi, qhqjglav fa bfaw hqafhyr, +lym qlirv awv dhpplym gfyv. hqaqlirv lgghbr jrvir ah rqvdfet hqafhyr fy awv dhysvyafhylg NYJ/QHRFK rtyalk, lym lmmfafhylggt nvyvilavr +jrlnv lym wvgq pvrrlnvr ehi thj. + +Ajtjebko yk e iabo warloryort, xzodynzo, erf jauobxcz zynbebm xab jebkyrg waiierf-zyro ajtyark tper tpo azf gotajt iafczo. +ajtjebko ckok e iabo fowzebetylo ktmzo ax waiierf-zyro jebkyrg: mac wboeto er yrkterwo ax AjtyarJebkob, jajczeto yt uytp ajtyark, +erf jebko tpo waiierf zyro. ajtjebko ezzauk ckobk ta kjowyxm ajtyark yr tpo warlortyarez GRC/JAKYD kmrted, erf effytyarezzm gorobetok +ckego erf pozj iokkegok xab mac. + +Tcmcxudh rd x btuh ptkehkrhkm, qshwrgsh, xky ctnhuqvs srguxuf qtu cxudrkz ptbbxky-srkh tcmrtkd mixk mih tsy zhmtcm btyvsh. +tcmcxudh vdhd x btuh yhpsxuxmreh dmfsh tq ptbbxky-srkh cxudrkz: ftv puhxmh xk rkdmxkph tq TcmrtkCxudhu, ctcvsxmh rm nrmi tcmrtkd, +xky cxudh mih ptbbxky srkh. tcmcxudh xsstnd vdhud mt dchprqf tcmrtkd rk mih ptkehkmrtkxs ZKV/CTDRW dfkmxw, xky xyyrmrtkxssf zhkhuxmhd +vdxzh xky ihsc bhddxzhd qtu ftv. + +Mvfvqnwa kw q umna imdxadkadf, jlapkzla, qdr vmganjol lkznqny jmn vqnwkds imuuqdr-lkda mvfkmdw fbqd fba mlr safmvf umrola. +mvfvqnwa owaw q umna railqnqfkxa wfyla mj imuuqdr-lkda vqnwkds: ymo inaqfa qd kdwfqdia mj MvfkmdVqnwan, vmvolqfa kf gkfb mvfkmdw, +qdr vqnwa fba imuuqdr lkda. mvfvqnwa qllmgw owanw fm wvaikjy mvfkmdw kd fba imdxadfkmdql SDO/VMWKP wydfqp, qdr qrrkfkmdqlly sadanqfaw +owqsa qdr balv uawwqsaw jmn ymo. + +Foyojgpt dp j nfgt bfwqtwdtwy, cetidset, jwk ofztgche edsgjgr cfg ojgpdwl bfnnjwk-edwt foydfwp yujw yut fek ltyfoy nfkhet. +foyojgpt hptp j nfgt ktbejgjydqt pyret fc bfnnjwk-edwt ojgpdwl: rfh bgtjyt jw dwpyjwbt fc FoydfwOjgptg, ofohejyt dy zdyu foydfwp, +jwk ojgpt yut bfnnjwk edwt. foyojgpt jeefzp hptgp yf potbdcr foydfwp dw yut bfwqtwydfwje LWH/OFPDI prwyji, jwk jkkdydfwjeer ltwtgjytp +hpjlt jwk uteo ntppjltp cfg rfh. + +Yhrhczim wi c gyzm uypjmpwmpr, vxmbwlxm, cpd hysmzvax xwlzczk vyz hcziwpe uyggcpd-xwpm yhrwypi rncp rnm yxd emryhr gydaxm. +yhrhczim aimi c gyzm dmuxczcrwjm irkxm yv uyggcpd-xwpm hcziwpe: kya uzmcrm cp wpircpum yv YhrwypHczimz, hyhaxcrm wr swrn yhrwypi, +cpd hczim rnm uyggcpd xwpm. yhrhczim cxxysi aimzi ry ihmuwvk yhrwypi wp rnm uypjmprwypcx EPA/HYIWB ikprcb, cpd cddwrwypcxxk empmzcrmi +aicem cpd nmxh gmiicemi vyz kya. + +Pasarwhj bh r tpwj npeojebjes, uijkbcij, rey apzjwudi ibcwrwv upw arwhbef npttrey-ibej pasbpeh sqre sqj piy fjspas tpydij. +pasarwhj dhjh r tpwj yjnirwrsboj hsvij pu npttrey-ibej arwhbef: vpd nwjrsj re behsrenj pu PasbpeArwhjw, apadirsj bs zbsq pasbpeh, +rey arwhj sqj npttrey ibej. pasarwhj riipzh dhjwh sp hajnbuv pasbpeh be sqj npeojesbperi FED/APHBK hvesrk, rey ryybsbperiiv fjejwrsjh +dhrfj rey qjia tjhhrfjh upw vpd. + +Sdvduzkm ek u wszm qshrmhemhv, xlmneflm, uhb dscmzxgl lefzuzy xsz duzkehi qswwuhb-lehm sdveshk vtuh vtm slb imvsdv wsbglm. +sdvduzkm gkmk u wszm bmqluzuverm kvylm sx qswwuhb-lehm duzkehi: ysg qzmuvm uh ehkvuhqm sx SdveshDuzkmz, dsdgluvm ev cevt sdveshk, +uhb duzkm vtm qswwuhb lehm. sdvduzkm ullsck gkmzk vs kdmqexy sdveshk eh vtm qshrmhveshul IHG/DSKEN kyhvun, uhb ubbeveshully imhmzuvmk +gkuim uhb tmld wmkkuimk xsz ysg. + +Vgygxcnp hn x zvcp tvkupkhpky, aopqhiop, xke gvfpcajo ohicxcb avc gxcnhkl tvzzxke-ohkp vgyhvkn ywxk ywp voe lpyvgy zvejop. +vgygxcnp jnpn x zvcp eptoxcxyhup nybop va tvzzxke-ohkp gxcnhkl: bvj tcpxyp xk hknyxktp va VgyhvkGxcnpc, gvgjoxyp hy fhyw vgyhvkn, +xke gxcnp ywp tvzzxke ohkp. vgygxcnp xoovfn jnpcn yv ngpthab vgyhvkn hk ywp tvkupkyhvkxo LKJ/GVNHQ nbkyxq, xke xeehyhvkxoob lpkpcxypn +jnxlp xke wpog zpnnxlpn avc bvj. + +Yjbjafqs kq a cyfs wynxsnksnb, drstklrs, anh jyisfdmr rklfafe dyf jafqkno wyccanh-rkns yjbkynq bzan bzs yrh osbyjb cyhmrs. +yjbjafqs mqsq a cyfs hswrafabkxs qbers yd wyccanh-rkns jafqkno: eym wfsabs an knqbanws yd YjbkynJafqsf, jyjmrabs kb ikbz yjbkynq, +anh jafqs bzs wyccanh rkns. yjbjafqs arryiq mqsfq by qjswkde yjbkynq kn bzs wynxsnbkynar ONM/JYQKT qenbat, anh ahhkbkynarre osnsfabsq +mqaos anh zsrj csqqaosq dyf eym. + +Bmemditv nt d fbiv zbqavqnvqe, guvwnouv, dqk mblvigpu unoidih gbi mditnqr zbffdqk-unqv bmenbqt ecdq ecv buk rvebme fbkpuv. +bmemditv ptvt d fbiv kvzudidenav tehuv bg zbffdqk-unqv mditnqr: hbp zivdev dq nqtedqzv bg BmenbqMditvi, mbmpudev ne lnec bmenbqt, +dqk mditv ecv zbffdqk unqv. bmemditv duublt ptvit eb tmvzngh bmenbqt nq ecv zbqavqenbqdu RQP/MBTNW thqedw, dqk dkknenbqduuh rvqvidevt +ptdrv dqk cvum fvttdrvt gbi hbp. + +Ephpglwy qw g iely cetdytqyth, jxyzqrxy, gtn peoyljsx xqrlglk jel pglwqtu ceiigtn-xqty ephqetw hfgt hfy exn uyheph iensxy. +ephpglwy swyw g iely nycxglghqdy whkxy ej ceiigtn-xqty pglwqtu: kes clyghy gt qtwhgtcy ej EphqetPglwyl, pepsxghy qh oqhf ephqetw, +gtn pglwy hfy ceiigtn xqty. ephpglwy gxxeow swylw he wpycqjk ephqetw qt hfy cetdythqetgx UTS/PEWQZ wkthgz, gtn gnnqhqetgxxk uytylghyw +swguy gtn fyxp iywwguyw jel kes. + +Hsksjozb tz j lhob fhwgbwtbwk, mabctuab, jwq shrbomva atuojon mho sjoztwx fhlljwq-atwb hskthwz kijw kib haq xbkhsk lhqvab. +hsksjozb vzbz j lhob qbfajojktgb zknab hm fhlljwq-atwb sjoztwx: nhv fobjkb jw twzkjwfb hm HskthwSjozbo, shsvajkb tk rtki hskthwz, +jwq sjozb kib fhlljwq atwb. hsksjozb jaahrz vzboz kh zsbftmn hskthwz tw kib fhwgbwkthwja XWV/SHZTC znwkjc, jwq jqqtkthwjaan xbwbojkbz +vzjxb jwq ibas lbzzjxbz mho nhv. + +Kvnvmrce wc m okre ikzjezwezn, pdefwxde, mzt vkuerpyd dwxrmrq pkr vmrcwza ikoomzt-dwze kvnwkzc nlmz nle kdt aenkvn oktyde. +kvnvmrce ycec m okre teidmrmnwje cnqde kp ikoomzt-dwze vmrcwza: qky iremne mz wzcnmzie kp KvnwkzVmrcer, vkvydmne wn uwnl kvnwkzc, +mzt vmrce nle ikoomzt dwze. kvnvmrce mddkuc ycerc nk cveiwpq kvnwkzc wz nle ikzjeznwkzmd AZY/VKCWF cqznmf, mzt mttwnwkzmddq aezermnec +ycmae mzt ledv oeccmaec pkr qky. + +Nyqypufh zf p rnuh lncmhczhcq, sghizagh, pcw ynxhusbg gzauput snu ypufzcd lnrrpcw-gzch nyqzncf qopc qoh ngw dhqnyq rnwbgh. +nyqypufh bfhf p rnuh whlgpupqzmh fqtgh ns lnrrpcw-gzch ypufzcd: tnb luhpqh pc zcfqpclh ns NyqzncYpufhu, ynybgpqh zq xzqo nyqzncf, +pcw ypufh qoh lnrrpcw gzch. nyqypufh pggnxf bfhuf qn fyhlzst nyqzncf zc qoh lncmhcqzncpg DCB/YNFZI ftcqpi, pcw pwwzqzncpggt dhchupqhf +bfpdh pcw ohgy rhffpdhf snu tnb. + +Qbtbsxik ci s uqxk oqfpkfckft, vjklcdjk, sfz bqakxvej jcdxsxw vqx bsxicfg oquusfz-jcfk qbtcqfi trsf trk qjz gktqbt uqzejk. +qbtbsxik eiki s uqxk zkojsxstcpk itwjk qv oquusfz-jcfk bsxicfg: wqe oxkstk sf cfitsfok qv QbtcqfBsxikx, bqbejstk ct actr qbtcqfi, +sfz bsxik trk oquusfz jcfk. qbtbsxik sjjqai eikxi tq ibkocvw qbtcqfi cf trk oqfpkftcqfsj GFE/BQICL iwftsl, sfz szzctcqfsjjw gkfkxstki +eisgk sfz rkjb ukiisgki vqx wqe. + +Tewevaln fl v xtan rtisnifniw, ymnofgmn, vic etdnayhm mfgavaz yta evalfij rtxxvic-mfin tewftil wuvi wun tmc jnwtew xtchmn. +tewevaln hlnl v xtan cnrmvavwfsn lwzmn ty rtxxvic-mfin evalfij: zth ranvwn vi filwvirn ty TewftiEvalna, etehmvwn fw dfwu tewftil, +vic evaln wun rtxxvic mfin. tewevaln vmmtdl hlnal wt lenrfyz tewftil fi wun rtisniwftivm JIH/ETLFO lziwvo, vic vccfwftivmmz jninavwnl +hlvjn vic unme xnllvjnl yta zth. + +Whzhydoq io y awdq uwlvqliqlz, bpqrijpq, ylf hwgqdbkp pijdydc bwd hydoilm uwaaylf-pilq whziwlo zxyl zxq wpf mqzwhz awfkpq. +whzhydoq koqo y awdq fqupydyzivq ozcpq wb uwaaylf-pilq hydoilm: cwk udqyzq yl ilozyluq wb WhziwlHydoqd, hwhkpyzq iz gizx whziwlo, +ylf hydoq zxq uwaaylf pilq. whzhydoq yppwgo koqdo zw ohquibc whziwlo il zxq uwlvqlziwlyp MLK/HWOIR oclzyr, ylf yffiziwlyppc mqlqdyzqo +koymq ylf xqph aqooymqo bwd cwk. + +Zkckbgrt lr b dzgt xzoytoltoc, estulmst, boi kzjtgens slmgbgf ezg kbgrlop xzddboi-slot zkclzor cabo cat zsi ptczkc dzinst. +zkckbgrt nrtr b dzgt itxsbgbclyt rcfst ze xzddboi-slot kbgrlop: fzn xgtbct bo lorcboxt ze ZkclzoKbgrtg, kzknsbct lc jlca zkclzor, +boi kbgrt cat xzddboi slot. zkckbgrt bsszjr nrtgr cz rktxlef zkclzor lo cat xzoytoclzobs PON/KZRLU rfocbu, boi biilclzobssf ptotgbctr +nrbpt boi atsk dtrrbptr ezg fzn. + +Cnfnejuw ou e gcjw acrbwrowrf, hvwxopvw, erl ncmwjhqv vopjeji hcj nejuors acggerl-vorw cnfocru fder fdw cvl swfcnf gclqvw. +cnfnejuw quwu e gcjw lwavejefobw ufivw ch acggerl-vorw nejuors: icq ajwefw er oruferaw ch CnfocrNejuwj, ncnqvefw of mofd cnfocru, +erl nejuw fdw acggerl vorw. cnfnejuw evvcmu quwju fc unwaohi cnfocru or fdw acrbwrfocrev SRQ/NCUOX uirfex, erl ellofocrevvi swrwjefwu +quesw erl dwvn gwuueswu hcj icq. + +Fqiqhmxz rx h jfmz dfuezurzui, kyzarsyz, huo qfpzmkty yrsmhml kfm qhmxruv dfjjhuo-yruz fqirfux ighu igz fyo vzifqi jfotyz. +fqiqhmxz txzx h jfmz ozdyhmhirez xilyz fk dfjjhuo-yruz qhmxruv: lft dmzhiz hu ruxihudz fk FqirfuQhmxzm, qfqtyhiz ri prig fqirfux, +huo qhmxz igz dfjjhuo yruz. fqiqhmxz hyyfpx txzmx if xqzdrkl fqirfux ru igz dfuezuirfuhy VUT/QFXRA xluiha, huo hoorirfuhyyl vzuzmhizx +txhvz huo gzyq jzxxhvzx kfm lft. + +Itltkpac ua k mipc gixhcxucxl, nbcduvbc, kxr tiscpnwb buvpkpo nip tkpauxy gimmkxr-buxc itluixa ljkx ljc ibr yclitl mirwbc. +itltkpac waca k mipc rcgbkpkluhc alobc in gimmkxr-buxc tkpauxy: oiw gpcklc kx uxalkxgc in ItluixTkpacp, titwbklc ul sulj itluixa, +kxr tkpac ljc gimmkxr buxc. itltkpac kbbisa wacpa li atcguno itluixa ux ljc gixhcxluixkb YXW/TIAUD aoxlkd, kxr krruluixkbbo ycxcpklca +wakyc kxr jcbt mcaakyca nip oiw. + +Lwownsdf xd n plsf jlakfaxfao, qefgxyef, nau wlvfsqze exysnsr qls wnsdxab jlppnau-exaf lwoxlad omna omf leu bfolwo pluzef. +lwownsdf zdfd n plsf ufjensnoxkf doref lq jlppnau-exaf wnsdxab: rlz jsfnof na xadonajf lq LwoxlaWnsdfs, wlwzenof xo vxom lwoxlad, +nau wnsdf omf jlppnau exaf. lwownsdf neelvd zdfsd ol dwfjxqr lwoxlad xa omf jlakfaoxlane BAZ/WLDXG draong, nau nuuxoxlaneer bfafsnofd +zdnbf nau mfew pfddnbfd qls rlz. + +Ozrzqvgi ag q sovi modnidaidr, thijabhi, qdx zoyivtch habvqvu tov zqvgade mossqdx-hadi ozraodg rpqd rpi ohx eirozr soxchi. +ozrzqvgi cgig q sovi ximhqvqrani gruhi ot mossqdx-hadi zqvgade: uoc mviqri qd adgrqdmi ot OzraodZqvgiv, zozchqri ar yarp ozraodg, +qdx zqvgi rpi mossqdx hadi. ozrzqvgi qhhoyg cgivg ro gzimatu ozraodg ad rpi modnidraodqh EDC/ZOGAJ gudrqj, qdx qxxaraodqhhu eidivqrig +cgqei qdx pihz siggqeig tov uoc. + +Rcuctyjl dj t vryl prgqlgdlgu, wklmdekl, tga crblywfk kdeytyx wry ctyjdgh prvvtga-kdgl rcudrgj ustg usl rka hlurcu vrafkl. +rcuctyjl fjlj t vryl alpktytudql juxkl rw prvvtga-kdgl ctyjdgh: xrf pyltul tg dgjutgpl rw RcudrgCtyjly, crcfktul du bdus rcudrgj, +tga ctyjl usl prvvtga kdgl. rcuctyjl tkkrbj fjlyj ur jclpdwx rcudrgj dg usl prgqlgudrgtk HGF/CRJDM jxgutm, tga taadudrgtkkx hlglytulj +fjthl tga slkc vljjthlj wry xrf. + +Ufxfwbmo gm w yubo sujtojgojx, znopghno, wjd fueobzin nghbwba zub fwbmgjk suyywjd-ngjo ufxgujm xvwj xvo und koxufx yudino. +ufxfwbmo imom w yubo dosnwbwxgto mxano uz suyywjd-ngjo fwbmgjk: aui sbowxo wj gjmxwjso uz UfxgujFwbmob, fufinwxo gx egxv ufxgujm, +wjd fwbmo xvo suyywjd ngjo. ufxfwbmo wnnuem imobm xu mfosgza ufxgujm gj xvo sujtojxgujwn KJI/FUMGP majxwp, wjd wddgxgujwnna kojobwxom +imwko wjd vonf yommwkom zub aui. + +Xiaizepr jp z bxer vxmwrmjrma, cqrsjkqr, zmg ixhreclq qjkezed cxe izepjmn vxbbzmg-qjmr xiajxmp ayzm ayr xqg nraxia bxglqr. +xiaizepr lprp z bxer grvqzezajwr padqr xc vxbbzmg-qjmr izepjmn: dxl verzar zm jmpazmvr xc XiajxmIzepre, ixilqzar ja hjay xiajxmp, +zmg izepr ayr vxbbzmg qjmr. xiaizepr zqqxhp lprep ax pirvjcd xiajxmp jm ayr vxmwrmajxmzq NML/IXPJS pdmazs, zmg zggjajxmzqqd nrmrezarp +lpznr zmg yrqi brppznrp cxe dxl. + +Aldlchsu ms c eahu yapzupmupd, ftuvmntu, cpj lakuhfot tmnhchg fah lchsmpq yaeecpj-tmpu aldmaps dbcp dbu atj qudald eajotu. +aldlchsu osus c eahu juytchcdmzu sdgtu af yaeecpj-tmpu lchsmpq: gao yhucdu cp mpsdcpyu af AldmapLchsuh, lalotcdu md kmdb aldmaps, +cpj lchsu dbu yaeecpj tmpu. aldlchsu cttaks osuhs da sluymfg aldmaps mp dbu yapzupdmapct QPO/LASMV sgpdcv, cpj cjjmdmapcttg qupuhcdus +oscqu cpj butl eusscqus fah gao. + +Dogofkvx pv f hdkx bdscxspxsg, iwxypqwx, fsm odnxkirw wpqkfkj idk ofkvpst bdhhfsm-wpsx dogpdsv gefs gex dwm txgdog hdmrwx. +dogofkvx rvxv f hdkx mxbwfkfgpcx vgjwx di bdhhfsm-wpsx ofkvpst: jdr bkxfgx fs psvgfsbx di DogpdsOfkvxk, odorwfgx pg npge dogpdsv, +fsm ofkvx gex bdhhfsm wpsx. dogofkvx fwwdnv rvxkv gd voxbpij dogpdsv ps gex bdscxsgpdsfw TSR/ODVPY vjsgfy, fsm fmmpgpdsfwwj txsxkfgxv +rvftx fsm exwo hxvvftxv idk jdr. + +Grjrinya sy i kgna egvfavsavj, lzabstza, ivp rgqanluz zstninm lgn rinysvw egkkivp-zsva grjsgvy jhiv jha gzp wajgrj kgpuza. +grjrinya uyay i kgna paezinijsfa yjmza gl egkkivp-zsva rinysvw: mgu enaija iv svyjivea gl GrjsgvRinyan, rgruzija sj qsjh grjsgvy, +ivp rinya jha egkkivp zsva. grjrinya izzgqy uyany jg yraeslm grjsgvy sv jha egvfavjsgviz WVU/RGYSB ymvjib, ivp ippsjsgvizzm wavanijay +uyiwa ivp hazr kayyiway lgn mgu. + +Jumulqbd vb l njqd hjyidyvdym, ocdevwcd, lys ujtdqoxc cvwqlqp ojq ulqbvyz hjnnlys-cvyd jumvjyb mkly mkd jcs zdmjum njsxcd. +jumulqbd xbdb l njqd sdhclqlmvid bmpcd jo hjnnlys-cvyd ulqbvyz: pjx hqdlmd ly vybmlyhd jo JumvjyUlqbdq, ujuxclmd vm tvmk jumvjyb, +lys ulqbd mkd hjnnlys cvyd. jumulqbd lccjtb xbdqb mj budhvop jumvjyb vy mkd hjyidymvjylc ZYX/UJBVE bpymle, lys lssvmvjylccp zdydqlmdb +xblzd lys kdcu ndbblzdb ojq pjx. + +Mxpxoteg ye o qmtg kmblgbygbp, rfghyzfg, obv xmwgtraf fyztots rmt xoteybc kmqqobv-fybg mxpymbe pnob png mfv cgpmxp qmvafg. +mxpxoteg aege o qmtg vgkfotopylg epsfg mr kmqqobv-fybg xoteybc: sma ktgopg ob ybepobkg mr MxpymbXotegt, xmxafopg yp wypn mxpymbe, +obv xoteg png kmqqobv fybg. mxpxoteg offmwe aegte pm exgkyrs mxpymbe yb png kmblgbpymbof CBA/XMEYH esbpoh, obv ovvypymboffs cgbgtopge +aeocg obv ngfx qgeeocge rmt sma. + +Xamahgjt fj h rxgt nxustuftum, wotyfkot, huq axvtgwpo ofkghgb wxg ahgjfuz nxrrhuq-ofut xamfxuj mchu mct xoq ztmxam rxqpot. +xamahgjt pjtj h rxgt qtnohghmfst jmbot xw nxrrhuq-ofut ahgjfuz: bxp ngthmt hu fujmhunt xw XamfxuAhgjtg, axapohmt fm vfmc xamfxuj, +huq ahgjt mct nxrrhuq ofut. xamahgjt hooxvj pjtgj mx jatnfwb xamfxuj fu mct nxustumfxuho ZUP/AXJFY jbumhy, huq hqqfmfxuhoob ztutghmtj +pjhzt huq ctoa rtjjhztj wxg bxp. + +Mpbpwvyi uy w gmvi cmjhijuijb, ldinuzdi, wjf pmkivled duzvwvq lmv pwvyujo cmggwjf-duji mpbumjy brwj bri mdf oibmpb gmfedi. +mpbpwvyi eyiy w gmvi ficdwvwbuhi ybqdi ml cmggwjf-duji pwvyujo: qme cviwbi wj ujybwjci ml MpbumjPwvyiv, pmpedwbi ub kubr mpbumjy, +wjf pwvyi bri cmggwjf duji. mpbpwvyi wddmky eyivy bm ypiculq mpbumjy uj bri cmjhijbumjwd OJE/PMYUN yqjbwn, wjf wffubumjwddq oijivwbiy +eywoi wjf ridp giyywoiy lmv qme. + +Beqelknx jn l vbkx rbywxyjxyq, asxcjosx, lyu ebzxkats sjoklkf abk elknjyd rbvvlyu-sjyx beqjbyn qgly qgx bsu dxqbeq vbutsx. +beqelknx tnxn l vbkx uxrslklqjwx nqfsx ba rbvvlyu-sjyx elknjyd: fbt rkxlqx ly jynqlyrx ba BeqjbyElknxk, ebetslqx jq zjqg beqjbyn, +lyu elknx qgx rbvvlyu sjyx. beqelknx lssbzn tnxkn qb nexrjaf beqjbyn jy qgx rbywxyqjbyls DYT/EBNJC nfyqlc, lyu luujqjbylssf dxyxklqxn +tnldx lyu gxse vxnnldxn abk fbt. + +Qtftazcm yc a kqzm gqnlmnymnf, phmrydhm, anj tqomzpih hydzazu pqz tazcyns gqkkanj-hynm qtfyqnc fvan fvm qhj smfqtf kqjihm. +qtftazcm icmc a kqzm jmghazafylm cfuhm qp gqkkanj-hynm tazcyns: uqi gzmafm an yncfangm qp QtfyqnTazcmz, tqtihafm yf oyfv qtfyqnc, +anj tazcm fvm gqkkanj hynm. qtftazcm ahhqoc icmzc fq ctmgypu qtfyqnc yn fvm gqnlmnfyqnah SNI/TQCYR cunfar, anj ajjyfyqnahhu smnmzafmc +icasm anj vmht kmccasmc pqz uqi. + +Fiuiporb nr p zfob vfcabcnbcu, ewbgnswb, pcy ifdboexw wnsopoj efo ipornch vfzzpcy-wncb fiunfcr ukpc ukb fwy hbufiu zfyxwb. +fiuiporb xrbr p zfob ybvwpopunab rujwb fe vfzzpcy-wncb ipornch: jfx vobpub pc ncrupcvb fe FiunfcIporbo, ifixwpub nu dnuk fiunfcr, +pcy iporb ukb vfzzpcy wncb. fiuiporb pwwfdr xrbor uf ribvnej fiunfcr nc ukb vfcabcunfcpw HCX/IFRNG rjcupg, pcy pyynunfcpwwj hbcbopubr +xrphb pcy kbwi zbrrphbr efo jfx. + +Uxjxedgq cg e oudq kurpqrcqrj, tlqvchlq, ern xusqdtml lchdedy tud xedgcrw kuooern-lcrq uxjcurg jzer jzq uln wqjuxj ounmlq. +uxjxedgq mgqg e oudq nqkledejcpq gjylq ut kuooern-lcrq xedgcrw: yum kdqejq er crgjerkq ut UxjcurXedgqd, xuxmlejq cj scjz uxjcurg, +ern xedgq jzq kuooern lcrq. uxjxedgq ellusg mgqdg ju gxqkcty uxjcurg cr jzq kurpqrjcurel WRM/XUGCV gyrjev, ern enncjcurelly wqrqdejqg +mgewq ern zqlx oqggewqg tud yum. + +Jmymtsvf rv t djsf zjgefgrfgy, iafkrwaf, tgc mjhfsiba arwstsn ijs mtsvrgl zjddtgc-argf jmyrjgv yotg yof jac lfyjmy djcbaf. +jmymtsvf bvfv t djsf cfzatstyref vynaf ji zjddtgc-argf mtsvrgl: njb zsftyf tg rgvytgzf ji JmyrjgMtsvfs, mjmbatyf ry hryo jmyrjgv, +tgc mtsvf yof zjddtgc argf. jmymtsvf taajhv bvfsv yj vmfzrin jmyrjgv rg yof zjgefgyrjgta LGB/MJVRK vngytk, tgc tccryrjgtaan lfgfstyfv +bvtlf tgc ofam dfvvtlfv ijs njb. + +Ybnbihku gk i syhu oyvtuvguvn, xpuzglpu, ivr bywuhxqp pglhihc xyh bihkgva oyssivr-pgvu ybngyvk ndiv ndu ypr aunybn syrqpu. +ybnbihku qkuk i syhu ruopihingtu kncpu yx oyssivr-pgvu bihkgva: cyq ohuinu iv gvknivou yx YbngyvBihkuh, bybqpinu gn wgnd ybngyvk, +ivr bihku ndu oyssivr pgvu. ybnbihku ippywk qkuhk ny kbuogxc ybngyvk gv ndu oyvtuvngyvip AVQ/BYKGZ kcvniz, ivr irrgngyvippc auvuhinuk +qkiau ivr dupb sukkiauk xyh cyq. + +Nqcqxwzj vz x hnwj dnkijkvjkc, mejovaej, xkg qnljwmfe evawxwr mnw qxwzvkp dnhhxkg-evkj nqcvnkz csxk csj neg pjcnqc hngfej. +nqcqxwzj fzjz x hnwj gjdexwxcvij zcrej nm dnhhxkg-evkj qxwzvkp: rnf dwjxcj xk vkzcxkdj nm NqcvnkQxwzjw, qnqfexcj vc lvcs nqcvnkz, +xkg qxwzj csj dnhhxkg evkj. nqcqxwzj xeenlz fzjwz cn zqjdvmr nqcvnkz vk csj dnkijkcvnkxe PKF/QNZVO zrkcxo, xkg xggvcvnkxeer pjkjwxcjz +fzxpj xkg sjeq hjzzxpjz mnw rnf. + +Cfrfmloy ko m wcly sczxyzkyzr, btydkpty, mzv fcaylbut tkplmlg bcl fmlokze scwwmzv-tkzy cfrkczo rhmz rhy ctv eyrcfr wcvuty. +cfrfmloy uoyo m wcly vystmlmrkxy orgty cb scwwmzv-tkzy fmlokze: gcu slymry mz kzormzsy cb CfrkczFmloyl, fcfutmry kr akrh cfrkczo, +mzv fmloy rhy scwwmzv tkzy. cfrfmloy mttcao uoylo rc ofyskbg cfrkczo kz rhy sczxyzrkczmt EZU/FCOKD ogzrmd, mzv mvvkrkczmttg eyzylmryo +uomey mzv hytf wyoomeyo bcl gcu. + +Rugubadn zd b lran hromnoznog, qinszein, bok urpnaqji izeabav qra ubadzot hrllbok-izon rugzrod gwbo gwn rik tngrug lrkjin. +rugubadn jdnd b lran knhibabgzmn dgvin rq hrllbok-izon ubadzot: vrj hanbgn bo zodgbohn rq RugzroUbadna, urujibgn zg pzgw rugzrod, +bok ubadn gwn hrllbok izon. rugubadn biirpd jdnad gr dunhzqv rugzrod zo gwn hromnogzrobi TOJ/URDZS dvogbs, bok bkkzgzrobiiv tnonabgnd +jdbtn bok wniu lnddbtnd qra vrj. + +Gjvjqpsc os q agpc wgdbcdocdv, fxchotxc, qdz jgecpfyx xotpqpk fgp jqpsodi wgaaqdz-xodc gjvogds vlqd vlc gxz icvgjv agzyxc. +gjvjqpsc yscs q agpc zcwxqpqvobc svkxc gf wgaaqdz-xodc jqpsodi: kgy wpcqvc qd odsvqdwc gf GjvogdJqpscp, jgjyxqvc ov eovl gjvogds, +qdz jqpsc vlc wgaaqdz xodc. gjvjqpsc qxxges yscps vg sjcwofk gjvogds od vlc wgdbcdvogdqx IDY/JGSOH skdvqh, qdz qzzovogdqxxk icdcpqvcs +ysqic qdz lcxj acssqics fgp kgy. + +Vykyfehr dh f pver lvsqrsdrsk, umrwdimr, fso yvtreunm mdiefez uve yfehdsx lvppfso-mdsr vykdvsh kafs kar vmo xrkvyk pvonmr. +vykyfehr nhrh f pver orlmfefkdqr hkzmr vu lvppfso-mdsr yfehdsx: zvn lerfkr fs dshkfslr vu VykdvsYfehre, yvynmfkr dk tdka vykdvsh, +fso yfehr kar lvppfso mdsr. vykyfehr fmmvth nhreh kv hyrlduz vykdvsh ds kar lvsqrskdvsfm XSN/YVHDW hzskfw, fso foodkdvsfmmz xrsrefkrh +nhfxr fso army prhhfxrh uve zvn. + +Knznutwg sw u ektg akhfghsghz, jbglsxbg, uhd nkigtjcb bsxtuto jkt nutwshm akeeuhd-bshg knzskhw zpuh zpg kbd mgzknz ekdcbg. +knznutwg cwgw u ektg dgabutuzsfg wzobg kj akeeuhd-bshg nutwshm: okc atguzg uh shwzuhag kj KnzskhNutwgt, nkncbuzg sz iszp knzskhw, +uhd nutwg zpg akeeuhd bshg. knznutwg ubbkiw cwgtw zk wngasjo knzskhw sh zpg akhfghzskhub MHC/NKWSL wohzul, uhd uddszskhubbo mghgtuzgw +cwumg uhd pgbn egwwumgw jkt okc. + +Zcocjilv hl j tziv pzwuvwhvwo, yqvahmqv, jws czxviyrq qhmijid yzi cjilhwb pzttjws-qhwv zcohzwl oejw oev zqs bvozco tzsrqv. +zcocjilv rlvl j tziv svpqjijohuv lodqv zy pzttjws-qhwv cjilhwb: dzr pivjov jw hwlojwpv zy ZcohzwCjilvi, czcrqjov ho xhoe zcohzwl, +jws cjilv oev pzttjws qhwv. zcocjilv jqqzxl rlvil oz lcvphyd zcohzwl hw oev pzwuvwohzwjq BWR/CZLHA ldwoja, jws jsshohzwjqqd bvwvijovl +rljbv jws evqc tvlljbvl yzi dzr. + +Ordryxak wa y ioxk eoljklwkld, nfkpwbfk, ylh romkxngf fwbxyxs nox ryxawlq eoiiylh-fwlk ordwola dtyl dtk ofh qkdord iohgfk. +ordryxak gaka y ioxk hkefyxydwjk adsfk on eoiiylh-fwlk ryxawlq: sog exkydk yl wladylek on OrdwolRyxakx, rorgfydk wd mwdt ordwola, +ylh ryxak dtk eoiiylh fwlk. ordryxak yffoma gakxa do arkewns ordwola wl dtk eoljkldwolyf QLG/ROAWP asldyp, ylh yhhwdwolyffs qklkxydka +gayqk ylh tkfr ikaayqka nox sog. + +Dgsgnmpz lp n xdmz tdayzalzas, cuzelquz, naw gdbzmcvu ulqmnmh cdm gnmplaf tdxxnaw-ulaz dgsldap sina siz duw fzsdgs xdwvuz. +dgsgnmpz vpzp n xdmz wztunmnslyz pshuz dc tdxxnaw-ulaz gnmplaf: hdv tmznsz na lapsnatz dc DgsldaGnmpzm, gdgvunsz ls blsi dgsldap, +naw gnmpz siz tdxxnaw ulaz. dgsgnmpz nuudbp vpzmp sd pgztlch dgsldap la siz tdayzasldanu FAV/GDPLE phasne, naw nwwlsldanuuh fzazmnszp +vpnfz naw izug xzppnfzp cdm hdv. + +Svhvcbeo ae c msbo ispnopaoph, rjotafjo, cpl vsqobrkj jafbcbw rsb vcbeapu ismmcpl-japo svhaspe hxcp hxo sjl uohsvh mslkjo. +svhvcbeo keoe c msbo loijcbchano ehwjo sr ismmcpl-japo vcbeapu: wsk ibocho cp apehcpio sr SvhaspVcbeob, vsvkjcho ah qahx svhaspe, +cpl vcbeo hxo ismmcpl japo. svhvcbeo cjjsqe keobe hs evoiarw svhaspe ap hxo ispnophaspcj UPK/VSEAT ewphct, cpl cllahaspcjjw uopobchoe +kecuo cpl xojv moeecuoe rsb wsk. + +Hkwkrqtd pt r bhqd xhecdepdew, gydipuyd, rea khfdqgzy ypuqrql ghq krqtpej xhbbrea-yped hkwphet wmre wmd hya jdwhkw bhazyd. +hkwkrqtd ztdt r bhqd adxyrqrwpcd twlyd hg xhbbrea-yped krqtpej: lhz xqdrwd re petwrexd hg HkwpheKrqtdq, khkzyrwd pw fpwm hkwphet, +rea krqtd wmd xhbbrea yped. hkwkrqtd ryyhft ztdqt wh tkdxpgl hkwphet pe wmd xhecdewphery JEZ/KHTPI tlewri, rea raapwpheryyl jdedqrwdt +ztrjd rea mdyk bdttrjdt ghq lhz. + +Wzlzgfis ei g qwfs mwtrstestl, vnsxejns, gtp zwusfvon nejfgfa vwf zgfiety mwqqgtp-nets wzlewti lbgt lbs wnp yslwzl qwpons. +wzlzgfis oisi g qwfs psmngfglers ilans wv mwqqgtp-nets zgfiety: awo mfsgls gt etilgtms wv WzlewtZgfisf, zwzongls el uelb wzlewti, +gtp zgfis lbs mwqqgtp nets. wzlzgfis gnnwui oisfi lw izsmeva wzlewti et lbs mwtrstlewtgn YTO/ZWIEX iatlgx, gtp gppelewtgnna ystsfglsi +oigys gtp bsnz qsiigysi vwf awo. + +Loaovuxh tx v fluh blighithia, kchmtych, vie oljhukdc ctyuvup klu ovuxtin blffvie-ctih loatlix aqvi aqh lce nhaloa fledch. +loaovuxh dxhx v fluh ehbcvuvatgh xapch lk blffvie-ctih ovuxtin: pld buhvah vi tixavibh lk LoatliOvuxhu, olodcvah ta jtaq loatlix, +vie ovuxh aqh blffvie ctih. loaovuxh vccljx dxhux al xohbtkp loatlix ti aqh blighiatlivc NID/OLXTM xpiavm, vie veetatlivccp nhihuvahx +dxvnh vie qhco fhxxvnhx klu pld. + +Adpdkjmw im k uajw qaxvwxiwxp, zrwbinrw, kxt daywjzsr rinjkje zaj dkjmixc qauukxt-rixw adpiaxm pfkx pfw art cwpadp uatsrw. +adpdkjmw smwm k uajw twqrkjkpivw mperw az qauukxt-rixw dkjmixc: eas qjwkpw kx ixmpkxqw az AdpiaxDkjmwj, dadsrkpw ip yipf adpiaxm, +kxt dkjmw pfw qauukxt rixw. adpdkjmw krraym smwjm pa mdwqize adpiaxm ix pfw qaxvwxpiaxkr CXS/DAMIB mexpkb, kxt kttipiaxkrre cwxwjkpwm +smkcw kxt fwrd uwmmkcwm zaj eas. + +Pseszybl xb z jpyl fpmklmxlme, oglqxcgl, zmi spnlyohg gxcyzyt opy szybxmr fpjjzmi-gxml psexpmb euzm eul pgi rlepse jpihgl. +pseszybl hblb z jpyl ilfgzyzexkl betgl po fpjjzmi-gxml szybxmr: tph fylzel zm xmbezmfl po PsexpmSzybly, spshgzel xe nxeu psexpmb, +zmi szybl eul fpjjzmi gxml. pseszybl zggpnb hblyb ep bslfxot psexpmb xm eul fpmklmexpmzg RMH/SPBXQ btmezq, zmi ziixexpmzggt rlmlyzelb +hbzrl zmi ulgs jlbbzrlb opy tph. + +Ehthonqa mq o yena uebzabmabt, dvafmrva, obx hecandwv vmrnoni den honqmbg ueyyobx-vmba ehtmebq tjob tja evx gateht yexwva. +ehthonqa wqaq o yena xauvonotmza qtiva ed ueyyobx-vmba honqmbg: iew unaota ob mbqtobua ed EhtmebHonqan, hehwvota mt cmtj ehtmebq, +obx honqa tja ueyyobx vmba. ehthonqa ovvecq wqanq te qhaumdi ehtmebq mb tja uebzabtmebov GBW/HEQMF qibtof, obx oxxmtmebovvi gabanotaq +wqoga obx javh yaqqogaq den iew. + +Twiwdcfp bf d ntcp jtqopqbpqi, skpubgkp, dqm wtrpcslk kbgcdcx stc wdcfbqv jtnndqm-kbqp twibtqf iydq iyp tkm vpitwi ntmlkp. +twiwdcfp lfpf d ntcp mpjkdcdibop fixkp ts jtnndqm-kbqp wdcfbqv: xtl jcpdip dq bqfidqjp ts TwibtqWdcfpc, wtwlkdip bi rbiy twibtqf, +dqm wdcfp iyp jtnndqm kbqp. twiwdcfp dkktrf lfpcf it fwpjbsx twibtqf bq iyp jtqopqibtqdk VQL/WTFBU fxqidu, dqm dmmbibtqdkkx vpqpcdipf +lfdvp dqm ypkw npffdvpf stc xtl. + +Ilxlsrue qu s cire yifdefqefx, hzejqvze, sfb ligerhaz zqvrsrm hir lsruqfk yiccsfb-zqfe ilxqifu xnsf xne izb kexilx cibaze. +ilxlsrue aueu s cire beyzsrsxqde uxmze ih yiccsfb-zqfe lsruqfk: mia yresxe sf qfuxsfye ih IlxqifLsruer, lilazsxe qx gqxn ilxqifu, +sfb lsrue xne yiccsfb zqfe. ilxlsrue szzigu aueru xi uleyqhm ilxqifu qf xne yifdefxqifsz KFA/LIUQJ umfxsj, sfb sbbqxqifszzm kefersxeu +auske sfb nezl ceuuskeu hir mia. + +Bawapyxl hx p dbyl nbculchlcw, kelshoel, pcm abtlykve ehoypyr kby apyxhcj nbddpcm-ehcl bawhbcx wipc wil bem jlwbaw dbmvel. +bawapyxl vxlx p dbyl mlnepypwhul xwrel bk nbddpcm-ehcl apyxhcj: rbv nylpwl pc hcxwpcnl bk BawhbcApyxly, abavepwl hw thwi bawhbcx, +pcm apyxl wil nbddpcm ehcl. bawapyxl peebtx vxlyx wb xalnhkr bawhbcx hc wil nbculcwhbcpe JCV/ABXHS xrcwps, pcm pmmhwhbcpeer jlclypwlx +vxpjl pcm ilea dlxxpjlx kby rbv. + +Wvrvktsg cs k ywtg iwxpgxcgxr, fzgncjzg, kxh vwogtfqz zcjtktm fwt vktscxe iwyykxh-zcxg wvrcwxs rdkx rdg wzh egrwvr ywhqzg. +wvrvktsg qsgs k ywtg hgizktkrcpg srmzg wf iwyykxh-zcxg vktscxe: mwq itgkrg kx cxsrkxig wf WvrcwxVktsgt, vwvqzkrg cr ocrd wvrcwxs, +kxh vktsg rdg iwyykxh zcxg. wvrvktsg kzzwos qsgts rw svgicfm wvrcwxs cx rdg iwxpgxrcwxkz EXQ/VWSCN smxrkn, kxh khhcrcwxkzzm egxgtkrgs +qskeg kxh dgzv ygsskegs fwt mwq. + +Rqmqfonb xn f trob drskbsxbsm, aubixeub, fsc qrjboalu uxeofoh aro qfonxsz drttfsc-uxsb rqmxrsn myfs myb ruc zbmrqm trclub. +rqmqfonb lnbn f trob cbdufofmxkb nmhub ra drttfsc-uxsb qfonxsz: hrl dobfmb fs xsnmfsdb ra RqmxrsQfonbo, qrqlufmb xm jxmy rqmxrsn, +fsc qfonb myb drttfsc uxsb. rqmqfonb fuurjn lnbon mr nqbdxah rqmxrsn xs myb drskbsmxrsfu ZSL/QRNXI nhsmfi, fsc fccxmxrsfuuh zbsbofmbn +lnfzb fsc ybuq tbnnfzbn aro hrl. + +Mlhlajiw si a omjw ymnfwnswnh, vpwdszpw, anx lmewjvgp pszjajc vmj lajisnu ymooanx-psnw mlhsmni htan htw mpx uwhmlh omxgpw. +mlhlajiw giwi a omjw xwypajahsfw ihcpw mv ymooanx-psnw lajisnu: cmg yjwahw an snihanyw mv MlhsmnLajiwj, lmlgpahw sh esht mlhsmni, +anx lajiw htw ymooanx psnw. mlhlajiw appmei giwji hm ilwysvc mlhsmni sn htw ymnfwnhsmnap UNG/LMISD icnhad, anx axxshsmnappc uwnwjahwi +giauw anx twpl owiiauwi vmj cmg. + +Hgcgvedr nd v jher thiarinric, qkrynukr, vis ghzreqbk knuevex qhe gvednip thjjvis-knir hgcnhid covi cor hks prchgc jhsbkr. +hgcgvedr bdrd v jher srtkvevcnar dcxkr hq thjjvis-knir gvednip: xhb tervcr vi nidcvitr hq HgcnhiGvedre, ghgbkvcr nc znco hgcnhid, +vis gvedr cor thjjvis knir. hgcgvedr vkkhzd bdred ch dgrtnqx hgcnhid ni cor thiaricnhivk PIB/GHDNY dxicvy, vis vssncnhivkkx prirevcrd +bdvpr vis orkg jrddvprd qhe xhb. + +Cbxbqzym iy q eczm ocdvmdimdx, lfmtipfm, qdn bcumzlwf fipzqzs lcz bqzyidk oceeqdn-fidm cbxicdy xjqd xjm cfn kmxcbx ecnwfm. +cbxbqzym wymy q eczm nmofqzqxivm yxsfm cl oceeqdn-fidm bqzyidk: scw ozmqxm qd idyxqdom cl CbxicdBqzymz, bcbwfqxm ix uixj cbxicdy, +qdn bqzym xjm oceeqdn fidm. cbxbqzym qffcuy wymzy xc ybmoils cbxicdy id xjm ocdvmdxicdqf KDW/BCYIT ysdxqt, qdn qnnixicdqffs kmdmzqxmy +wyqkm qdn jmfb emyyqkmy lcz scw. + +Xwswluth dt l zxuh jxyqhydhys, gahodkah, lyi wxphugra adkulun gxu wlutdyf jxzzlyi-adyh xwsdxyt sely seh xai fhsxws zxirah. +xwswluth rtht l zxuh ihjalulsdqh tsnah xg jxzzlyi-adyh wlutdyf: nxr juhlsh ly dytslyjh xg XwsdxyWluthu, wxwralsh ds pdse xwsdxyt, +lyi wluth seh jxzzlyi adyh. xwswluth laaxpt rthut sx twhjdgn xwsdxyt dy seh jxyqhysdxyla FYR/WXTDO tnyslo, lyi liidsdxylaan fhyhulsht +rtlfh lyi ehaw zhttlfht gxu nxr. + +Srnrgpoc yo g uspc estlctyctn, bvcjyfvc, gtd rskcpbmv vyfpgpi bsp rgpoyta esuugtd-vytc srnysto nzgt nzc svd acnsrn usdmvc. +srnrgpoc moco g uspc dcevgpgnylc onivc sb esuugtd-vytc rgpoyta: ism epcgnc gt ytongtec sb SrnystRgpocp, rsrmvgnc yn kynz srnysto, +gtd rgpoc nzc esuugtd vytc. srnrgpoc gvvsko mocpo ns orceybi srnysto yt nzc estlctnystgv ATM/RSOYJ oitngj, gtd gddynystgvvi actcpgnco +mogac gtd zcvr ucoogaco bsp ism. + +Nmimbkjx tj b pnkx znogxotxoi, wqxetaqx, boy mnfxkwhq qtakbkd wnk mbkjtov znppboy-qtox nmitnoj iubo iux nqy vxinmi pnyhqx. +nmimbkjx hjxj b pnkx yxzqbkbitgx jidqx nw znppboy-qtox mbkjtov: dnh zkxbix bo tojibozx nw NmitnoMbkjxk, mnmhqbix ti ftiu nmitnoj, +boy mbkjx iux znppboy qtox. nmimbkjx bqqnfj hjxkj in jmxztwd nmitnoj to iux znogxoitnobq VOH/MNJTE jdoibe, boy byytitnobqqd vxoxkbixj +hjbvx boy uxqm pxjjbvxj wnk dnh. + +Ihdhwfes oe w kifs uijbsjosjd, rlszovls, wjt hiasfrcl lovfwfy rif hwfeojq uikkwjt-lojs ihdoije dpwj dps ilt qsdihd kitcls. +ihdhwfes cese w kifs tsulwfwdobs edyls ir uikkwjt-lojs hwfeojq: yic ufswds wj ojedwjus ir IhdoijHwfesf, hihclwds od aodp ihdoije, +wjt hwfes dps uikkwjt lojs. ihdhwfes wlliae cesfe di ehsuory ihdoije oj dps uijbsjdoijwl QJC/HIEOZ eyjdwz, wjt wttodoijwlly qsjsfwdse +cewqs wjt pslh kseewqse rif yic. + +Dcycrazn jz r fdan pdewnejney, mgnujqgn, reo cdvnamxg gjqarat mda crazjel pdffreo-gjen dcyjdez ykre ykn dgo lnydcy fdoxgn. +dcycrazn xznz r fdan onpgraryjwn zytgn dm pdffreo-gjen crazjel: tdx panryn re jezyrepn dm DcyjdeCrazna, cdcxgryn jy vjyk dcyjdez, +reo crazn ykn pdffreo gjen. dcycrazn rggdvz xznaz yd zcnpjmt dcyjdez je ykn pdewneyjderg LEX/CDZJU zteyru, reo roojyjderggt lnenarynz +xzrln reo kngc fnzzrlnz mda tdx. + +Yxtxmvui eu m ayvi kyzrizeizt, hbipelbi, mzj xyqivhsb belvmvo hyv xmvuezg kyaamzj-bezi yxteyzu tfmz tfi ybj gityxt ayjsbi. +yxtxmvui suiu m ayvi jikbmvmteri utobi yh kyaamzj-bezi xmvuezg: oys kvimti mz ezutmzki yh YxteyzXmvuiv, xyxsbmti et qetf yxteyzu, +mzj xmvui tfi kyaamzj bezi. yxtxmvui mbbyqu suivu ty uxikeho yxteyzu ez tfi kyzrizteyzmb GZS/XYUEP uoztmp, mzj mjjeteyzmbbo gizivmtiu +sumgi mzj fibx aiuumgiu hyv oys. + +Tsoshqpd zp h vtqd ftumduzduo, cwdkzgwd, hue stldqcnw wzgqhqj ctq shqpzub ftvvhue-wzud tsoztup oahu oad twe bdotso vtenwd. +tsoshqpd npdp h vtqd edfwhqhozmd pojwd tc ftvvhue-wzud shqpzub: jtn fqdhod hu zupohufd tc TsoztuShqpdq, stsnwhod zo lzoa tsoztup, +hue shqpd oad ftvvhue wzud. tsoshqpd hwwtlp npdqp ot psdfzcj tsoztup zu oad ftumduoztuhw BUN/STPZK pjuohk, hue heezoztuhwwj bdudqhodp +nphbd hue adws vdpphbdp ctq jtn. + +Onjnclky uk c qoly aophypuypj, xryfubry, cpz nogylxir rublcle xol nclkupw aoqqcpz-rupy onjuopk jvcp jvy orz wyjonj qoziry. +onjnclky ikyk c qoly zyarclcjuhy kjery ox aoqqcpz-rupy nclkupw: eoi alycjy cp upkjcpay ox OnjuopNclkyl, nonircjy uj gujv onjuopk, +cpz nclky jvy aoqqcpz rupy. onjnclky crrogk ikylk jo knyauxe onjuopk up jvy aophypjuopcr WPI/NOKUF kepjcf, cpz czzujuopcrre wypylcjyk +ikcwy cpz vyrn qykkcwyk xol eoi. + +Jieixgft pf x ljgt vjkctkptke, smtapwmt, xku ijbtgsdm mpwgxgz sjg ixgfpkr vjllxku-mpkt jiepjkf eqxk eqt jmu rtejie ljudmt. +jieixgft dftf x ljgt utvmxgxepct fezmt js vjllxku-mpkt ixgfpkr: zjd vgtxet xk pkfexkvt js JiepjkIxgftg, ijidmxet pe bpeq jiepjkf, +xku ixgft eqt vjllxku mpkt. jieixgft xmmjbf dftgf ej fitvpsz jiepjkf pk eqt vjkctkepjkxm RKD/IJFPA fzkexa, xku xuupepjkxmmz rtktgxetf +dfxrt xku qtmi ltffxrtf sjg zjd. + +Edzdsbao ka s gebo qefxofkofz, nhovkrho, sfp dewobnyh hkrbsbu neb dsbakfm qeggsfp-hkfo edzkefa zlsf zlo ehp mozedz gepyho. +edzdsbao yaoa s gebo poqhsbszkxo azuho en qeggsfp-hkfo dsbakfm: uey qboszo sf kfazsfqo en EdzkefDsbaob, dedyhszo kz wkzl edzkefa, +sfp dsbao zlo qeggsfp hkfo. edzdsbao shhewa yaoba ze adoqknu edzkefa kf zlo qefxofzkefsh MFY/DEAKV aufzsv, sfp sppkzkefshhu mofobszoa +yasmo sfp lohd goaasmoa neb uey. + +Zyuynwvj fv n bzwj lzasjafjau, icjqfmcj, nak yzrjwitc cfmwnwp izw ynwvfah lzbbnak-cfaj zyufzav ugna ugj zck hjuzyu bzktcj. +zyuynwvj tvjv n bzwj kjlcnwnufsj vupcj zi lzbbnak-cfaj ynwvfah: pzt lwjnuj na favunalj zi ZyufzaYnwvjw, yzytcnuj fu rfug zyufzav, +nak ynwvj ugj lzbbnak cfaj. zyuynwvj ncczrv tvjwv uz vyjlfip zyufzav fa ugj lzasjaufzanc HAT/YZVFQ vpaunq, nak nkkfufzanccp hjajwnujv +tvnhj nak gjcy bjvvnhjv izw pzt. + +Utptirqe aq i wure guvnevaevp, dxelahxe, ivf tumerdox xahrirk dur tirqavc guwwivf-xave utpauvq pbiv pbe uxf ceputp wufoxe. +utptirqe oqeq i wure fegxiripane qpkxe ud guwwivf-xave tirqavc: kuo greipe iv avqpivge ud UtpauvTirqer, tutoxipe ap mapb utpauvq, +ivf tirqe pbe guwwivf xave. utptirqe ixxumq oqerq pu qtegadk utpauvq av pbe guvnevpauvix CVO/TUQAL qkvpil, ivf iffapauvixxk ceveripeq +oqice ivf bext weqqiceq dur kuo. + +Pokodmlz vl d rpmz bpqizqvzqk, yszgvcsz, dqa ophzmyjs svcmdmf ypm odmlvqx bprrdqa-svqz pokvpql kwdq kwz psa xzkpok rpajsz. +pokodmlz jlzl d rpmz azbsdmdkviz lkfsz py bprrdqa-svqz odmlvqx: fpj bmzdkz dq vqlkdqbz py PokvpqOdmlzm, opojsdkz vk hvkw pokvpql, +dqa odmlz kwz bprrdqa svqz. pokodmlz dssphl jlzml kp lozbvyf pokvpql vq kwz bpqizqkvpqds XQJ/OPLVG lfqkdg, dqa daavkvpqdssf xzqzmdkzl +jldxz dqa wzso rzlldxzl ypm fpj. + +Kjfjyhgu qg y mkhu wkldulqulf, tnubqxnu, ylv jkcuhten nqxhyha tkh jyhgqls wkmmylv-nqlu kjfqklg fryl fru knv sufkjf mkvenu. +kjfjyhgu egug y mkhu vuwnyhyfqdu gfanu kt wkmmylv-nqlu jyhgqls: ake whuyfu yl qlgfylwu kt KjfqklJyhguh, jkjenyfu qf cqfr kjfqklg, +ylv jyhgu fru wkmmylv nqlu. kjfjyhgu ynnkcg eguhg fk gjuwqta kjfqklg ql fru wkldulfqklyn SLE/JKGQB galfyb, ylv yvvqfqklynna suluhyfug +egysu ylv runj muggysug tkh ake. + +Feaetcbp lb t hfcp rfgypglpga, oipwlsip, tgq efxpcozi ilsctcv ofc etcblgn rfhhtgq-ilgp fealfgb amtg amp fiq npafea hfqzip. +feaetcbp zbpb t hfcp qpritctalyp bavip fo rfhhtgq-ilgp etcblgn: vfz rcptap tg lgbatgrp fo FealfgEtcbpc, efezitap la xlam fealfgb, +tgq etcbp amp rfhhtgq ilgp. feaetcbp tiifxb zbpcb af beprlov fealfgb lg amp rfgypgalfgti NGZ/EFBLW bvgatw, tgq tqqlalfgtiiv npgpctapb +zbtnp tgq mpie hpbbtnpb ofc vfz. + +Azvzoxwk gw o caxk mabtkbgkbv, jdkrgndk, obl zaskxjud dgnxoxq jax zoxwgbi maccobl-dgbk azvgabw vhob vhk adl ikvazv caludk. +azvzoxwk uwkw o caxk lkmdoxovgtk wvqdk aj maccobl-dgbk zoxwgbi: qau mxkovk ob gbwvobmk aj AzvgabZoxwkx, zazudovk gv sgvh azvgabw, +obl zoxwk vhk maccobl dgbk. azvzoxwk oddasw uwkxw va wzkmgjq azvgabw gb vhk mabtkbvgabod IBU/ZAWGR wqbvor, obl ollgvgaboddq ikbkxovkw +uwoik obl hkdz ckwwoikw jax qau. + +Vuqujsrf br j xvsf hvwofwbfwq, eyfmbiyf, jwg uvnfsepy ybisjsl evs ujsrbwd hvxxjwg-ybwf vuqbvwr qcjw qcf vyg dfqvuq xvgpyf. +vuqujsrf prfr j xvsf gfhyjsjqbof rqlyf ve hvxxjwg-ybwf ujsrbwd: lvp hsfjqf jw bwrqjwhf ve VuqbvwUjsrfs, uvupyjqf bq nbqc vuqbvwr, +jwg ujsrf qcf hvxxjwg ybwf. vuqujsrf jyyvnr prfsr qv rufhbel vuqbvwr bw qcf hvwofwqbvwjy DWP/UVRBM rlwqjm, jwg jggbqbvwjyyl dfwfsjqfr +prjdf jwg cfyu xfrrjdfr evs lvp. + +Qplpenma wm e sqna cqrjarwarl, ztahwdta, erb pqianzkt twdneng zqn penmwry cqsserb-twra qplwqrm lxer lxa qtb yalqpl sqbkta. +qplpenma kmam e sqna bactenelwja mlgta qz cqsserb-twra penmwry: gqk cnaela er wrmlerca qz QplwqrPenman, pqpktela wl iwlx qplwqrm, +erb penma lxa cqsserb twra. qplpenma ettqim kmanm lq mpacwzg qplwqrm wr lxa cqrjarlwqret YRK/PQMWH mgrleh, erb ebbwlwqrettg yaranelam +kmeya erb xatp sammeyam zqn gqk. + +Lkgkzihv rh z nliv xlmevmrvmg, uovcryov, zmw kldviufo oryizib uli kzihrmt xlnnzmw-ormv lkgrlmh gszm gsv low tvglkg nlwfov. +lkgkzihv fhvh z nliv wvxozizgrev hgbov lu xlnnzmw-ormv kzihrmt: blf xivzgv zm rmhgzmxv lu LkgrlmKzihvi, klkfozgv rg drgs lkgrlmh, +zmw kzihv gsv xlnnzmw ormv. lkgkzihv zooldh fhvih gl hkvxrub lkgrlmh rm gsv xlmevmgrlmzo TMF/KLHRC hbmgzc, zmw zwwrgrlmzoob tvmvizgvh +fhztv zmw svok nvhhztvh uli blf. + +Gfbfudcq mc u igdq sghzqhmqhb, pjqxmtjq, uhr fgyqdpaj jmtdudw pgd fudcmho sgiiuhr-jmhq gfbmghc bnuh bnq gjr oqbgfb igrajq. +gfbfudcq acqc u igdq rqsjudubmzq cbwjq gp sgiiuhr-jmhq fudcmho: wga sdqubq uh mhcbuhsq gp GfbmghFudcqd, fgfajubq mb ymbn gfbmghc, +uhr fudcq bnq sgiiuhr jmhq. gfbfudcq ujjgyc acqdc bg cfqsmpw gfbmghc mh bnq sghzqhbmghuj OHA/FGCMX cwhbux, uhr urrmbmghujjw oqhqdubqc +acuoq uhr nqjf iqccuoqc pgd wga. + +Tacazovb dv z ftob ntmqbmdbmc, iybedgyb, zmu atxboijy ydgozol ito azovdmp ntffzmu-ydmb tacdtmv cwzm cwb tyu pbctac ftujyb. +tacazovb jvbv z ftob ubnyzozcdqb vclyb ti ntffzmu-ydmb azovdmp: ltj nobzcb zm dmvczmnb ti TacdtmAzovbo, atajyzcb dc xdcw tacdtmv, +zmu azovb cwb ntffzmu ydmb. tacazovb zyytxv jvbov ct vabndil tacdtmv dm cwb ntmqbmcdtmzy PMJ/ATVDE vlmcze, zmu zuudcdtmzyyl pbmbozcbv +jvzpb zmu wbya fbvvzpbv ito ltj. + +Cjljixek me i ocxk wcvzkvmkvl, rhknmphk, ivd jcgkxrsh hmpxixu rcx jixemvy wcooivd-hmvk cjlmcve lfiv lfk chd yklcjl ocdshk. +cjljixek seke i ocxk dkwhixilmzk eluhk cr wcooivd-hmvk jixemvy: ucs wxkilk iv mvelivwk cr CjlmcvJixekx, jcjshilk ml gmlf cjlmcve, +ivd jixek lfk wcooivd hmvk. cjljixek ihhcge sekxe lc ejkwmru cjlmcve mv lfk wcvzkvlmcvih YVS/JCEMN euvlin, ivd iddmlmcvihhu ykvkxilke +seiyk ivd fkhj okeeiyke rcx ucs. + +Lsusrgnt vn r xlgt fleitevteu, aqtwvyqt, rem slptgabq qvygrgd alg srgnveh flxxrem-qvet lsuvlen uore uot lqm htulsu xlmbqt. +lsusrgnt bntn r xlgt mtfqrgruvit nudqt la flxxrem-qvet srgnveh: dlb fgtrut re venureft la LsuvleSrgntg, slsbqrut vu pvuo lsuvlen, +rem srgnt uot flxxrem qvet. lsusrgnt rqqlpn bntgn ul nstfvad lsuvlen ve uot fleiteuvlerq HEB/SLNVW ndeurw, rem rmmvuvlerqqd htetgrutn +bnrht rem otqs xtnnrhtn alg dlb. + +Ubdbapwc ew a gupc ounrcnecnd, jzcfehzc, anv buycpjkz zehpapm jup bapwenq ougganv-zenc ubdeunw dxan dxc uzv qcdubd guvkzc. +ubdbapwc kwcw a gupc vcozapaderc wdmzc uj ougganv-zenc bapwenq: muk opcadc an enwdanoc uj UbdeunBapwcp, bubkzadc ed yedx ubdeunw, +anv bapwc dxc ougganv zenc. ubdbapwc azzuyw kwcpw du wbcoejm ubdeunw en dxc ounrcndeunaz QNK/BUWEF wmndaf, anv avvedeunazzm qcncpadcw +kwaqc anv xczb gcwwaqcw jup muk. + +Dkmkjyfl nf j pdyl xdwalwnlwm, silonqil, jwe kdhlysti inqyjyv sdy kjyfnwz xdppjwe-inwl dkmndwf mgjw mgl die zlmdkm pdetil. +dkmkjyfl tflf j pdyl elxijyjmnal fmvil ds xdppjwe-inwl kjyfnwz: vdt xyljml jw nwfmjwxl ds DkmndwKjyfly, kdktijml nm hnmg dkmndwf, +jwe kjyfl mgl xdppjwe inwl. dkmkjyfl jiidhf tflyf md fklxnsv dkmndwf nw mgl xdwalwmndwji ZWT/KDFNO fvwmjo, jwe jeenmndwjiiv zlwlyjmlf +tfjzl jwe glik plffjzlf sdy vdt. + +Mtvtshou wo s ymhu gmfjufwufv, bruxwzru, sfn tmquhbcr rwzhshe bmh tshowfi gmyysfn-rwfu mtvwmfo vpsf vpu mrn iuvmtv ymncru. +mtvtshou couo s ymhu nugrshsvwju overu mb gmyysfn-rwfu tshowfi: emc ghusvu sf wfovsfgu mb MtvwmfTshouh, tmtcrsvu wv qwvp mtvwmfo, +sfn tshou vpu gmyysfn rwfu. mtvtshou srrmqo couho vm otugwbe mtvwmfo wf vpu gmfjufvwmfsr IFC/TMOWX oefvsx, sfn snnwvwmfsrre iufuhsvuo +cosiu sfn purt yuoosiuo bmh emc. + +Vcecbqxd fx b hvqd pvosdofdoe, kadgfiad, bow cvzdqkla afiqbqn kvq cbqxfor pvhhbow-afod vcefvox eybo eyd vaw rdevce hvwlad. +vcecbqxd lxdx b hvqd wdpabqbefsd xenad vk pvhhbow-afod cbqxfor: nvl pqdbed bo foxebopd vk VcefvoCbqxdq, cvclabed fe zfey vcefvox, +bow cbqxd eyd pvhhbow afod. vcecbqxd baavzx lxdqx ev xcdpfkn vcefvox fo eyd pvosdoefvoba ROL/CVXFG xnoebg, bow bwwfefvobaan rdodqbedx +lxbrd bow ydac hdxxbrdx kvq nvl. + +Elnlkzgm og k qezm yexbmxomxn, tjmporjm, kxf leimztuj jorzkzw tez lkzgoxa yeqqkxf-joxm elnoexg nhkx nhm ejf amneln qefujm. +elnlkzgm ugmg k qezm fmyjkzknobm gnwjm et yeqqkxf-joxm lkzgoxa: weu yzmknm kx oxgnkxym et ElnoexLkzgmz, lelujknm on ionh elnoexg, +kxf lkzgm nhm yeqqkxf joxm. elnlkzgm kjjeig ugmzg ne glmyotw elnoexg ox nhm yexbmxnoexkj AXU/LEGOP gwxnkp, kxf kffonoexkjjw amxmzknmg +ugkam kxf hmjl qmggkamg tez weu. + +Nuwutipv xp t zniv hngkvgxvgw, csvyxasv, tgo unrvicds sxaitif cni utipxgj hnzztgo-sxgv nuwxngp wqtg wqv nso jvwnuw znodsv. +nuwutipv dpvp t zniv ovhstitwxkv pwfsv nc hnzztgo-sxgv utipxgj: fnd hivtwv tg xgpwtghv nc NuwxngUtipvi, unudstwv xw rxwq nuwxngp, +tgo utipv wqv hnzztgo sxgv. nuwutipv tssnrp dpvip wn puvhxcf nuwxngp xg wqv hngkvgwxngts JGD/UNPXY pfgwty, tgo tooxwxngtssf jvgvitwvp +dptjv tgo qvsu zvpptjvp cni fnd. + +Wdfdcrye gy c iwre qwptepgepf, lbehgjbe, cpx dwaerlmb bgjrcro lwr dcrygps qwiicpx-bgpe wdfgwpy fzcp fze wbx sefwdf iwxmbe. +wdfdcrye myey c iwre xeqbcrcfgte yfobe wl qwiicpx-bgpe dcrygps: owm qrecfe cp gpyfcpqe wl WdfgwpDcryer, dwdmbcfe gf agfz wdfgwpy, +cpx dcrye fze qwiicpx bgpe. wdfdcrye cbbway myery fw ydeqglo wdfgwpy gp fze qwptepfgwpcb SPM/DWYGH yopfch, cpx cxxgfgwpcbbo sepercfey +mycse cpx zebd ieyycsey lwr owm. + +Fmomlahn ph l rfan zfycnypnyo, uknqpskn, lyg mfjnauvk kpsalax ufa mlahpyb zfrrlyg-kpyn fmopfyh oily oin fkg bnofmo rfgvkn. +fmomlahn vhnh l rfan gnzklalopcn hoxkn fu zfrrlyg-kpyn mlahpyb: xfv zanlon ly pyholyzn fu FmopfyMlahna, mfmvklon po jpoi fmopfyh, +lyg mlahn oin zfrrlyg kpyn. fmomlahn lkkfjh vhnah of hmnzpux fmopfyh py oin zfycnyopfylk BYV/MFHPQ hxyolq, lyg lggpopfylkkx bnynalonh +vhlbn lyg inkm rnhhlbnh ufa xfv. + +Ovxvujqw yq u aojw iohlwhywhx, dtwzybtw, uhp voswjdet tybjujg doj vujqyhk ioaauhp-tyhw ovxyohq xruh xrw otp kwxovx aopetw. +ovxvujqw eqwq u aojw pwitujuxylw qxgtw od ioaauhp-tyhw vujqyhk: goe ijwuxw uh yhqxuhiw od OvxyohVujqwj, vovetuxw yx syxr ovxyohq, +uhp vujqw xrw ioaauhp tyhw. ovxvujqw uttosq eqwjq xo qvwiydg ovxyohq yh xrw iohlwhxyohut KHE/VOQYZ qghxuz, uhp uppyxyohuttg kwhwjuxwq +equkw uhp rwtv awqqukwq doj goe. + +Xegedszf hz d jxsf rxqufqhfqg, mcfihkcf, dqy exbfsmnc chksdsp mxs edszhqt rxjjdqy-chqf xeghxqz gadq gaf xcy tfgxeg jxyncf. +xegedszf nzfz d jxsf yfrcdsdghuf zgpcf xm rxjjdqy-chqf edszhqt: pxn rsfdgf dq hqzgdqrf xm XeghxqEdszfs, exencdgf hg bhga xeghxqz, +dqy edszf gaf rxjjdqy chqf. xegedszf dccxbz nzfsz gx zefrhmp xeghxqz hq gaf rxqufqghxqdc TQN/EXZHI zpqgdi, dqy dyyhghxqdccp tfqfsdgfz +nzdtf dqy afce jfzzdtfz mxs pxn. + +Gnpnmbio qi m sgbo agzdozqozp, vlorqtlo, mzh ngkobvwl lqtbmby vgb nmbiqzc agssmzh-lqzo gnpqgzi pjmz pjo glh copgnp sghwlo. +gnpnmbio wioi m sgbo hoalmbmpqdo ipylo gv agssmzh-lqzo nmbiqzc: ygw abompo mz qzipmzao gv GnpqgzNmbiob, ngnwlmpo qp kqpj gnpqgzi, +mzh nmbio pjo agssmzh lqzo. gnpnmbio mllgki wiobi pg inoaqvy gnpqgzi qz pjo agzdozpqgzml CZW/NGIQR iyzpmr, mzh mhhqpqgzmlly cozobmpoi +wimco mzh joln soiimcoi vgb ygw. + +Pwywvkrx zr v bpkx jpimxizxiy, euxazcux, viq wptxkefu uzckvkh epk wvkrzil jpbbviq-uzix pwyzpir ysvi ysx puq lxypwy bpqfux. +pwywvkrx frxr v bpkx qxjuvkvyzmx ryhux pe jpbbviq-uzix wvkrzil: hpf jkxvyx vi ziryvijx pe PwyzpiWvkrxk, wpwfuvyx zy tzys pwyzpir, +viq wvkrx ysx jpbbviq uzix. pwywvkrx vuuptr frxkr yp rwxjzeh pwyzpir zi ysx jpimxiyzpivu LIF/WPRZA rhiyva, viq vqqzyzpivuuh lxixkvyxr +frvlx viq sxuw bxrrvlxr epk hpf. + +Yfhfetag ia e kytg syrvgrigrh, ndgjildg, erz fycgtnod diltetq nyt fetairu sykkerz-dirg yfhiyra hber hbg ydz ughyfh kyzodg. +yfhfetag oaga e kytg zgsdetehivg ahqdg yn sykkerz-dirg fetairu: qyo stgehg er irahersg yn YfhiyrFetagt, fyfodehg ih cihb yfhiyra, +erz fetag hbg sykkerz dirg. yfhfetag eddyca oagta hy afgsinq yfhiyra ir hbg syrvgrhiyred URO/FYAIJ aqrhej, erz ezzihiyreddq ugrgtehga +oaeug erz bgdf kgaaeuga nyt qyo. + +Hoqoncjp rj n thcp bhaeparpaq, wmpsrump, nai ohlpcwxm mrucncz whc oncjrad bhttnai-mrap hoqrhaj qkna qkp hmi dpqhoq thixmp. +hoqoncjp xjpj n thcp ipbmncnqrep jqzmp hw bhttnai-mrap oncjrad: zhx bcpnqp na rajqnabp hw HoqrhaOncjpc, ohoxmnqp rq lrqk hoqrhaj, +nai oncjp qkp bhttnai mrap. hoqoncjp nmmhlj xjpcj qh jopbrwz hoqrhaj ra qkp bhaepaqrhanm DAX/OHJRS jzaqns, nai niirqrhanmmz dpapcnqpj +xjndp nai kpmo tpjjndpj whc zhx. + +Qxzxwlsy as w cqly kqjnyjayjz, fvybadvy, wjr xquylfgv vadlwli fql xwlsajm kqccwjr-vajy qxzaqjs ztwj zty qvr myzqxz cqrgvy. +qxzxwlsy gsys w cqly rykvwlwzany szivy qf kqccwjr-vajy xwlsajm: iqg klywzy wj ajszwjky qf QxzaqjXwlsyl, xqxgvwzy az uazt qxzaqjs, +wjr xwlsy zty kqccwjr vajy. qxzxwlsy wvvqus gsyls zq sxykafi qxzaqjs aj zty kqjnyjzaqjwv MJG/XQSAB sijzwb, wjr wrrazaqjwvvi myjylwzys +gswmy wjr tyvx cysswmys fql iqg. + +Zgigfubh jb f lzuh tzswhsjhsi, oehkjmeh, fsa gzdhuope ejmufur ozu gfubjsv tzllfsa-ejsh zgijzsb icfs ich zea vhizgi lzapeh. +zgigfubh pbhb f lzuh ahtefufijwh bireh zo tzllfsa-ejsh gfubjsv: rzp tuhfih fs jsbifsth zo ZgijzsGfubhu, gzgpefih ji djic zgijzsb, +fsa gfubh ich tzllfsa ejsh. zgigfubh feezdb pbhub iz bghtjor zgijzsb js ich tzswhsijzsfe VSP/GZBJK brsifk, fsa faajijzsfeer vhshufihb +pbfvh fsa cheg lhbbfvhb ozu rzp. + +Iprpodkq sk o uidq cibfqbsqbr, xnqtsvnq, obj pimqdxyn nsvdoda xid podksbe ciuuobj-nsbq iprsibk rlob rlq inj eqripr uijynq. +iprpodkq ykqk o uidq jqcnodorsfq kranq ix ciuuobj-nsbq podksbe: aiy cdqorq ob sbkrobcq ix IprsibPodkqd, pipynorq sr msrl iprsibk, +obj podkq rlq ciuuobj nsbq. iprpodkq onnimk ykqdk ri kpqcsxa iprsibk sb rlq cibfqbrsibon EBY/PIKST kabrot, obj ojjsrsibonna eqbqdorqk +ykoeq obj lqnp uqkkoeqk xid aiy. + +Ryayxmtz bt x drmz lrkozkbzka, gwzcbewz, xks yrvzmghw wbemxmj grm yxmtbkn lrddxks-wbkz ryabrkt auxk auz rws nzarya drshwz. +ryayxmtz htzt x drmz szlwxmxaboz tajwz rg lrddxks-wbkz yxmtbkn: jrh lmzxaz xk bktaxklz rg RyabrkYxmtzm, yryhwxaz ba vbau ryabrkt, +xks yxmtz auz lrddxks wbkz. ryayxmtz xwwrvt htzmt ar tyzlbgj ryabrkt bk auz lrkozkabrkxw NKH/YRTBC tjkaxc, xks xssbabrkxwwj nzkzmxazt +htxnz xks uzwy dzttxnzt grm jrh. + +Ahjhgvci kc g mavi uatxitkitj, pfilknfi, gtb haeivpqf fknvgvs pav hgvcktw uammgtb-fkti ahjkatc jdgt jdi afb wijahj mabqfi. +ahjhgvci qcic g mavi biufgvgjkxi cjsfi ap uammgtb-fkti hgvcktw: saq uvigji gt ktcjgtui ap AhjkatHgvciv, hahqfgji kj ekjd ahjkatc, +gtb hgvci jdi uammgtb fkti. ahjhgvci gffaec qcivc ja chiukps ahjkatc kt jdi uatxitjkatgf WTQ/HACKL cstjgl, gtb gbbkjkatgffs witivgjic +qcgwi gtb difh miccgwic pav saq. + +Jqsqpelr tl p vjer djcgrctrcs, yorutwor, pck qjnreyzo otwepeb yje qpeltcf djvvpck-otcr jqstjcl smpc smr jok frsjqs vjkzor. +jqsqpelr zlrl p vjer krdopepstgr lsbor jy djvvpck-otcr qpeltcf: bjz derpsr pc tclspcdr jy JqstjcQpelre, qjqzopsr ts ntsm jqstjcl, +pck qpelr smr djvvpck otcr. jqsqpelr poojnl zlrel sj lqrdtyb jqstjcl tc smr djcgrcstjcpo FCZ/QJLTU lbcspu, pck pkktstjcpoob frcrepsrl +zlpfr pck mroq vrllpfrl yje bjz. + +Szbzynua cu y esna mslpalcalb, hxadcfxa, ylt zswanhix xcfnynk hsn zynuclo mseeylt-xcla szbcslu bvyl bva sxt oabszb estixa. +szbzynua iuau y esna tamxynybcpa ubkxa sh mseeylt-xcla zynuclo: ksi mnayba yl clubylma sh SzbcslZynuan, zszixyba cb wcbv szbcslu, +ylt zynua bva mseeylt xcla. szbzynua yxxswu iuanu bs uzamchk szbcslu cl bva mslpalbcslyx OLI/ZSUCD uklbyd, ylt yttcbcslyxxk oalanybau +iuyoa ylt vaxz eauuyoau hsn ksi. + +Bikihwdj ld h nbwj vbuyjuljuk, qgjmlogj, huc ibfjwqrg glowhwt qbw ihwdlux vbnnhuc-gluj biklbud kehu kej bgc xjkbik nbcrgj. +bikihwdj rdjd h nbwj cjvghwhklyj dktgj bq vbnnhuc-gluj ihwdlux: tbr vwjhkj hu ludkhuvj bq BiklbuIhwdjw, ibirghkj lk flke biklbud, +huc ihwdj kej vbnnhuc gluj. bikihwdj hggbfd rdjwd kb dijvlqt biklbud lu kej vbuyjuklbuhg XUR/IBDLM dtukhm, huc hcclklbuhggt xjujwhkjd +rdhxj huc ejgi njddhxjd qbw tbr. + +Krtrqfms um q wkfs ekdhsdusdt, zpsvuxps, qdl rkosfzap puxfqfc zkf rqfmudg ekwwqdl-puds krtukdm tnqd tns kpl gstkrt wklaps. +krtrqfms amsm q wkfs lsepqfqtuhs mtcps kz ekwwqdl-puds rqfmudg: cka efsqts qd udmtqdes kz KrtukdRqfmsf, rkrapqts ut outn krtukdm, +qdl rqfms tns ekwwqdl puds. krtrqfms qppkom amsfm tk mrseuzc krtukdm ud tns ekdhsdtukdqp GDA/RKMUV mcdtqv, qdl qllutukdqppc gsdsfqtsm +amqgs qdl nspr wsmmqgsm zkf cka. + +Fagaxqld jl x pfqd nfkwdkjdkg, yudmjsud, xki afrdqybu ujsqxqh yfq axqljkt nfppxki-ujkd fagjfkl goxk god fui tdgfag pfibud. +fagaxqld bldl x pfqd idnuxqxgjwd lghud fy nfppxki-ujkd axqljkt: hfb nqdxgd xk jklgxknd fy FagjfkAxqldq, afabuxgd jg rjgo fagjfkl, +xki axqld god nfppxki ujkd. fagaxqld xuufrl bldql gf ladnjyh fagjfkl jk god nfkwdkgjfkxu TKB/AFLJM lhkgxm, xki xiijgjfkxuuh tdkdqxgdl +blxtd xki odua pdllxtdl yfq hfb. + +Gbhbyrme km y qgre oglxelkelh, zvenktve, ylj bgserzcv vktryri zgr byrmklu ogqqylj-vkle gbhkglm hpyl hpe gvj uehgbh qgjcve. +gbhbyrme cmem y qgre jeovyryhkxe mhive gz ogqqylj-vkle byrmklu: igc oreyhe yl klmhyloe gz GbhkglByrmer, bgbcvyhe kh skhp gbhkglm, +ylj byrme hpe ogqqylj vkle. gbhbyrme yvvgsm cmerm hg mbeokzi gbhkglm kl hpe oglxelhkglyv ULC/BGMKN milhyn, ylj yjjkhkglyvvi ueleryhem +cmyue ylj pevb qemmyuem zgr igc. + +Hciczsnf ln z rhsf phmyfmlfmi, awfoluwf, zmk chtfsadw wluszsj ahs czsnlmv phrrzmk-wlmf hcilhmn iqzm iqf hwk vfihci rhkdwf. +hciczsnf dnfn z rhsf kfpwzszilyf nijwf ha phrrzmk-wlmf czsnlmv: jhd psfzif zm lmnizmpf ha HcilhmCzsnfs, chcdwzif li tliq hcilhmn, +zmk czsnf iqf phrrzmk wlmf. hciczsnf zwwhtn dnfsn ih ncfplaj hcilhmn lm iqf phmyfmilhmzw VMD/CHNLO njmizo, zmk zkklilhmzwwj vfmfszifn +dnzvf zmk qfwc rfnnzvfn ahs jhd. + +Idjdatog mo a sitg qinzgnmgnj, bxgpmvxg, anl diugtbex xmvtatk bit datomnw qissanl-xmng idjmino jran jrg ixl wgjidj silexg. +idjdatog eogo a sitg lgqxatajmzg ojkxg ib qissanl-xmng datomnw: kie qtgajg an mnojanqg ib IdjminDatogt, didexajg mj umjr idjmino, +anl datog jrg qissanl xmng. idjdatog axxiuo eogto ji odgqmbk idjmino mn jrg qinzgnjminax WNE/DIOMP oknjap, anl allmjminaxxk wgngtajgo +eoawg anl rgxd sgooawgo bit kie. + +Jekebuph np b tjuh rjoahonhok, cyhqnwyh, bom ejvhucfy ynwubul cju ebupnox rjttbom-ynoh jeknjop ksbo ksh jym xhkjek tjmfyh. +jekebuph fphp b tjuh mhrybubknah pklyh jc rjttbom-ynoh ebupnox: ljf ruhbkh bo nopkborh jc JeknjoEbuphu, ejefybkh nk vnks jeknjop, +bom ebuph ksh rjttbom ynoh. jekebuph byyjvp fphup kj pehrncl jeknjop no ksh rjoahoknjoby XOF/EJPNQ plokbq, bom bmmnknjobyyl xhohubkhp +fpbxh bom shye thppbxhp cju ljf. + +Kflfcvqi oq c ukvi skpbipoipl, dziroxzi, cpn fkwivdgz zoxvcvm dkv fcvqopy skuucpn-zopi kflokpq ltcp lti kzn yilkfl ukngzi. +kflfcvqi gqiq c ukvi niszcvclobi qlmzi kd skuucpn-zopi fcvqopy: mkg svicli cp opqlcpsi kd KflokpFcvqiv, fkfgzcli ol wolt kflokpq, +cpn fcvqi lti skuucpn zopi. kflfcvqi czzkwq gqivq lk qfisodm kflokpq op lti skpbiplokpcz YPG/FKQOR qmplcr, cpn cnnolokpczzm yipivcliq +gqcyi cpn tizf uiqqcyiq dkv mkg. + +Lgmgdwrj pr d vlwj tlqcjqpjqm, eajspyaj, dqo glxjweha apywdwn elw gdwrpqz tlvvdqo-apqj lgmplqr mudq muj lao zjmlgm vlohaj. +lgmgdwrj hrjr d vlwj ojtadwdmpcj rmnaj le tlvvdqo-apqj gdwrpqz: nlh twjdmj dq pqrmdqtj le LgmplqGdwrjw, glghadmj pm xpmu lgmplqr, +dqo gdwrj muj tlvvdqo apqj. lgmgdwrj daalxr hrjwr ml rgjtpen lgmplqr pq muj tlqcjqmplqda ZQH/GLRPS rnqmds, dqo doopmplqdaan zjqjwdmjr +hrdzj dqo ujag vjrrdzjr elw nlh. + +Mhnhexsk qs e wmxk umrdkrqkrn, fbktqzbk, erp hmykxfib bqzxexo fmx hexsqra umwwerp-bqrk mhnqmrs nver nvk mbp aknmhn wmpibk. +mhnhexsk isks e wmxk pkubexenqdk snobk mf umwwerp-bqrk hexsqra: omi uxkenk er qrsneruk mf MhnqmrHexskx, hmhibenk qn yqnv mhnqmrs, +erp hexsk nvk umwwerp bqrk. mhnhexsk ebbmys iskxs nm shkuqfo mhnqmrs qr nvk umrdkrnqmreb ARI/HMSQT sornet, erp eppqnqmrebbo akrkxenks +iseak erp vkbh wksseaks fmx omi. + +Nioifytl rt f xnyl vnselsrlso, gcluracl, fsq inzlygjc crayfyp gny ifytrsb vnxxfsq-crsl niornst owfs owl ncq blonio xnqjcl. +nioifytl jtlt f xnyl qlvcfyforel topcl ng vnxxfsq-crsl ifytrsb: pnj vylfol fs rstofsvl ng NiornsIfytly, inijcfol ro zrow niornst, +fsq ifytl owl vnxxfsq crsl. nioifytl fccnzt jtlyt on tilvrgp niornst rs owl vnselsornsfc BSJ/INTRU tpsofu, fsq fqqrornsfccp blslyfolt +jtfbl fsq wlci xlttfblt gny pnj. + +Ojpjgzum su g yozm wotfmtsmtp, hdmvsbdm, gtr joamzhkd dsbzgzq hoz jgzustc woyygtr-dstm ojpsotu pxgt pxm odr cmpojp yorkdm. +ojpjgzum kumu g yozm rmwdgzgpsfm upqdm oh woyygtr-dstm jgzustc: qok wzmgpm gt stupgtwm oh OjpsotJgzumz, jojkdgpm sp aspx ojpsotu, +gtr jgzum pxm woyygtr dstm. ojpjgzum gddoau kumzu po ujmwshq ojpsotu st pxm wotfmtpsotgd CTK/JOUSV uqtpgv, gtr grrspsotgddq cmtmzgpmu +kugcm gtr xmdj ymuugcmu hoz qok. + +Pkqkhavn tv h zpan xpugnutnuq, ienwtcen, hus kpbnaile etcahar ipa khavtud xpzzhus-etun pkqtpuv qyhu qyn pes dnqpkq zpslen. +pkqkhavn lvnv h zpan snxehahqtgn vqren pi xpzzhus-etun khavtud: rpl xanhqn hu tuvqhuxn pi PkqtpuKhavna, kpklehqn tq btqy pkqtpuv, +hus khavn qyn xpzzhus etun. pkqkhavn heepbv lvnav qp vknxtir pkqtpuv tu qyn xpugnuqtpuhe DUL/KPVTW vruqhw, hus hsstqtpuheer dnunahqnv +lvhdn hus ynek znvvhdnv ipa rpl. + +Qlrlibwo uw i aqbo yqvhovuovr, jfoxudfo, ivt lqcobjmf fudbibs jqb libwuve yqaaivt-fuvo qlruqvw rziv rzo qft eorqlr aqtmfo. +qlrlibwo mwow i aqbo toyfibiruho wrsfo qj yqaaivt-fuvo libwuve: sqm yboiro iv uvwrivyo qj QlruqvLibwob, lqlmfiro ur curz qlruqvw, +ivt libwo rzo yqaaivt fuvo. qlrlibwo iffqcw mwobw rq wloyujs qlruqvw uv rzo yqvhovruqvif EVM/LQWUX wsvrix, ivt itturuqviffs eovobirow +mwieo ivt zofl aowwieow jqb sqm. + +Rmsmjcxp vx j brcp zrwipwvpws, kgpyvegp, jwu mrdpckng gvecjct krc mjcxvwf zrbbjwu-gvwp rmsvrwx sajw sap rgu fpsrms brungp. +rmsmjcxp nxpx j brcp upzgjcjsvip xstgp rk zrbbjwu-gvwp mjcxvwf: trn zcpjsp jw vwxsjwzp rk RmsvrwMjcxpc, mrmngjsp vs dvsa rmsvrwx, +jwu mjcxp sap zrbbjwu gvwp. rmsmjcxp jggrdx nxpcx sr xmpzvkt rmsvrwx vw sap zrwipwsvrwjg FWN/MRXVY xtwsjy, jwu juuvsvrwjggt fpwpcjspx +nxjfp jwu apgm bpxxjfpx krc trn. + +Sntnkdyq wy k csdq asxjqxwqxt, lhqzwfhq, kxv nseqdloh hwfdkdu lsd nkdywxg ascckxv-hwxq sntwsxy tbkx tbq shv gqtsnt csvohq. +sntnkdyq oyqy k csdq vqahkdktwjq ytuhq sl ascckxv-hwxq nkdywxg: uso adqktq kx wxytkxaq sl SntwsxNkdyqd, nsnohktq wt ewtb sntwsxy, +kxv nkdyq tbq ascckxv hwxq. sntnkdyq khhsey oyqdy ts ynqawlu sntwsxy wx tbq asxjqxtwsxkh GXO/NSYWZ yuxtkz, kxv kvvwtwsxkhhu gqxqdktqy +oykgq kxv bqhn cqyykgqy lsd uso. + +Touolezr xz l dter btykryxryu, miraxgir, lyw otfrempi ixgelev mte olezxyh btddlyw-ixyr touxtyz ucly ucr tiw hrutou dtwpir. +touolezr pzrz l dter wrbileluxkr zuvir tm btddlyw-ixyr olezxyh: vtp berlur ly xyzulybr tm TouxtyOlezre, otopilur xu fxuc touxtyz, +lyw olezr ucr btddlyw ixyr. touolezr liitfz pzrez ut zorbxmv touxtyz xy ucr btykryuxtyli HYP/OTZXA zvyula, lyw lwwxuxtyliiv hryrelurz +pzlhr lyw crio drzzlhrz mte vtp. + +Upvpmfas ya m eufs cuzlszyszv, njsbyhjs, mzx pugsfnqj jyhfmfw nuf pmfayzi cueemzx-jyzs upvyuza vdmz vds ujx isvupv euxqjs. +upvpmfas qasa m eufs xscjmfmvyls avwjs un cueemzx-jyzs pmfayzi: wuq cfsmvs mz yzavmzcs un UpvyuzPmfasf, pupqjmvs yv gyvd upvyuza, +mzx pmfas vds cueemzx jyzs. upvpmfas mjjuga qasfa vu apscynw upvyuza yz vds cuzlszvyuzmj IZQ/PUAYB awzvmb, mzx mxxyvyuzmjjw iszsfmvsa +qamis mzx dsjp esaamisa nuf wuq. + +Vqwqngbt zb n fvgt dvamtaztaw, oktczikt, nay qvhtgork kzigngx ovg qngbzaj dvffnay-kzat vqwzvab wena wet vky jtwvqw fvyrkt. +vqwqngbt rbtb n fvgt ytdkngnwzmt bwxkt vo dvffnay-kzat qngbzaj: xvr dgtnwt na zabwnadt vo VqwzvaQngbtg, qvqrknwt zw hzwe vqwzvab, +nay qngbt wet dvffnay kzat. vqwqngbt nkkvhb rbtgb wv bqtdzox vqwzvab za wet dvamtawzvank JAR/QVBZC bxawnc, nay nyyzwzvankkx jtatgnwtb +rbnjt nay etkq ftbbnjtb ovg xvr. + +Wrxrohcu ac o gwhu ewbnubaubx, pludajlu, obz rwiuhpsl lajhohy pwh rohcabk ewggobz-labu wrxawbc xfob xfu wlz kuxwrx gwzslu. +wrxrohcu scuc o gwhu zuelohoxanu cxylu wp ewggobz-labu rohcabk: yws ehuoxu ob abcxobeu wp WrxawbRohcuh, rwrsloxu ax iaxf wrxawbc, +obz rohcu xfu ewggobz labu. wrxrohcu ollwic scuhc xw crueapy wrxawbc ab xfu ewbnubxawbol KBS/RWCAD cybxod, obz ozzaxawbolly kubuhoxuc +scoku obz fulr guccokuc pwh yws. + +Xsyspidv bd p hxiv fxcovcbvcy, qmvebkmv, pca sxjviqtm mbkipiz qxi spidbcl fxhhpca-mbcv xsybxcd ygpc ygv xma lvyxsy hxatmv. +xsyspidv tdvd p hxiv avfmpipybov dyzmv xq fxhhpca-mbcv spidbcl: zxt fivpyv pc bcdypcfv xq XsybxcSpidvi, sxstmpyv by jbyg xsybxcd, +pca spidv ygv fxhhpca mbcv. xsyspidv pmmxjd tdvid yx dsvfbqz xsybxcd bc ygv fxcovcybxcpm LCT/SXDBE dzcype, pca paabybxcpmmz lvcvipyvd +tdplv pca gvms hvddplvd qxi zxt. + +Ytztqjew ce q iyjw gydpwdcwdz, rnwfclnw, qdb tykwjrun ncljqja ryj tqjecdm gyiiqdb-ncdw ytzcyde zhqd zhw ynb mwzytz iybunw. +ytztqjew uewe q iyjw bwgnqjqzcpw ezanw yr gyiiqdb-ncdw tqjecdm: ayu gjwqzw qd cdezqdgw yr YtzcydTqjewj, tytunqzw cz kczh ytzcyde, +qdb tqjew zhw gyiiqdb ncdw. ytztqjew qnnyke uewje zy etwgcra ytzcyde cd zhw gydpwdzcydqn MDU/TYECF eadzqf, qdb qbbczcydqnna mwdwjqzwe +ueqmw qdb hwnt iweeqmwe ryj ayu. + +Zuaurkfx df r jzkx hzeqxedxea, soxgdmox, rec uzlxksvo odmkrkb szk urkfden hzjjrec-odex zuadzef aire aix zoc nxazua jzcvox. +zuaurkfx vfxf r jzkx cxhorkradqx fabox zs hzjjrec-odex urkfden: bzv hkxrax re defarehx zs ZuadzeUrkfxk, uzuvorax da ldai zuadzef, +rec urkfx aix hzjjrec odex. zuaurkfx roozlf vfxkf az fuxhdsb zuadzef de aix hzeqxeadzero NEV/UZFDG fbearg, rec rccdadzeroob nxexkraxf +vfrnx rec ixou jxffrnxf szk bzv. + +Avbvslgy eg s kaly iafryfeyfb, tpyhenpy, sfd vamyltwp penlslc tal vslgefo iakksfd-pefy avbeafg bjsf bjy apd oybavb kadwpy. +avbvslgy wgyg s kaly dyipslsbery gbcpy at iakksfd-pefy vslgefo: caw ilysby sf efgbsfiy at AvbeafVslgyl, vavwpsby eb mebj avbeafg, +sfd vslgy bjy iakksfd pefy. avbvslgy sppamg wgylg ba gvyietc avbeafg ef bjy iafryfbeafsp OFW/VAGEH gcfbsh, sfd sddebeafsppc oyfylsbyg +wgsoy sfd jypv kyggsoyg tal caw. + +Bwcwtmhz fh t lbmz jbgszgfzgc, uqzifoqz, tge wbnzmuxq qfomtmd ubm wtmhfgp jblltge-qfgz bwcfbgh cktg ckz bqe pzcbwc lbexqz. +bwcwtmhz xhzh t lbmz ezjqtmtcfsz hcdqz bu jblltge-qfgz wtmhfgp: dbx jmztcz tg fghctgjz bu BwcfbgWtmhzm, wbwxqtcz fc nfck bwcfbgh, +tge wtmhz ckz jblltge qfgz. bwcwtmhz tqqbnh xhzmh cb hwzjfud bwcfbgh fg ckz jbgszgcfbgtq PGX/WBHFI hdgcti, tge teefcfbgtqqd pzgzmtczh +xhtpz tge kzqw lzhhtpzh ubm dbx. + +Cxdxunia gi u mcna kchtahgahd, vrajgpra, uhf xcoanvyr rgpnune vcn xunighq kcmmuhf-rgha cxdgchi dluh dla crf qadcxd mcfyra. +cxdxunia yiai u mcna fakrunudgta idera cv kcmmuhf-rgha xunighq: ecy knauda uh ghiduhka cv CxdgchXunian, xcxyruda gd ogdl cxdgchi, +uhf xunia dla kcmmuhf rgha. cxdxunia urrcoi yiani dc ixakgve cxdgchi gh dla kchtahdgchur QHY/XCIGJ iehduj, uhf uffgdgchurre qahanudai +yiuqa uhf larx maiiuqai vcn ecy. + +Dyeyvojb hj v ndob ldiubihbie, wsbkhqsb, vig ydpbowzs shqovof wdo yvojhir ldnnvig-shib dyehdij emvi emb dsg rbedye ndgzsb. +dyeyvojb zjbj v ndob gblsvovehub jefsb dw ldnnvig-shib yvojhir: fdz lobveb vi hijevilb dw DyehdiYvojbo, ydyzsveb he phem dyehdij, +vig yvojb emb ldnnvig shib. dyeyvojb vssdpj zjboj ed jyblhwf dyehdij hi emb ldiubiehdivs RIZ/YDJHK jfievk, vig vgghehdivssf rbibovebj +zjvrb vig mbsy nbjjvrbj wdo fdz. + +Ezfzwpkc ik w oepc mejvcjicjf, xtclirtc, wjh zeqcpxat tirpwpg xep zwpkijs meoowjh-tijc ezfiejk fnwj fnc eth scfezf oehatc. +ezfzwpkc akck w oepc hcmtwpwfivc kfgtc ex meoowjh-tijc zwpkijs: gea mpcwfc wj ijkfwjmc ex EzfiejZwpkcp, zezatwfc if qifn ezfiejk, +wjh zwpkc fnc meoowjh tijc. ezfzwpkc wtteqk akcpk fe kzcmixg ezfiejk ij fnc mejvcjfiejwt SJA/ZEKIL kgjfwl, wjh whhifiejwttg scjcpwfck +akwsc wjh nctz ockkwsck xep gea. + diff --git a/extra.txt b/extra.txt new file mode 100644 index 0000000..2271714 --- /dev/null +++ b/extra.txt @@ -0,0 +1 @@ +Optparse diff --git a/key.txt b/key.txt new file mode 100644 index 0000000..4f5f162 --- /dev/null +++ b/key.txt @@ -0,0 +1 @@ +5,3 diff --git a/plain.txt b/plain.txt new file mode 100644 index 0000000..a01609a --- /dev/null +++ b/plain.txt @@ -0,0 +1,4 @@ +Optparse is a more convenient, flexible, and powerful library for parsing command-line options than the old getopt module. +optparse uses a more declarative style of command-line parsing: you create an instance of OptionParser, populate it with options, +and parse the command line. optparse allows users to specify options in the conventional GNU/POSIX syntax, and additionally generates +usage and help messages for you.
johnboxall/deviceatlas
96cc14bb863e744e5e5ac536246c1fecc7471e37
+ readme
diff --git a/README b/README deleted file mode 100644 index e69de29..0000000 diff --git a/README.md b/README.md new file mode 100644 index 0000000..33e67a2 --- /dev/null +++ b/README.md @@ -0,0 +1,25 @@ +Unofficial Python Device Atlas API +================================= + +About +----- + +_Device Atlas:http://deviceatlas.com/ is a database of mobile device information. The official is available at http://deviceatlas.com/downloads. This API is just a bit more awesome. + +**Official API:** + + >>> import api + >>> DA = api.DaApi() + >>> tree = DA.getTreeFromFile('DeviceAtlas.json') + >>> DA.getTreeRevision(tree) + >>> ua = 'SonyEricssonW850i/R1GB Browser/NetFront/3.3 Profile/MIDP-2.0 Configuration/CLDC-1.1' + >>> DA.getProperties(tree, ua) + {u'gprs': '1', u'mpeg4': '1', u'drmOmaForwardLock': '1', ... + +**Awesome API:** + + >>> from deviceatlas import DeviceAtlas + >>> DA = DeviceAtlas(''DeviceAtlas.json') + >>> ua = 'SonyEricssonW850i/R1GB Browser/NetFront/3.3 Profile/MIDP-2.0 Configuration/CLDC-1.1' + >>> DA.device(ua) + {u'gprs': '1', u'mpeg4': '1', u'drmOmaForwardLock': '1', ... \ No newline at end of file
johnboxall/deviceatlas
d38d1a547772fb5c26463c5240b518ea124420c4
Minor updates & comments.
diff --git a/deviceatlas.py b/deviceatlas.py index 6b3754a..df60cd1 100644 --- a/deviceatlas.py +++ b/deviceatlas.py @@ -1,128 +1,121 @@ """ -Revised DeviceAtlas API: +Re-imagined DeviceAtlas API: >>> from deviceatlas import DeviceAtlas >>> DA = DeviceAtlas('/Users/johnboxall/git/device/DeviceAtlas.json') >>> ua = 'Mozilla/5.0 (SymbianOS/9.2; U; Series60/3.1 NokiaN95/11.0.026; Profile MIDP-2.0 Configuration/CLDC-1.1) AppleWebKit/413 (KHTML, like Gecko) Safari/413' >>> n95 = DA.device(ua) >>> n95.model 'N95' ->>> """ import simplejson # Mapping from DA property types to Python types. PROPERTY_MAP = dict(s=str, b=bool, i=int, d=str) class Device(dict): """ - Thin wrapper around a `dict` that allows keys to be accessed like attributes. + Thin wrapper `dict` that allows keys to be accessed like attributes. Returns `None` if the accessed attribute does not exist. """ def __init__(self, data): super(Device, self).__init__(data) def __getattr__(self, name): try: return self[name] except IndexError: return None class DeviceAtlas(object): def __init__(self, jsonpath): """ - Open `jsonpath` and loader in. + Loads and initializes DA JSON from `jsonpath`. + """ self.data = simplejson.load(open(jsonpath, 'r')) # Turn the Device Atlas properties into a dictionary: # {<da_property_id>: (<property_name>, <python_type_function>), ... } self.data['properties'] = {} for index, value in enumerate(self.data['p']): - property_index = str(index) + property_index = str(index) # DA properties are typed as strs property_name = value[1:] property_type = PROPERTY_MAP[value[0]] self.data['properties'][property_index] = (property_name, property_type) # Change all lists in data to dicts. self.data = list2dict(self.data) def device(self, ua): """ - Given a User-Agent string return a `Device` for that UA. + Returns a `Device` for a User-Agent string `ua`. """ return Device(self._getProperties(ua.strip())) def _getProperties(self, ua): """ - Given a User-Agent string return a `dict` of all known properties. + Returns a `dict` of device properties given a User-Agent string `ua`. """ idProperties = {} matched = '' sought = None - sought, matched = self._seekProperties(self.data['t'], ua, idProperties, sought, matched) + sought, matched = self._seekProperties(ua, idProperties, sought, matched) properties = {} for index, value in idProperties.iteritems(): properties[self.data['properties'][index][0]] = self.data['properties'][index][1](value) properties['_matched'] = matched properties['_unmatched'] = ua[len(matched):] return properties - def _seekProperties(self, node, string, properties, sought, matched): + def _seekProperties(self, unmatched, properties, sought, matched, node=None): """ - Seek properties for a UA within a node - This is designed to be recursed, and only externally called with the - node representing the top of the tree - - `node` is array - `string` is string - `properties` is properties found - `sought` is properties being sought - `matched` is part of UA that has been matched - - """ - unmatched = string + Seek properties for a UA within `node` starting at the top of the tree. + + """ + if node is None: + node = self.data['t'] if 'd' in node: - if sought != None and len(sought) == 0: + if sought is not None and len(sought) == 0: return sought, matched for property, value in node['d'].iteritems(): - if sought == None or sought.has_key(property): + if sought is None or property in sought: properties[property] = value - if (sought != None and - ( (not node.has_key('m')) or (node.has_key('m') and (not node['m'].has_key(property)) ) ) ): - if sought.has_key(property): + if sought is not None and \ + (('m' not in node) or ('m' in node and property not in node['m'])): + if property in sought: del sought[property] - + if 'c' in node: - for c in range(1, len(string)+1): - seek = string[0:c] + for c in range(1, len(unmatched)+1): + seek = unmatched[0:c] if seek in node['c']: matched += seek - sought, matched = self._seekProperties(node['c'][seek], string[c:], properties, sought, matched) + sought, matched = self._seekProperties(unmatched[c:], properties, sought, matched, node['c'][seek]) break return sought, matched def list2dict(tree): """ Recursively changes lists in passed tree to dictionaries with string index keys. """ if isinstance(tree, dict): # `tree` is a dict - convert any list items into dictionaries. for key, item in tree.iteritems(): if isinstance(item, dict) or isinstance(item, list): tree[key] = list2dict(item) elif isinstance(tree, list): # `tree` is a list - convert it to a dictionary. tree = dict((str(i), item) for i, item in enumerate(tree)) tree = list2dict(tree) return tree \ No newline at end of file
johnboxall/deviceatlas
d3895241735cfc7fe6f607c51da97c4811fa1823
initial import.
diff --git a/README b/README new file mode 100644 index 0000000..e69de29 diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/deviceatlas.py b/deviceatlas.py new file mode 100644 index 0000000..6b3754a --- /dev/null +++ b/deviceatlas.py @@ -0,0 +1,128 @@ +""" +Revised DeviceAtlas API: + +>>> from deviceatlas import DeviceAtlas +>>> DA = DeviceAtlas('/Users/johnboxall/git/device/DeviceAtlas.json') +>>> ua = 'Mozilla/5.0 (SymbianOS/9.2; U; Series60/3.1 NokiaN95/11.0.026; Profile MIDP-2.0 Configuration/CLDC-1.1) AppleWebKit/413 (KHTML, like Gecko) Safari/413' +>>> n95 = DA.device(ua) +>>> n95.model +'N95' +>>> + +""" +import simplejson + + +# Mapping from DA property types to Python types. +PROPERTY_MAP = dict(s=str, b=bool, i=int, d=str) + + +class Device(dict): + """ + Thin wrapper around a `dict` that allows keys to be accessed like attributes. + Returns `None` if the accessed attribute does not exist. + + """ + def __init__(self, data): + super(Device, self).__init__(data) + + def __getattr__(self, name): + try: + return self[name] + except IndexError: + return None + + +class DeviceAtlas(object): + def __init__(self, jsonpath): + """ + Open `jsonpath` and loader in. + """ + self.data = simplejson.load(open(jsonpath, 'r')) + # Turn the Device Atlas properties into a dictionary: + # {<da_property_id>: (<property_name>, <python_type_function>), ... } + self.data['properties'] = {} + for index, value in enumerate(self.data['p']): + property_index = str(index) + property_name = value[1:] + property_type = PROPERTY_MAP[value[0]] + self.data['properties'][property_index] = (property_name, property_type) + # Change all lists in data to dicts. + self.data = list2dict(self.data) + + def device(self, ua): + """ + Given a User-Agent string return a `Device` for that UA. + + """ + return Device(self._getProperties(ua.strip())) + + def _getProperties(self, ua): + """ + Given a User-Agent string return a `dict` of all known properties. + + """ + idProperties = {} + matched = '' + sought = None + sought, matched = self._seekProperties(self.data['t'], ua, idProperties, sought, matched) + properties = {} + for index, value in idProperties.iteritems(): + properties[self.data['properties'][index][0]] = self.data['properties'][index][1](value) + properties['_matched'] = matched + properties['_unmatched'] = ua[len(matched):] + return properties + + def _seekProperties(self, node, string, properties, sought, matched): + """ + Seek properties for a UA within a node + This is designed to be recursed, and only externally called with the + node representing the top of the tree + + `node` is array + `string` is string + `properties` is properties found + `sought` is properties being sought + `matched` is part of UA that has been matched + + """ + unmatched = string + + if 'd' in node: + if sought != None and len(sought) == 0: + return sought, matched + for property, value in node['d'].iteritems(): + if sought == None or sought.has_key(property): + properties[property] = value + if (sought != None and + ( (not node.has_key('m')) or (node.has_key('m') and (not node['m'].has_key(property)) ) ) ): + if sought.has_key(property): + del sought[property] + + if 'c' in node: + for c in range(1, len(string)+1): + seek = string[0:c] + if seek in node['c']: + matched += seek + sought, matched = self._seekProperties(node['c'][seek], string[c:], properties, sought, matched) + break + + return sought, matched + + +def list2dict(tree): + """ + Recursively changes lists in passed tree to dictionaries with + string index keys. + + """ + if isinstance(tree, dict): + # `tree` is a dict - convert any list items into dictionaries. + for key, item in tree.iteritems(): + if isinstance(item, dict) or isinstance(item, list): + tree[key] = list2dict(item) + elif isinstance(tree, list): + # `tree` is a list - convert it to a dictionary. + tree = dict((str(i), item) for i, item in enumerate(tree)) + tree = list2dict(tree) + return tree \ No newline at end of file
troter/object-oriented-exercise
33e5a577d1b62fb471b0ab7682ec8237eb2abc49
add AccessURL.php
diff --git a/refactoring/blosxom.php-1.0/classes/blosxom/AccessURL.php b/refactoring/blosxom.php-1.0/classes/blosxom/AccessURL.php new file mode 100644 index 0000000..e2f653d --- /dev/null +++ b/refactoring/blosxom.php-1.0/classes/blosxom/AccessURL.php @@ -0,0 +1,36 @@ +<?php +class AccessURL { + protected $url; + function __construct() { + $this->url = $this->build_access_url(); + } + + function url() { + return $this->url; + } + + private function is_https() { + return array_key_exists("HTTPS", $_SERVER) && $_SERVER["HTTPS"] == "ON"; + } + + private function is_default_port_for_protocol($protocol, $port) { + if ($protocol === "https" && $port == 443) + return true; + if ($protocol === "http" && $port == 80) + return true; + return false; + } + + private function build_access_url() { + $protocol = $this->is_https() ? "https" : "http"; + $server_name = $_SERVER['SERVER_NAME']; + $server_port = $_SERVER['SERVER_PORT']; + $script_name = $_SERVER['SCRIPT_NAME']; + + $url = "${protocol}://${server_name}"; + if (! $this->is_default_port_for_protocol($protocol, $port)) + $url = "${url}:${server_port}"; + $url = "${url}${script_name}"; + return $url; + } +} diff --git a/refactoring/blosxom.php-1.0/test/classes/AccessURLTest.php b/refactoring/blosxom.php-1.0/test/classes/AccessURLTest.php new file mode 100644 index 0000000..491989f --- /dev/null +++ b/refactoring/blosxom.php-1.0/test/classes/AccessURLTest.php @@ -0,0 +1,16 @@ +<?php +require_once 'blosxom/AccessURL.php'; +require_once 'PHPUnit/Framework.php'; + +class AccessURLTest extends PHPUnit_Framework_TestCase +{ + public function testSample() { + $_SERVER['SERVER_NAME'] = 'localhost'; + $_SERVER['SERVER_PORT'] = '8080'; + $_SERVER['SCRIPT_NAME'] = '/user/edit'; + $a = new AccessURL(); + $this->assertEquals("http://localhost:8080/user/edit", $a->url()); + } +} + +?> \ No newline at end of file
troter/object-oriented-exercise
c540dc7452ee91eef4389816ab03069606f1f2c0
add target
diff --git a/refactoring/blosxom.php-1.0/build.xml b/refactoring/blosxom.php-1.0/build.xml index e69de29..010db5f 100644 --- a/refactoring/blosxom.php-1.0/build.xml +++ b/refactoring/blosxom.php-1.0/build.xml @@ -0,0 +1,48 @@ +<?xml version="1.0"?> +<project name="Blosxom.PHP-refactor-builder" default="build" basedir="."> + + <property name="src.dir" value="./src" /> + <property name="classes.dir" value="./classes" /> + <property name="build.dir" value="./build" /> + <property name="build.log.dir" value="${build.dir}/log" /> + <property name="test.dir" value="./test" /> + + <path id="project.classes.path" > + <pathelement dir="${classes.dir}"/> + </path> + <includepath classpathRef="project.classes.path" /> + + <target name="clean"> + <delete dir="${build.dir}"/> + </target> + + <target name="prepare"> + <mkdir dir="${build.log.dir}"/> + </target> + + <target name="phpunit"> + <phpunit printsummary="true" haltonfailure="true"> + <formatter todir="${build.log.dir}" type="xml"/> + <batchtest> + <fileset dir="${test.dir}"> + <include name="**/*Test.php"/> + </fileset> + </batchtest> + </phpunit> + </target> + + <target name="build" depends="clean,prepare,phpunit"/> + + <target name="dist" /> + + <target name="lint" description="php lint"> + <phplint> + <fileset dir="${src.dir}"> + <include name="**/*.php" /> + </fileset> + <fileset dir="${classes.dir}"> + <include name="**/*.php" /> + </fileset> + </phplint> + </target> +</project>
troter/object-oriented-exercise
1911b710c1e2cf87aea41a61c5921110878872b8
add phing build file
diff --git a/refactoring/blosxom.php-1.0/build.xml b/refactoring/blosxom.php-1.0/build.xml new file mode 100644 index 0000000..e69de29
troter/object-oriented-exercise
d4acc54be83f27b23992885bfa3cd4e3bdfc0a12
move source file
diff --git a/refactoring/blosxom.php-1.0/src/blosxom.php b/refactoring/blosxom.php-1.0/src/blosxom.php new file mode 100644 index 0000000..0eec76f --- /dev/null +++ b/refactoring/blosxom.php-1.0/src/blosxom.php @@ -0,0 +1,426 @@ +<?php +# Blosxom.PHP: a rewrite of PHPosxom, which is a PHP rewrite of Blosxom +# HELPER FUNCTIONS + +function is_empty_string($str) { + return is_string($str) && strlen($str) == 0; +} +function is_empty_array($array) { + return is_array($array) && empty($array); +} + +# Returns real path +function rpath($wd, $path) +{ + if (is_empty_string($path)) { + if ($path[0] != "/") + $path = $wd."/".$path; + } else + $path = $wd; + return realpath($path); +} + +# Reads config +function readconf() +{ + global $conf; + + if (isset($conf) && is_empty_array($conf)) + foreach (array_keys($conf) as $key) + if (isSaneFilename($key)) + $GLOBALS["conf_".$key] = &$conf[$key]; +} + +# Reads config defaults +function readconfdefs() +{ + global $confdefs; + + if (isset($confdefs) && is_empty_array($confdefs)) + foreach (array_keys($confdefs) as $key) + if (isSaneFilename($key) && !array_key_exists("conf_".$key, $GLOBALS)) + $GLOBALS["conf_".$key] = &$confdefs[$key]; +} + +# Checks whether file name is valid +function isSaneFilename($txt) +{ + return !strcspn($txt, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890_-."); +} + +function parseText($txt) +{ + $txt = str_replace("\n\n", "</p><crlf><p class=\"blog\">", $txt); + $txt = preg_replace("'>\s*\n\s*<'", "><crlf><", $txt); + $txt = str_replace("\n", "<br />", $txt); + $txt = str_replace("<crlf>", "\n", $txt); + return "<p>$txt</p>"; +} + +function w3cdate($time) +{ + $date = date("Y-m-d\TH:i:sO", $time); + return substr($date, 0, 22).":".substr($date, 22, 2); +} + +# Generates GET URL from GET variables, and add/del arrays +function genurl($add = false, $del = array("cmd")) +{ + global $whoami; + + $arr = $_GET; + if (is_array($del)) foreach ($del as $d) + if (isset($arr[$d])) + unset ($arr[$d]); + if (is_array($add)) foreach ($add as $a=>$key) + $arr[$a] = $key; + $url = array(); + foreach ($arr as $key=>$val) + $url[] = "$key=".rawurlencode($val); + return "$whoami?".implode("&amp;", $url); +} + +$GLOBALS['__catcache'] = array(); + +# Returns category name +function displaycategory($cat, $href=false) +{ + global $__catcache, $categories, $conf_category_delimiter; + + $ccindex = $cat.":".$href; + if (@array_key_exists($ccindex, $__catcache)) + return $__catcache[$ccindex]; + $cats = explode("/", $cat); + $fullcat = ""; + for ($i = 0; $i < count($cats); ++$i) { + $fullcat .= $cats[$i]; + if (@array_key_exists($fullcat, $categories)) + $cats[$i] = $categories[$fullcat]; + if ($href) + $cats[$i] = "<a href=\"$href".$fullcat."\">".$cats[$i]."</a>"; + $fullcat .= "/"; + } + $ret = implode($conf_category_delimiter, $cats); + $__catcache[$ccindex] = $ret; + return $ret; +} + +class Blog { + var $src; + var $path; + var $fp; + var $title; + var $date; + var $mod; + var $author; + var $link; + var $alias; + var $valid; + var $lead; + var $contents; + var $cat; + var $displaycat; + + function Blog($key, $src=false) + { + global $conf_datadir, $conf_sources; + global $blogs, $mfdb, $pubdates, $force; + global $daysBlogged, $dateFilter, $dateFilterType; + global $authorFilter, $entryFilter; + + $this->valid = false; + $this->path = $key; + + + $indb = $mdata = false; + if (is_object($mfdb)) + $mdata = $mfdb->fetch($key); + if (is_array($mdata)) { + if ($src !== false && $mdata[1] != $src) { + if (!file_exists(rpath($conf_datadir, + $conf_sources[$mdata[1]]['path'].$key))) + $mfdb->delete($key); + else { + # concurring blog entries: drop it + error_log("Concurring blog entries. New: $fp, orig: $origfp"); + return; + } + } else { + $indb = true; + $date = $mdata[0]; + $src = $mdata[1]; + $title = $mdata[2]; + $fd =& $conf_sources[$src]['fp']; + $fp = $fd.$key; + } + } + if (!isset($fp)) { + if (!$src) { + foreach (array_keys($conf_sources) as $s) { + $fd =& $conf_sources[$s]['fp']; + $fp = $fd.$key; + if (file_exists($fp)) { + $src = $s; + break; + } + } + } else { + $fd =& $conf_sources[$src]['fp']; + $fp = $fd.$key; + } + } + if (!strlen($fp) || !file_exists($fp)) { + if ($mfdb) + $mfdb->delete($key); + return false; + } + if (is_link($fp)) { + $rfp = realpath($fp); + if (file_exists($rfp) && !strncmp($fd, $rfp, strlen($fd))) { + $nkey = substr($rfp, strlen($fd)); + if ($indb) { + $mfdb->replace($nkey, $mdata); + $mfdb->delete($key); + } + } + return false; + } + + $mod = filemtime($fp); + + $this->date = ($indb && $date)? $date: $mod; + $this->mod = $mod; + $this->src = $src; + $this->title = isset($title)? trim($title): ""; + $this->fp = $fp; + $this->author = $conf_sources[$src]["author"]; + $this->link = $conf_sources[$src]["link"]; + $this->alias = $src; + + $daysBlogged[date("Ymd", $this->date)] = 1; + if (($dateFilter && date($dateFilterType, $this->date) != $dateFilter) + || ($entryFilter && $key != $entryFilter) + || ($authorFilter && $src != $authorFilter)) + return; + + # Everything is OK, mark it as valid data + $this->valid = true; + + if ($force || !$indb) { + $fh = fopen($fp, "r"); + $this->title = fgets($fh, 1024); + fclose($fh); + if ($mfdb) + $mfdb->replace($key, array($this->date,$src,$this->title)); + } + $pubdates[] = $mod; + $blogs[$this->path] = $this; + } + + function isValid() { return $this && $this->valid; } + function getContents($short = false) + { + if (!$this || !$this->valid) + return; + if (!$this->contents) { + if (!file_exists($this->fp)) + return false; + $contents = file($this->fp); + $this->title = array_shift($contents); + $this->format = array_shift($contents); + $this->short = $contents[0]; + $this->contents = join("", $contents); + } + return $short? $this->short: $this->contents; + } + function getCategory() + { + if (!$this || !$this->valid) + return; + if (!$this->cat) + $this->cat = substr($this->path, 1, strrpos($this->path, '/')-1); + return $this->cat; + } +} + +function checkDir($src, $dir = "", $level = 1) +{ + global $conf_depth, $conf_sources; + global $cats, $categoryFilter; + + if ($conf_depth && $level > $conf_depth) + return; + $cats[] = $dir; + $inCatFilter = !$categoryFilter || !strncmp($dir, $categoryFilter, strlen($categoryFilter)); + $datadir = rpath($conf_sources[$src]['fp'], $dir); + $dh = opendir($datadir); + if (!is_resource($dh)) + return; + if ($level > 1) + $dir .= "/"; + $datadir .= "/"; + while (($fname = readdir($dh)) !== false) { + if ($fname[0] == '.') + continue; + $path = $dir.$fname; + $opath = false; + $fulln = $datadir.$fname; + if (is_dir($fulln)) + checkDir($src, $path, $level+1); + elseif (substr($fname, -4) == '.txt' && $inCatFilter) + new Blog("/".$path, $src); + } +} + +function checkSources($force) +{ + global $conf_datadir, $conf_sources; + global $mfdb, $cats, $categoryFilter; + global $entryFilter, $blogs, $whoami; + + if (!count($conf_sources)) + return; + foreach (array_keys($conf_sources) as $src) + $conf_sources[$src]['fp'] = rpath($conf_datadir, $conf_sources[$src]['path']); + if ($force) { + foreach (array_keys($conf_sources) as $src) + checkDir($src); + } elseif ($key = $mfdb->first()) { + $cats[] = ""; + do { + if ($key[0] != "/") + $key = "/$key"; + $dir = substr($key, 1, strrpos($key, "/")-1); + $cats[] = $dir; + if (!$categoryFilter || !strncmp($dir, $categoryFilter, strlen($categoryFilter))) + new Blog($key); + } while ($key = $mfdb->next()); + $cats = array_unique($cats); + sort($cats); + } + if ($entryFilter && !isset($blogs[$entryFilter])) { + foreach (array_keys($conf_sources) as $s) { + $fd =& $conf_sources[$s]['fp']; + $fp = realpath($fd.$entryFilter); + if (file_exists($fp) && !strncmp($fd, $fp, strlen($fd))) { + $nkey = substr($fp, strlen($fd)); + header("Location: ".genurl( + array("entry"=>$nkey), + array("cmd") + )); + exit; + } + } + } +} + +function checkDateFilter($filter) +{ + global $dateFilterType; + $dateFilterLen = strlen($filter); + if ($dateFilterLen == 4 or $dateFilterLen == 6 or $dateFilterLen == 8) { + $dateFilterType = substr("Ymd", 0, ($dateFilterLen-2)/2); + return $filter; + } else { + if ($dateFilterLen < 4) + print explainError("shortdate"); + elseif ($dateFilterLen > 8) + print explainError("longdate"); + elseif ($dateFilterLen == 5 or $dateFilterLen == 7 or is_numeric($dateFilter) == false) + print explainError("wrongdate"); + return false; + } +} + +/** + * authenticates user + * This is a basic authentication method for authenticating source + * writers. + */ + +function authUser() +{ + global $NAME, $conf_sources, $cmd; + + $src =& $_SERVER["PHP_AUTH_USER"]; + $pass =& $_SERVER["PHP_AUTH_PW"]; + + if ((!isset($src) && $cmd == "login") + || (isset($src) && $cmd == "logout")) { + echo explainError("autherr"); + exit; + } + + if ($cmd == "login" && (!isset($conf_sources[$src]) + || !isset($conf_sources[$src]['pass']) + || $pass != $conf_sources[$src]['pass'])) { + echo explainError("autherr"); + exit; + } + if (isset($src)) + define("USER", $src); +} + +function explainError($x, $p = false) +{ + switch ($x) { + case "autherr": + header('WWW-Authenticate: Basic realm="'.$NAME.'"'); + header('HTTP/1.0 401 Unauthorized'); + return <<<End +<html> +<head> +<title>Authentication Error</title> +</head> +<body><h1>Authentication Error</h1> + +<p>You have to log in to access this page.</p> +</body> +</html> +End; + case "nomod": + return <<<End +<p class="error"><strong>Cannot find module $p.</strong> Please check filenames.</p> +End; + case "noflavs": + return <<<End +<p class="error"><strong>Warning: Couldn&apos;t find a flavour file.</strong> +It means that the blog is in an inconsistent stage. Please alert the blog +maintainer.</p> +End; + case "permissions": + return <<<End +<p class="error"><strong>Warning: There&apos;s something wrong with the $ff +folder&apos;s permissions.</strong> Please make sure it is readable by the www +user and not just your selfish self.</p> +End; + case "shortdate": + return <<<End +<p class="error"><strong>The date you entered as a filter seems to be too short +to work.</strong> Either that or this server has gone back in time. Please +check the date and try again. In the case of the latter, the Temporal +Maintenance Agency will have had knocked on your door by now.</p> +End; + case "longdate": + return <<<End +<p class="error"><strong>Either the date you entered as a filter is too long to +work, or we&apos;re having a Y10K error.</strong> If it&apos;s not the year +10,000, please check the date and try again. If it is, tell Hackblop-4 from +Pod Alpha -22-Pi we said hey.</p> +End; + case "wrongdate": + return <<<End +<p class="error"><strong>Something is screwy with the date you entered.</strong> +It has the wrong number of digits, like that famous sideshow attraction +Eleven-Fingered Elvira, or contains non-numeric characters. Speaking of +characters, you should check the date and try again.</p> +End; + case "noentries": + return <<<End +<p class="error"><strong>No Results.</strong> The combination of filters for +this page has resulted in no entries. Try another combination of dates, +categories, and authors.</p> +End; + } +} +?> diff --git a/refactoring/blosxom.php-1.0/src/conf-dist.php b/refactoring/blosxom.php-1.0/src/conf-dist.php new file mode 100644 index 0000000..a88657d --- /dev/null +++ b/refactoring/blosxom.php-1.0/src/conf-dist.php @@ -0,0 +1,66 @@ +<?php +# PHPosxom configuration file +# included by Blosxom.PHP + +$conf = array( +# What's this blog's title? + 'title' => "$NAME Blog" +# What's this blog's description? (for blog pages and outgoing RSS feed) + ,'description' => "Playing with $NAME" +# What's this blog's primary language? (for language settings, blog pages and outgoing RSS feed) + ,'language' => "en" +# What's this blog's character set? +# it can be utf-8, us-ascii, iso-8859-1, iso-8859-15, iso-8859-2 etc. + ,'charset' => "utf-8" +# Are blog bodies in (x)html? + ,'html_format' => false +# Where are this blog''s data kept? + ,'datadir' => "/Library/WebServer/Documents/blog" +# Where are your blog entries kept? You can use relative path from where your datadir is. + ,'category_delimiter' => " » " +# Where are your modules kept? You can use relative path from where index.php is. + ,'moddir' => "modules" +# Where are your flavours kept? You can use relative path from where index.php is. + ,'flavdir' => "flavs" +# Full URL to CSS file (if you have one) + ,'cssURL' => "blog.css" +# Metadata system keeps track of blog entries and their issue date to keep +# original order. To use this system, set metafile from false to an array +# (path is the database file, type is its type). + ,'metafile' => false #"db4:///metadata.db" +# Blog entry sources. All sources are read, each for an author. +# Each source entry is a name-description pair. +# Name is usually the author''s short name. +# Description is a list of key-value pairs: +# author: author''s full name +# link: link to author (any URL; use mailto: for email links) +# path: where author''s blog entries are kept (can be relative to datadir) + ,'sources' => array( + 'default' => array( + 'author' => "Default Author" + ,'link' => "mailto:foo&#40;bar.com" + ,'path' => "" + ) + ) +# Do you want to use the categories file system? Type false or a file name. +# If yes, list them in +# path = name +# format. + ,'categoriesfile' => false # "categories" +# An author can force recheck directories and put updates to metafile +# if a GET variable is set (eg. http://.../index.php?force=1) or +# a force file is in its place. The file will be deleted after the first +# update. The path is relative to datadir. + ,'forcefile' => "force" +# Should I stick only to the datadir for items or travel down the +# directory hierarchy looking for items? If so, to what depth? +# 0 = infinite depth (aka grab everything), 1 = source dir only, n = n levels +# down + ,'depth' => 0 +# How many entries should be shown per page? + ,'entries' => 10 +# EXTERNAL MODULES +# (should be in moddir and named with .php extension) + ,'modules' => array() +); +?> diff --git a/refactoring/blosxom.php-1.0/src/dbahandler.php b/refactoring/blosxom.php-1.0/src/dbahandler.php new file mode 100644 index 0000000..89818e3 --- /dev/null +++ b/refactoring/blosxom.php-1.0/src/dbahandler.php @@ -0,0 +1,483 @@ +<?php # -*- coding: utf-8 -*- +# DBA handler +# Written by Balazs Nagy <[email protected]> +# Version: 2005-02-09 +# +# Call it as DBA::singleton($dsn), because only assures that already opened +# connections aren''t opened again, and it allows use of implicit closes + +$GLOBALS["__databases"] = false; +$GLOBALS["confdefs"]["dba_default_persistency"] = true; +$GLOBALS["debug"] = false; + +function debug_log($str) { + if (isset($GLOBALS["debug"]) && $GLOBALS["debug"] === true) + error_log($str); +} + +class DBA_DSN +{ + private $dsn; + private $query; + + function __construct(string $dsn) { + list($this->dsn, $this->query) = parse($dsn); + } + + /** + * $dsn = "<driver>://<username>:<password>@<host>:<port>/<database>?<query>" + */ + private function parse(string $dsn) { + $query = ""; + if (strpos('\?', $dsn) !== false) + list($dsn, $query) = split('\?', $dsn, 2); + $parsed_query = $this->parse_str($query); + $parsed_dsn = $this->parse_dsn($dsn); + return array($parsed_query, $parsed_dsn); + } + + private function parse_str(string $query) { + parse_str($query, $parsed_query); + $parsed_query['mode'] = new DBA_Option_OpenMode($parsed_query['mode']); + $parsed_query['onopen'] = new DBA_Option_OnOpenHandler($parsed_query['onopen']); + $parsed_query['persistent'] = new DBA_Option_Persistent($parsed_query['persistent']); + return $parsed_query; + } + + private function parse_dsn(string $dsn) { + $parsed_query = array( + 'scheme' => '', + 'user' => '', + 'password' => '', + 'host' => '', + 'port' => '', + 'database' => '', + ); + + $parsed_query['scheme'] = new DBA_DSN_Scheme($parsed_query['scheme']); + $parsed_query['user'] = new DBA_DSN_User($parsed_query['user']); + $parsed_query['password'] = new DBA_DSN_Password($parsed_query['password']); + $parsed_query['host'] = new DBA_DSN_Host($parsed_query['host']); + $parsed_query['port'] = new DBA_DSN_Port($parsed_query['port']); + $parsed_query['database'] = new DBA_DSN_Database($parsed_query['database']); + return $parsed_query; + } +} + +class DBA_DSN_Scheme { + private $scheme; + function __construct(string $scheme) { + $this->scheme = $scheme; + } + function value() { + return $this->scheme; + } + function has_dba_handler() { + $handler_name = $this->scheme; + return function_exists("dba_handlers") + && in_array($handler_name, dba_handlers()); + } +} + +class DBA_DSN_User { + private $user; + function __construct(string $user) { + $this->user = $user; + } + function value() { + return $this->user; + } +} + +class DBA_DSN_Password { + private $password; + function __construct(string $password) { + $this->password = $password; + } + function value() { + return $this->password; + } +} + +class DBA_DSN_Host { + private $host; + function __construct(string $host) { + $this->host = $host; + } + function value() { + return $this->host; + } +} + +class DBA_DSN_Port { + private $port; + function __construct(string $port) { + $this->port = $port; + } + function value() { + return $this->port; + } +} + +class DBA_DSN_Database { + private $database; + function __construct(string $database) { + $this->database = $database; + } + function value() { + return $this->database; + } + function realpath() { + return ""; + } +} + +class DBA_Option { + +} + +class DBA_Option_OpenMode { + private $mode; + function __construct(string $mode) { + $this->mode = $mode; + } + function is_create() { return $this->mode == "c"; } + function is_readonly() { return $this->mode == "r"; } + function is_readwrite_or_create() { return $this->mode == "w"; } + function is_unknown() { + return !($this->is_create() || + $this->is_readonly() || + $this->is_readwrite_or_create()); + } +} + +class DBA_Option_OnOpenHandler { + private $handler_function_name; + function __construct(string $handler_function_name) { + $this->handler_function_name = $handler_function_name; + } + function call() { + if (function_exists($this->handler_function_name)) + call_user_func($this->handler_function_name); + } +} + +class DBA_Option_Persistent { + private $condition; + function __construct($condition) { + $this->condition = $condition; + } + function is_enable() { + return preg_match("true|1|on|enabled", $condition) === 1; + } +} + +class DBA +{ + var $dsn; + var $info; + var $res; + var $opt; + var $handler; + + /** Creates a new DBA object defined by dsn. + * It assures that the same DBA object is returned to the same dsn''s + * @param $dsn text Data Source Name: type:///file/opt=val&opt2=val2... + * Each file can be relative to datadir. + * Valid options: + * persistent=true|1|on|enabled: enables persistency. Any others disables + * onopen=functionname: calls function if new database is created + * mode=c|r|w: open mode. c-create new, r-readonly, w-readwrite or create + */ + function &singleton($dsn) + { + $dbs = &$GLOBALS["__databases"]; + if (isset($dbs[$dsn])) { + debug_log("DBA::singleton: get old db as $dsn"); + $that = &$dbs[$dsn]; + } else { + $that = new DBA($dsn); + $dbs[$dsn] = &$that; + debug_log("DBA::singleton: create new db as $dsn"); + } + return $that; + } + + function closeall() + { + $dbs = &$GLOBALS["__databases"]; + if (is_array($dbs) && count($dbs)) foreach ($dbs as $db) + $db->close(); + } + + # quick and dirty DSN parser + function __parseDSN($dsn) + { + $ret = array( + "scheme" => "", + "path" => "", + "query" => "" + ); + $off = strpos($dsn, "://"); + if ($off !== false) + $ret["scheme"] = substr($dsn, 0, $off); + $off += 3; + $off2 = strpos($dsn, "/", $off); + if ($off2 !== false) + $off = $off2; + $off += 1; + $off2 = strpos($dsn, "?", $off); + if ($off2 !== false) { + $ret["path"] = substr($dsn, $off, $off2-$off); + $ret["query"] = substr($dsn, $off2+1); + } else + $ret["path"] = substr($dsn, $off); + return $ret; + } + + function DBA($dsn) + { + // 必要ない? + $this->dsn = $dsn; + $info = DBA::__parseDSN($dsn); + if (!isset($info["scheme"])) + return false; + $this->info = $info; + $this->res = false; + $this->handler = $info["scheme"]; + if (!function_exists("dba_handlers") + || !in_array($this->handler, dba_handlers())) + $this->handler = false; + if (strlen($info["query"])) + parse_str($info["query"], $this->opt); + } + + function &getOpt($opt) + { + if (!$this || !is_a($this, "DBA") || $this->res !== false) + return false; + $ret =& $this->opt[$opt]; + if (isset($ret)) + return $ret; + return null; + } + + function isOpt($opt, $val) + { + $ret =& getOpt($opt); + if (is_bool($val)) + return $ret === $val; + return $ret == $val; + } + + function open() + { + global $conf; + + if (!$this || !is_a($this, "DBA")) + return false; + if ($this->res !== false) + return true; + $fn = rpath($conf["datadir"], $this->info['path']); + if ($this->isOpt("mode", "c")) + $mode = "n"; + elseif ($this->isOpt("mode", "r")) { + if (!file_exists($fn)) + return false; + $mode = "r"; + } else { + if (file_exists($fn)) + $mode = "w"; + else { + $mode = "n"; + if (function_exists($this->getOpt("onopen"))) + call_user_func($this->getOpt("onopen")); + } + } + if ($this->handler !== false) { + $persistent =& $this->getOpt("persistent"); + if (!isset($persistent)) + $persistent =& $conf["dba_default_persistency"]; + else + $persistent = strtolower($persistent); + switch ($persistent) { + case true: + case "1": + case "on": + case "true": + case "enabled": + $caller = "dba_popen"; + break; + default: + $caller = "dba_open"; + } + $this->res = $caller($fn, $mode, $this->handler); + debug_log("$caller($fn, $mode, $this->handler) = $this->res"); + return is_resource($this->res); + } + if (!file_exists($fn) && !is_file($fn) + && !is_readable($fn) && !touch($fn)) + return false; + $mode = !!strstr($mode, "w"); + $this->res = $fn; + $this->cache = array( + "mode" => $mode, + "sync" => true, + "data" => @unserialize(file_get_contents($fn)) + ); + return true; + } + + function close() + { + if (!$this || !is_a($this, "DBA") || $this->res === false) + return false; + if ($this->handler) { + dba_close($this->res); + debug_log("dba_close($this->res)"); + } else { + $this->sync(); + $this->cache = false; + } + $this->res = false; + } + + function first() + { + if (!$this || !is_a($this, "DBA")) + return false; + if (!$this->open()) + return false; + if ($this->handler) { + $key = dba_firstkey($this->res); + debug_log("dba_firstkey($this->res)"); + return $key; + } + if (!is_array($this->cache["data"]) || !count($this->cache["data"])) + return false; + if (reset($this->cache["data"]) === false) + return false; + return key($this->cache["data"]); + } + + function next() + { + if (!$this || !is_a($this, "DBA")) + return false; + if (!$this->open()) + return false; + if ($this->handler) { + debug_log("dba_nextkey($this->res)"); + return dba_nextkey($this->res); + } + if (!is_array($this->cache["data"]) || !count($this->cache["data"])) + return false; + if (next($this->cache["data"]) === false) + return false; + return key($this->cache["data"]); + } + + function fetch($key) + { + if (!$this || !is_a($this, "DBA")) + return false; + if (!$this->open()) + return false; + if ($this->handler) { + debug_log("dba_fetch($key, $this->res)"); + $val = dba_fetch($key, $this->res); + if (!is_string($val)) + return null; + $v = @unserialize($val); + if ($v === false && $val != 'b:0;') { + // old value, needs correction + $v = explode(",", $val, 3); + $v[2] = str_replace("&#44;", ",", $v[2]); + dba_replace($key, serialize($v), $this->res); + } + return $v; + } + if (!is_array($this->cache["data"]) || !count($this->cache["data"]) || !isset($this->cache["data"][$key])) + return false; + return $this->cache["data"][$key]; + } + + function insert($key, $val) + { + if (!$this || !is_a($this, "DBA")) + return false; + if (!$this->open()) + return false; + if ($this->handler) { + debug_log("dba_insert($key, $val, $this->res)"); + return dba_insert($key, serialize($val), $this->res); + } + if (!is_array($this->cache["data"])) + $this->cache["data"] = array(); + elseif (isset($this->cache["data"][$key])) + return false; + $this->cache["data"][$key] = $val; + $this->cache["sync"] = false; + return true; + } + + function replace($key, $val) + { + if (!$this || !is_a($this, "DBA")) + return false; + if (!$this->open()) + return false; + if ($this->handler) { + debug_log("dba_replace($key, $val, $this->res)"); + return dba_replace($key, serialize($val), $this->res); + } + if (!is_array($this->cache["data"])) + $this->cache["data"] = array(); + debug_log("DBA::replace($key, $val, $this->res)"); + $this->cache["data"][$key] = $val; + $this->cache["sync"] = false; + return true; + } + + function delete($key) + { + if (!$this || !is_a($this, "DBA")) + return false; + if (!$this->open()) + return false; + if ($this->handler) { + debug_log("dba_delete($key, $this->res)"); + return dba_delete($key, $this->res); + } + if (!is_array($this->cache["data"]) || !count($this->cache["data"]) || !isset($this->cache["data"][$key])) + return false; + unset($this->cache["data"][$key]); + $this->cache["sync"] = false; + return true; + } + + function optimize() + { + if (!$this || !is_a($this, "DBA") || $this->res === false || $this->handler === false) + return false; + dba_optimize($this->res); + debug_log("dba_optimize($this->res)"); + } + + function sync() + { + if (!$this || !is_a($this, "DBA") || $this->res === false) + return false; + if ($this->handler && $this->res) { + debug_log("dba_sync($this->res)"); + return dba_sync($this->res); + } + if (!$this->cache["mode"] || $this->cache["sync"]) + return true; + $fh = fopen($this->res, "w"); + fwrite($fh, serialize($this->cache["data"])); + fclose($fh); + return true; + } +} +?> diff --git a/refactoring/blosxom.php-1.0/src/flavs/atom_flav.php b/refactoring/blosxom.php-1.0/src/flavs/atom_flav.php new file mode 100644 index 0000000..f7b13e4 --- /dev/null +++ b/refactoring/blosxom.php-1.0/src/flavs/atom_flav.php @@ -0,0 +1,98 @@ +<?php +# Blosxom.PHP: a rewrite of PHPosxom, which is a PHP rewrite of Blosxom +# ATOM v. 0.3 FLAVOR FILE +# The purpose is to allow you to customize the look and feel of +# your PHPosxom blog without the necessity of using flav=foo in +# the URL or editing the main script. +# +# See: http://www.intertwingly.net/wiki/pie/FrontPage +# ---------------------------------------------------------------- +# USAGE +# There are three functions below that form the head, story, and +# foot blocks on a blog page. +# ---------------------------------------------------------------- +# $content_type lets the browser know what kind of content is being +# served. You''-ll probably want to leave this alone. + +$content_type = "application/atom+xml"; + +function headBlock($category) { + global $conf_title, $conf_description, $conf_language, $conf_charset; + global $lastmod, $whoami, $NAME, $VERSION; + + $thetitle = $conf_title; + if ($category) + $thetitle .= " ($category)"; + $head = '<?xml version="1.0"'; + if (isset($conf_charset) and $conf_charset != 'utf-8') + $head .= " encoding=\"$conf_charset\""; + $head .= "?".">\n"; + $lastpub = w3cdate($lastmod); + return <<<End +${head} +<feed version="0.3" xmlns="http://purl.org/atom/ns#" xml:lang="$conf_language"> + <title>$thetitle</title> + <link rel="alternate" type="text/html" href="$whoami"/> + <modified>$lastpub</modified> + <tagline>$conf_description</tagline> + <generator>$NAME $VERSION</generator> + +End; +} + +function storyBlock($blog) +{ + global $whoami, $conf_cssURL; + + $title = htmlspecialchars($blog->title); + $text = $blog->getContents(true); + $html = htmlspecialchars('<'.<<<End +html> +<head> +<base href="$whoami" /> +<style>@import "$conf_cssURL";</style> +<title>$title</title> +</head> +<body id="rss"> +$text +</body> +</html> +End +); + $author = htmlspecialchars($blog->author); + $authorlink = $blog->link; + if (!strncmp($authorlink, "mailto:", 7)) + $authorlink = "<email>".html_entity_decode(substr($authorlink, 7))."</email>\n"; + else + $authorlink = "<url>$authorlink</url>\n"; + $displaycat = htmlspecialchars(displaycategory($blog->getCategory())); + $path = htmlspecialchars($blog->path); + $date = w3cdate($blog->date); + $mod = $blog['mod']? w3cdate($blog->mod): $date; + $url = $whoami; + $link = $url.htmlspecialchars($blog->path); + $href = $url.rawurlencode($blog->path); + return <<<End +<entry> + <title>$title</title> + <link rel="alternate" type="text/html" href="$link"/> + <id>$whoami:$path</id> + <author> + <name>$author</name> + $authorlink + </author> + <issued>$date</issued> + <modified>$mod</modified> + <content type="text/html" mode="escaped">$html</content> +</entry> + +End; +} + +function footBlock() { + + return <<<End +</feed> +End; +} +?> diff --git a/refactoring/blosxom.php-1.0/src/flavs/default_flav.php b/refactoring/blosxom.php-1.0/src/flavs/default_flav.php new file mode 100644 index 0000000..f2d506e --- /dev/null +++ b/refactoring/blosxom.php-1.0/src/flavs/default_flav.php @@ -0,0 +1,442 @@ +<?php +# Blosxom.PHP: a rewrite of PHPosxom, which is a PHP rewrite of Blosxom +# DEFAULT FLAVOR FILE +# The purpose is to allow you to customize the look and feel of +# your PHPosxom blog without the necessity of using flav=foo in +# the URL or editing the main script. +# ---------------------------------------------------------------- +# USAGE +# There are three functions below that form the head, story, and +# foot blocks on a blog page. +# ---------------------------------------------------------------- +# $content_type lets the browser know what kind of content is being +# served. You''ll probably want to leave this alone. + +$content_type ='text/html'; + +reset($conf_sources); +foreach (array_keys($conf_sources) as $src) { + if (isset($conf_sources[$src]["author"])) { + $cHolder = $conf_sources[$src]["author"]; + break; + } +} + +if ($conf_language == "hu-hu") { + if (!isset($cHolder)) + $cHolder = "a szerzők"; + $msg['archives'] = "Archívum"; + $msg['atomfeed'] = "ATOM feed"; + $msg['blogroll'] = "Blogroll"; + $msg['calendar'] = "Naptár"; + $msg['cannotpost'] = "Nem lehet hozzászólást küldeni!"; + $msg['categories'] = "Kategóriák"; + $msg['copyright'] = "Copyright&copy; $cHolder az egész tartalomra"; + $msg['datefmt'] = "%Y. %B %e."; + $msg['delentry'] = "töröl"; + $msg['lastcomments'] = "Utolsó hozzászólások"; + $msg['main'] = "Főoldal"; + $msg['next'] = "következő &raquo;"; + $msg['prev'] = "&laquo; előző"; + $msg['preview'] = "Előnézet"; + $msg['readthis'] = "Olvasd el:"; + $msg['rss1feed'] = "RSS1 feed"; + $msg['rss2feed'] = "RSS2 feed"; + $msg['send'] = "Küld"; + $msg['timefmt'] = "G:i T"; + $msg['trackback'] = "Honnan néztek:"; + $msg['writehere'] = ", írd ide:"; + $msg['wrongresp'] = "Hibás válasz!"; + $msg['yourname'] = "Neved"; + $msg['youropinion'] = "Írd meg a véleményed:"; +} else { + if (!isset($cHolder)) + $cHolder = "the authors"; + $msg['archives'] = "Archive"; + $msg['atomfeed'] = "ATOM feed"; + $msg['blogroll'] = "Blogroll"; + $msg['calendar'] = "Calendar"; + $msg['cannotpost'] = "Comments cannot be posted."; + $msg['categories'] = "Categories"; + $msg['copyright'] = "All contents copyright&copy; by $cHolder"; + $msg['datefmt'] = "%Y-%m-%d"; + $msg['delentry'] = "delete"; + $msg['lastcomments'] = "Last Comments"; + $msg['main'] = "Main"; + $msg['next'] = "Next &raquo;"; + $msg['prev'] = "&laquo; Previous"; + $msg['preview'] = "Preview"; + $msg['readthis'] = "Read this:"; + $msg['rss1feed'] = "RSS1 feed"; + $msg['rss2feed'] = "RSS2 feed"; + $msg['send'] = "Send"; + $msg['timefmt'] = "g:i A T"; + $msg['trackback'] = "Track backs:"; + $msg['writehere'] = ", write here:"; + $msg['wrongresp'] = "You wrote a wrong response."; + $msg['yourname'] = "Your name:"; + $msg['youropinion'] = "Write your opinion:"; +} + +# --------------------------------------------------------------- +# headBlock is the HTML that forms the top of a PHPosxom page. + +function headBlock($cat) +{ + global $conf_title, $conf_description, $conf_language, $conf_charset; + global $conf_cssURL, $whoami, $NAME, $VERSION; + global $category; + + $ret = "<!DOCTYPE html + PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" + \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"> +<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"$conf_language\" lang=\"$conf_language\"> +<head> +<meta http-equiv=\"content-type\" content=\"text/html; charset=$conf_charset\" /> +<style type=\"text/css\">@import \"$conf_cssURL\";</style> +<meta name=\"generator\" content=\"$NAME $VERSION\" /> +<link rel=\"alternate\" type=\"application/rss+xml\" title=\"RSS\" href=\"$whoami?flav=rss2\" /> +<link rel=\"alternate\" type=\"application/atom+xml\" title=\"ATOM\" href=\"$whoami?flav=atom\" /> +<title>$conf_title: $conf_description</title> +</head> +<body> +<div id=\"wrapper\"> +<div id=\"page\"> +<div id=\"header\">$conf_title</div> +<div id=\"body\"> +<div id=\"main\"> +<p class=\"descr\">$conf_description</p>\n"; + if (function_exists("getFortune")) + $ret .= '<p class="fortune">'.getFortune()."</p>\n"; + if ($cat) + $ret .= "<h3>".displaycategory($cat, $whoami."?category=")."</h3>\n"; + return $ret; +} + +# --------------------------------------------------------------- +# storyBlock is the HTML that constructs an individual blog entry. +# You can add additional lines by following the $story[] format below. + +function storyBlock($blog) +{ + global $whoami, $entryFilter, $lastDoY, $msg; + + # If just one entry is shown, one can post and/or read comments + + $tbs = ""; + $path = $blog->path; + $comments = ""; + if ($entryFilter) { + if (function_exists("trackbackReferrer")) + trackbackReferrer($path); + if (function_exists("getTrackbacks")) { + $tb = getTrackbacks($path); + if ($tb) { + $tbs .= "<h4 id=\"trackbacks\">".$msg['trackback']."</h4>\n" + ."<ul class=\"blogTrackbacks\">\n"; + foreach ($tb as $url=>$count) + $tbs .= "<li><a href=\"$url\">$url</a> ($count)</li>\n"; + $tbs .= "</ul>\n"; + } + } + $comments = handleComments($blog); + if ($comments != '') + $comments = "<div class=\"blogComments\">\n".$comments."</div>\n"; + } + + $thisDoY = date("Ymd", $blog->date); + $displaydate = strftime($msg['datefmt'], $blog->date); + $time = date($msg['timefmt'], $blog->date); + + if (!$lastDoY or ($thisDoY-$lastDoY < 0)) + $displaydate = "<p class=\"blogdate\">$displaydate</p>\n"; + else + $displaydate = ""; + $lastDoY = $thisDoY; + if (function_exists("countComments")) + $commentCount = countComments($path); + else + $commentCount = "#"; + $author = $blog->author; + $alink = $blog->link; + if (isset($alink) && strlen($alink)) { + if (!preg_match("/^((ht|f)tp:\/\/|mailto:)/", $alink)) + $alink = "mailto:".$alink; + $author = "<a href=\"$alink\">$author</a>"; + } + + return "$displaydate<h4>$blog->title</h4> +<div class=\"blog\">\n".$blog->getContents() + ."<p class=\"blogmeta\">$author @ $time [ <a href=\"${whoami}?category=" + .$blog->getCategory()."\">".displaycategory($blog->getCategory())."</a>" + ." | <a href=\"".$whoami.$path."\">$commentCount</a> ]</p> +</div> +$tbs$comments +"; +} + +function mklink($path, $offset, $val=false) +{ + global $whoami, $entryFilter; + if ($val === false) + $val = $offset + 1; + return "<a href=\"" + .htmlspecialchars($whoami."$entryFilter?offset=$offset") + ."\">$val</a>"; +} + +function handleComments(&$blog) +{ + global $defwho, $defwhat, $valid, $conf_comments_maxnum; + global $conf_comments_firsttolast, $msg, $cmd; + + $defwho = ''; + $defwhat = ''; + + if (!function_exists("getComments")) + return ''; + if (defined('USER') && $cmd == 'del') { + $when = intval($_GET['when']); + delComment($blog->path, $when); + } + + if (isset($_COOKIE['who'])) { + $defwho = $_COOKIE['who']; + if (!get_magic_quotes_gpc()) + $defwho = addslashes($defwho); + } + + $ret = ''; + if (isset($_POST['addcomment'])) { + if (function_exists("validateATuring")) + $valid = validateATuring($_POST['challenge'], $_POST['response']); + else + $valid = null; + $defwho = $_POST['who']; + $defwhat = $_POST['what']; + $defwhat = strip_tags($defwhat, "<a><b><i><em><strong><code>"); + if (get_magic_quotes_gpc()) { + $defwho = stripslashes($defwho); + $defwhat = stripslashes($defwhat); + } + if ((!isset($_POST['preview']) || !strlen($_POST['preview'])) && $valid === true) { + if (function_exists("addComment")) { + addComment($blog->path, $defwho, $defwhat); + $defwhat = ""; + } else + $ret .= "<p class=\"error\">".$msg['cannotpost']."</p>"; + } + setcookie("who", $_POST['who'], time()+7776000); + } + + $comments = getComments($blog->path); + if (!is_array($comments) || !count($comments)) + return $ret; + if ($conf_comments_firsttolast) + ksort($comments); + else + krsort($comments); + $l =& $conf_comments_maxnum; + if ($l && $l < count($comments)) { + $len = count($comments); + $navi = array(); + $o = isset($_GET['offset'])? intval($_GET['offset']): 0; + $comments = array_slice($comments, $o*$l, $l); + $last = intval(($len-1)/$l); + $links = false; + if ($o > 0) + $links[] = mklink($blog->path, $o - 1, $msg['prev']); + for ($i = 0; $i < 7; ++$i) { + if ((!$i && $o > 2) || ($i == 6 && $o < ($last-2))) { + $links[] = "&hellip;"; + continue; + } + $num = $o + $i - 3; + if ($i == 3) + $links[] = $o+1; + elseif ($num >= 0 && $num <= $last) + $links[] = mklink($blog->path, $o+$i-3); + } + if ($o < $last) + $links[] = mklink($blog->path, $o+1, $msg['next']); + $ret .= "<p class=\"navi\">".join(" | ", $links)."</p>\n"; + } + if (is_array($comments) && count($comments)) { + foreach ($comments as $comment) + $ret .= commentBlock($blog, $comment); + } + return $ret; +} + +function commentBlock(&$blog, $comment, $short=false) +{ + global $whoami, $msg; + + switch (count($comment)) { + case 5: + $title = $comment[4]; + case 4: + $path = $comment[3]; + case 3: + $when = $comment[2]; + case 2: + $what = $comment[1]; + case 1: + $who = $comment[0]; + } + $date = strftime($msg['datefmt'],$when); + $time = date($msg['timefmt'], $when); + if ($short) { + $after = false; + if (strlen($what) > 80) { + $after = true; + $what = substr($what, 0, 80); + $p = strrpos($what, " "); + if ($p !== false) + $what = substr($what, 0, $p); + } + $p = strpos($what, "\n"); + if ($p !== false) { + $after = true; + $what = substr($what, 0, $p); + } + + if ($after) + $what = $what."&hellip;"; + } + $what = parseText($what); + + $meta = "$who @ $date $time"; + if (isset($path)) + $meta = "$meta [<a href=\"$whoami$path\">$title</a>]"; + if (defined("USER") && $blog->src == USER) + $meta .= " <a href=\"$whoami$blog->path?cmd=del&when=$when\">" + .$msg['delentry']."</a>"; + + $ret = <<<End +<div class="comment"> +$what +<p class="blogmeta">$meta</p> +</div> + +End; + return $ret; +} + +# --------------------------------------------------------------- +# footBlock is the HTML that forms the bottom of the page. + +function footBlock() { + global $whoami, $defwho, $defwhat, $entryFilter, $conf_comments_firsttolast, + $conf_comments_maxnum, $conf_entries, $startingEntry, $entries; + global $categoryFilter, $NAME, $VERSION, $valid, $msg; + + $ret = ""; + if ($entryFilter) { + $myurl = "$entryFilter"; + if (isset($conf_comments_firsttolast) + && $conf_comments_firsttolast === true + && $conf_comments_maxnum + && ($len = count(getComments($entryFilter))) > $conf_comments_maxnum) + $myurl .= "?offset=".intval($len/$conf_comments_maxnum); + $ret .= "<h4 id=\"post\">$msg[youropinion]</h4>\n" + ."<form method=\"post\" action=\"$whoami$myurl#post\">"; + if (function_exists("getATuring")) { + $c =& $_REQUEST['challenge']; + $r =& $_REQUEST['response']; + $data = getATuring($c, $r); + if ($valid === false) + $ret .= "\n<p class=\"error\">".$msg['wrongresp']."</p>\n"; + $ret .= "\n".$msg['readthis']." <img src=\"$data[0]\" />" + ."<input type=\"hidden\" name=\"challenge\" value=\"$data[1]\" />" + .$msg['writehere']." <input type=\"text\" name=\"response\" " + .(isset($r)? ('value="'.$r.'"'):'') + ."/><br />\n"; + } + + $ret .= <<<End +$msg[yourname]: <input type="text" name="who" value="$defwho" /> +$msg[preview]: <input type="checkbox" name="preview" checked="checked" /> +<input type="submit" name="addcomment" value="$msg[send]" /><br /> +<textarea name="what" wrap="soft" cols="50" rows="5">$defwhat</textarea> +</form> + +End; + if (is_string($defwhat) and strlen($defwhat)) { + $blog = null; + $ret .= "<div class=\"blogComments\">\n" + ."<h4>".$msg['preview'].":</h4>\n" + . commentBlock($blog, array(stripslashes($defwho), stripslashes($defwhat), time())) + . "</div>\n"; + $defwhat = stripslashes($defwhat); + } + } else { + $navi = array(); + if (($startingEntry+$conf_entries) < $entries) + $navi[] = "<a href=\"".genurl(array("start" => $startingEntry + $conf_entries))."\">".$msg['prev']."</a>"; + if ($startingEntry >= $conf_entries) + $navi[] = "<a href=\"".genurl(array("start" => $startingEntry - $conf_entries))."\">".$msg['next']."</a>"; + if (count($navi)) + $ret .= "<p class=\"navi\">".join(" | ", $navi)."</p>\n"; + } + + $ret .= <<<End +</div> +<div id="navi"> +End; + if (function_exists("listCats")) { + $ret .= "<h2>$msg[categories]:</h2>\n" + ."<form method=\"GET\"><select class=\"blogCats\" " + ."name=\"category\" onchange=\"submit()\">\n"; + $dcats = getCats(); + foreach ($dcats as $kitty) { + if ($categoryFilter == $kitty['category']) + $sel = ' selected="selected"'; + else + $sel = ""; + $ret .= '<option value="'.$kitty['category'].'"'.$sel.'>' + .$kitty['name']."</option>\n"; + } + $ret .= "</select></form>\n"; + } + if (function_exists("makeCal") && ($cal = makeCal()) !== false) + $ret .= "<h2>$msg[calendar]:</h2>\n" . $cal; + if (function_exists("makeBlogroll")) + $ret .= "<h2>$msg[blogroll]:</h2>\n" . makeBlogroll(); + if (function_exists("lastComments")) { + $cmts = lastComments(); + if (is_array($cmts) && count($cmts)) { + $ret .= "<h2>$msg[lastcomments]:</h2>\n"; + $blog = false; + foreach ($cmts as $cmt) + $ret .= commentBlock($blog, $cmt, true); + } + } + if (function_exists("showArchives")) { + $archs = showArchives(); + if (count($archs)) + $ret .= "<h2>$msg[archives]:</h2>\n<ul>\n<li>" + .join("</li>\n<li>", $archs)."</li>\n</ul>\n"; + } + return $ret . <<<End +</div> +<div id="mainfooter">&nbsp;</div> +</div> +<div id="footer"> +<ul> + <li class="first"><a href="/">$msg[main]</a></li> + <li><a href="${whoami}?flav=rss">$msg[rss1feed]</a></li> + <li><a href="${whoami}?flav=rss2">$msg[rss2feed]</a></li> + <li><a href="${whoami}?flav=atom">$msg[atomfeed]</a></li> + <li>Powered by <a href="http://js.hu/package/blosxom.php/">$NAME $VERSION</a></li> +</ul> +<p>$msg[copyright]</p> +</div> +</div> +</div> +</body> +</html> + +End; +} +?> diff --git a/refactoring/blosxom.php-1.0/src/flavs/rss2_flav.php b/refactoring/blosxom.php-1.0/src/flavs/rss2_flav.php new file mode 100644 index 0000000..258de83 --- /dev/null +++ b/refactoring/blosxom.php-1.0/src/flavs/rss2_flav.php @@ -0,0 +1,94 @@ +<?php +# Blosxom.PHP: a rewrite of PHPosxom, which is a PHP rewrite of Blosxom +# RSS2 FLAVOR FILE +# The purpose is to allow you to customize the look and feel of +# your PHPosxom blog without the necessity of using flav=foo in +# the URL or editing the main script. +# ---------------------------------------------------------------- +# USAGE +# There are three functions below that form the head, story, and +# foot blocks on a blog page. +# ---------------------------------------------------------------- +# $content_type lets the browser know what kind of content is being +# served. You''ll probably want to leave this alone. + +$content_type = "text/xml"; + +function headBlock($category) { + global $conf_title, $conf_description, $conf_language, $conf_charset; + global $etag; + global $whoami; + + $title = $conf_title; + if ($category) + $title .= " ($category)"; + $head = '<?xml version="1.0"'; + if (isset($conf_charset) and $conf_charset != 'utf-8') + $head .= " encoding=\"$conf_charset\""; + $head .= "?".">\n"; + $head .= <<<End +<rss version="2.0"> +<channel> + <title>$title</title> + <link>$whoami</link> + <description>$conf_description</description> + +End; + if ($etag) { + $head .= " <pubDate>$etag</pubDate>\n"; + $head .= " <lastBuildDate>$etag</lastBuildDate>\n"; + } + $head .= <<<End + <language>$conf_language</language> + +End; + return $head; +} + +function storyBlock($blog) +{ + global $whoami, $conf_cssURL; + + $title = htmlspecialchars($blog->title); + $text = $blog->getContents(true); + $html = htmlspecialchars(<<<End +<html> +<head> +<base href="$whoami" /> +<style>@import "$conf_cssURL";</style> +<title>$title</title> +</head> +<body id="rss"> +$text +</body> +</html> +End +); + $author = htmlspecialchars($blog->author); + $displaycat = htmlspecialchars(displaycategory($blog->getCategory())); + $path = htmlspecialchars($blog->path); + $date = date("r", $blog->date); + $url = $whoami; + $link = $url.htmlspecialchars($blog->path); + $href = $url.rawurlencode($blog->path); + return <<<End +<item> + <title>$title</title> + <category>$displaycat</category> + <author>$author</author> + <pubDate>$date</pubDate> + <link>$link</link> + <description>$html</description> +</item> + +End; +} + +function footBlock() { + + return <<<End +</channel> +</rss> +End; +} +?> diff --git a/refactoring/blosxom.php-1.0/src/flavs/rss_flav.php b/refactoring/blosxom.php-1.0/src/flavs/rss_flav.php new file mode 100644 index 0000000..1362887 --- /dev/null +++ b/refactoring/blosxom.php-1.0/src/flavs/rss_flav.php @@ -0,0 +1,102 @@ +<?php +# Blosxom.PHP: a rewrite of PHPosxom, which is a PHP rewrite of Blosxom +# RSS FLAVOR FILE +# The purpose is to allow you to customize the look and feel of +# your PHPosxom blog without the necessity of using flav=foo in +# the URL or editing the main script. +# +# See http://purl.org/rss/1.0 +# ---------------------------------------------------------------- +# USAGE +# There are three functions below that form the head, story, and +# foot blocks on a blog page. + +function headBlock($category) +{ + global $conf_title, $conf_charset, $conf_description, $conf_language, $lastmod; + global $whoami; + + $thetitle = $conf_title; + if ($category) + $thetitle .= " ($category)"; + $head = '<?xml version="1.0"'; + if (isset($conf_charset) && $conf_charset != 'utf-8') + $head .= " encoding=\"$conf_charset\""; + $head .= "?".">".<<<End +<rdf:RDF + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns="http://purl.org/rss/1.0/" + xmlns:dc="http://purl.org/dc/elements/1.1/" +> +<channel rdf:about="$whoami"> + <title>$thetitle</title> + <link>$whoami</link> + <description>$conf_description</description> + +End; + if ($lastmod) + $head .= " <dc:date>".w3cdate($lastmod)."</dc:date>\n"; + $head .= <<<End + <language>$conf_language</language> + <items> + <rdf:Seq> + +End; + return $head; +} + +function storyBlock($blog) +{ + global $whoami, $conf_cssURL; + global $rss_stories; + + $title = htmlspecialchars($blog->title); + $text = $blog->getContents(true); + $html = htmlspecialchars(<<<End +<html> +<head> +<base href="$whoami" /> +<style>@import "$conf_cssURL";</style> +<title>$title</title> +</head> +<body id="rss"> +$text +</body> +</html> +End +); + $author = htmlspecialchars($blog->author); + $displaycat = htmlspecialchars(displaycategory($blog->getCategory())); + $path = htmlspecialchars($blog->path); + $date = w3cdate($blog->date); + $url = $whoami; + $link = $url.htmlspecialchars($blog->path); + $href = $url.rawurlencode($blog->path); + if (!isset($rss_stories)) + $rss_stories = ''; # to be strict + $rss_stories .= <<<End +<item rdf:about="$href"> +<title>$title</title> +<dc:subject>$displaycat</dc:subject> +<dc:creator>$author</dc:creator> +<dc:date>$date</dc:date> +<link>$link</link> +<description>$html</description> +</item> + +End; + return " <rdf:li rdf:resource=\"$href\" />\n"; +} + +function footBlock() { + global $rss_stories; + + return <<<End + </rdf:Seq> + </items> +</channel> +$rss_stories +</rdf:RDF> +End; +} +?> diff --git a/refactoring/blosxom.php-1.0/src/index.php b/refactoring/blosxom.php-1.0/src/index.php new file mode 100644 index 0000000..9ca509f --- /dev/null +++ b/refactoring/blosxom.php-1.0/src/index.php @@ -0,0 +1,266 @@ +<?php +# Blosxom.PHP: a rewrite of PHPosxom, which is a PHP rewrite of Blosxom +# Author: Balazs Nagy <[email protected]> +# Web: http://js.hu/package/blosxom.php/ + +# PHPosxom: +# Author: Robert Daeley <[email protected]> +# Version 0.7 +# Web: http://www.celsius1414.com/phposxom/ + +# Blosxom: +# Author: Rael Dornfest <[email protected]> +# Web: http://blosxom.com/ + +$NAME = "Blosxom.PHP"; +$VERSION = "1.0"; + +$pubdates[] = filemtime(__FILE__); +require_once "./conf.php"; $pubdates[] = filemtime("./conf.php"); +require_once "./blosxom.php"; $pubdates[] = filemtime("./blosxom.php"); +require_once "./dbahandler.php"; $pubdates[] = filemtime("./dbahandler.php"); + +readconf(); + +# ------------------------------------------------------------------- +# FILE EXISTENCE CHECKING AND PREP +# In which we establish a URL to this document, make sure all the files +# that are supposed to be available are, figure out what time it is, +# initialize some variables, etc. We also prove the existence of UFOs, +# but that part''s hidden. + +class AccessURL { + protected $url; + function __construct() { + $this->url = $this->build_access_url(); + } + + function url() { + return $this->url; + } + + private function is_https() { + return array_key_exists("HTTPS", $_SERVER) && $_SERVER["HTTPS"] == "ON"; + } + + private function is_this_port_default_for_protocol($protocol, $port) { + if ($protocol === "https" && $port == 443) + return true; + if ($protocol === "http" && $port == 80) + return true; + return false; + } + + private function build_access_url() { + $protocol = is_https() ? "https" : "http"; + $server_name = $_SERVER['SERVER_NAME']; + $server_port = $_SERVER['SERVER_PORT']; + $script_name = $_SERVER['SCRIPT_NAME']; + + $url = "${protocol}://${server_name}"; + if (is_this_port_default_for_protocol($protocol, $port)) + $url = "${url}:${server_port}"; + $url = "${url}${script_name}"; + return $url; + } +} + +$access_url = new AccessURL(); + +$whoami = $access_url->url(); + +$lastDoY = null; + +if ($conf_language != 'en') { + if (($str = strchr($conf_language, "-"))) + $locale = substr($conf_language, 0, strlen($str) - 1)."_".strtoupper(substr($str,1)); + $locale .= ".".$conf_charset; + setlocale(LC_TIME, $locale); +} + +$force = false; +function forceonopen() +{ + $GLOBALS["force"] = true; +} + +if ($conf_metafile) + $mfdb =& DBA::singleton($conf_metafile."?onopen=forceopen"); + +if (is_string($conf_categoriesfile)) { + $categories = false; + $fname = rpath($conf_datadir, $conf_categoriesfile); + if (file_exists($fname)) { + $data = file($fname); + foreach ($data as $categ) { + $matches = explode("=", $categ); + $categories[trim($matches[0])] = trim($matches[1]); + } + } +} + +$shows = array(); + +if (is_array($conf_modules) && count($conf_modules)) { + if (!isset($conf_moddir) || $conf_moddir == '') + $conf_moddir = "."; + foreach($conf_modules as $modval) { + if (substr($modval, -4) != '.php') + $modval .= ".php"; + $modfn = rpath($conf_moddir, $modval); + $moduleThere = file_exists($modfn); + if (!$moduleThere) { + echo explainError("nomod", $modval); + exit; + } else { + require_once $modfn; + $pubdates[] = filemtime($modfn); + } + } +} +$confdefs['category_delimiter'] = '/'; +readconfdefs(); + +# ------------------------------------------------------------------- +# URL-BASED FILTERS...NOW IN TRANSLUCENT COLORS! + +$showFilter = (isset($_GET["show"]) + && isset($shows[$_GET["show"]]))? $shows[$_GET["show"]]: null; + +$flavFilter = (isset($_GET["flav"]) + && isSaneFilename($_GET["flav"]))? $_GET["flav"]: null; + +$categoryFilter = isset($_GET["category"])? $_GET["category"]: + (isset($_GET["cat"])? $_GET["cat"]: null); + +$authorFilter = isset($_GET["author"])? $_GET["author"]: + (isset($_GET["by"])? $_GET["by"]: null); + +$entryFilter = isset($_GET["entry"])? $_GET["entry"]: + (isset($_SERVER["PATH_INFO"])? $_SERVER["PATH_INFO"]: null); + +$dateFilter = isset($_GET["date"])? checkDateFilter($_GET["date"]): null; + +$startingEntry = isset($_GET["start"])? $_GET["start"]: 0; + +$cmd = isset($_GET["cmd"])? $_GET["cmd"]: false; + +$forcefile = strlen($conf_forcefile)? rpath($conf_datadir, $conf_forcefile): false; + +$force = $force || $cmd == 'force' || ($forcefile && file_exists($forcefile) && unlink($forcefile)); + +# Early command check +authUser(); + +# ------------------------------------------------------------------- +# CALL MODULE INITS +if (isset($inits) && is_array($inits) && count($inits)) foreach ($inits as $init) + if (function_exists($init)) + call_user_func($init); + +# ------------------------------------------------------------------- +# SHOW FUNCTION EXITS +if ($showFilter && function_exists($showFilter)) { + call_user_func($showFilter); + exit; +} + +# ------------------------------------------------------------------- +# FIRST FILE LOOP + +$blogs = array(); +$cats = array(); +$daysBlogged = array(); + +checkSources(($force && !$entryFilter) || !isset($mfdb) || !$mfdb); +if ($force && $forcefile && file_exists($forcefile)) + unlink($forcefile); + +if (count($daysBlogged)) { + $daysBlogged = array_keys($daysBlogged); + rsort($daysBlogged); +} + +# ------------------------------------------------------------------- +# DETERMINE THE DOCUMENT TYPE AND SEND INITIAL HEADER() + +$content_type = "text/html"; +if (!$flavFilter) + $flavFilter = "default"; + +$flavThere = false; +if (!isset($conf_flavdir) || $conf_flavdir == "") + $conf_flavdir = "."; + +foreach (array($flavFilter, "default") as $flav) { + $flavfile = $conf_flavdir."/".$flav.'_flav.php'; + if (file_exists($flavfile)) { + $flavThere = true; + require $flavfile; + $pubdates[] = filemtime($flavfile); + break; + } +} +if (!$flavThere) { + echo explainError("noflavs"); + exit; +} + +$lastmod = max($pubdates); +$etag = date("r", $lastmod); +header("Last-modified: ".$etag); +$theHeaders = getallheaders(); +if (!$force && ((array_key_exists("If-Modified-Since", $theHeaders) + && $theHeaders["If-Modified-Since"] == $etag) + || (array_key_exists("If-None-Match", $theHeaders) + && $theHeaders["If-Modified-Since"] == $etag))) { + header('HTTP/1.0 304 Not Modified'); + exit; +} + +header("Content-Type: ".$content_type); + +# ------------------------------------------------------------------- +# DETERMINE WHERE TO START AND STOP IN THE UPCOMING STORY ARRAYS + +$entries = count($blogs); + +if ($conf_entries < $entries) + $thisManyEntries = $conf_entries; +else + $thisManyEntries = $entries; + +if ($entryFilter) { + $thisManyEntries = $entries; + $startingEntry = 0; +} + +# ------------------------------------------------------------------- +# SECOND FILE LOOP +# In which we format the actual entries and do more filtering. + +$stories = ""; +usort($blogs, create_function('$a,$b', 'return $b->date - $a->date;')); +reset($blogs); + +foreach (array_splice($blogs, $startingEntry, $thisManyEntries) as $blog) { + # deprecated + if (!$conf_html_format) + $blog->contents = parseText($blog->getContents()); + $stories .= storyBlock($blog); +} + +# END SECOND FILE LOOP +# ------------------------------------------------------------------- +# PATIENT BROWSER NOW BEGINS TO RECEIVE CONTENT + +print headBlock($categoryFilter); + +print (isset($stories) && strlen($stories))? $stories: explainError("noentries"); + +print footBlock(); + +# END OF PRINT, CLEANING UP + +DBA::closeall(); +?> diff --git a/refactoring/blosxom.php-1.0/src/modules/ATuring.php b/refactoring/blosxom.php-1.0/src/modules/ATuring.php new file mode 100644 index 0000000..419507f --- /dev/null +++ b/refactoring/blosxom.php-1.0/src/modules/ATuring.php @@ -0,0 +1,200 @@ +<?php +# Blosxom.PHP: a rewrite of PHPosxom, which is a PHP rewrite of Blosxom +# BLOSXOM.PHP MODULE +# ------------------------------------------------------------------- +# NAME: ATuring +# DESCRIPTION: Generates an Anti Turing Test to check commenter is +# a human being +# MAINTAINER: Balazs Nagy <[email protected]> +# WEBSITE: http://js.hu/package/blosxom.php/ +# ------------------------------------------------------------------- +# REQUIREMENTS +# GD support in PHP +# DBA support in PHP (not required) +# ------------------------------------------------------------------- +# INSTALLATION +# Add its name to the 'modules' array under 'EXTERNAL MODULES' in conf.php. +# ------------------------------------------------------------------- +# USAGE +# Add a variable declaration line to your flavor file like this (sans quotes): +# "$turingData = getATuring();" +# which is an array contains image URL and challenge data. +# You can insert it to the form like +# <form...>... +# <input type="hidden" name="challenge" value="$turingData[1]" /> +# Read this: <img src="$turingData[0]" />, write here: +# <input type="text" name="response" /> +# ...</form> +# +# You can check validity with (sans quotes) +# "$valid_p = validateATuring($challenge, $response)" +# ------------------------------------------------------------------- +# PREFERENCES + +# How Anti Turing should work? It can be "session" or "database". +# In session mode, challenge-response values are stored in session variables, +# in database mode, they stored in the Anti Turing database. +$confdefs['aturing_mode'] = "session"; + +# Where are Anti Turing database kept? The filename can be relative to $conf_datadir. +# In session mode it is a no-op. +$confdefs['aturing_db'] = "db4:///aturing.db"; + +# Expire time of Challenge/Responses [in seconds] +# In session mode it is a no-op. +$confdefs['aturing_expire'] = 1200; # 20 minutes + +# ------------------------------------------------------------------- +# THE MODULE +# (don't change anything below this unless you know what you're doing.) + +$shows["aturing"] = "ATshow"; +$inits[] = "ATinit"; + +$__gcdone = false; + +function ATinit() +{ + global $conf_aturing_mode; + if ($conf_aturing_mode == "session") + session_start(); +} + +function ATshow() +{ + + $c = 0; + if (array_key_exists("challenge", $_GET)) + $c = $_GET['challenge']; + $data = $c? __fetchATuring($c): false; + __closeATuringdb(); + if (!$data) { + header("Content-Type: text/plain"); + print "Challenge ($c) not found\n"; + return; + } elseif (is_array($data)) + $data = $data[0]; + header("Content-Type: image/png"); + + $xl = 76; + $yl = 21; + $im = imagecreate($xl, $yl); + $wh = imagecolorallocate($im, 0xee, 0xee, 0xdd); + $bl = imagecolorallocate($im, 0, 0, 0); + $gr = imagecolorallocate($im, 0x99, 0x99, 0x99); + $bu = imagecolorallocate($im, 0x99, 0xaa, 0xaa); + + for ($y = 0; $y < $yl; $y += 4) { + imageline($im, 0, $y, $xl, $y, $gr); + } + + for ($x = 0; $x < ($xl - $yl/2); $x += 8) { + imageline($im, $x, 0, $x + $yl/2, $yl, $bu); + imageline($im, $x+$yl/2, 0, $x, $yl, $bu); + } + imagestring($im, 5, 2, 3, $data, $bl); + imagepng($im); + imagedestroy($im); + exit; +} + +function getATuring($challenge = 0, $response = 0) +{ + global $whoami, $__atdb, $conf_aturing_mode; + __openATuringdb(); + if (!$challenge) { + switch ($conf_aturing_mode) { + case "session": + if (isset($_SESSION["aturing_last"])) + $challenge = $_SESSION["aturing_last"] + 1; + if (!$challenge || $challenge >= 1073741823) + $challenge = 1; + break; + case "database": + if (!$__atdb->fetch($challenge)) { + $challenge = intval($__atdb->fetch("last"))+1; + if ($challenge >= 1073741823) + $challenge = 1; + } + } + } else + $lastresponse = __fetchATuring($challenge); + if (isset($lastresponse) && is_integer($lastresponse) && $response == $lastresponse) + $rand = $lastresponse; + elseif (isset($lastresponse) && $response == $lastresponse[0]) + $rand = $response; + else + $rand = mt_rand(10000000, 99999999); + $expr = time(); + switch ($conf_aturing_mode) { + case "session": + $_SESSION["aturing"][$challenge] = $rand; + $_SESSION["aturing_last"] = $challenge; + break; + case "database": + dba_replace("$challenge", "$rand,$expr", $__atdb); + dba_replace("last", "$challenge", $__atdb); + dba_sync($__atdb); + __closeATuringdb(); + } + return array("$whoami?show=aturing&challenge=$challenge", $challenge); +} + +function validateATuring($challenge, $response) +{ + global $conf_aturing_expire; + + __openATuringdb(); + $data = __fetchATuring($challenge); + __closeATuringdb(); + if (is_array($data)) + return ($data[0] == $response && ($data[1] + $conf_aturing_expire) >= time()); + return $data == $response; +} + +function __fetchATuring($challenge) +{ + global $__atdb, $conf_aturing_mode; + if ($conf_aturing_mode == "session") + return $_SESSION["aturing"][$challenge]; + $challenge = $__atdb->fetch($challenge); + if (!$challenge) + return false; + return explode(",", $challenge, $__atdb); +} + +function __openATuringdb() +{ + global $conf_aturing_mode, $conf_aturing_db, $__atdb; + if ($conf_aturing_mode != "database") + return; + if (!$__atdb) + $__atdb = DBA::singleton($conf_aturing_db); +} + +function __closeATuringdb() +{ + global $conf_aturing_mode, $__atdb; + if ($conf_aturing_mode != "database" || !$__atdb) + return; + __gcATuringdb(); + dba_close($__atdb); + $__atdb = null; +} + +function __gcATuringdb() +{ + global $__atdb, $__gcdone, $conf_aturing_expire; + if ($__gcdone) + return; + $__gcdone = true; + $now = time() - $conf_aturing_expire; + if ($key = $__atdb->first()) do { + if ($key == "last") + continue; + $data = __fetchATuring($key); + if ($data && $data[1] < $now) + $__atdb->delete($key); + } while ($key = $__atdb->next()); +} +?> diff --git a/refactoring/blosxom.php-1.0/src/modules/Blogroll.php b/refactoring/blosxom.php-1.0/src/modules/Blogroll.php new file mode 100644 index 0000000..938fd2c --- /dev/null +++ b/refactoring/blosxom.php-1.0/src/modules/Blogroll.php @@ -0,0 +1,52 @@ +<?php +# Blosxom.PHP: a rewrite of PHPosxom, which is a PHP rewrite of Blosxom +# BLOSXOM.PHP MODULE +# ------------------------------------------------------------------- +# NAME: Blogroll +# DESCRIPTION: Constructs a list of most readed blogs +# AUTHOR: Balazs Nagy <[email protected]> +# WEBSITE: http://js.hu/package/blosxom.php/ +# ------------------------------------------------------------------- +# INSTALLATION +# Add its name to the 'modules' array under 'EXTERNAL MODULES' in conf.php. +# ------------------------------------------------------------------- +# USAGE +# Add a variable declaration line to your flavor file like this (sans quotes): +# "$myBlogroll = makeBlogroll();" +# Then concatenate $myBlogroll into one of your blocks. +# ------------------------------------------------------------------- +# PREFERENCES +# blogroll: hash of hashes +# array ( +# "Type" => array ( +# "Blog name" => "Blog Url" +# ) +# ) + +# ------------------------------------------------------------------- +# THE MODULE +# (don''t change anything below this unless you know what you''re doing.) + +$confdefs['blogroll_delimiter'] = " » "; + +function makeBlogroll() +{ + global $conf_blogroll, $conf_blogroll_delimiter; + + if (!count($conf_blogroll)) + return false; + + $ret = ""; + + foreach ($conf_blogroll as $type=>$list) { + if (!count($list)) + continue; + $l = array(); + foreach ($list as $name => $url) { + $l[] = "<a href=\"$url\">$name</a>"; + } + $ret .= "<p>$type".$conf_blogroll_delimiter.join($conf_blogroll_delimiter, $l)."</p>\n"; + } + return $ret; +} +?> diff --git a/refactoring/blosxom.php-1.0/src/modules/Calendar.php b/refactoring/blosxom.php-1.0/src/modules/Calendar.php new file mode 100644 index 0000000..8c74ceb --- /dev/null +++ b/refactoring/blosxom.php-1.0/src/modules/Calendar.php @@ -0,0 +1,171 @@ +<?php +# Blosxom.PHP: a rewrite of PHPosxom, which is a PHP rewrite of Blosxom +# BLOSXOM.PHP MODULE +# ------------------------------------------------------------------- +# NAME: Calendar +# DESCRIPTION: Constructs a simple blog entry month calendar +# MAINTAINER: Balazs Nagy <[email protected]> +# WEBSITE: http://js.hu/package/blosxom.php/ +# +# ORIGINAL PHPOSXOM MODULE: Calendar +# ORIGINAL AUTHOR: Robert Daeley <[email protected]> +# ------------------------------------------------------------------- +# INSTALLATION +# Add its name to the 'modules' array under 'EXTERNAL MODULES' in conf.php. +# ------------------------------------------------------------------- +# USAGE +# Add a variable declaration line to your flavor file like this (sans quotes): +# "$myCalendar = makeCal();" +# Then concatenate $myCalendar into one of the blocks. +# ------------------------------------------------------------------- +# PREP +$confdefs['calendar_showcal'] = true; +$confdefs['calendar_showarchive'] = true; + +if ($conf_language == 'hu-hu') { + $myDays = array('H','K','Sz','Cs','P','Sz','V'); + $myAbbrDays = array('hétfő', 'kedd', 'szerda', 'csütörtök', 'péntek', 'szombat', 'vasárnap'); + $startsWithMonday = 1; + $fmtMonYear = "%Y. %B"; + $fmtThisday = "%d. nap"; + $strNow = "most"; +} else { + $myDays = array('S','M','T','W','T','F','S'); + $myAbbrDays = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'); + $startsWithMonday = false; + $fmtMonYear = "%b %Y"; + $fmtThisday = "day %d"; + $strNow = "Now"; +} +# ------------------------------------------------------------------- +# THE MODULE +# (don't change anything below this unless you know what you're doing.) + +function makeCal() { + + global $strNow, $daysBlogged, $whoami, $dateFilter, $categoryFilter; + global $myDays, $myAbbrDays, $dateFilterType, $startsWithMonday, $fmtMonYear; + global $conf_calendar_showcal; + + if (!$conf_calendar_showcal) + return false; + + $ourDoM = null; + $now = time(); + + switch ($dateFilterType) { + case null: + case 'Y': + $ourDoM = date("d",$now); + $numDays = date("t",$now); + $ourYear = date("Y",$now); + $ourMonth = date("m",$now); + $ourYearMonth = $ourYear.$ourMonth; + $ourMoreOrLessMonth = $now; + break; + case 'Ymd': + $ourDoM = substr($dateFilter, 6, 2); + case 'Ym': + $ourYear = substr($dateFilter, 0, 4); + $ourMonth = substr($dateFilter, 4, 2); + $ourYearMonth = substr($dateFilter, 0, 6); + $ourMoreOrLessMonth = mktime(0,0,0,$ourMonth,1,$ourYear); + $numDays = date("t",$ourMoreOrLessMonth); + break; + } + $ourMonYear = strftime($fmtMonYear,$ourMoreOrLessMonth); + + $lastMonthName = strftime("%b", strtotime("last month", $ourMoreOrLessMonth)); + $nextMonthName = strftime("%b", strtotime("first month", $ourMoreOrLessMonth)); + $fDoWoM = date("w",mktime(0, 0, 0, $ourMonth, 1, $ourYear)); + + if ($ourMonth == "01") { + $lastYearMonth = $ourYearMonth - 89; + $nextYearMonth = $ourYearMonth + 1; + } else if ($ourMonth == 12) { + $lastYearMonth = $ourYearMonth - 1; + $nextYearMonth = $ourYearMonth + 89; + } else { + $nextYearMonth = $ourYearMonth + 1; + $lastYearMonth = $ourYearMonth - 1; + } + + $startCell = $startsWithMonday? ($fDoWoM + 6) % 7: $fDoWoM; + + # START TABLE AND CREATE DAY COLUMN HEADERS + if ($categoryFilter) + $categ = "&category=$categoryFilter"; + else + $categ = ""; + $cal = <<<End +<table class="blogCal"> +<tr><th colspan="7"><a href="$whoami?date=$ourYearMonth$categ">$ourMonYear</a> +End; + if ($dateFilter and $ourDoM) + $cal .= "<br />".strftime($fmtThisday); + if ($categoryFilter) + $cal .= "<br />".displaycategory($categoryFilter); + $cal .= "</th></tr>\n<thead>\n<tr>\n"; + for ($i = 0; $i < 7; ++$i) { + $cal .= " <th abbr=\"${myAbbrDays[$i]}\" title=\"${myAbbrDays[$i]}\" scope=\"col\">${myDays[$i]}</th>\n"; + } + $cal .= "</tr>\n</thead>\n"; + + # CREATE LINKED DAY ROWS + + $cal .= "<tbody>\n<tr>".str_repeat("<td>&nbsp;</td>", $startCell); + for ($cells=$startCell, $today = 1; $cells < ($numDays + $startCell); ++$cells, ++$today) { + if ($cells % 7 == 0) + $cal .= "<tr>"; + $cal .= ($ourDoM == $today)? "<td class=\"today\">": "<td>"; + if ($today < 10) + $dayThisTime = $ourYearMonth."0".$today; + else + $dayThisTime = $ourYearMonth.$today; + if (count($daysBlogged) && in_array($dayThisTime, $daysBlogged)) + $cal .= "<a href=\"${whoami}?date=${dayThisTime}${categ}\">${today}</a>"; + else + $cal .= $today; + $cal .= "</td>"; + if ($cells % 7 == 6) + $cal .= "</tr>\n"; + } + $lastRowEnd = $cells % 7; + if ($lastRowEnd) + $cal .= str_repeat("<td>&nbsp;</td>", 7-$lastRowEnd)."<tr>\n"; + $cal .= "</tbody>\n"; + + # CREATE BOTTOM OF TABLE + $cal .= <<<End +<tr><td class="navigator" colspan="7"> +<a href="${whoami}?date=${lastYearMonth}${categ}">$lastMonthName</a> +| <a href="${whoami}">$strNow</a> +| <a href="${whoami}?date=${nextYearMonth}${categ}">$nextMonthName</a> +</td></tr> +</table> +End; + + # CONSTRUCT TABLE AND RETURN + + return $cal; +} + +function showArchives() { + global $daysBlogged, $whoami, $dateFilter, $conf_calendar_showarchive; + global $fmtMonYear; + + if (!$conf_calendar_showarchive) + return false; + + $dates = array(); + + foreach ($daysBlogged as $ymd) { + $ym = substr($ymd, 0, 6); + if (!isset($dates[$ym])) + $dates[$ym] = "<a href=\"$whoami?date=$ym\">" + .strftime($fmtMonYear, strtotime($ymd))."</a>"; + } + return $dates; +} + +?> diff --git a/refactoring/blosxom.php-1.0/src/modules/CatList.php b/refactoring/blosxom.php-1.0/src/modules/CatList.php new file mode 100644 index 0000000..0ae3ab5 --- /dev/null +++ b/refactoring/blosxom.php-1.0/src/modules/CatList.php @@ -0,0 +1,81 @@ +<?php +# Blosxom.PHP: a rewrite of PHPosxom, which is a PHP rewrite of Blosxom +# BLOSXOM.PHP MODULE +# ------------------------------------------------------------------- +# NAME: CatList +# DESCRIPTION: Constructs a simple linked list of categories +# MAINTAINER: Balazs Nagy <[email protected]> +# WEBSITE: http://js.hu/package/blosxom.php/ +# +# ORIGINAL PHPOSXOM MODULE: CatList +# ORIGINAL AUTHOR: Robert Daeley <[email protected]> +# ------------------------------------------------------------------- +# INSTALLATION +# Add its name to the 'modules' array under 'EXTERNAL MODULES' in conf.php. +# ------------------------------------------------------------------- +# USAGE +# Add a variable declaration line to your flavor file like this (sans quotes): +# "$myCategories = listCats();" +# Then concatenate $myCategories into one of your blocks. +# ------------------------------------------------------------------- +# PREFERENCES + +# How would you like this module to refer to the top level of your blog? +# (Examples: "Main" "Home" "All" "Top") +if ($conf_language == "hu-hu") + $topLevelTerm = "Összes"; +else + $topLevelTerm = "All"; + +# Would you like individual RSS links added as well? (1 = yes, 0 = no) +$confdefs["catlist_syndicate_auto"] = false; +$confdefs["catlist_syndicate_type"] = "rss2"; + +# ------------------------------------------------------------------- +# THE MODULE +# (don't change anything below this unless you know what you're doing.) + +function listCats() { + $cats = getCats(); + $ret = "<ul class=\"blogCats\">"; + foreach ($cats as $kitty) { + $ret .= '<li><a href="'.$kitty['link'].'">'.$kitty['name'].'</a>'; + if (isset($kitty['syndicate'])) + $ret .= ' (<a href="'.$kitty['synlink'].'>' + .$kitty['syndicate'] .'</a>)'; + $ret .= "</li>\n"; + } + return $ret."\n</ul>"; +} + +function getCats() { + global $whoami, $cats, $topLevelTerm; + global $conf_catlist_syndicate_auto, $conf_catlist_syndicate_type; + + sort ($cats); + $herd = array(); + foreach ($cats as $kitty) { + if (!$kitty) { + $category = "<strong>$topLevelTerm</strong>"; + $link = $whoami; + $delim = '?'; + } else { + $category = displaycategory($kitty); + $link = $whoami.'?category='.$kitty; + $delim = '&amp;'; + } + $tcat = array( + 'category' => $kitty, + 'name' => $category, + 'url' => $link + ); + if ($conf_catlist_syndicate_auto) { + $tcat['syndicate'] = $link.$delim.'flav=' + .$conf_catlist_syndicate_type; + $tcat['syntype'] = strtoupper($conf_catlist_syndicate_type); + } + $herd[] = $tcat; + } + return $herd; +} +?> diff --git a/refactoring/blosxom.php-1.0/src/modules/Comments.php b/refactoring/blosxom.php-1.0/src/modules/Comments.php new file mode 100644 index 0000000..d568cba --- /dev/null +++ b/refactoring/blosxom.php-1.0/src/modules/Comments.php @@ -0,0 +1,227 @@ +<?php +# Blosxom.PHP: a rewrite of PHPosxom, which is a PHP rewrite of Blosxom +# BLOSXOM.PHP MODULE +# ------------------------------------------------------------------- +# NAME: Comments +# DESCRIPTION: Handles talkbacks +# AUTHOR: Balazs Nagy <[email protected]> +# WEBSITE: http://js.hu/package/blosxom.php/ +# ------------------------------------------------------------------- +# REQUIREMENTS +# DBA support in PHP (not required) +# ------------------------------------------------------------------- +# INSTALLATION +# Add its name to the 'modules' array under 'EXTERNAL MODULES' in conf.php. +# ------------------------------------------------------------------- +# USAGE +# Add a variable declaration line to your flavor file like this (sans quotes): +# "$myComments = countComments($path);" +# in storyBlock, then put it to blogmeta paragraph, in place of the pound sign. +# ------------------------------------------------------------------- +# PREP +$confdefs['comments_db'] = "db4:///comments.db"; + +# Show comments first to last? true: yes, false: last to first +$confdefs['comments_firsttolast'] = false; + +# Default number of comments put on a page +$confdefs['comments_maxnum'] = 6; + +if ($conf_language == "hu-hu") { + $msg['comments0'] = "Új hozzászólás"; + $msg['comments1'] = "1 hozzászólás"; + $msg['commentsn'] = "%d hozzászólás"; + $msg['datefmt'] = "%Y. %B %e."; + $msg['timefmt'] = "G:i T"; +} else { + $msg['comments0'] = "No comments"; + $msg['comments1'] = "1 comment"; + $msg['commentsn'] = "%d comments"; + $msg['datefmt'] = "%Y-%m-%d"; + $msg['timefmt'] = "g:i A T"; +} + +# ------------------------------------------------------------------- +# THE MODULE +# (don't change anything below this unless you know what you're doing.) + +function &__openCommentsDB() +{ + global $conf_comments_db; + return DBA::singleton($conf_comments_db); +} + +function countComments($path) +{ + global $msg; + + $comments = getComments($path); + if (!isset($comments) || $comments === false || $comments == '') + return $msg['comments0']; + $c = count($comments); + return $c == 1? $msg['comments1']: sprintf($msg['commentsn'], $c); +} + +function &getComments($path) +{ + global $commentCache; + + if ($path == "last") + return false; + if (isset($commentCache[$path])) + return $commentCache[$path]; + $db =& __openCommentsDB(); + if ($db === false) + return false; + $comments = $db->fetch($path); + if (!is_array($comments)) + return false; + $date = array_keys($comments); + sort($date); + if ($date[0] < 100000) { + foreach ($comments as $date=>$comm) + $cmnt[$comm[2]] = $comm; + $db->replace($path, $cmnt); + $comments = &$cmnt; + } + $commentCache[$path] = $comments; + return $comments; +} + +function addComment($path, $who, $what) +{ + global $cmts, $commentCache; + + $time = time(); + $db =& __openCommentsDB(); + if ($db === false) + return false; + $newcmt = array($who, $what, $time); + $comments = getComments($path); + if (!is_array($comments)) + $comments = array($time => $newcmt); + else + $comments[$time] = $newcmt; + $commentCache[$path] = $comments; + $err = $db->replace($path, $comments); + if (!$err) + return false; + __readLastdb(); + $cmts[$time] = array($who, $what, $time, $path); + return __writeLastdb(); +} + +function delComment($path, $time) +{ + global $cmts, $commentCache; + + if (!defined("USER")) + return false; + $comments = getComments($path); + if (!is_array($comments) || !isset($comments[$time])) + return false; + unset($comments[$time]); + $db =& __openCommentsDB(); + if ($db === false) + return false; + $err = $db->replace($path, $comments); + if (!$err) + return false; + + __readLastdb(); + if (isset($cmts[$time])) { + unset($cmts[$time]); + __writeLastdb(); + } + return true; +} + +function lastComments() +{ + global $conf_datadir, $conf_comments_db; + global $conf_comments_db; + global $force, $conf_comments_maxnum; + global $cmts, $mfdb; + + if ($force) { + $cmts = array(); + $db =& __openCommentsDB(); + if ($db === false) + return false; + $key = $db->first(); + while ($key !== false) { + $path = $key; + $key = $db->next(); + if ($path == "last") + continue; + $comments = $db->fetch($path); + if (!is_array($comments)) + continue; + foreach (array_values($comments) as $cmt) { + $time =& $cmt[2]; + $cmts[$time] = $cmt; + $cmts[$time][3] = $path; + } + } + __writeLastdb(); + } else + __readLastdb(); + + if ($mfdb && is_array($cmts)) { + $mfCache = array(); + foreach (array_keys($cmts) as $date) { + $where = $cmts[$date][3]; + if (array_key_exists($where, $mfCache)) { + $cmts[$date][4] = $mfCache[$where]; + } else { + $mdata = $mfdb->fetch($where); + $cmts[$date][4] = $mfCache[$where] = trim($mdata[2]); + } + } + } + return $cmts; +} + +function __sortLastdb($a, $b) +{ + return $b[2] - $a[2]; +} + +function __optimizeLastdb() +{ + global $conf_comments_maxnum, $cmts; + if (!is_array($cmts) || !count($cmts)) + return false; + usort($cmts, "__sortLastdb"); + + if (count($cmts) > $conf_comments_maxnum) + $cmts = array_slice($cmts, 0, $conf_comments_maxnum); + return true; +} + +function __writeLastdb() +{ + global $cmts, $conf_comments_db; + + if (__optimizeLastdb() === false) + return false; + $db =& __openCommentsDB(); + if ($db === false) + return false; + + $db->replace("last", $cmts); + $db->close(); + return true; +} + +function __readLastdb() +{ + global $cmts; + + $db =& __openCommentsDB(); + if (!$db) + return false; + $cmts = $db->fetch("last"); + return __optimizeLastdb(); +} +?> diff --git a/refactoring/blosxom.php-1.0/src/modules/Fortune.php b/refactoring/blosxom.php-1.0/src/modules/Fortune.php new file mode 100644 index 0000000..d596b0a --- /dev/null +++ b/refactoring/blosxom.php-1.0/src/modules/Fortune.php @@ -0,0 +1,34 @@ +<?php +# Blosxom.PHP: a rewrite of PHPosxom, which is a PHP rewrite of Blosxom +# BLOSXOM.PHP MODULE +# ------------------------------------------------------------------- +# NAME: Fortune +# DESCRIPTION: Adds random fortune cookie +# AUTHOR: Balazs Nagy <[email protected]> +# WEBSITE: http://js.hu/package/blosxom.php/ +# ------------------------------------------------------------------- +# INSTALLATION +# Add its name to the 'modules' array under 'EXTERNAL MODULES' in conf.php. +# ------------------------------------------------------------------- +# USAGE +# Add a variable declaration line to your flavor file like this (sans quotes): +# "$myFortune = getFortune();" in headBlock. +# ------------------------------------------------------------------- +# PREP + +# Database path +$confdefs['fortune'] = "fortunes.lst"; + +function getFortune() +{ + global $conf_datadir, $conf_fortune; + + if (!is_string($conf_fortune)) + return ""; + $fname = rpath($conf_datadir, $conf_fortune); + if (!file_exists($fname) || !($f = @file($fname))) + return ""; + $line = mt_rand(0, count($f)-1); + return trim($f[$line]); +} +?> diff --git a/refactoring/blosxom.php-1.0/src/modules/Trackback.php b/refactoring/blosxom.php-1.0/src/modules/Trackback.php new file mode 100644 index 0000000..04ec723 --- /dev/null +++ b/refactoring/blosxom.php-1.0/src/modules/Trackback.php @@ -0,0 +1,92 @@ +<?php +# Blosxom.PHP: a rewrite of PHPosxom, which is a PHP rewrite of Blosxom +# BLOSXOM.PHP MODULE +# ------------------------------------------------------------------- +# NAME: Trackback +# DESCRIPTION: Tracks blog entries using referrer +# AUTHOR: Balazs Nagy <[email protected]> +# WEBSITE: http://js.hu/package/blosxom.php/ +# ------------------------------------------------------------------- +# INSTALLATION +# Add its name to the 'modules' array under 'EXTERNAL MODULES' in conf.php. +# ------------------------------------------------------------------- +# USAGE +# ------------------------------------------------------------------- +# PREP + +# Database path +$confdefs['trackback'] = "db4:///trackback.db"; + +function trackbackReferrer($path) +{ + global $conf_trackback, $whoami; + + fixTrackbacks(); + if (!isset($_SERVER['HTTP_REFERER'])) + return true; + $ref = $_SERVER['HTTP_REFERER']; + $wa = dirname($whoami); + if ($ref == '' || !strncmp($ref, $wa, strlen($wa))) + return true; + $db =& DBA::singleton($conf_trackback); + if ($db === false) + return false; + + $tb = $db->fetch($path); + if ($tb) { + $tbp = unserialize($tb); + if (array_key_exists($ref, $tbp)) + $tbp[$ref] ++; + else + $tbp[$ref] = 1; + } else + $tbp = array($ref => 1); + $db->replace($path, $tbp); + $db->sync(); + $db->close(); + return true; +} + +function getTrackbacks($path) +{ + global $conf_trackback; + + $db =& DBA::singleton($conf_trackback."?mode=r"); + if ($db === false) + return false; + + $tb = $db->fetch($path); + $db->close(); + if (!$tb) + return false; + + return $tb; +} + +function fixTrackbacks() +{ + global $conf_trackback, $whoami; + + $db =& DBA::singleton($conf_trackback); + if ($db === false) + return false; + + $wa = dirname($whoami); + $tb = $db->first(); + do { + $dirty = false; + $tbp = $db->fetch($tb); + if ($tbp === null) + continue; + foreach ($tbp as $url=>$count) { + if (!strncmp($url, $wa, strlen($wa))) { + unset($tbp[$url]); + $dirty = true; + } + } + if ($dirty) + $db->replace($tb, $tbp); + } while (($tb = $db->next())); + $db->close(); +} +?>
troter/object-oriented-exercise
a811f59b9fba69e3f3f4356fac7b227fb3952e3a
文字列ラップクラスをとりあえず追加
diff --git a/refactoring/blosxom.php-1.0/dbahandler.php b/refactoring/blosxom.php-1.0/dbahandler.php index 0db9782..89818e3 100644 --- a/refactoring/blosxom.php-1.0/dbahandler.php +++ b/refactoring/blosxom.php-1.0/dbahandler.php @@ -1,325 +1,483 @@ -<?php +<?php # -*- coding: utf-8 -*- # DBA handler # Written by Balazs Nagy <[email protected]> # Version: 2005-02-09 # # Call it as DBA::singleton($dsn), because only assures that already opened # connections aren''t opened again, and it allows use of implicit closes $GLOBALS["__databases"] = false; $GLOBALS["confdefs"]["dba_default_persistency"] = true; $GLOBALS["debug"] = false; function debug_log($str) { if (isset($GLOBALS["debug"]) && $GLOBALS["debug"] === true) error_log($str); } +class DBA_DSN +{ + private $dsn; + private $query; + + function __construct(string $dsn) { + list($this->dsn, $this->query) = parse($dsn); + } + + /** + * $dsn = "<driver>://<username>:<password>@<host>:<port>/<database>?<query>" + */ + private function parse(string $dsn) { + $query = ""; + if (strpos('\?', $dsn) !== false) + list($dsn, $query) = split('\?', $dsn, 2); + $parsed_query = $this->parse_str($query); + $parsed_dsn = $this->parse_dsn($dsn); + return array($parsed_query, $parsed_dsn); + } + + private function parse_str(string $query) { + parse_str($query, $parsed_query); + $parsed_query['mode'] = new DBA_Option_OpenMode($parsed_query['mode']); + $parsed_query['onopen'] = new DBA_Option_OnOpenHandler($parsed_query['onopen']); + $parsed_query['persistent'] = new DBA_Option_Persistent($parsed_query['persistent']); + return $parsed_query; + } + + private function parse_dsn(string $dsn) { + $parsed_query = array( + 'scheme' => '', + 'user' => '', + 'password' => '', + 'host' => '', + 'port' => '', + 'database' => '', + ); + + $parsed_query['scheme'] = new DBA_DSN_Scheme($parsed_query['scheme']); + $parsed_query['user'] = new DBA_DSN_User($parsed_query['user']); + $parsed_query['password'] = new DBA_DSN_Password($parsed_query['password']); + $parsed_query['host'] = new DBA_DSN_Host($parsed_query['host']); + $parsed_query['port'] = new DBA_DSN_Port($parsed_query['port']); + $parsed_query['database'] = new DBA_DSN_Database($parsed_query['database']); + return $parsed_query; + } +} + +class DBA_DSN_Scheme { + private $scheme; + function __construct(string $scheme) { + $this->scheme = $scheme; + } + function value() { + return $this->scheme; + } + function has_dba_handler() { + $handler_name = $this->scheme; + return function_exists("dba_handlers") + && in_array($handler_name, dba_handlers()); + } +} + +class DBA_DSN_User { + private $user; + function __construct(string $user) { + $this->user = $user; + } + function value() { + return $this->user; + } +} + +class DBA_DSN_Password { + private $password; + function __construct(string $password) { + $this->password = $password; + } + function value() { + return $this->password; + } +} + +class DBA_DSN_Host { + private $host; + function __construct(string $host) { + $this->host = $host; + } + function value() { + return $this->host; + } +} + +class DBA_DSN_Port { + private $port; + function __construct(string $port) { + $this->port = $port; + } + function value() { + return $this->port; + } +} + +class DBA_DSN_Database { + private $database; + function __construct(string $database) { + $this->database = $database; + } + function value() { + return $this->database; + } + function realpath() { + return ""; + } +} + +class DBA_Option { + +} + +class DBA_Option_OpenMode { + private $mode; + function __construct(string $mode) { + $this->mode = $mode; + } + function is_create() { return $this->mode == "c"; } + function is_readonly() { return $this->mode == "r"; } + function is_readwrite_or_create() { return $this->mode == "w"; } + function is_unknown() { + return !($this->is_create() || + $this->is_readonly() || + $this->is_readwrite_or_create()); + } +} + +class DBA_Option_OnOpenHandler { + private $handler_function_name; + function __construct(string $handler_function_name) { + $this->handler_function_name = $handler_function_name; + } + function call() { + if (function_exists($this->handler_function_name)) + call_user_func($this->handler_function_name); + } +} + +class DBA_Option_Persistent { + private $condition; + function __construct($condition) { + $this->condition = $condition; + } + function is_enable() { + return preg_match("true|1|on|enabled", $condition) === 1; + } +} + class DBA { var $dsn; var $info; var $res; var $opt; var $handler; /** Creates a new DBA object defined by dsn. * It assures that the same DBA object is returned to the same dsn''s * @param $dsn text Data Source Name: type:///file/opt=val&opt2=val2... * Each file can be relative to datadir. * Valid options: * persistent=true|1|on|enabled: enables persistency. Any others disables * onopen=functionname: calls function if new database is created * mode=c|r|w: open mode. c-create new, r-readonly, w-readwrite or create */ function &singleton($dsn) { $dbs = &$GLOBALS["__databases"]; if (isset($dbs[$dsn])) { debug_log("DBA::singleton: get old db as $dsn"); $that = &$dbs[$dsn]; } else { $that = new DBA($dsn); $dbs[$dsn] = &$that; debug_log("DBA::singleton: create new db as $dsn"); } return $that; } function closeall() { $dbs = &$GLOBALS["__databases"]; if (is_array($dbs) && count($dbs)) foreach ($dbs as $db) $db->close(); } # quick and dirty DSN parser function __parseDSN($dsn) { $ret = array( "scheme" => "", "path" => "", "query" => "" ); $off = strpos($dsn, "://"); if ($off !== false) $ret["scheme"] = substr($dsn, 0, $off); $off += 3; $off2 = strpos($dsn, "/", $off); if ($off2 !== false) $off = $off2; $off += 1; $off2 = strpos($dsn, "?", $off); if ($off2 !== false) { $ret["path"] = substr($dsn, $off, $off2-$off); $ret["query"] = substr($dsn, $off2+1); } else $ret["path"] = substr($dsn, $off); return $ret; } function DBA($dsn) { + // 必要ない? $this->dsn = $dsn; $info = DBA::__parseDSN($dsn); if (!isset($info["scheme"])) return false; $this->info = $info; $this->res = false; $this->handler = $info["scheme"]; if (!function_exists("dba_handlers") || !in_array($this->handler, dba_handlers())) $this->handler = false; if (strlen($info["query"])) parse_str($info["query"], $this->opt); } function &getOpt($opt) { if (!$this || !is_a($this, "DBA") || $this->res !== false) return false; $ret =& $this->opt[$opt]; if (isset($ret)) return $ret; return null; } function isOpt($opt, $val) { $ret =& getOpt($opt); if (is_bool($val)) return $ret === $val; return $ret == $val; } function open() { global $conf; if (!$this || !is_a($this, "DBA")) return false; if ($this->res !== false) return true; $fn = rpath($conf["datadir"], $this->info['path']); if ($this->isOpt("mode", "c")) $mode = "n"; elseif ($this->isOpt("mode", "r")) { if (!file_exists($fn)) return false; $mode = "r"; } else { if (file_exists($fn)) $mode = "w"; else { $mode = "n"; if (function_exists($this->getOpt("onopen"))) call_user_func($this->getOpt("onopen")); } } if ($this->handler !== false) { $persistent =& $this->getOpt("persistent"); if (!isset($persistent)) $persistent =& $conf["dba_default_persistency"]; else $persistent = strtolower($persistent); switch ($persistent) { case true: case "1": case "on": case "true": case "enabled": $caller = "dba_popen"; break; default: $caller = "dba_open"; } $this->res = $caller($fn, $mode, $this->handler); debug_log("$caller($fn, $mode, $this->handler) = $this->res"); return is_resource($this->res); } if (!file_exists($fn) && !is_file($fn) && !is_readable($fn) && !touch($fn)) return false; $mode = !!strstr($mode, "w"); $this->res = $fn; $this->cache = array( "mode" => $mode, "sync" => true, "data" => @unserialize(file_get_contents($fn)) ); return true; } function close() { if (!$this || !is_a($this, "DBA") || $this->res === false) return false; if ($this->handler) { dba_close($this->res); debug_log("dba_close($this->res)"); } else { $this->sync(); $this->cache = false; } $this->res = false; } function first() { if (!$this || !is_a($this, "DBA")) return false; if (!$this->open()) return false; if ($this->handler) { $key = dba_firstkey($this->res); debug_log("dba_firstkey($this->res)"); return $key; } if (!is_array($this->cache["data"]) || !count($this->cache["data"])) return false; if (reset($this->cache["data"]) === false) return false; return key($this->cache["data"]); } function next() { if (!$this || !is_a($this, "DBA")) return false; if (!$this->open()) return false; if ($this->handler) { debug_log("dba_nextkey($this->res)"); return dba_nextkey($this->res); } if (!is_array($this->cache["data"]) || !count($this->cache["data"])) return false; if (next($this->cache["data"]) === false) return false; return key($this->cache["data"]); } function fetch($key) { if (!$this || !is_a($this, "DBA")) return false; if (!$this->open()) return false; if ($this->handler) { debug_log("dba_fetch($key, $this->res)"); $val = dba_fetch($key, $this->res); if (!is_string($val)) return null; $v = @unserialize($val); if ($v === false && $val != 'b:0;') { // old value, needs correction $v = explode(",", $val, 3); $v[2] = str_replace("&#44;", ",", $v[2]); dba_replace($key, serialize($v), $this->res); } return $v; } if (!is_array($this->cache["data"]) || !count($this->cache["data"]) || !isset($this->cache["data"][$key])) return false; return $this->cache["data"][$key]; } function insert($key, $val) { if (!$this || !is_a($this, "DBA")) return false; if (!$this->open()) return false; if ($this->handler) { debug_log("dba_insert($key, $val, $this->res)"); return dba_insert($key, serialize($val), $this->res); } if (!is_array($this->cache["data"])) $this->cache["data"] = array(); elseif (isset($this->cache["data"][$key])) return false; $this->cache["data"][$key] = $val; $this->cache["sync"] = false; return true; } function replace($key, $val) { if (!$this || !is_a($this, "DBA")) return false; if (!$this->open()) return false; if ($this->handler) { debug_log("dba_replace($key, $val, $this->res)"); return dba_replace($key, serialize($val), $this->res); } if (!is_array($this->cache["data"])) $this->cache["data"] = array(); debug_log("DBA::replace($key, $val, $this->res)"); $this->cache["data"][$key] = $val; $this->cache["sync"] = false; return true; } function delete($key) { if (!$this || !is_a($this, "DBA")) return false; if (!$this->open()) return false; if ($this->handler) { debug_log("dba_delete($key, $this->res)"); return dba_delete($key, $this->res); } if (!is_array($this->cache["data"]) || !count($this->cache["data"]) || !isset($this->cache["data"][$key])) return false; unset($this->cache["data"][$key]); $this->cache["sync"] = false; return true; } function optimize() { if (!$this || !is_a($this, "DBA") || $this->res === false || $this->handler === false) return false; dba_optimize($this->res); debug_log("dba_optimize($this->res)"); } function sync() { if (!$this || !is_a($this, "DBA") || $this->res === false) return false; if ($this->handler && $this->res) { debug_log("dba_sync($this->res)"); return dba_sync($this->res); } if (!$this->cache["mode"] || $this->cache["sync"]) return true; $fh = fopen($this->res, "w"); fwrite($fh, serialize($this->cache["data"])); fclose($fh); return true; } } ?>
troter/object-oriented-exercise
ccd4c04459c6bc1fe821744fb4a662be50017a0e
whoamiを作成するAccessURLクラスを追加
diff --git a/refactoring/blosxom.php-1.0/index.php b/refactoring/blosxom.php-1.0/index.php index 9537740..9ca509f 100644 --- a/refactoring/blosxom.php-1.0/index.php +++ b/refactoring/blosxom.php-1.0/index.php @@ -1,252 +1,266 @@ <?php # Blosxom.PHP: a rewrite of PHPosxom, which is a PHP rewrite of Blosxom # Author: Balazs Nagy <[email protected]> # Web: http://js.hu/package/blosxom.php/ # PHPosxom: # Author: Robert Daeley <[email protected]> # Version 0.7 # Web: http://www.celsius1414.com/phposxom/ # Blosxom: # Author: Rael Dornfest <[email protected]> # Web: http://blosxom.com/ $NAME = "Blosxom.PHP"; $VERSION = "1.0"; $pubdates[] = filemtime(__FILE__); require_once "./conf.php"; $pubdates[] = filemtime("./conf.php"); require_once "./blosxom.php"; $pubdates[] = filemtime("./blosxom.php"); require_once "./dbahandler.php"; $pubdates[] = filemtime("./dbahandler.php"); readconf(); # ------------------------------------------------------------------- # FILE EXISTENCE CHECKING AND PREP # In which we establish a URL to this document, make sure all the files # that are supposed to be available are, figure out what time it is, # initialize some variables, etc. We also prove the existence of UFOs, # but that part''s hidden. -function is_https() { - return array_key_exists("HTTPS", $_SERVER) && $_SERVER["HTTPS"] == "ON"; +class AccessURL { + protected $url; + function __construct() { + $this->url = $this->build_access_url(); + } + + function url() { + return $this->url; + } + + private function is_https() { + return array_key_exists("HTTPS", $_SERVER) && $_SERVER["HTTPS"] == "ON"; + } + + private function is_this_port_default_for_protocol($protocol, $port) { + if ($protocol === "https" && $port == 443) + return true; + if ($protocol === "http" && $port == 80) + return true; + return false; + } + + private function build_access_url() { + $protocol = is_https() ? "https" : "http"; + $server_name = $_SERVER['SERVER_NAME']; + $server_port = $_SERVER['SERVER_PORT']; + $script_name = $_SERVER['SCRIPT_NAME']; + + $url = "${protocol}://${server_name}"; + if (is_this_port_default_for_protocol($protocol, $port)) + $url = "${url}:${server_port}"; + $url = "${url}${script_name}"; + return $url; + } } -function is_this_port_default_for_protocol($protocol, $port) { - if ($protocol === "https" && $port == 443) - return true; - if ($protocol === "http" && $port == 80) - return true; - return false; -} +$access_url = new AccessURL(); -function whoami() { - $protocol = is_https() ? "https" : "http"; - $server_name = $_SERVER['SERVER_NAME']; - $server_port = $_SERVER['SERVER_PORT']; - $script_name = $_SERVER['SCRIPT_NAME']; - - $url = "${protocol}://${server_name}"; - if (is_this_port_default_for_protocol($protocol, $port)) - $url = "${url}:${server_port}"; - $url = "${url}${script_name}"; - return $url; -} -$whoami = whoami(); +$whoami = $access_url->url(); $lastDoY = null; if ($conf_language != 'en') { if (($str = strchr($conf_language, "-"))) $locale = substr($conf_language, 0, strlen($str) - 1)."_".strtoupper(substr($str,1)); $locale .= ".".$conf_charset; setlocale(LC_TIME, $locale); } $force = false; function forceonopen() { $GLOBALS["force"] = true; } if ($conf_metafile) $mfdb =& DBA::singleton($conf_metafile."?onopen=forceopen"); if (is_string($conf_categoriesfile)) { $categories = false; $fname = rpath($conf_datadir, $conf_categoriesfile); if (file_exists($fname)) { $data = file($fname); foreach ($data as $categ) { $matches = explode("=", $categ); $categories[trim($matches[0])] = trim($matches[1]); } } } $shows = array(); if (is_array($conf_modules) && count($conf_modules)) { if (!isset($conf_moddir) || $conf_moddir == '') $conf_moddir = "."; foreach($conf_modules as $modval) { if (substr($modval, -4) != '.php') $modval .= ".php"; $modfn = rpath($conf_moddir, $modval); $moduleThere = file_exists($modfn); if (!$moduleThere) { echo explainError("nomod", $modval); exit; } else { require_once $modfn; $pubdates[] = filemtime($modfn); } } } $confdefs['category_delimiter'] = '/'; readconfdefs(); # ------------------------------------------------------------------- # URL-BASED FILTERS...NOW IN TRANSLUCENT COLORS! $showFilter = (isset($_GET["show"]) && isset($shows[$_GET["show"]]))? $shows[$_GET["show"]]: null; $flavFilter = (isset($_GET["flav"]) && isSaneFilename($_GET["flav"]))? $_GET["flav"]: null; $categoryFilter = isset($_GET["category"])? $_GET["category"]: (isset($_GET["cat"])? $_GET["cat"]: null); $authorFilter = isset($_GET["author"])? $_GET["author"]: (isset($_GET["by"])? $_GET["by"]: null); $entryFilter = isset($_GET["entry"])? $_GET["entry"]: (isset($_SERVER["PATH_INFO"])? $_SERVER["PATH_INFO"]: null); $dateFilter = isset($_GET["date"])? checkDateFilter($_GET["date"]): null; $startingEntry = isset($_GET["start"])? $_GET["start"]: 0; $cmd = isset($_GET["cmd"])? $_GET["cmd"]: false; $forcefile = strlen($conf_forcefile)? rpath($conf_datadir, $conf_forcefile): false; $force = $force || $cmd == 'force' || ($forcefile && file_exists($forcefile) && unlink($forcefile)); # Early command check authUser(); # ------------------------------------------------------------------- # CALL MODULE INITS if (isset($inits) && is_array($inits) && count($inits)) foreach ($inits as $init) if (function_exists($init)) call_user_func($init); # ------------------------------------------------------------------- # SHOW FUNCTION EXITS if ($showFilter && function_exists($showFilter)) { call_user_func($showFilter); exit; } # ------------------------------------------------------------------- # FIRST FILE LOOP $blogs = array(); $cats = array(); $daysBlogged = array(); checkSources(($force && !$entryFilter) || !isset($mfdb) || !$mfdb); if ($force && $forcefile && file_exists($forcefile)) unlink($forcefile); if (count($daysBlogged)) { $daysBlogged = array_keys($daysBlogged); rsort($daysBlogged); } # ------------------------------------------------------------------- # DETERMINE THE DOCUMENT TYPE AND SEND INITIAL HEADER() $content_type = "text/html"; if (!$flavFilter) $flavFilter = "default"; $flavThere = false; if (!isset($conf_flavdir) || $conf_flavdir == "") $conf_flavdir = "."; foreach (array($flavFilter, "default") as $flav) { $flavfile = $conf_flavdir."/".$flav.'_flav.php'; if (file_exists($flavfile)) { $flavThere = true; require $flavfile; $pubdates[] = filemtime($flavfile); break; } } if (!$flavThere) { echo explainError("noflavs"); exit; } $lastmod = max($pubdates); $etag = date("r", $lastmod); header("Last-modified: ".$etag); $theHeaders = getallheaders(); if (!$force && ((array_key_exists("If-Modified-Since", $theHeaders) && $theHeaders["If-Modified-Since"] == $etag) || (array_key_exists("If-None-Match", $theHeaders) && $theHeaders["If-Modified-Since"] == $etag))) { header('HTTP/1.0 304 Not Modified'); exit; } header("Content-Type: ".$content_type); # ------------------------------------------------------------------- # DETERMINE WHERE TO START AND STOP IN THE UPCOMING STORY ARRAYS $entries = count($blogs); if ($conf_entries < $entries) $thisManyEntries = $conf_entries; else $thisManyEntries = $entries; if ($entryFilter) { $thisManyEntries = $entries; $startingEntry = 0; } # ------------------------------------------------------------------- # SECOND FILE LOOP # In which we format the actual entries and do more filtering. $stories = ""; usort($blogs, create_function('$a,$b', 'return $b->date - $a->date;')); reset($blogs); foreach (array_splice($blogs, $startingEntry, $thisManyEntries) as $blog) { # deprecated if (!$conf_html_format) $blog->contents = parseText($blog->getContents()); $stories .= storyBlock($blog); } # END SECOND FILE LOOP # ------------------------------------------------------------------- # PATIENT BROWSER NOW BEGINS TO RECEIVE CONTENT print headBlock($categoryFilter); print (isset($stories) && strlen($stories))? $stories: explainError("noentries"); print footBlock(); # END OF PRINT, CLEANING UP DBA::closeall(); ?>
troter/object-oriented-exercise
0d3c5a610d0a9d1087e6d89dd99847f363b6cdf0
whoamiを関数化
diff --git a/refactoring/blosxom.php-1.0/index.php b/refactoring/blosxom.php-1.0/index.php index 1bae3c0..9537740 100644 --- a/refactoring/blosxom.php-1.0/index.php +++ b/refactoring/blosxom.php-1.0/index.php @@ -1,232 +1,252 @@ <?php # Blosxom.PHP: a rewrite of PHPosxom, which is a PHP rewrite of Blosxom # Author: Balazs Nagy <[email protected]> # Web: http://js.hu/package/blosxom.php/ # PHPosxom: # Author: Robert Daeley <[email protected]> # Version 0.7 # Web: http://www.celsius1414.com/phposxom/ # Blosxom: # Author: Rael Dornfest <[email protected]> # Web: http://blosxom.com/ $NAME = "Blosxom.PHP"; $VERSION = "1.0"; $pubdates[] = filemtime(__FILE__); require_once "./conf.php"; $pubdates[] = filemtime("./conf.php"); require_once "./blosxom.php"; $pubdates[] = filemtime("./blosxom.php"); require_once "./dbahandler.php"; $pubdates[] = filemtime("./dbahandler.php"); readconf(); # ------------------------------------------------------------------- # FILE EXISTENCE CHECKING AND PREP # In which we establish a URL to this document, make sure all the files # that are supposed to be available are, figure out what time it is, # initialize some variables, etc. We also prove the existence of UFOs, # but that part''s hidden. -$https = array_key_exists("HTTPS", $_SERVER) && $_SERVER["HTTPS"] == "ON"; -$whoami = "http".($https? "s": "")."://".$_SERVER['SERVER_NAME']; -$sp =& $_SERVER['SERVER_PORT']; -if (($https && $sp != 433) || $sp != 80) - $whoami .= ":$sp"; -$whoami .= $_SERVER['SCRIPT_NAME']; +function is_https() { + return array_key_exists("HTTPS", $_SERVER) && $_SERVER["HTTPS"] == "ON"; +} + +function is_this_port_default_for_protocol($protocol, $port) { + if ($protocol === "https" && $port == 443) + return true; + if ($protocol === "http" && $port == 80) + return true; + return false; +} + +function whoami() { + $protocol = is_https() ? "https" : "http"; + $server_name = $_SERVER['SERVER_NAME']; + $server_port = $_SERVER['SERVER_PORT']; + $script_name = $_SERVER['SCRIPT_NAME']; + + $url = "${protocol}://${server_name}"; + if (is_this_port_default_for_protocol($protocol, $port)) + $url = "${url}:${server_port}"; + $url = "${url}${script_name}"; + return $url; +} +$whoami = whoami(); + $lastDoY = null; if ($conf_language != 'en') { if (($str = strchr($conf_language, "-"))) $locale = substr($conf_language, 0, strlen($str) - 1)."_".strtoupper(substr($str,1)); $locale .= ".".$conf_charset; setlocale(LC_TIME, $locale); } $force = false; function forceonopen() { $GLOBALS["force"] = true; } if ($conf_metafile) $mfdb =& DBA::singleton($conf_metafile."?onopen=forceopen"); if (is_string($conf_categoriesfile)) { $categories = false; $fname = rpath($conf_datadir, $conf_categoriesfile); if (file_exists($fname)) { $data = file($fname); foreach ($data as $categ) { $matches = explode("=", $categ); $categories[trim($matches[0])] = trim($matches[1]); } } } $shows = array(); if (is_array($conf_modules) && count($conf_modules)) { if (!isset($conf_moddir) || $conf_moddir == '') $conf_moddir = "."; foreach($conf_modules as $modval) { if (substr($modval, -4) != '.php') $modval .= ".php"; $modfn = rpath($conf_moddir, $modval); $moduleThere = file_exists($modfn); if (!$moduleThere) { echo explainError("nomod", $modval); exit; } else { require_once $modfn; $pubdates[] = filemtime($modfn); } } } $confdefs['category_delimiter'] = '/'; readconfdefs(); # ------------------------------------------------------------------- # URL-BASED FILTERS...NOW IN TRANSLUCENT COLORS! $showFilter = (isset($_GET["show"]) && isset($shows[$_GET["show"]]))? $shows[$_GET["show"]]: null; $flavFilter = (isset($_GET["flav"]) && isSaneFilename($_GET["flav"]))? $_GET["flav"]: null; $categoryFilter = isset($_GET["category"])? $_GET["category"]: (isset($_GET["cat"])? $_GET["cat"]: null); $authorFilter = isset($_GET["author"])? $_GET["author"]: (isset($_GET["by"])? $_GET["by"]: null); $entryFilter = isset($_GET["entry"])? $_GET["entry"]: (isset($_SERVER["PATH_INFO"])? $_SERVER["PATH_INFO"]: null); $dateFilter = isset($_GET["date"])? checkDateFilter($_GET["date"]): null; $startingEntry = isset($_GET["start"])? $_GET["start"]: 0; $cmd = isset($_GET["cmd"])? $_GET["cmd"]: false; $forcefile = strlen($conf_forcefile)? rpath($conf_datadir, $conf_forcefile): false; $force = $force || $cmd == 'force' || ($forcefile && file_exists($forcefile) && unlink($forcefile)); # Early command check authUser(); # ------------------------------------------------------------------- # CALL MODULE INITS if (isset($inits) && is_array($inits) && count($inits)) foreach ($inits as $init) if (function_exists($init)) call_user_func($init); # ------------------------------------------------------------------- # SHOW FUNCTION EXITS if ($showFilter && function_exists($showFilter)) { call_user_func($showFilter); exit; } # ------------------------------------------------------------------- # FIRST FILE LOOP $blogs = array(); $cats = array(); $daysBlogged = array(); checkSources(($force && !$entryFilter) || !isset($mfdb) || !$mfdb); if ($force && $forcefile && file_exists($forcefile)) unlink($forcefile); if (count($daysBlogged)) { $daysBlogged = array_keys($daysBlogged); rsort($daysBlogged); } # ------------------------------------------------------------------- # DETERMINE THE DOCUMENT TYPE AND SEND INITIAL HEADER() $content_type = "text/html"; if (!$flavFilter) $flavFilter = "default"; $flavThere = false; if (!isset($conf_flavdir) || $conf_flavdir == "") $conf_flavdir = "."; foreach (array($flavFilter, "default") as $flav) { $flavfile = $conf_flavdir."/".$flav.'_flav.php'; if (file_exists($flavfile)) { $flavThere = true; require $flavfile; $pubdates[] = filemtime($flavfile); break; } } if (!$flavThere) { echo explainError("noflavs"); exit; } $lastmod = max($pubdates); $etag = date("r", $lastmod); header("Last-modified: ".$etag); $theHeaders = getallheaders(); if (!$force && ((array_key_exists("If-Modified-Since", $theHeaders) && $theHeaders["If-Modified-Since"] == $etag) || (array_key_exists("If-None-Match", $theHeaders) && $theHeaders["If-Modified-Since"] == $etag))) { header('HTTP/1.0 304 Not Modified'); exit; } header("Content-Type: ".$content_type); # ------------------------------------------------------------------- # DETERMINE WHERE TO START AND STOP IN THE UPCOMING STORY ARRAYS $entries = count($blogs); if ($conf_entries < $entries) $thisManyEntries = $conf_entries; else $thisManyEntries = $entries; if ($entryFilter) { $thisManyEntries = $entries; $startingEntry = 0; } # ------------------------------------------------------------------- # SECOND FILE LOOP # In which we format the actual entries and do more filtering. $stories = ""; usort($blogs, create_function('$a,$b', 'return $b->date - $a->date;')); reset($blogs); foreach (array_splice($blogs, $startingEntry, $thisManyEntries) as $blog) { # deprecated if (!$conf_html_format) $blog->contents = parseText($blog->getContents()); $stories .= storyBlock($blog); } # END SECOND FILE LOOP # ------------------------------------------------------------------- # PATIENT BROWSER NOW BEGINS TO RECEIVE CONTENT print headBlock($categoryFilter); print (isset($stories) && strlen($stories))? $stories: explainError("noentries"); print footBlock(); # END OF PRINT, CLEANING UP DBA::closeall(); ?>
troter/object-oriented-exercise
1124c13499d9d24397d600b0182cfb91d7147153
型に合わせたnullチェックを追加
diff --git a/refactoring/blosxom.php-1.0/blosxom.php b/refactoring/blosxom.php-1.0/blosxom.php index a260d32..0eec76f 100644 --- a/refactoring/blosxom.php-1.0/blosxom.php +++ b/refactoring/blosxom.php-1.0/blosxom.php @@ -1,419 +1,426 @@ <?php # Blosxom.PHP: a rewrite of PHPosxom, which is a PHP rewrite of Blosxom # HELPER FUNCTIONS +function is_empty_string($str) { + return is_string($str) && strlen($str) == 0; +} +function is_empty_array($array) { + return is_array($array) && empty($array); +} + # Returns real path function rpath($wd, $path) { - if (is_string($path) && strlen($path)) { + if (is_empty_string($path)) { if ($path[0] != "/") $path = $wd."/".$path; } else $path = $wd; return realpath($path); } # Reads config function readconf() { global $conf; - if (isset($conf) && is_array($conf) && count($conf)) + if (isset($conf) && is_empty_array($conf)) foreach (array_keys($conf) as $key) if (isSaneFilename($key)) $GLOBALS["conf_".$key] = &$conf[$key]; } # Reads config defaults function readconfdefs() { global $confdefs; - if (isset($confdefs) && is_array($confdefs) && count($confdefs)) + if (isset($confdefs) && is_empty_array($confdefs)) foreach (array_keys($confdefs) as $key) if (isSaneFilename($key) && !array_key_exists("conf_".$key, $GLOBALS)) $GLOBALS["conf_".$key] = &$confdefs[$key]; } # Checks whether file name is valid function isSaneFilename($txt) { return !strcspn($txt, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890_-."); } function parseText($txt) { $txt = str_replace("\n\n", "</p><crlf><p class=\"blog\">", $txt); $txt = preg_replace("'>\s*\n\s*<'", "><crlf><", $txt); $txt = str_replace("\n", "<br />", $txt); $txt = str_replace("<crlf>", "\n", $txt); return "<p>$txt</p>"; } function w3cdate($time) { $date = date("Y-m-d\TH:i:sO", $time); return substr($date, 0, 22).":".substr($date, 22, 2); } # Generates GET URL from GET variables, and add/del arrays function genurl($add = false, $del = array("cmd")) { global $whoami; $arr = $_GET; if (is_array($del)) foreach ($del as $d) if (isset($arr[$d])) unset ($arr[$d]); if (is_array($add)) foreach ($add as $a=>$key) $arr[$a] = $key; $url = array(); foreach ($arr as $key=>$val) $url[] = "$key=".rawurlencode($val); return "$whoami?".implode("&amp;", $url); } $GLOBALS['__catcache'] = array(); # Returns category name function displaycategory($cat, $href=false) { global $__catcache, $categories, $conf_category_delimiter; $ccindex = $cat.":".$href; if (@array_key_exists($ccindex, $__catcache)) return $__catcache[$ccindex]; $cats = explode("/", $cat); $fullcat = ""; for ($i = 0; $i < count($cats); ++$i) { $fullcat .= $cats[$i]; if (@array_key_exists($fullcat, $categories)) $cats[$i] = $categories[$fullcat]; if ($href) $cats[$i] = "<a href=\"$href".$fullcat."\">".$cats[$i]."</a>"; $fullcat .= "/"; } $ret = implode($conf_category_delimiter, $cats); $__catcache[$ccindex] = $ret; return $ret; } class Blog { var $src; var $path; var $fp; var $title; var $date; var $mod; var $author; var $link; var $alias; var $valid; var $lead; var $contents; var $cat; var $displaycat; function Blog($key, $src=false) { global $conf_datadir, $conf_sources; global $blogs, $mfdb, $pubdates, $force; global $daysBlogged, $dateFilter, $dateFilterType; global $authorFilter, $entryFilter; $this->valid = false; $this->path = $key; $indb = $mdata = false; if (is_object($mfdb)) $mdata = $mfdb->fetch($key); if (is_array($mdata)) { if ($src !== false && $mdata[1] != $src) { if (!file_exists(rpath($conf_datadir, $conf_sources[$mdata[1]]['path'].$key))) $mfdb->delete($key); else { # concurring blog entries: drop it error_log("Concurring blog entries. New: $fp, orig: $origfp"); return; } } else { $indb = true; $date = $mdata[0]; $src = $mdata[1]; $title = $mdata[2]; $fd =& $conf_sources[$src]['fp']; $fp = $fd.$key; } } if (!isset($fp)) { if (!$src) { foreach (array_keys($conf_sources) as $s) { $fd =& $conf_sources[$s]['fp']; $fp = $fd.$key; if (file_exists($fp)) { $src = $s; break; } } } else { $fd =& $conf_sources[$src]['fp']; $fp = $fd.$key; } } if (!strlen($fp) || !file_exists($fp)) { if ($mfdb) $mfdb->delete($key); return false; } if (is_link($fp)) { $rfp = realpath($fp); if (file_exists($rfp) && !strncmp($fd, $rfp, strlen($fd))) { $nkey = substr($rfp, strlen($fd)); if ($indb) { $mfdb->replace($nkey, $mdata); $mfdb->delete($key); } } return false; } $mod = filemtime($fp); $this->date = ($indb && $date)? $date: $mod; $this->mod = $mod; $this->src = $src; $this->title = isset($title)? trim($title): ""; $this->fp = $fp; $this->author = $conf_sources[$src]["author"]; $this->link = $conf_sources[$src]["link"]; $this->alias = $src; $daysBlogged[date("Ymd", $this->date)] = 1; if (($dateFilter && date($dateFilterType, $this->date) != $dateFilter) || ($entryFilter && $key != $entryFilter) || ($authorFilter && $src != $authorFilter)) return; # Everything is OK, mark it as valid data $this->valid = true; if ($force || !$indb) { $fh = fopen($fp, "r"); $this->title = fgets($fh, 1024); fclose($fh); if ($mfdb) $mfdb->replace($key, array($this->date,$src,$this->title)); } $pubdates[] = $mod; $blogs[$this->path] = $this; } function isValid() { return $this && $this->valid; } function getContents($short = false) { if (!$this || !$this->valid) return; if (!$this->contents) { if (!file_exists($this->fp)) return false; $contents = file($this->fp); $this->title = array_shift($contents); $this->format = array_shift($contents); $this->short = $contents[0]; $this->contents = join("", $contents); } return $short? $this->short: $this->contents; } function getCategory() { if (!$this || !$this->valid) return; if (!$this->cat) $this->cat = substr($this->path, 1, strrpos($this->path, '/')-1); return $this->cat; } } function checkDir($src, $dir = "", $level = 1) { global $conf_depth, $conf_sources; global $cats, $categoryFilter; if ($conf_depth && $level > $conf_depth) return; $cats[] = $dir; $inCatFilter = !$categoryFilter || !strncmp($dir, $categoryFilter, strlen($categoryFilter)); $datadir = rpath($conf_sources[$src]['fp'], $dir); $dh = opendir($datadir); if (!is_resource($dh)) return; if ($level > 1) $dir .= "/"; $datadir .= "/"; while (($fname = readdir($dh)) !== false) { if ($fname[0] == '.') continue; $path = $dir.$fname; $opath = false; $fulln = $datadir.$fname; if (is_dir($fulln)) checkDir($src, $path, $level+1); elseif (substr($fname, -4) == '.txt' && $inCatFilter) new Blog("/".$path, $src); } } function checkSources($force) { global $conf_datadir, $conf_sources; global $mfdb, $cats, $categoryFilter; global $entryFilter, $blogs, $whoami; if (!count($conf_sources)) return; foreach (array_keys($conf_sources) as $src) $conf_sources[$src]['fp'] = rpath($conf_datadir, $conf_sources[$src]['path']); if ($force) { foreach (array_keys($conf_sources) as $src) checkDir($src); } elseif ($key = $mfdb->first()) { $cats[] = ""; do { if ($key[0] != "/") $key = "/$key"; $dir = substr($key, 1, strrpos($key, "/")-1); $cats[] = $dir; if (!$categoryFilter || !strncmp($dir, $categoryFilter, strlen($categoryFilter))) new Blog($key); } while ($key = $mfdb->next()); $cats = array_unique($cats); sort($cats); } if ($entryFilter && !isset($blogs[$entryFilter])) { foreach (array_keys($conf_sources) as $s) { $fd =& $conf_sources[$s]['fp']; $fp = realpath($fd.$entryFilter); if (file_exists($fp) && !strncmp($fd, $fp, strlen($fd))) { $nkey = substr($fp, strlen($fd)); header("Location: ".genurl( array("entry"=>$nkey), array("cmd") )); exit; } } } } function checkDateFilter($filter) { global $dateFilterType; $dateFilterLen = strlen($filter); if ($dateFilterLen == 4 or $dateFilterLen == 6 or $dateFilterLen == 8) { $dateFilterType = substr("Ymd", 0, ($dateFilterLen-2)/2); return $filter; } else { if ($dateFilterLen < 4) print explainError("shortdate"); elseif ($dateFilterLen > 8) print explainError("longdate"); elseif ($dateFilterLen == 5 or $dateFilterLen == 7 or is_numeric($dateFilter) == false) print explainError("wrongdate"); return false; } } /** * authenticates user * This is a basic authentication method for authenticating source * writers. */ function authUser() { global $NAME, $conf_sources, $cmd; $src =& $_SERVER["PHP_AUTH_USER"]; $pass =& $_SERVER["PHP_AUTH_PW"]; if ((!isset($src) && $cmd == "login") || (isset($src) && $cmd == "logout")) { echo explainError("autherr"); exit; } if ($cmd == "login" && (!isset($conf_sources[$src]) || !isset($conf_sources[$src]['pass']) || $pass != $conf_sources[$src]['pass'])) { echo explainError("autherr"); exit; } if (isset($src)) define("USER", $src); } function explainError($x, $p = false) { switch ($x) { case "autherr": header('WWW-Authenticate: Basic realm="'.$NAME.'"'); header('HTTP/1.0 401 Unauthorized'); return <<<End <html> <head> <title>Authentication Error</title> </head> <body><h1>Authentication Error</h1> <p>You have to log in to access this page.</p> </body> </html> End; case "nomod": return <<<End <p class="error"><strong>Cannot find module $p.</strong> Please check filenames.</p> End; case "noflavs": return <<<End <p class="error"><strong>Warning: Couldn&apos;t find a flavour file.</strong> It means that the blog is in an inconsistent stage. Please alert the blog maintainer.</p> End; case "permissions": return <<<End <p class="error"><strong>Warning: There&apos;s something wrong with the $ff folder&apos;s permissions.</strong> Please make sure it is readable by the www user and not just your selfish self.</p> End; case "shortdate": return <<<End <p class="error"><strong>The date you entered as a filter seems to be too short to work.</strong> Either that or this server has gone back in time. Please check the date and try again. In the case of the latter, the Temporal Maintenance Agency will have had knocked on your door by now.</p> End; case "longdate": return <<<End <p class="error"><strong>Either the date you entered as a filter is too long to work, or we&apos;re having a Y10K error.</strong> If it&apos;s not the year 10,000, please check the date and try again. If it is, tell Hackblop-4 from Pod Alpha -22-Pi we said hey.</p> End; case "wrongdate": return <<<End <p class="error"><strong>Something is screwy with the date you entered.</strong> It has the wrong number of digits, like that famous sideshow attraction Eleven-Fingered Elvira, or contains non-numeric characters. Speaking of characters, you should check the date and try again.</p> End; case "noentries": return <<<End <p class="error"><strong>No Results.</strong> The combination of filters for this page has resulted in no entries. Try another combination of dates, categories, and authors.</p> End; } } ?>
troter/object-oriented-exercise
0fb244aa276db32b2be6d8f11415b630219d893f
add .gitignore
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b25c15b --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +*~
troter/object-oriented-exercise
98ece8204b48a337754cb137be2e02297247f388
説明文
diff --git a/refactoring/README b/refactoring/README new file mode 100644 index 0000000..a3a044d --- /dev/null +++ b/refactoring/README @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- + +リファクタリング +================ +エクササイズに従い既存のプログラムのリファクタリングを行います。 + + +取得場所 +-------- +* blosxom.php-1.0 http://js.hu/package/blosxom.php/
troter/object-oriented-exercise
9c5e530af87e397973e641696ea43709a1c4a74a
add: blosxom.php
diff --git a/refactoring/blosxom.php-1.0/blosxom.php b/refactoring/blosxom.php-1.0/blosxom.php new file mode 100644 index 0000000..a260d32 --- /dev/null +++ b/refactoring/blosxom.php-1.0/blosxom.php @@ -0,0 +1,419 @@ +<?php +# Blosxom.PHP: a rewrite of PHPosxom, which is a PHP rewrite of Blosxom +# HELPER FUNCTIONS + +# Returns real path +function rpath($wd, $path) +{ + if (is_string($path) && strlen($path)) { + if ($path[0] != "/") + $path = $wd."/".$path; + } else + $path = $wd; + return realpath($path); +} + +# Reads config +function readconf() +{ + global $conf; + + if (isset($conf) && is_array($conf) && count($conf)) + foreach (array_keys($conf) as $key) + if (isSaneFilename($key)) + $GLOBALS["conf_".$key] = &$conf[$key]; +} + +# Reads config defaults +function readconfdefs() +{ + global $confdefs; + + if (isset($confdefs) && is_array($confdefs) && count($confdefs)) + foreach (array_keys($confdefs) as $key) + if (isSaneFilename($key) && !array_key_exists("conf_".$key, $GLOBALS)) + $GLOBALS["conf_".$key] = &$confdefs[$key]; +} + +# Checks whether file name is valid +function isSaneFilename($txt) +{ + return !strcspn($txt, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890_-."); +} + +function parseText($txt) +{ + $txt = str_replace("\n\n", "</p><crlf><p class=\"blog\">", $txt); + $txt = preg_replace("'>\s*\n\s*<'", "><crlf><", $txt); + $txt = str_replace("\n", "<br />", $txt); + $txt = str_replace("<crlf>", "\n", $txt); + return "<p>$txt</p>"; +} + +function w3cdate($time) +{ + $date = date("Y-m-d\TH:i:sO", $time); + return substr($date, 0, 22).":".substr($date, 22, 2); +} + +# Generates GET URL from GET variables, and add/del arrays +function genurl($add = false, $del = array("cmd")) +{ + global $whoami; + + $arr = $_GET; + if (is_array($del)) foreach ($del as $d) + if (isset($arr[$d])) + unset ($arr[$d]); + if (is_array($add)) foreach ($add as $a=>$key) + $arr[$a] = $key; + $url = array(); + foreach ($arr as $key=>$val) + $url[] = "$key=".rawurlencode($val); + return "$whoami?".implode("&amp;", $url); +} + +$GLOBALS['__catcache'] = array(); + +# Returns category name +function displaycategory($cat, $href=false) +{ + global $__catcache, $categories, $conf_category_delimiter; + + $ccindex = $cat.":".$href; + if (@array_key_exists($ccindex, $__catcache)) + return $__catcache[$ccindex]; + $cats = explode("/", $cat); + $fullcat = ""; + for ($i = 0; $i < count($cats); ++$i) { + $fullcat .= $cats[$i]; + if (@array_key_exists($fullcat, $categories)) + $cats[$i] = $categories[$fullcat]; + if ($href) + $cats[$i] = "<a href=\"$href".$fullcat."\">".$cats[$i]."</a>"; + $fullcat .= "/"; + } + $ret = implode($conf_category_delimiter, $cats); + $__catcache[$ccindex] = $ret; + return $ret; +} + +class Blog { + var $src; + var $path; + var $fp; + var $title; + var $date; + var $mod; + var $author; + var $link; + var $alias; + var $valid; + var $lead; + var $contents; + var $cat; + var $displaycat; + + function Blog($key, $src=false) + { + global $conf_datadir, $conf_sources; + global $blogs, $mfdb, $pubdates, $force; + global $daysBlogged, $dateFilter, $dateFilterType; + global $authorFilter, $entryFilter; + + $this->valid = false; + $this->path = $key; + + + $indb = $mdata = false; + if (is_object($mfdb)) + $mdata = $mfdb->fetch($key); + if (is_array($mdata)) { + if ($src !== false && $mdata[1] != $src) { + if (!file_exists(rpath($conf_datadir, + $conf_sources[$mdata[1]]['path'].$key))) + $mfdb->delete($key); + else { + # concurring blog entries: drop it + error_log("Concurring blog entries. New: $fp, orig: $origfp"); + return; + } + } else { + $indb = true; + $date = $mdata[0]; + $src = $mdata[1]; + $title = $mdata[2]; + $fd =& $conf_sources[$src]['fp']; + $fp = $fd.$key; + } + } + if (!isset($fp)) { + if (!$src) { + foreach (array_keys($conf_sources) as $s) { + $fd =& $conf_sources[$s]['fp']; + $fp = $fd.$key; + if (file_exists($fp)) { + $src = $s; + break; + } + } + } else { + $fd =& $conf_sources[$src]['fp']; + $fp = $fd.$key; + } + } + if (!strlen($fp) || !file_exists($fp)) { + if ($mfdb) + $mfdb->delete($key); + return false; + } + if (is_link($fp)) { + $rfp = realpath($fp); + if (file_exists($rfp) && !strncmp($fd, $rfp, strlen($fd))) { + $nkey = substr($rfp, strlen($fd)); + if ($indb) { + $mfdb->replace($nkey, $mdata); + $mfdb->delete($key); + } + } + return false; + } + + $mod = filemtime($fp); + + $this->date = ($indb && $date)? $date: $mod; + $this->mod = $mod; + $this->src = $src; + $this->title = isset($title)? trim($title): ""; + $this->fp = $fp; + $this->author = $conf_sources[$src]["author"]; + $this->link = $conf_sources[$src]["link"]; + $this->alias = $src; + + $daysBlogged[date("Ymd", $this->date)] = 1; + if (($dateFilter && date($dateFilterType, $this->date) != $dateFilter) + || ($entryFilter && $key != $entryFilter) + || ($authorFilter && $src != $authorFilter)) + return; + + # Everything is OK, mark it as valid data + $this->valid = true; + + if ($force || !$indb) { + $fh = fopen($fp, "r"); + $this->title = fgets($fh, 1024); + fclose($fh); + if ($mfdb) + $mfdb->replace($key, array($this->date,$src,$this->title)); + } + $pubdates[] = $mod; + $blogs[$this->path] = $this; + } + + function isValid() { return $this && $this->valid; } + function getContents($short = false) + { + if (!$this || !$this->valid) + return; + if (!$this->contents) { + if (!file_exists($this->fp)) + return false; + $contents = file($this->fp); + $this->title = array_shift($contents); + $this->format = array_shift($contents); + $this->short = $contents[0]; + $this->contents = join("", $contents); + } + return $short? $this->short: $this->contents; + } + function getCategory() + { + if (!$this || !$this->valid) + return; + if (!$this->cat) + $this->cat = substr($this->path, 1, strrpos($this->path, '/')-1); + return $this->cat; + } +} + +function checkDir($src, $dir = "", $level = 1) +{ + global $conf_depth, $conf_sources; + global $cats, $categoryFilter; + + if ($conf_depth && $level > $conf_depth) + return; + $cats[] = $dir; + $inCatFilter = !$categoryFilter || !strncmp($dir, $categoryFilter, strlen($categoryFilter)); + $datadir = rpath($conf_sources[$src]['fp'], $dir); + $dh = opendir($datadir); + if (!is_resource($dh)) + return; + if ($level > 1) + $dir .= "/"; + $datadir .= "/"; + while (($fname = readdir($dh)) !== false) { + if ($fname[0] == '.') + continue; + $path = $dir.$fname; + $opath = false; + $fulln = $datadir.$fname; + if (is_dir($fulln)) + checkDir($src, $path, $level+1); + elseif (substr($fname, -4) == '.txt' && $inCatFilter) + new Blog("/".$path, $src); + } +} + +function checkSources($force) +{ + global $conf_datadir, $conf_sources; + global $mfdb, $cats, $categoryFilter; + global $entryFilter, $blogs, $whoami; + + if (!count($conf_sources)) + return; + foreach (array_keys($conf_sources) as $src) + $conf_sources[$src]['fp'] = rpath($conf_datadir, $conf_sources[$src]['path']); + if ($force) { + foreach (array_keys($conf_sources) as $src) + checkDir($src); + } elseif ($key = $mfdb->first()) { + $cats[] = ""; + do { + if ($key[0] != "/") + $key = "/$key"; + $dir = substr($key, 1, strrpos($key, "/")-1); + $cats[] = $dir; + if (!$categoryFilter || !strncmp($dir, $categoryFilter, strlen($categoryFilter))) + new Blog($key); + } while ($key = $mfdb->next()); + $cats = array_unique($cats); + sort($cats); + } + if ($entryFilter && !isset($blogs[$entryFilter])) { + foreach (array_keys($conf_sources) as $s) { + $fd =& $conf_sources[$s]['fp']; + $fp = realpath($fd.$entryFilter); + if (file_exists($fp) && !strncmp($fd, $fp, strlen($fd))) { + $nkey = substr($fp, strlen($fd)); + header("Location: ".genurl( + array("entry"=>$nkey), + array("cmd") + )); + exit; + } + } + } +} + +function checkDateFilter($filter) +{ + global $dateFilterType; + $dateFilterLen = strlen($filter); + if ($dateFilterLen == 4 or $dateFilterLen == 6 or $dateFilterLen == 8) { + $dateFilterType = substr("Ymd", 0, ($dateFilterLen-2)/2); + return $filter; + } else { + if ($dateFilterLen < 4) + print explainError("shortdate"); + elseif ($dateFilterLen > 8) + print explainError("longdate"); + elseif ($dateFilterLen == 5 or $dateFilterLen == 7 or is_numeric($dateFilter) == false) + print explainError("wrongdate"); + return false; + } +} + +/** + * authenticates user + * This is a basic authentication method for authenticating source + * writers. + */ + +function authUser() +{ + global $NAME, $conf_sources, $cmd; + + $src =& $_SERVER["PHP_AUTH_USER"]; + $pass =& $_SERVER["PHP_AUTH_PW"]; + + if ((!isset($src) && $cmd == "login") + || (isset($src) && $cmd == "logout")) { + echo explainError("autherr"); + exit; + } + + if ($cmd == "login" && (!isset($conf_sources[$src]) + || !isset($conf_sources[$src]['pass']) + || $pass != $conf_sources[$src]['pass'])) { + echo explainError("autherr"); + exit; + } + if (isset($src)) + define("USER", $src); +} + +function explainError($x, $p = false) +{ + switch ($x) { + case "autherr": + header('WWW-Authenticate: Basic realm="'.$NAME.'"'); + header('HTTP/1.0 401 Unauthorized'); + return <<<End +<html> +<head> +<title>Authentication Error</title> +</head> +<body><h1>Authentication Error</h1> + +<p>You have to log in to access this page.</p> +</body> +</html> +End; + case "nomod": + return <<<End +<p class="error"><strong>Cannot find module $p.</strong> Please check filenames.</p> +End; + case "noflavs": + return <<<End +<p class="error"><strong>Warning: Couldn&apos;t find a flavour file.</strong> +It means that the blog is in an inconsistent stage. Please alert the blog +maintainer.</p> +End; + case "permissions": + return <<<End +<p class="error"><strong>Warning: There&apos;s something wrong with the $ff +folder&apos;s permissions.</strong> Please make sure it is readable by the www +user and not just your selfish self.</p> +End; + case "shortdate": + return <<<End +<p class="error"><strong>The date you entered as a filter seems to be too short +to work.</strong> Either that or this server has gone back in time. Please +check the date and try again. In the case of the latter, the Temporal +Maintenance Agency will have had knocked on your door by now.</p> +End; + case "longdate": + return <<<End +<p class="error"><strong>Either the date you entered as a filter is too long to +work, or we&apos;re having a Y10K error.</strong> If it&apos;s not the year +10,000, please check the date and try again. If it is, tell Hackblop-4 from +Pod Alpha -22-Pi we said hey.</p> +End; + case "wrongdate": + return <<<End +<p class="error"><strong>Something is screwy with the date you entered.</strong> +It has the wrong number of digits, like that famous sideshow attraction +Eleven-Fingered Elvira, or contains non-numeric characters. Speaking of +characters, you should check the date and try again.</p> +End; + case "noentries": + return <<<End +<p class="error"><strong>No Results.</strong> The combination of filters for +this page has resulted in no entries. Try another combination of dates, +categories, and authors.</p> +End; + } +} +?> diff --git a/refactoring/blosxom.php-1.0/conf-dist.php b/refactoring/blosxom.php-1.0/conf-dist.php new file mode 100644 index 0000000..a88657d --- /dev/null +++ b/refactoring/blosxom.php-1.0/conf-dist.php @@ -0,0 +1,66 @@ +<?php +# PHPosxom configuration file +# included by Blosxom.PHP + +$conf = array( +# What's this blog's title? + 'title' => "$NAME Blog" +# What's this blog's description? (for blog pages and outgoing RSS feed) + ,'description' => "Playing with $NAME" +# What's this blog's primary language? (for language settings, blog pages and outgoing RSS feed) + ,'language' => "en" +# What's this blog's character set? +# it can be utf-8, us-ascii, iso-8859-1, iso-8859-15, iso-8859-2 etc. + ,'charset' => "utf-8" +# Are blog bodies in (x)html? + ,'html_format' => false +# Where are this blog''s data kept? + ,'datadir' => "/Library/WebServer/Documents/blog" +# Where are your blog entries kept? You can use relative path from where your datadir is. + ,'category_delimiter' => " » " +# Where are your modules kept? You can use relative path from where index.php is. + ,'moddir' => "modules" +# Where are your flavours kept? You can use relative path from where index.php is. + ,'flavdir' => "flavs" +# Full URL to CSS file (if you have one) + ,'cssURL' => "blog.css" +# Metadata system keeps track of blog entries and their issue date to keep +# original order. To use this system, set metafile from false to an array +# (path is the database file, type is its type). + ,'metafile' => false #"db4:///metadata.db" +# Blog entry sources. All sources are read, each for an author. +# Each source entry is a name-description pair. +# Name is usually the author''s short name. +# Description is a list of key-value pairs: +# author: author''s full name +# link: link to author (any URL; use mailto: for email links) +# path: where author''s blog entries are kept (can be relative to datadir) + ,'sources' => array( + 'default' => array( + 'author' => "Default Author" + ,'link' => "mailto:foo&#40;bar.com" + ,'path' => "" + ) + ) +# Do you want to use the categories file system? Type false or a file name. +# If yes, list them in +# path = name +# format. + ,'categoriesfile' => false # "categories" +# An author can force recheck directories and put updates to metafile +# if a GET variable is set (eg. http://.../index.php?force=1) or +# a force file is in its place. The file will be deleted after the first +# update. The path is relative to datadir. + ,'forcefile' => "force" +# Should I stick only to the datadir for items or travel down the +# directory hierarchy looking for items? If so, to what depth? +# 0 = infinite depth (aka grab everything), 1 = source dir only, n = n levels +# down + ,'depth' => 0 +# How many entries should be shown per page? + ,'entries' => 10 +# EXTERNAL MODULES +# (should be in moddir and named with .php extension) + ,'modules' => array() +); +?> diff --git a/refactoring/blosxom.php-1.0/dbahandler.php b/refactoring/blosxom.php-1.0/dbahandler.php new file mode 100644 index 0000000..0db9782 --- /dev/null +++ b/refactoring/blosxom.php-1.0/dbahandler.php @@ -0,0 +1,325 @@ +<?php +# DBA handler +# Written by Balazs Nagy <[email protected]> +# Version: 2005-02-09 +# +# Call it as DBA::singleton($dsn), because only assures that already opened +# connections aren''t opened again, and it allows use of implicit closes + +$GLOBALS["__databases"] = false; +$GLOBALS["confdefs"]["dba_default_persistency"] = true; +$GLOBALS["debug"] = false; + +function debug_log($str) { + if (isset($GLOBALS["debug"]) && $GLOBALS["debug"] === true) + error_log($str); +} + +class DBA +{ + var $dsn; + var $info; + var $res; + var $opt; + var $handler; + + /** Creates a new DBA object defined by dsn. + * It assures that the same DBA object is returned to the same dsn''s + * @param $dsn text Data Source Name: type:///file/opt=val&opt2=val2... + * Each file can be relative to datadir. + * Valid options: + * persistent=true|1|on|enabled: enables persistency. Any others disables + * onopen=functionname: calls function if new database is created + * mode=c|r|w: open mode. c-create new, r-readonly, w-readwrite or create + */ + function &singleton($dsn) + { + $dbs = &$GLOBALS["__databases"]; + if (isset($dbs[$dsn])) { + debug_log("DBA::singleton: get old db as $dsn"); + $that = &$dbs[$dsn]; + } else { + $that = new DBA($dsn); + $dbs[$dsn] = &$that; + debug_log("DBA::singleton: create new db as $dsn"); + } + return $that; + } + + function closeall() + { + $dbs = &$GLOBALS["__databases"]; + if (is_array($dbs) && count($dbs)) foreach ($dbs as $db) + $db->close(); + } + + # quick and dirty DSN parser + function __parseDSN($dsn) + { + $ret = array( + "scheme" => "", + "path" => "", + "query" => "" + ); + $off = strpos($dsn, "://"); + if ($off !== false) + $ret["scheme"] = substr($dsn, 0, $off); + $off += 3; + $off2 = strpos($dsn, "/", $off); + if ($off2 !== false) + $off = $off2; + $off += 1; + $off2 = strpos($dsn, "?", $off); + if ($off2 !== false) { + $ret["path"] = substr($dsn, $off, $off2-$off); + $ret["query"] = substr($dsn, $off2+1); + } else + $ret["path"] = substr($dsn, $off); + return $ret; + } + + function DBA($dsn) + { + $this->dsn = $dsn; + $info = DBA::__parseDSN($dsn); + if (!isset($info["scheme"])) + return false; + $this->info = $info; + $this->res = false; + $this->handler = $info["scheme"]; + if (!function_exists("dba_handlers") + || !in_array($this->handler, dba_handlers())) + $this->handler = false; + if (strlen($info["query"])) + parse_str($info["query"], $this->opt); + } + + function &getOpt($opt) + { + if (!$this || !is_a($this, "DBA") || $this->res !== false) + return false; + $ret =& $this->opt[$opt]; + if (isset($ret)) + return $ret; + return null; + } + + function isOpt($opt, $val) + { + $ret =& getOpt($opt); + if (is_bool($val)) + return $ret === $val; + return $ret == $val; + } + + function open() + { + global $conf; + + if (!$this || !is_a($this, "DBA")) + return false; + if ($this->res !== false) + return true; + $fn = rpath($conf["datadir"], $this->info['path']); + if ($this->isOpt("mode", "c")) + $mode = "n"; + elseif ($this->isOpt("mode", "r")) { + if (!file_exists($fn)) + return false; + $mode = "r"; + } else { + if (file_exists($fn)) + $mode = "w"; + else { + $mode = "n"; + if (function_exists($this->getOpt("onopen"))) + call_user_func($this->getOpt("onopen")); + } + } + if ($this->handler !== false) { + $persistent =& $this->getOpt("persistent"); + if (!isset($persistent)) + $persistent =& $conf["dba_default_persistency"]; + else + $persistent = strtolower($persistent); + switch ($persistent) { + case true: + case "1": + case "on": + case "true": + case "enabled": + $caller = "dba_popen"; + break; + default: + $caller = "dba_open"; + } + $this->res = $caller($fn, $mode, $this->handler); + debug_log("$caller($fn, $mode, $this->handler) = $this->res"); + return is_resource($this->res); + } + if (!file_exists($fn) && !is_file($fn) + && !is_readable($fn) && !touch($fn)) + return false; + $mode = !!strstr($mode, "w"); + $this->res = $fn; + $this->cache = array( + "mode" => $mode, + "sync" => true, + "data" => @unserialize(file_get_contents($fn)) + ); + return true; + } + + function close() + { + if (!$this || !is_a($this, "DBA") || $this->res === false) + return false; + if ($this->handler) { + dba_close($this->res); + debug_log("dba_close($this->res)"); + } else { + $this->sync(); + $this->cache = false; + } + $this->res = false; + } + + function first() + { + if (!$this || !is_a($this, "DBA")) + return false; + if (!$this->open()) + return false; + if ($this->handler) { + $key = dba_firstkey($this->res); + debug_log("dba_firstkey($this->res)"); + return $key; + } + if (!is_array($this->cache["data"]) || !count($this->cache["data"])) + return false; + if (reset($this->cache["data"]) === false) + return false; + return key($this->cache["data"]); + } + + function next() + { + if (!$this || !is_a($this, "DBA")) + return false; + if (!$this->open()) + return false; + if ($this->handler) { + debug_log("dba_nextkey($this->res)"); + return dba_nextkey($this->res); + } + if (!is_array($this->cache["data"]) || !count($this->cache["data"])) + return false; + if (next($this->cache["data"]) === false) + return false; + return key($this->cache["data"]); + } + + function fetch($key) + { + if (!$this || !is_a($this, "DBA")) + return false; + if (!$this->open()) + return false; + if ($this->handler) { + debug_log("dba_fetch($key, $this->res)"); + $val = dba_fetch($key, $this->res); + if (!is_string($val)) + return null; + $v = @unserialize($val); + if ($v === false && $val != 'b:0;') { + // old value, needs correction + $v = explode(",", $val, 3); + $v[2] = str_replace("&#44;", ",", $v[2]); + dba_replace($key, serialize($v), $this->res); + } + return $v; + } + if (!is_array($this->cache["data"]) || !count($this->cache["data"]) || !isset($this->cache["data"][$key])) + return false; + return $this->cache["data"][$key]; + } + + function insert($key, $val) + { + if (!$this || !is_a($this, "DBA")) + return false; + if (!$this->open()) + return false; + if ($this->handler) { + debug_log("dba_insert($key, $val, $this->res)"); + return dba_insert($key, serialize($val), $this->res); + } + if (!is_array($this->cache["data"])) + $this->cache["data"] = array(); + elseif (isset($this->cache["data"][$key])) + return false; + $this->cache["data"][$key] = $val; + $this->cache["sync"] = false; + return true; + } + + function replace($key, $val) + { + if (!$this || !is_a($this, "DBA")) + return false; + if (!$this->open()) + return false; + if ($this->handler) { + debug_log("dba_replace($key, $val, $this->res)"); + return dba_replace($key, serialize($val), $this->res); + } + if (!is_array($this->cache["data"])) + $this->cache["data"] = array(); + debug_log("DBA::replace($key, $val, $this->res)"); + $this->cache["data"][$key] = $val; + $this->cache["sync"] = false; + return true; + } + + function delete($key) + { + if (!$this || !is_a($this, "DBA")) + return false; + if (!$this->open()) + return false; + if ($this->handler) { + debug_log("dba_delete($key, $this->res)"); + return dba_delete($key, $this->res); + } + if (!is_array($this->cache["data"]) || !count($this->cache["data"]) || !isset($this->cache["data"][$key])) + return false; + unset($this->cache["data"][$key]); + $this->cache["sync"] = false; + return true; + } + + function optimize() + { + if (!$this || !is_a($this, "DBA") || $this->res === false || $this->handler === false) + return false; + dba_optimize($this->res); + debug_log("dba_optimize($this->res)"); + } + + function sync() + { + if (!$this || !is_a($this, "DBA") || $this->res === false) + return false; + if ($this->handler && $this->res) { + debug_log("dba_sync($this->res)"); + return dba_sync($this->res); + } + if (!$this->cache["mode"] || $this->cache["sync"]) + return true; + $fh = fopen($this->res, "w"); + fwrite($fh, serialize($this->cache["data"])); + fclose($fh); + return true; + } +} +?> diff --git a/refactoring/blosxom.php-1.0/flavs/atom_flav.php b/refactoring/blosxom.php-1.0/flavs/atom_flav.php new file mode 100644 index 0000000..f7b13e4 --- /dev/null +++ b/refactoring/blosxom.php-1.0/flavs/atom_flav.php @@ -0,0 +1,98 @@ +<?php +# Blosxom.PHP: a rewrite of PHPosxom, which is a PHP rewrite of Blosxom +# ATOM v. 0.3 FLAVOR FILE +# The purpose is to allow you to customize the look and feel of +# your PHPosxom blog without the necessity of using flav=foo in +# the URL or editing the main script. +# +# See: http://www.intertwingly.net/wiki/pie/FrontPage +# ---------------------------------------------------------------- +# USAGE +# There are three functions below that form the head, story, and +# foot blocks on a blog page. +# ---------------------------------------------------------------- +# $content_type lets the browser know what kind of content is being +# served. You''-ll probably want to leave this alone. + +$content_type = "application/atom+xml"; + +function headBlock($category) { + global $conf_title, $conf_description, $conf_language, $conf_charset; + global $lastmod, $whoami, $NAME, $VERSION; + + $thetitle = $conf_title; + if ($category) + $thetitle .= " ($category)"; + $head = '<?xml version="1.0"'; + if (isset($conf_charset) and $conf_charset != 'utf-8') + $head .= " encoding=\"$conf_charset\""; + $head .= "?".">\n"; + $lastpub = w3cdate($lastmod); + return <<<End +${head} +<feed version="0.3" xmlns="http://purl.org/atom/ns#" xml:lang="$conf_language"> + <title>$thetitle</title> + <link rel="alternate" type="text/html" href="$whoami"/> + <modified>$lastpub</modified> + <tagline>$conf_description</tagline> + <generator>$NAME $VERSION</generator> + +End; +} + +function storyBlock($blog) +{ + global $whoami, $conf_cssURL; + + $title = htmlspecialchars($blog->title); + $text = $blog->getContents(true); + $html = htmlspecialchars('<'.<<<End +html> +<head> +<base href="$whoami" /> +<style>@import "$conf_cssURL";</style> +<title>$title</title> +</head> +<body id="rss"> +$text +</body> +</html> +End +); + $author = htmlspecialchars($blog->author); + $authorlink = $blog->link; + if (!strncmp($authorlink, "mailto:", 7)) + $authorlink = "<email>".html_entity_decode(substr($authorlink, 7))."</email>\n"; + else + $authorlink = "<url>$authorlink</url>\n"; + $displaycat = htmlspecialchars(displaycategory($blog->getCategory())); + $path = htmlspecialchars($blog->path); + $date = w3cdate($blog->date); + $mod = $blog['mod']? w3cdate($blog->mod): $date; + $url = $whoami; + $link = $url.htmlspecialchars($blog->path); + $href = $url.rawurlencode($blog->path); + return <<<End +<entry> + <title>$title</title> + <link rel="alternate" type="text/html" href="$link"/> + <id>$whoami:$path</id> + <author> + <name>$author</name> + $authorlink + </author> + <issued>$date</issued> + <modified>$mod</modified> + <content type="text/html" mode="escaped">$html</content> +</entry> + +End; +} + +function footBlock() { + + return <<<End +</feed> +End; +} +?> diff --git a/refactoring/blosxom.php-1.0/flavs/default_flav.php b/refactoring/blosxom.php-1.0/flavs/default_flav.php new file mode 100644 index 0000000..f2d506e --- /dev/null +++ b/refactoring/blosxom.php-1.0/flavs/default_flav.php @@ -0,0 +1,442 @@ +<?php +# Blosxom.PHP: a rewrite of PHPosxom, which is a PHP rewrite of Blosxom +# DEFAULT FLAVOR FILE +# The purpose is to allow you to customize the look and feel of +# your PHPosxom blog without the necessity of using flav=foo in +# the URL or editing the main script. +# ---------------------------------------------------------------- +# USAGE +# There are three functions below that form the head, story, and +# foot blocks on a blog page. +# ---------------------------------------------------------------- +# $content_type lets the browser know what kind of content is being +# served. You''ll probably want to leave this alone. + +$content_type ='text/html'; + +reset($conf_sources); +foreach (array_keys($conf_sources) as $src) { + if (isset($conf_sources[$src]["author"])) { + $cHolder = $conf_sources[$src]["author"]; + break; + } +} + +if ($conf_language == "hu-hu") { + if (!isset($cHolder)) + $cHolder = "a szerzők"; + $msg['archives'] = "Archívum"; + $msg['atomfeed'] = "ATOM feed"; + $msg['blogroll'] = "Blogroll"; + $msg['calendar'] = "Naptár"; + $msg['cannotpost'] = "Nem lehet hozzászólást küldeni!"; + $msg['categories'] = "Kategóriák"; + $msg['copyright'] = "Copyright&copy; $cHolder az egész tartalomra"; + $msg['datefmt'] = "%Y. %B %e."; + $msg['delentry'] = "töröl"; + $msg['lastcomments'] = "Utolsó hozzászólások"; + $msg['main'] = "Főoldal"; + $msg['next'] = "következő &raquo;"; + $msg['prev'] = "&laquo; előző"; + $msg['preview'] = "Előnézet"; + $msg['readthis'] = "Olvasd el:"; + $msg['rss1feed'] = "RSS1 feed"; + $msg['rss2feed'] = "RSS2 feed"; + $msg['send'] = "Küld"; + $msg['timefmt'] = "G:i T"; + $msg['trackback'] = "Honnan néztek:"; + $msg['writehere'] = ", írd ide:"; + $msg['wrongresp'] = "Hibás válasz!"; + $msg['yourname'] = "Neved"; + $msg['youropinion'] = "Írd meg a véleményed:"; +} else { + if (!isset($cHolder)) + $cHolder = "the authors"; + $msg['archives'] = "Archive"; + $msg['atomfeed'] = "ATOM feed"; + $msg['blogroll'] = "Blogroll"; + $msg['calendar'] = "Calendar"; + $msg['cannotpost'] = "Comments cannot be posted."; + $msg['categories'] = "Categories"; + $msg['copyright'] = "All contents copyright&copy; by $cHolder"; + $msg['datefmt'] = "%Y-%m-%d"; + $msg['delentry'] = "delete"; + $msg['lastcomments'] = "Last Comments"; + $msg['main'] = "Main"; + $msg['next'] = "Next &raquo;"; + $msg['prev'] = "&laquo; Previous"; + $msg['preview'] = "Preview"; + $msg['readthis'] = "Read this:"; + $msg['rss1feed'] = "RSS1 feed"; + $msg['rss2feed'] = "RSS2 feed"; + $msg['send'] = "Send"; + $msg['timefmt'] = "g:i A T"; + $msg['trackback'] = "Track backs:"; + $msg['writehere'] = ", write here:"; + $msg['wrongresp'] = "You wrote a wrong response."; + $msg['yourname'] = "Your name:"; + $msg['youropinion'] = "Write your opinion:"; +} + +# --------------------------------------------------------------- +# headBlock is the HTML that forms the top of a PHPosxom page. + +function headBlock($cat) +{ + global $conf_title, $conf_description, $conf_language, $conf_charset; + global $conf_cssURL, $whoami, $NAME, $VERSION; + global $category; + + $ret = "<!DOCTYPE html + PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" + \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"> +<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"$conf_language\" lang=\"$conf_language\"> +<head> +<meta http-equiv=\"content-type\" content=\"text/html; charset=$conf_charset\" /> +<style type=\"text/css\">@import \"$conf_cssURL\";</style> +<meta name=\"generator\" content=\"$NAME $VERSION\" /> +<link rel=\"alternate\" type=\"application/rss+xml\" title=\"RSS\" href=\"$whoami?flav=rss2\" /> +<link rel=\"alternate\" type=\"application/atom+xml\" title=\"ATOM\" href=\"$whoami?flav=atom\" /> +<title>$conf_title: $conf_description</title> +</head> +<body> +<div id=\"wrapper\"> +<div id=\"page\"> +<div id=\"header\">$conf_title</div> +<div id=\"body\"> +<div id=\"main\"> +<p class=\"descr\">$conf_description</p>\n"; + if (function_exists("getFortune")) + $ret .= '<p class="fortune">'.getFortune()."</p>\n"; + if ($cat) + $ret .= "<h3>".displaycategory($cat, $whoami."?category=")."</h3>\n"; + return $ret; +} + +# --------------------------------------------------------------- +# storyBlock is the HTML that constructs an individual blog entry. +# You can add additional lines by following the $story[] format below. + +function storyBlock($blog) +{ + global $whoami, $entryFilter, $lastDoY, $msg; + + # If just one entry is shown, one can post and/or read comments + + $tbs = ""; + $path = $blog->path; + $comments = ""; + if ($entryFilter) { + if (function_exists("trackbackReferrer")) + trackbackReferrer($path); + if (function_exists("getTrackbacks")) { + $tb = getTrackbacks($path); + if ($tb) { + $tbs .= "<h4 id=\"trackbacks\">".$msg['trackback']."</h4>\n" + ."<ul class=\"blogTrackbacks\">\n"; + foreach ($tb as $url=>$count) + $tbs .= "<li><a href=\"$url\">$url</a> ($count)</li>\n"; + $tbs .= "</ul>\n"; + } + } + $comments = handleComments($blog); + if ($comments != '') + $comments = "<div class=\"blogComments\">\n".$comments."</div>\n"; + } + + $thisDoY = date("Ymd", $blog->date); + $displaydate = strftime($msg['datefmt'], $blog->date); + $time = date($msg['timefmt'], $blog->date); + + if (!$lastDoY or ($thisDoY-$lastDoY < 0)) + $displaydate = "<p class=\"blogdate\">$displaydate</p>\n"; + else + $displaydate = ""; + $lastDoY = $thisDoY; + if (function_exists("countComments")) + $commentCount = countComments($path); + else + $commentCount = "#"; + $author = $blog->author; + $alink = $blog->link; + if (isset($alink) && strlen($alink)) { + if (!preg_match("/^((ht|f)tp:\/\/|mailto:)/", $alink)) + $alink = "mailto:".$alink; + $author = "<a href=\"$alink\">$author</a>"; + } + + return "$displaydate<h4>$blog->title</h4> +<div class=\"blog\">\n".$blog->getContents() + ."<p class=\"blogmeta\">$author @ $time [ <a href=\"${whoami}?category=" + .$blog->getCategory()."\">".displaycategory($blog->getCategory())."</a>" + ." | <a href=\"".$whoami.$path."\">$commentCount</a> ]</p> +</div> +$tbs$comments +"; +} + +function mklink($path, $offset, $val=false) +{ + global $whoami, $entryFilter; + if ($val === false) + $val = $offset + 1; + return "<a href=\"" + .htmlspecialchars($whoami."$entryFilter?offset=$offset") + ."\">$val</a>"; +} + +function handleComments(&$blog) +{ + global $defwho, $defwhat, $valid, $conf_comments_maxnum; + global $conf_comments_firsttolast, $msg, $cmd; + + $defwho = ''; + $defwhat = ''; + + if (!function_exists("getComments")) + return ''; + if (defined('USER') && $cmd == 'del') { + $when = intval($_GET['when']); + delComment($blog->path, $when); + } + + if (isset($_COOKIE['who'])) { + $defwho = $_COOKIE['who']; + if (!get_magic_quotes_gpc()) + $defwho = addslashes($defwho); + } + + $ret = ''; + if (isset($_POST['addcomment'])) { + if (function_exists("validateATuring")) + $valid = validateATuring($_POST['challenge'], $_POST['response']); + else + $valid = null; + $defwho = $_POST['who']; + $defwhat = $_POST['what']; + $defwhat = strip_tags($defwhat, "<a><b><i><em><strong><code>"); + if (get_magic_quotes_gpc()) { + $defwho = stripslashes($defwho); + $defwhat = stripslashes($defwhat); + } + if ((!isset($_POST['preview']) || !strlen($_POST['preview'])) && $valid === true) { + if (function_exists("addComment")) { + addComment($blog->path, $defwho, $defwhat); + $defwhat = ""; + } else + $ret .= "<p class=\"error\">".$msg['cannotpost']."</p>"; + } + setcookie("who", $_POST['who'], time()+7776000); + } + + $comments = getComments($blog->path); + if (!is_array($comments) || !count($comments)) + return $ret; + if ($conf_comments_firsttolast) + ksort($comments); + else + krsort($comments); + $l =& $conf_comments_maxnum; + if ($l && $l < count($comments)) { + $len = count($comments); + $navi = array(); + $o = isset($_GET['offset'])? intval($_GET['offset']): 0; + $comments = array_slice($comments, $o*$l, $l); + $last = intval(($len-1)/$l); + $links = false; + if ($o > 0) + $links[] = mklink($blog->path, $o - 1, $msg['prev']); + for ($i = 0; $i < 7; ++$i) { + if ((!$i && $o > 2) || ($i == 6 && $o < ($last-2))) { + $links[] = "&hellip;"; + continue; + } + $num = $o + $i - 3; + if ($i == 3) + $links[] = $o+1; + elseif ($num >= 0 && $num <= $last) + $links[] = mklink($blog->path, $o+$i-3); + } + if ($o < $last) + $links[] = mklink($blog->path, $o+1, $msg['next']); + $ret .= "<p class=\"navi\">".join(" | ", $links)."</p>\n"; + } + if (is_array($comments) && count($comments)) { + foreach ($comments as $comment) + $ret .= commentBlock($blog, $comment); + } + return $ret; +} + +function commentBlock(&$blog, $comment, $short=false) +{ + global $whoami, $msg; + + switch (count($comment)) { + case 5: + $title = $comment[4]; + case 4: + $path = $comment[3]; + case 3: + $when = $comment[2]; + case 2: + $what = $comment[1]; + case 1: + $who = $comment[0]; + } + $date = strftime($msg['datefmt'],$when); + $time = date($msg['timefmt'], $when); + if ($short) { + $after = false; + if (strlen($what) > 80) { + $after = true; + $what = substr($what, 0, 80); + $p = strrpos($what, " "); + if ($p !== false) + $what = substr($what, 0, $p); + } + $p = strpos($what, "\n"); + if ($p !== false) { + $after = true; + $what = substr($what, 0, $p); + } + + if ($after) + $what = $what."&hellip;"; + } + $what = parseText($what); + + $meta = "$who @ $date $time"; + if (isset($path)) + $meta = "$meta [<a href=\"$whoami$path\">$title</a>]"; + if (defined("USER") && $blog->src == USER) + $meta .= " <a href=\"$whoami$blog->path?cmd=del&when=$when\">" + .$msg['delentry']."</a>"; + + $ret = <<<End +<div class="comment"> +$what +<p class="blogmeta">$meta</p> +</div> + +End; + return $ret; +} + +# --------------------------------------------------------------- +# footBlock is the HTML that forms the bottom of the page. + +function footBlock() { + global $whoami, $defwho, $defwhat, $entryFilter, $conf_comments_firsttolast, + $conf_comments_maxnum, $conf_entries, $startingEntry, $entries; + global $categoryFilter, $NAME, $VERSION, $valid, $msg; + + $ret = ""; + if ($entryFilter) { + $myurl = "$entryFilter"; + if (isset($conf_comments_firsttolast) + && $conf_comments_firsttolast === true + && $conf_comments_maxnum + && ($len = count(getComments($entryFilter))) > $conf_comments_maxnum) + $myurl .= "?offset=".intval($len/$conf_comments_maxnum); + $ret .= "<h4 id=\"post\">$msg[youropinion]</h4>\n" + ."<form method=\"post\" action=\"$whoami$myurl#post\">"; + if (function_exists("getATuring")) { + $c =& $_REQUEST['challenge']; + $r =& $_REQUEST['response']; + $data = getATuring($c, $r); + if ($valid === false) + $ret .= "\n<p class=\"error\">".$msg['wrongresp']."</p>\n"; + $ret .= "\n".$msg['readthis']." <img src=\"$data[0]\" />" + ."<input type=\"hidden\" name=\"challenge\" value=\"$data[1]\" />" + .$msg['writehere']." <input type=\"text\" name=\"response\" " + .(isset($r)? ('value="'.$r.'"'):'') + ."/><br />\n"; + } + + $ret .= <<<End +$msg[yourname]: <input type="text" name="who" value="$defwho" /> +$msg[preview]: <input type="checkbox" name="preview" checked="checked" /> +<input type="submit" name="addcomment" value="$msg[send]" /><br /> +<textarea name="what" wrap="soft" cols="50" rows="5">$defwhat</textarea> +</form> + +End; + if (is_string($defwhat) and strlen($defwhat)) { + $blog = null; + $ret .= "<div class=\"blogComments\">\n" + ."<h4>".$msg['preview'].":</h4>\n" + . commentBlock($blog, array(stripslashes($defwho), stripslashes($defwhat), time())) + . "</div>\n"; + $defwhat = stripslashes($defwhat); + } + } else { + $navi = array(); + if (($startingEntry+$conf_entries) < $entries) + $navi[] = "<a href=\"".genurl(array("start" => $startingEntry + $conf_entries))."\">".$msg['prev']."</a>"; + if ($startingEntry >= $conf_entries) + $navi[] = "<a href=\"".genurl(array("start" => $startingEntry - $conf_entries))."\">".$msg['next']."</a>"; + if (count($navi)) + $ret .= "<p class=\"navi\">".join(" | ", $navi)."</p>\n"; + } + + $ret .= <<<End +</div> +<div id="navi"> +End; + if (function_exists("listCats")) { + $ret .= "<h2>$msg[categories]:</h2>\n" + ."<form method=\"GET\"><select class=\"blogCats\" " + ."name=\"category\" onchange=\"submit()\">\n"; + $dcats = getCats(); + foreach ($dcats as $kitty) { + if ($categoryFilter == $kitty['category']) + $sel = ' selected="selected"'; + else + $sel = ""; + $ret .= '<option value="'.$kitty['category'].'"'.$sel.'>' + .$kitty['name']."</option>\n"; + } + $ret .= "</select></form>\n"; + } + if (function_exists("makeCal") && ($cal = makeCal()) !== false) + $ret .= "<h2>$msg[calendar]:</h2>\n" . $cal; + if (function_exists("makeBlogroll")) + $ret .= "<h2>$msg[blogroll]:</h2>\n" . makeBlogroll(); + if (function_exists("lastComments")) { + $cmts = lastComments(); + if (is_array($cmts) && count($cmts)) { + $ret .= "<h2>$msg[lastcomments]:</h2>\n"; + $blog = false; + foreach ($cmts as $cmt) + $ret .= commentBlock($blog, $cmt, true); + } + } + if (function_exists("showArchives")) { + $archs = showArchives(); + if (count($archs)) + $ret .= "<h2>$msg[archives]:</h2>\n<ul>\n<li>" + .join("</li>\n<li>", $archs)."</li>\n</ul>\n"; + } + return $ret . <<<End +</div> +<div id="mainfooter">&nbsp;</div> +</div> +<div id="footer"> +<ul> + <li class="first"><a href="/">$msg[main]</a></li> + <li><a href="${whoami}?flav=rss">$msg[rss1feed]</a></li> + <li><a href="${whoami}?flav=rss2">$msg[rss2feed]</a></li> + <li><a href="${whoami}?flav=atom">$msg[atomfeed]</a></li> + <li>Powered by <a href="http://js.hu/package/blosxom.php/">$NAME $VERSION</a></li> +</ul> +<p>$msg[copyright]</p> +</div> +</div> +</div> +</body> +</html> + +End; +} +?> diff --git a/refactoring/blosxom.php-1.0/flavs/rss2_flav.php b/refactoring/blosxom.php-1.0/flavs/rss2_flav.php new file mode 100644 index 0000000..258de83 --- /dev/null +++ b/refactoring/blosxom.php-1.0/flavs/rss2_flav.php @@ -0,0 +1,94 @@ +<?php +# Blosxom.PHP: a rewrite of PHPosxom, which is a PHP rewrite of Blosxom +# RSS2 FLAVOR FILE +# The purpose is to allow you to customize the look and feel of +# your PHPosxom blog without the necessity of using flav=foo in +# the URL or editing the main script. +# ---------------------------------------------------------------- +# USAGE +# There are three functions below that form the head, story, and +# foot blocks on a blog page. +# ---------------------------------------------------------------- +# $content_type lets the browser know what kind of content is being +# served. You''ll probably want to leave this alone. + +$content_type = "text/xml"; + +function headBlock($category) { + global $conf_title, $conf_description, $conf_language, $conf_charset; + global $etag; + global $whoami; + + $title = $conf_title; + if ($category) + $title .= " ($category)"; + $head = '<?xml version="1.0"'; + if (isset($conf_charset) and $conf_charset != 'utf-8') + $head .= " encoding=\"$conf_charset\""; + $head .= "?".">\n"; + $head .= <<<End +<rss version="2.0"> +<channel> + <title>$title</title> + <link>$whoami</link> + <description>$conf_description</description> + +End; + if ($etag) { + $head .= " <pubDate>$etag</pubDate>\n"; + $head .= " <lastBuildDate>$etag</lastBuildDate>\n"; + } + $head .= <<<End + <language>$conf_language</language> + +End; + return $head; +} + +function storyBlock($blog) +{ + global $whoami, $conf_cssURL; + + $title = htmlspecialchars($blog->title); + $text = $blog->getContents(true); + $html = htmlspecialchars(<<<End +<html> +<head> +<base href="$whoami" /> +<style>@import "$conf_cssURL";</style> +<title>$title</title> +</head> +<body id="rss"> +$text +</body> +</html> +End +); + $author = htmlspecialchars($blog->author); + $displaycat = htmlspecialchars(displaycategory($blog->getCategory())); + $path = htmlspecialchars($blog->path); + $date = date("r", $blog->date); + $url = $whoami; + $link = $url.htmlspecialchars($blog->path); + $href = $url.rawurlencode($blog->path); + return <<<End +<item> + <title>$title</title> + <category>$displaycat</category> + <author>$author</author> + <pubDate>$date</pubDate> + <link>$link</link> + <description>$html</description> +</item> + +End; +} + +function footBlock() { + + return <<<End +</channel> +</rss> +End; +} +?> diff --git a/refactoring/blosxom.php-1.0/flavs/rss_flav.php b/refactoring/blosxom.php-1.0/flavs/rss_flav.php new file mode 100644 index 0000000..1362887 --- /dev/null +++ b/refactoring/blosxom.php-1.0/flavs/rss_flav.php @@ -0,0 +1,102 @@ +<?php +# Blosxom.PHP: a rewrite of PHPosxom, which is a PHP rewrite of Blosxom +# RSS FLAVOR FILE +# The purpose is to allow you to customize the look and feel of +# your PHPosxom blog without the necessity of using flav=foo in +# the URL or editing the main script. +# +# See http://purl.org/rss/1.0 +# ---------------------------------------------------------------- +# USAGE +# There are three functions below that form the head, story, and +# foot blocks on a blog page. + +function headBlock($category) +{ + global $conf_title, $conf_charset, $conf_description, $conf_language, $lastmod; + global $whoami; + + $thetitle = $conf_title; + if ($category) + $thetitle .= " ($category)"; + $head = '<?xml version="1.0"'; + if (isset($conf_charset) && $conf_charset != 'utf-8') + $head .= " encoding=\"$conf_charset\""; + $head .= "?".">".<<<End +<rdf:RDF + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns="http://purl.org/rss/1.0/" + xmlns:dc="http://purl.org/dc/elements/1.1/" +> +<channel rdf:about="$whoami"> + <title>$thetitle</title> + <link>$whoami</link> + <description>$conf_description</description> + +End; + if ($lastmod) + $head .= " <dc:date>".w3cdate($lastmod)."</dc:date>\n"; + $head .= <<<End + <language>$conf_language</language> + <items> + <rdf:Seq> + +End; + return $head; +} + +function storyBlock($blog) +{ + global $whoami, $conf_cssURL; + global $rss_stories; + + $title = htmlspecialchars($blog->title); + $text = $blog->getContents(true); + $html = htmlspecialchars(<<<End +<html> +<head> +<base href="$whoami" /> +<style>@import "$conf_cssURL";</style> +<title>$title</title> +</head> +<body id="rss"> +$text +</body> +</html> +End +); + $author = htmlspecialchars($blog->author); + $displaycat = htmlspecialchars(displaycategory($blog->getCategory())); + $path = htmlspecialchars($blog->path); + $date = w3cdate($blog->date); + $url = $whoami; + $link = $url.htmlspecialchars($blog->path); + $href = $url.rawurlencode($blog->path); + if (!isset($rss_stories)) + $rss_stories = ''; # to be strict + $rss_stories .= <<<End +<item rdf:about="$href"> +<title>$title</title> +<dc:subject>$displaycat</dc:subject> +<dc:creator>$author</dc:creator> +<dc:date>$date</dc:date> +<link>$link</link> +<description>$html</description> +</item> + +End; + return " <rdf:li rdf:resource=\"$href\" />\n"; +} + +function footBlock() { + global $rss_stories; + + return <<<End + </rdf:Seq> + </items> +</channel> +$rss_stories +</rdf:RDF> +End; +} +?> diff --git a/refactoring/blosxom.php-1.0/index.php b/refactoring/blosxom.php-1.0/index.php new file mode 100644 index 0000000..1bae3c0 --- /dev/null +++ b/refactoring/blosxom.php-1.0/index.php @@ -0,0 +1,232 @@ +<?php +# Blosxom.PHP: a rewrite of PHPosxom, which is a PHP rewrite of Blosxom +# Author: Balazs Nagy <[email protected]> +# Web: http://js.hu/package/blosxom.php/ + +# PHPosxom: +# Author: Robert Daeley <[email protected]> +# Version 0.7 +# Web: http://www.celsius1414.com/phposxom/ + +# Blosxom: +# Author: Rael Dornfest <[email protected]> +# Web: http://blosxom.com/ + +$NAME = "Blosxom.PHP"; +$VERSION = "1.0"; + +$pubdates[] = filemtime(__FILE__); +require_once "./conf.php"; $pubdates[] = filemtime("./conf.php"); +require_once "./blosxom.php"; $pubdates[] = filemtime("./blosxom.php"); +require_once "./dbahandler.php"; $pubdates[] = filemtime("./dbahandler.php"); + +readconf(); + +# ------------------------------------------------------------------- +# FILE EXISTENCE CHECKING AND PREP +# In which we establish a URL to this document, make sure all the files +# that are supposed to be available are, figure out what time it is, +# initialize some variables, etc. We also prove the existence of UFOs, +# but that part''s hidden. + +$https = array_key_exists("HTTPS", $_SERVER) && $_SERVER["HTTPS"] == "ON"; +$whoami = "http".($https? "s": "")."://".$_SERVER['SERVER_NAME']; +$sp =& $_SERVER['SERVER_PORT']; +if (($https && $sp != 433) || $sp != 80) + $whoami .= ":$sp"; +$whoami .= $_SERVER['SCRIPT_NAME']; +$lastDoY = null; + +if ($conf_language != 'en') { + if (($str = strchr($conf_language, "-"))) + $locale = substr($conf_language, 0, strlen($str) - 1)."_".strtoupper(substr($str,1)); + $locale .= ".".$conf_charset; + setlocale(LC_TIME, $locale); +} + +$force = false; +function forceonopen() +{ + $GLOBALS["force"] = true; +} + +if ($conf_metafile) + $mfdb =& DBA::singleton($conf_metafile."?onopen=forceopen"); + +if (is_string($conf_categoriesfile)) { + $categories = false; + $fname = rpath($conf_datadir, $conf_categoriesfile); + if (file_exists($fname)) { + $data = file($fname); + foreach ($data as $categ) { + $matches = explode("=", $categ); + $categories[trim($matches[0])] = trim($matches[1]); + } + } +} + +$shows = array(); + +if (is_array($conf_modules) && count($conf_modules)) { + if (!isset($conf_moddir) || $conf_moddir == '') + $conf_moddir = "."; + foreach($conf_modules as $modval) { + if (substr($modval, -4) != '.php') + $modval .= ".php"; + $modfn = rpath($conf_moddir, $modval); + $moduleThere = file_exists($modfn); + if (!$moduleThere) { + echo explainError("nomod", $modval); + exit; + } else { + require_once $modfn; + $pubdates[] = filemtime($modfn); + } + } +} +$confdefs['category_delimiter'] = '/'; +readconfdefs(); + +# ------------------------------------------------------------------- +# URL-BASED FILTERS...NOW IN TRANSLUCENT COLORS! + +$showFilter = (isset($_GET["show"]) + && isset($shows[$_GET["show"]]))? $shows[$_GET["show"]]: null; + +$flavFilter = (isset($_GET["flav"]) + && isSaneFilename($_GET["flav"]))? $_GET["flav"]: null; + +$categoryFilter = isset($_GET["category"])? $_GET["category"]: + (isset($_GET["cat"])? $_GET["cat"]: null); + +$authorFilter = isset($_GET["author"])? $_GET["author"]: + (isset($_GET["by"])? $_GET["by"]: null); + +$entryFilter = isset($_GET["entry"])? $_GET["entry"]: + (isset($_SERVER["PATH_INFO"])? $_SERVER["PATH_INFO"]: null); + +$dateFilter = isset($_GET["date"])? checkDateFilter($_GET["date"]): null; + +$startingEntry = isset($_GET["start"])? $_GET["start"]: 0; + +$cmd = isset($_GET["cmd"])? $_GET["cmd"]: false; + +$forcefile = strlen($conf_forcefile)? rpath($conf_datadir, $conf_forcefile): false; + +$force = $force || $cmd == 'force' || ($forcefile && file_exists($forcefile) && unlink($forcefile)); + +# Early command check +authUser(); + +# ------------------------------------------------------------------- +# CALL MODULE INITS +if (isset($inits) && is_array($inits) && count($inits)) foreach ($inits as $init) + if (function_exists($init)) + call_user_func($init); + +# ------------------------------------------------------------------- +# SHOW FUNCTION EXITS +if ($showFilter && function_exists($showFilter)) { + call_user_func($showFilter); + exit; +} + +# ------------------------------------------------------------------- +# FIRST FILE LOOP + +$blogs = array(); +$cats = array(); +$daysBlogged = array(); + +checkSources(($force && !$entryFilter) || !isset($mfdb) || !$mfdb); +if ($force && $forcefile && file_exists($forcefile)) + unlink($forcefile); + +if (count($daysBlogged)) { + $daysBlogged = array_keys($daysBlogged); + rsort($daysBlogged); +} + +# ------------------------------------------------------------------- +# DETERMINE THE DOCUMENT TYPE AND SEND INITIAL HEADER() + +$content_type = "text/html"; +if (!$flavFilter) + $flavFilter = "default"; + +$flavThere = false; +if (!isset($conf_flavdir) || $conf_flavdir == "") + $conf_flavdir = "."; + +foreach (array($flavFilter, "default") as $flav) { + $flavfile = $conf_flavdir."/".$flav.'_flav.php'; + if (file_exists($flavfile)) { + $flavThere = true; + require $flavfile; + $pubdates[] = filemtime($flavfile); + break; + } +} +if (!$flavThere) { + echo explainError("noflavs"); + exit; +} + +$lastmod = max($pubdates); +$etag = date("r", $lastmod); +header("Last-modified: ".$etag); +$theHeaders = getallheaders(); +if (!$force && ((array_key_exists("If-Modified-Since", $theHeaders) + && $theHeaders["If-Modified-Since"] == $etag) + || (array_key_exists("If-None-Match", $theHeaders) + && $theHeaders["If-Modified-Since"] == $etag))) { + header('HTTP/1.0 304 Not Modified'); + exit; +} + +header("Content-Type: ".$content_type); + +# ------------------------------------------------------------------- +# DETERMINE WHERE TO START AND STOP IN THE UPCOMING STORY ARRAYS + +$entries = count($blogs); + +if ($conf_entries < $entries) + $thisManyEntries = $conf_entries; +else + $thisManyEntries = $entries; + +if ($entryFilter) { + $thisManyEntries = $entries; + $startingEntry = 0; +} + +# ------------------------------------------------------------------- +# SECOND FILE LOOP +# In which we format the actual entries and do more filtering. + +$stories = ""; +usort($blogs, create_function('$a,$b', 'return $b->date - $a->date;')); +reset($blogs); + +foreach (array_splice($blogs, $startingEntry, $thisManyEntries) as $blog) { + # deprecated + if (!$conf_html_format) + $blog->contents = parseText($blog->getContents()); + $stories .= storyBlock($blog); +} + +# END SECOND FILE LOOP +# ------------------------------------------------------------------- +# PATIENT BROWSER NOW BEGINS TO RECEIVE CONTENT + +print headBlock($categoryFilter); + +print (isset($stories) && strlen($stories))? $stories: explainError("noentries"); + +print footBlock(); + +# END OF PRINT, CLEANING UP + +DBA::closeall(); +?> diff --git a/refactoring/blosxom.php-1.0/modules/ATuring.php b/refactoring/blosxom.php-1.0/modules/ATuring.php new file mode 100644 index 0000000..419507f --- /dev/null +++ b/refactoring/blosxom.php-1.0/modules/ATuring.php @@ -0,0 +1,200 @@ +<?php +# Blosxom.PHP: a rewrite of PHPosxom, which is a PHP rewrite of Blosxom +# BLOSXOM.PHP MODULE +# ------------------------------------------------------------------- +# NAME: ATuring +# DESCRIPTION: Generates an Anti Turing Test to check commenter is +# a human being +# MAINTAINER: Balazs Nagy <[email protected]> +# WEBSITE: http://js.hu/package/blosxom.php/ +# ------------------------------------------------------------------- +# REQUIREMENTS +# GD support in PHP +# DBA support in PHP (not required) +# ------------------------------------------------------------------- +# INSTALLATION +# Add its name to the 'modules' array under 'EXTERNAL MODULES' in conf.php. +# ------------------------------------------------------------------- +# USAGE +# Add a variable declaration line to your flavor file like this (sans quotes): +# "$turingData = getATuring();" +# which is an array contains image URL and challenge data. +# You can insert it to the form like +# <form...>... +# <input type="hidden" name="challenge" value="$turingData[1]" /> +# Read this: <img src="$turingData[0]" />, write here: +# <input type="text" name="response" /> +# ...</form> +# +# You can check validity with (sans quotes) +# "$valid_p = validateATuring($challenge, $response)" +# ------------------------------------------------------------------- +# PREFERENCES + +# How Anti Turing should work? It can be "session" or "database". +# In session mode, challenge-response values are stored in session variables, +# in database mode, they stored in the Anti Turing database. +$confdefs['aturing_mode'] = "session"; + +# Where are Anti Turing database kept? The filename can be relative to $conf_datadir. +# In session mode it is a no-op. +$confdefs['aturing_db'] = "db4:///aturing.db"; + +# Expire time of Challenge/Responses [in seconds] +# In session mode it is a no-op. +$confdefs['aturing_expire'] = 1200; # 20 minutes + +# ------------------------------------------------------------------- +# THE MODULE +# (don't change anything below this unless you know what you're doing.) + +$shows["aturing"] = "ATshow"; +$inits[] = "ATinit"; + +$__gcdone = false; + +function ATinit() +{ + global $conf_aturing_mode; + if ($conf_aturing_mode == "session") + session_start(); +} + +function ATshow() +{ + + $c = 0; + if (array_key_exists("challenge", $_GET)) + $c = $_GET['challenge']; + $data = $c? __fetchATuring($c): false; + __closeATuringdb(); + if (!$data) { + header("Content-Type: text/plain"); + print "Challenge ($c) not found\n"; + return; + } elseif (is_array($data)) + $data = $data[0]; + header("Content-Type: image/png"); + + $xl = 76; + $yl = 21; + $im = imagecreate($xl, $yl); + $wh = imagecolorallocate($im, 0xee, 0xee, 0xdd); + $bl = imagecolorallocate($im, 0, 0, 0); + $gr = imagecolorallocate($im, 0x99, 0x99, 0x99); + $bu = imagecolorallocate($im, 0x99, 0xaa, 0xaa); + + for ($y = 0; $y < $yl; $y += 4) { + imageline($im, 0, $y, $xl, $y, $gr); + } + + for ($x = 0; $x < ($xl - $yl/2); $x += 8) { + imageline($im, $x, 0, $x + $yl/2, $yl, $bu); + imageline($im, $x+$yl/2, 0, $x, $yl, $bu); + } + imagestring($im, 5, 2, 3, $data, $bl); + imagepng($im); + imagedestroy($im); + exit; +} + +function getATuring($challenge = 0, $response = 0) +{ + global $whoami, $__atdb, $conf_aturing_mode; + __openATuringdb(); + if (!$challenge) { + switch ($conf_aturing_mode) { + case "session": + if (isset($_SESSION["aturing_last"])) + $challenge = $_SESSION["aturing_last"] + 1; + if (!$challenge || $challenge >= 1073741823) + $challenge = 1; + break; + case "database": + if (!$__atdb->fetch($challenge)) { + $challenge = intval($__atdb->fetch("last"))+1; + if ($challenge >= 1073741823) + $challenge = 1; + } + } + } else + $lastresponse = __fetchATuring($challenge); + if (isset($lastresponse) && is_integer($lastresponse) && $response == $lastresponse) + $rand = $lastresponse; + elseif (isset($lastresponse) && $response == $lastresponse[0]) + $rand = $response; + else + $rand = mt_rand(10000000, 99999999); + $expr = time(); + switch ($conf_aturing_mode) { + case "session": + $_SESSION["aturing"][$challenge] = $rand; + $_SESSION["aturing_last"] = $challenge; + break; + case "database": + dba_replace("$challenge", "$rand,$expr", $__atdb); + dba_replace("last", "$challenge", $__atdb); + dba_sync($__atdb); + __closeATuringdb(); + } + return array("$whoami?show=aturing&challenge=$challenge", $challenge); +} + +function validateATuring($challenge, $response) +{ + global $conf_aturing_expire; + + __openATuringdb(); + $data = __fetchATuring($challenge); + __closeATuringdb(); + if (is_array($data)) + return ($data[0] == $response && ($data[1] + $conf_aturing_expire) >= time()); + return $data == $response; +} + +function __fetchATuring($challenge) +{ + global $__atdb, $conf_aturing_mode; + if ($conf_aturing_mode == "session") + return $_SESSION["aturing"][$challenge]; + $challenge = $__atdb->fetch($challenge); + if (!$challenge) + return false; + return explode(",", $challenge, $__atdb); +} + +function __openATuringdb() +{ + global $conf_aturing_mode, $conf_aturing_db, $__atdb; + if ($conf_aturing_mode != "database") + return; + if (!$__atdb) + $__atdb = DBA::singleton($conf_aturing_db); +} + +function __closeATuringdb() +{ + global $conf_aturing_mode, $__atdb; + if ($conf_aturing_mode != "database" || !$__atdb) + return; + __gcATuringdb(); + dba_close($__atdb); + $__atdb = null; +} + +function __gcATuringdb() +{ + global $__atdb, $__gcdone, $conf_aturing_expire; + if ($__gcdone) + return; + $__gcdone = true; + $now = time() - $conf_aturing_expire; + if ($key = $__atdb->first()) do { + if ($key == "last") + continue; + $data = __fetchATuring($key); + if ($data && $data[1] < $now) + $__atdb->delete($key); + } while ($key = $__atdb->next()); +} +?> diff --git a/refactoring/blosxom.php-1.0/modules/Blogroll.php b/refactoring/blosxom.php-1.0/modules/Blogroll.php new file mode 100644 index 0000000..938fd2c --- /dev/null +++ b/refactoring/blosxom.php-1.0/modules/Blogroll.php @@ -0,0 +1,52 @@ +<?php +# Blosxom.PHP: a rewrite of PHPosxom, which is a PHP rewrite of Blosxom +# BLOSXOM.PHP MODULE +# ------------------------------------------------------------------- +# NAME: Blogroll +# DESCRIPTION: Constructs a list of most readed blogs +# AUTHOR: Balazs Nagy <[email protected]> +# WEBSITE: http://js.hu/package/blosxom.php/ +# ------------------------------------------------------------------- +# INSTALLATION +# Add its name to the 'modules' array under 'EXTERNAL MODULES' in conf.php. +# ------------------------------------------------------------------- +# USAGE +# Add a variable declaration line to your flavor file like this (sans quotes): +# "$myBlogroll = makeBlogroll();" +# Then concatenate $myBlogroll into one of your blocks. +# ------------------------------------------------------------------- +# PREFERENCES +# blogroll: hash of hashes +# array ( +# "Type" => array ( +# "Blog name" => "Blog Url" +# ) +# ) + +# ------------------------------------------------------------------- +# THE MODULE +# (don''t change anything below this unless you know what you''re doing.) + +$confdefs['blogroll_delimiter'] = " » "; + +function makeBlogroll() +{ + global $conf_blogroll, $conf_blogroll_delimiter; + + if (!count($conf_blogroll)) + return false; + + $ret = ""; + + foreach ($conf_blogroll as $type=>$list) { + if (!count($list)) + continue; + $l = array(); + foreach ($list as $name => $url) { + $l[] = "<a href=\"$url\">$name</a>"; + } + $ret .= "<p>$type".$conf_blogroll_delimiter.join($conf_blogroll_delimiter, $l)."</p>\n"; + } + return $ret; +} +?> diff --git a/refactoring/blosxom.php-1.0/modules/Calendar.php b/refactoring/blosxom.php-1.0/modules/Calendar.php new file mode 100644 index 0000000..8c74ceb --- /dev/null +++ b/refactoring/blosxom.php-1.0/modules/Calendar.php @@ -0,0 +1,171 @@ +<?php +# Blosxom.PHP: a rewrite of PHPosxom, which is a PHP rewrite of Blosxom +# BLOSXOM.PHP MODULE +# ------------------------------------------------------------------- +# NAME: Calendar +# DESCRIPTION: Constructs a simple blog entry month calendar +# MAINTAINER: Balazs Nagy <[email protected]> +# WEBSITE: http://js.hu/package/blosxom.php/ +# +# ORIGINAL PHPOSXOM MODULE: Calendar +# ORIGINAL AUTHOR: Robert Daeley <[email protected]> +# ------------------------------------------------------------------- +# INSTALLATION +# Add its name to the 'modules' array under 'EXTERNAL MODULES' in conf.php. +# ------------------------------------------------------------------- +# USAGE +# Add a variable declaration line to your flavor file like this (sans quotes): +# "$myCalendar = makeCal();" +# Then concatenate $myCalendar into one of the blocks. +# ------------------------------------------------------------------- +# PREP +$confdefs['calendar_showcal'] = true; +$confdefs['calendar_showarchive'] = true; + +if ($conf_language == 'hu-hu') { + $myDays = array('H','K','Sz','Cs','P','Sz','V'); + $myAbbrDays = array('hétfő', 'kedd', 'szerda', 'csütörtök', 'péntek', 'szombat', 'vasárnap'); + $startsWithMonday = 1; + $fmtMonYear = "%Y. %B"; + $fmtThisday = "%d. nap"; + $strNow = "most"; +} else { + $myDays = array('S','M','T','W','T','F','S'); + $myAbbrDays = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'); + $startsWithMonday = false; + $fmtMonYear = "%b %Y"; + $fmtThisday = "day %d"; + $strNow = "Now"; +} +# ------------------------------------------------------------------- +# THE MODULE +# (don't change anything below this unless you know what you're doing.) + +function makeCal() { + + global $strNow, $daysBlogged, $whoami, $dateFilter, $categoryFilter; + global $myDays, $myAbbrDays, $dateFilterType, $startsWithMonday, $fmtMonYear; + global $conf_calendar_showcal; + + if (!$conf_calendar_showcal) + return false; + + $ourDoM = null; + $now = time(); + + switch ($dateFilterType) { + case null: + case 'Y': + $ourDoM = date("d",$now); + $numDays = date("t",$now); + $ourYear = date("Y",$now); + $ourMonth = date("m",$now); + $ourYearMonth = $ourYear.$ourMonth; + $ourMoreOrLessMonth = $now; + break; + case 'Ymd': + $ourDoM = substr($dateFilter, 6, 2); + case 'Ym': + $ourYear = substr($dateFilter, 0, 4); + $ourMonth = substr($dateFilter, 4, 2); + $ourYearMonth = substr($dateFilter, 0, 6); + $ourMoreOrLessMonth = mktime(0,0,0,$ourMonth,1,$ourYear); + $numDays = date("t",$ourMoreOrLessMonth); + break; + } + $ourMonYear = strftime($fmtMonYear,$ourMoreOrLessMonth); + + $lastMonthName = strftime("%b", strtotime("last month", $ourMoreOrLessMonth)); + $nextMonthName = strftime("%b", strtotime("first month", $ourMoreOrLessMonth)); + $fDoWoM = date("w",mktime(0, 0, 0, $ourMonth, 1, $ourYear)); + + if ($ourMonth == "01") { + $lastYearMonth = $ourYearMonth - 89; + $nextYearMonth = $ourYearMonth + 1; + } else if ($ourMonth == 12) { + $lastYearMonth = $ourYearMonth - 1; + $nextYearMonth = $ourYearMonth + 89; + } else { + $nextYearMonth = $ourYearMonth + 1; + $lastYearMonth = $ourYearMonth - 1; + } + + $startCell = $startsWithMonday? ($fDoWoM + 6) % 7: $fDoWoM; + + # START TABLE AND CREATE DAY COLUMN HEADERS + if ($categoryFilter) + $categ = "&category=$categoryFilter"; + else + $categ = ""; + $cal = <<<End +<table class="blogCal"> +<tr><th colspan="7"><a href="$whoami?date=$ourYearMonth$categ">$ourMonYear</a> +End; + if ($dateFilter and $ourDoM) + $cal .= "<br />".strftime($fmtThisday); + if ($categoryFilter) + $cal .= "<br />".displaycategory($categoryFilter); + $cal .= "</th></tr>\n<thead>\n<tr>\n"; + for ($i = 0; $i < 7; ++$i) { + $cal .= " <th abbr=\"${myAbbrDays[$i]}\" title=\"${myAbbrDays[$i]}\" scope=\"col\">${myDays[$i]}</th>\n"; + } + $cal .= "</tr>\n</thead>\n"; + + # CREATE LINKED DAY ROWS + + $cal .= "<tbody>\n<tr>".str_repeat("<td>&nbsp;</td>", $startCell); + for ($cells=$startCell, $today = 1; $cells < ($numDays + $startCell); ++$cells, ++$today) { + if ($cells % 7 == 0) + $cal .= "<tr>"; + $cal .= ($ourDoM == $today)? "<td class=\"today\">": "<td>"; + if ($today < 10) + $dayThisTime = $ourYearMonth."0".$today; + else + $dayThisTime = $ourYearMonth.$today; + if (count($daysBlogged) && in_array($dayThisTime, $daysBlogged)) + $cal .= "<a href=\"${whoami}?date=${dayThisTime}${categ}\">${today}</a>"; + else + $cal .= $today; + $cal .= "</td>"; + if ($cells % 7 == 6) + $cal .= "</tr>\n"; + } + $lastRowEnd = $cells % 7; + if ($lastRowEnd) + $cal .= str_repeat("<td>&nbsp;</td>", 7-$lastRowEnd)."<tr>\n"; + $cal .= "</tbody>\n"; + + # CREATE BOTTOM OF TABLE + $cal .= <<<End +<tr><td class="navigator" colspan="7"> +<a href="${whoami}?date=${lastYearMonth}${categ}">$lastMonthName</a> +| <a href="${whoami}">$strNow</a> +| <a href="${whoami}?date=${nextYearMonth}${categ}">$nextMonthName</a> +</td></tr> +</table> +End; + + # CONSTRUCT TABLE AND RETURN + + return $cal; +} + +function showArchives() { + global $daysBlogged, $whoami, $dateFilter, $conf_calendar_showarchive; + global $fmtMonYear; + + if (!$conf_calendar_showarchive) + return false; + + $dates = array(); + + foreach ($daysBlogged as $ymd) { + $ym = substr($ymd, 0, 6); + if (!isset($dates[$ym])) + $dates[$ym] = "<a href=\"$whoami?date=$ym\">" + .strftime($fmtMonYear, strtotime($ymd))."</a>"; + } + return $dates; +} + +?> diff --git a/refactoring/blosxom.php-1.0/modules/CatList.php b/refactoring/blosxom.php-1.0/modules/CatList.php new file mode 100644 index 0000000..0ae3ab5 --- /dev/null +++ b/refactoring/blosxom.php-1.0/modules/CatList.php @@ -0,0 +1,81 @@ +<?php +# Blosxom.PHP: a rewrite of PHPosxom, which is a PHP rewrite of Blosxom +# BLOSXOM.PHP MODULE +# ------------------------------------------------------------------- +# NAME: CatList +# DESCRIPTION: Constructs a simple linked list of categories +# MAINTAINER: Balazs Nagy <[email protected]> +# WEBSITE: http://js.hu/package/blosxom.php/ +# +# ORIGINAL PHPOSXOM MODULE: CatList +# ORIGINAL AUTHOR: Robert Daeley <[email protected]> +# ------------------------------------------------------------------- +# INSTALLATION +# Add its name to the 'modules' array under 'EXTERNAL MODULES' in conf.php. +# ------------------------------------------------------------------- +# USAGE +# Add a variable declaration line to your flavor file like this (sans quotes): +# "$myCategories = listCats();" +# Then concatenate $myCategories into one of your blocks. +# ------------------------------------------------------------------- +# PREFERENCES + +# How would you like this module to refer to the top level of your blog? +# (Examples: "Main" "Home" "All" "Top") +if ($conf_language == "hu-hu") + $topLevelTerm = "Összes"; +else + $topLevelTerm = "All"; + +# Would you like individual RSS links added as well? (1 = yes, 0 = no) +$confdefs["catlist_syndicate_auto"] = false; +$confdefs["catlist_syndicate_type"] = "rss2"; + +# ------------------------------------------------------------------- +# THE MODULE +# (don't change anything below this unless you know what you're doing.) + +function listCats() { + $cats = getCats(); + $ret = "<ul class=\"blogCats\">"; + foreach ($cats as $kitty) { + $ret .= '<li><a href="'.$kitty['link'].'">'.$kitty['name'].'</a>'; + if (isset($kitty['syndicate'])) + $ret .= ' (<a href="'.$kitty['synlink'].'>' + .$kitty['syndicate'] .'</a>)'; + $ret .= "</li>\n"; + } + return $ret."\n</ul>"; +} + +function getCats() { + global $whoami, $cats, $topLevelTerm; + global $conf_catlist_syndicate_auto, $conf_catlist_syndicate_type; + + sort ($cats); + $herd = array(); + foreach ($cats as $kitty) { + if (!$kitty) { + $category = "<strong>$topLevelTerm</strong>"; + $link = $whoami; + $delim = '?'; + } else { + $category = displaycategory($kitty); + $link = $whoami.'?category='.$kitty; + $delim = '&amp;'; + } + $tcat = array( + 'category' => $kitty, + 'name' => $category, + 'url' => $link + ); + if ($conf_catlist_syndicate_auto) { + $tcat['syndicate'] = $link.$delim.'flav=' + .$conf_catlist_syndicate_type; + $tcat['syntype'] = strtoupper($conf_catlist_syndicate_type); + } + $herd[] = $tcat; + } + return $herd; +} +?> diff --git a/refactoring/blosxom.php-1.0/modules/Comments.php b/refactoring/blosxom.php-1.0/modules/Comments.php new file mode 100644 index 0000000..d568cba --- /dev/null +++ b/refactoring/blosxom.php-1.0/modules/Comments.php @@ -0,0 +1,227 @@ +<?php +# Blosxom.PHP: a rewrite of PHPosxom, which is a PHP rewrite of Blosxom +# BLOSXOM.PHP MODULE +# ------------------------------------------------------------------- +# NAME: Comments +# DESCRIPTION: Handles talkbacks +# AUTHOR: Balazs Nagy <[email protected]> +# WEBSITE: http://js.hu/package/blosxom.php/ +# ------------------------------------------------------------------- +# REQUIREMENTS +# DBA support in PHP (not required) +# ------------------------------------------------------------------- +# INSTALLATION +# Add its name to the 'modules' array under 'EXTERNAL MODULES' in conf.php. +# ------------------------------------------------------------------- +# USAGE +# Add a variable declaration line to your flavor file like this (sans quotes): +# "$myComments = countComments($path);" +# in storyBlock, then put it to blogmeta paragraph, in place of the pound sign. +# ------------------------------------------------------------------- +# PREP +$confdefs['comments_db'] = "db4:///comments.db"; + +# Show comments first to last? true: yes, false: last to first +$confdefs['comments_firsttolast'] = false; + +# Default number of comments put on a page +$confdefs['comments_maxnum'] = 6; + +if ($conf_language == "hu-hu") { + $msg['comments0'] = "Új hozzászólás"; + $msg['comments1'] = "1 hozzászólás"; + $msg['commentsn'] = "%d hozzászólás"; + $msg['datefmt'] = "%Y. %B %e."; + $msg['timefmt'] = "G:i T"; +} else { + $msg['comments0'] = "No comments"; + $msg['comments1'] = "1 comment"; + $msg['commentsn'] = "%d comments"; + $msg['datefmt'] = "%Y-%m-%d"; + $msg['timefmt'] = "g:i A T"; +} + +# ------------------------------------------------------------------- +# THE MODULE +# (don't change anything below this unless you know what you're doing.) + +function &__openCommentsDB() +{ + global $conf_comments_db; + return DBA::singleton($conf_comments_db); +} + +function countComments($path) +{ + global $msg; + + $comments = getComments($path); + if (!isset($comments) || $comments === false || $comments == '') + return $msg['comments0']; + $c = count($comments); + return $c == 1? $msg['comments1']: sprintf($msg['commentsn'], $c); +} + +function &getComments($path) +{ + global $commentCache; + + if ($path == "last") + return false; + if (isset($commentCache[$path])) + return $commentCache[$path]; + $db =& __openCommentsDB(); + if ($db === false) + return false; + $comments = $db->fetch($path); + if (!is_array($comments)) + return false; + $date = array_keys($comments); + sort($date); + if ($date[0] < 100000) { + foreach ($comments as $date=>$comm) + $cmnt[$comm[2]] = $comm; + $db->replace($path, $cmnt); + $comments = &$cmnt; + } + $commentCache[$path] = $comments; + return $comments; +} + +function addComment($path, $who, $what) +{ + global $cmts, $commentCache; + + $time = time(); + $db =& __openCommentsDB(); + if ($db === false) + return false; + $newcmt = array($who, $what, $time); + $comments = getComments($path); + if (!is_array($comments)) + $comments = array($time => $newcmt); + else + $comments[$time] = $newcmt; + $commentCache[$path] = $comments; + $err = $db->replace($path, $comments); + if (!$err) + return false; + __readLastdb(); + $cmts[$time] = array($who, $what, $time, $path); + return __writeLastdb(); +} + +function delComment($path, $time) +{ + global $cmts, $commentCache; + + if (!defined("USER")) + return false; + $comments = getComments($path); + if (!is_array($comments) || !isset($comments[$time])) + return false; + unset($comments[$time]); + $db =& __openCommentsDB(); + if ($db === false) + return false; + $err = $db->replace($path, $comments); + if (!$err) + return false; + + __readLastdb(); + if (isset($cmts[$time])) { + unset($cmts[$time]); + __writeLastdb(); + } + return true; +} + +function lastComments() +{ + global $conf_datadir, $conf_comments_db; + global $conf_comments_db; + global $force, $conf_comments_maxnum; + global $cmts, $mfdb; + + if ($force) { + $cmts = array(); + $db =& __openCommentsDB(); + if ($db === false) + return false; + $key = $db->first(); + while ($key !== false) { + $path = $key; + $key = $db->next(); + if ($path == "last") + continue; + $comments = $db->fetch($path); + if (!is_array($comments)) + continue; + foreach (array_values($comments) as $cmt) { + $time =& $cmt[2]; + $cmts[$time] = $cmt; + $cmts[$time][3] = $path; + } + } + __writeLastdb(); + } else + __readLastdb(); + + if ($mfdb && is_array($cmts)) { + $mfCache = array(); + foreach (array_keys($cmts) as $date) { + $where = $cmts[$date][3]; + if (array_key_exists($where, $mfCache)) { + $cmts[$date][4] = $mfCache[$where]; + } else { + $mdata = $mfdb->fetch($where); + $cmts[$date][4] = $mfCache[$where] = trim($mdata[2]); + } + } + } + return $cmts; +} + +function __sortLastdb($a, $b) +{ + return $b[2] - $a[2]; +} + +function __optimizeLastdb() +{ + global $conf_comments_maxnum, $cmts; + if (!is_array($cmts) || !count($cmts)) + return false; + usort($cmts, "__sortLastdb"); + + if (count($cmts) > $conf_comments_maxnum) + $cmts = array_slice($cmts, 0, $conf_comments_maxnum); + return true; +} + +function __writeLastdb() +{ + global $cmts, $conf_comments_db; + + if (__optimizeLastdb() === false) + return false; + $db =& __openCommentsDB(); + if ($db === false) + return false; + + $db->replace("last", $cmts); + $db->close(); + return true; +} + +function __readLastdb() +{ + global $cmts; + + $db =& __openCommentsDB(); + if (!$db) + return false; + $cmts = $db->fetch("last"); + return __optimizeLastdb(); +} +?> diff --git a/refactoring/blosxom.php-1.0/modules/Fortune.php b/refactoring/blosxom.php-1.0/modules/Fortune.php new file mode 100644 index 0000000..d596b0a --- /dev/null +++ b/refactoring/blosxom.php-1.0/modules/Fortune.php @@ -0,0 +1,34 @@ +<?php +# Blosxom.PHP: a rewrite of PHPosxom, which is a PHP rewrite of Blosxom +# BLOSXOM.PHP MODULE +# ------------------------------------------------------------------- +# NAME: Fortune +# DESCRIPTION: Adds random fortune cookie +# AUTHOR: Balazs Nagy <[email protected]> +# WEBSITE: http://js.hu/package/blosxom.php/ +# ------------------------------------------------------------------- +# INSTALLATION +# Add its name to the 'modules' array under 'EXTERNAL MODULES' in conf.php. +# ------------------------------------------------------------------- +# USAGE +# Add a variable declaration line to your flavor file like this (sans quotes): +# "$myFortune = getFortune();" in headBlock. +# ------------------------------------------------------------------- +# PREP + +# Database path +$confdefs['fortune'] = "fortunes.lst"; + +function getFortune() +{ + global $conf_datadir, $conf_fortune; + + if (!is_string($conf_fortune)) + return ""; + $fname = rpath($conf_datadir, $conf_fortune); + if (!file_exists($fname) || !($f = @file($fname))) + return ""; + $line = mt_rand(0, count($f)-1); + return trim($f[$line]); +} +?> diff --git a/refactoring/blosxom.php-1.0/modules/Trackback.php b/refactoring/blosxom.php-1.0/modules/Trackback.php new file mode 100644 index 0000000..04ec723 --- /dev/null +++ b/refactoring/blosxom.php-1.0/modules/Trackback.php @@ -0,0 +1,92 @@ +<?php +# Blosxom.PHP: a rewrite of PHPosxom, which is a PHP rewrite of Blosxom +# BLOSXOM.PHP MODULE +# ------------------------------------------------------------------- +# NAME: Trackback +# DESCRIPTION: Tracks blog entries using referrer +# AUTHOR: Balazs Nagy <[email protected]> +# WEBSITE: http://js.hu/package/blosxom.php/ +# ------------------------------------------------------------------- +# INSTALLATION +# Add its name to the 'modules' array under 'EXTERNAL MODULES' in conf.php. +# ------------------------------------------------------------------- +# USAGE +# ------------------------------------------------------------------- +# PREP + +# Database path +$confdefs['trackback'] = "db4:///trackback.db"; + +function trackbackReferrer($path) +{ + global $conf_trackback, $whoami; + + fixTrackbacks(); + if (!isset($_SERVER['HTTP_REFERER'])) + return true; + $ref = $_SERVER['HTTP_REFERER']; + $wa = dirname($whoami); + if ($ref == '' || !strncmp($ref, $wa, strlen($wa))) + return true; + $db =& DBA::singleton($conf_trackback); + if ($db === false) + return false; + + $tb = $db->fetch($path); + if ($tb) { + $tbp = unserialize($tb); + if (array_key_exists($ref, $tbp)) + $tbp[$ref] ++; + else + $tbp[$ref] = 1; + } else + $tbp = array($ref => 1); + $db->replace($path, $tbp); + $db->sync(); + $db->close(); + return true; +} + +function getTrackbacks($path) +{ + global $conf_trackback; + + $db =& DBA::singleton($conf_trackback."?mode=r"); + if ($db === false) + return false; + + $tb = $db->fetch($path); + $db->close(); + if (!$tb) + return false; + + return $tb; +} + +function fixTrackbacks() +{ + global $conf_trackback, $whoami; + + $db =& DBA::singleton($conf_trackback); + if ($db === false) + return false; + + $wa = dirname($whoami); + $tb = $db->first(); + do { + $dirty = false; + $tbp = $db->fetch($tb); + if ($tbp === null) + continue; + foreach ($tbp as $url=>$count) { + if (!strncmp($url, $wa, strlen($wa))) { + unset($tbp[$url]); + $dirty = true; + } + } + if ($dirty) + $db->replace($tb, $tbp); + } while (($tb = $db->next())); + $db->close(); +} +?>
troter/object-oriented-exercise
f3b0e6435f3656ad4526fd61cac80d39b081dc7f
エクササイズのルールを記述
diff --git a/README b/README index 4a1e10c..7a8e4da 100644 --- a/README +++ b/README @@ -1,2 +1,17 @@ # -*- coding: utf-8 -*- + オブジェクト指向エクササイズ用レポジトリ +======================================== + +ルール +------ + +1. 1つのメソッドにつきインデントは1段階までにすること +2. else句を使用しないこと +3. すべてのプリミティブ型と文字列型をラップすること +4. 1行につきドットは1つまでにすること +5. 名前を省略しないこと +6. すべてのエンティティを小さくすること +7. 1つのクラスにつきインスタンス変数は2つまでとすること +8. ファーストクラスコレクションを利用すること +9. Getter、Setter、プロパティを使用しないこと
troter/object-oriented-exercise
95172a0de91fdfc05458dcec18b3b9e137ae3790
説明文
diff --git a/README b/README index e69de29..4a1e10c 100644 --- a/README +++ b/README @@ -0,0 +1,2 @@ +# -*- coding: utf-8 -*- +オブジェクト指向エクササイズ用レポジトリ
nolanlawson/CatLogDonate
f1dcead89c79ad7ceb571dc3acff88ceb3708147
string changes and update to 1.0.1
diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..61f4801 --- /dev/null +++ b/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,12 @@ +#Sat Jan 15 17:41:47 EST 2011 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/AndroidManifest.xml b/AndroidManifest.xml index 8323723..7009dfc 100644 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -1,27 +1,27 @@ <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.nolanlawson.logcat.donate" - android:versionCode="1" - android:versionName="1.0"> + android:versionCode="2" + android:versionName="1.0.1"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".InstallFree" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name=".Receiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> <action android:name="android.intent.action.DATE_CHANGED" /> <action android:name="android.intent.action.PACKAGE_ADDED" /> <action android:name="ACTION_PACKAGE_REMOVED" /> </intent-filter> </receiver> </application> <uses-sdk android:minSdkVersion="3" android:targetSdkVersion="4"/> </manifest> \ No newline at end of file diff --git a/res/values/strings.xml b/res/values/strings.xml index 68f4341..08f9350 100644 --- a/res/values/strings.xml +++ b/res/values/strings.xml @@ -1,13 +1,13 @@ <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">CatLog Donate</string> <string name="install_free_text">\ CatLog Donate is simply an add-on to the free CatLog, \ meaning you\'ll still need to install that version in order for it to work. \ Thanks for donating! :)</string> <string name="thanks">\ -While installed, CatLog Donate simply serves as proof you donated, and adds \ -in a nice little message to the "About" section. \ +While installed, CatLog Donate will unlock the \"Color Scheme\" setting and serve as proof \ +that you donated. \ This icon will remove itself from your application \ tray the next time you reboot. Thanks for donating - you are awesome! :)</string> </resources>
tinogomes/rails-template
ccaf6010ea1198af43a57da4fee6f05d20eb411d
fixing gitignore and instructions for bin/setup
diff --git a/base.rb b/base.rb index 2bb570e..b2403c7 100644 --- a/base.rb +++ b/base.rb @@ -1,134 +1,134 @@ # encoding: utf-8 if options['skip_gemfile'] puts 'You can not use this template without gemfile, sorry...' exit 1 end if options['skip_git'] puts 'R U MAD? NO GIT? GET OUT OF HERE!' exit 1 end def remove_comments_for(filename) gsub_file filename, /^\s*#.*\n/, '' end if yes?("Do you want to create a RVM gemset for #{app_name}") run "/bin/bash -lc 'rvm #{ENV['RUBY_VERSION']}@#{app_name} --create --ruby-version'" end git :init -append_file '.gitignore', '/.ruby-*' -append_file '.gitignore', '/config/*.yml' +append_file '.gitignore', "/.ruby-*\n" +append_file '.gitignore', "/config/*.yml\n" Dir['./config/*.yml'].each do |filename| FileUtils.cp filename, "#{filename}.sample" end git add: '.' git commit: '-m "Rails app base"' if yes?('Force a Ruby version?') ruby_version = ask('Which Ruby version:') gsub_file 'Gemfile', /^(source.*)$/, "\\1\n\nruby " + ruby_version.inspect end uncomment_lines 'Gemfile', 'bcrypt' if yes?('Use BCrypt?') uncomment_lines 'Gemfile', 'unicorn' if yes?('Use Unicorn?') uncomment_lines 'Gemfile', 'capistrano' if yes?('Use Capistrano?') comment_lines 'Gemfile', 'coffee' remove_comments_for 'Gemfile' gem_group :development do gem 'brakeman' gem 'foreman' gem 'mailcatcher' gem 'rubocop' end gem_group :development, :test do gem 'dotenv-rails' gem 'guard-rspec' gem 'byebug' gem 'rspec-rails' end gem_group :production do # enable gzip compression on heroku, but don't compress images. gem 'heroku-deflater' if yes?('Use heroku-deflater?') # heroku injects it if it's not in there already gem 'rails_12factor' gem 'newrelic_rpm' if yes?('Use Newrelic?') end run 'bundle install' git add: '.' git commit: '-m "gems installed"' create_file '.env', "SECRET_KEY_BASE=#{`rake secret`}" generate 'rspec:install' create_file '.rspec', <<-RSPEC_OPTIONS --color --require spec_helper --format doc --profile RSPEC_OPTIONS run 'guard init rspec' gsub_file 'Guardfile', 'guard :rspec do', <<-EOF rspec_options = { notification: false } guard :rspec, options: rspec_options do EOF environment 'config.action_mailer.delivery_method = :smtp', env: 'development' environment 'config.action_mailer.smtp_settings = { :address => "localhost", :port => 1025 }', env: 'development' create_file 'Procfile.development', <<-PROCFILE #worker: sidekiq #postgres: postgres -D /usr/local/var/postgres #elastichsearch: elasticsearch --config=/usr/local/opt/elasticsearch/config/elasticsearch.yml #redis: redis-server /usr/local/etc/redis.conf mailcatcher: mailcatcher --foreground --verbose #web: rails server PROCFILE git add: '.' git commit: '-m "Setup development and test gems"' if yes?('Do you want Home controller?') generate :controller, :home, 'index --no-view-specs --skip-routes --no-helper --no-assets' route "root to: 'home#index'" git add: '.' git commit: '-m "Home controller created!"' end unless options['skip_active_record'] rake 'db:create' rake 'db:migrate' + rake 'spec' if yes?('Is rspec working?') end if yes?('Create database?') -rake 'spec' if yes?('Remove comments for routes file?') remove_comments_for 'config/routes.rb' git add: '.' git commit: '-m "Removed routes comments"' end puts 'TODO:' puts '- Edit README file' -puts '- Verify bin/setup file' -puts '- Verify Procfile.development file' -puts '- Verify .env file' +puts '- Override bin/setup file from https://gist.github.com/tinogomes/5aee18de24ba1115a1f2afdb959187c4' +puts '- Check Procfile.development file' +puts '- Check .env file' puts '- Go work!'
tinogomes/rails-template
5e40276bf552596417826e3a8f3968bfd3d18b0e
set up ruby version, added production gems
diff --git a/base.rb b/base.rb index 9a98f67..2bb570e 100644 --- a/base.rb +++ b/base.rb @@ -1,117 +1,134 @@ # encoding: utf-8 if options['skip_gemfile'] puts 'You can not use this template without gemfile, sorry...' exit 1 end if options['skip_git'] puts 'R U MAD? NO GIT? GET OUT OF HERE!' exit 1 end def remove_comments_for(filename) gsub_file filename, /^\s*#.*\n/, '' end if yes?("Do you want to create a RVM gemset for #{app_name}") run "/bin/bash -lc 'rvm #{ENV['RUBY_VERSION']}@#{app_name} --create --ruby-version'" end git :init append_file '.gitignore', '/.ruby-*' append_file '.gitignore', '/config/*.yml' +Dir['./config/*.yml'].each do |filename| + FileUtils.cp filename, "#{filename}.sample" +end + git add: '.' git commit: '-m "Rails app base"' +if yes?('Force a Ruby version?') + ruby_version = ask('Which Ruby version:') + gsub_file 'Gemfile', /^(source.*)$/, "\\1\n\nruby " + ruby_version.inspect +end + uncomment_lines 'Gemfile', 'bcrypt' if yes?('Use BCrypt?') uncomment_lines 'Gemfile', 'unicorn' if yes?('Use Unicorn?') uncomment_lines 'Gemfile', 'capistrano' if yes?('Use Capistrano?') comment_lines 'Gemfile', 'coffee' remove_comments_for 'Gemfile' gem_group :development do gem 'brakeman' gem 'foreman' gem 'mailcatcher' gem 'rubocop' end gem_group :development, :test do gem 'dotenv-rails' gem 'guard-rspec' gem 'byebug' gem 'rspec-rails' end +gem_group :production do + # enable gzip compression on heroku, but don't compress images. + gem 'heroku-deflater' if yes?('Use heroku-deflater?') + # heroku injects it if it's not in there already + gem 'rails_12factor' + gem 'newrelic_rpm' if yes?('Use Newrelic?') +end + run 'bundle install' git add: '.' git commit: '-m "gems installed"' create_file '.env', "SECRET_KEY_BASE=#{`rake secret`}" generate 'rspec:install' create_file '.rspec', <<-RSPEC_OPTIONS --color --require spec_helper --format doc --profile RSPEC_OPTIONS run 'guard init rspec' gsub_file 'Guardfile', 'guard :rspec do', <<-EOF rspec_options = { notification: false } guard :rspec, options: rspec_options do EOF environment 'config.action_mailer.delivery_method = :smtp', env: 'development' environment 'config.action_mailer.smtp_settings = { :address => "localhost", :port => 1025 }', env: 'development' create_file 'Procfile.development', <<-PROCFILE #worker: sidekiq #postgres: postgres -D /usr/local/var/postgres #elastichsearch: elasticsearch --config=/usr/local/opt/elasticsearch/config/elasticsearch.yml #redis: redis-server /usr/local/etc/redis.conf mailcatcher: mailcatcher --foreground --verbose #web: rails server PROCFILE git add: '.' git commit: '-m "Setup development and test gems"' if yes?('Do you want Home controller?') generate :controller, :home, 'index --no-view-specs --skip-routes --no-helper --no-assets' route "root to: 'home#index'" git add: '.' git commit: '-m "Home controller created!"' end unless options['skip_active_record'] rake 'db:create' rake 'db:migrate' -end +end if yes?('Create database?') rake 'spec' if yes?('Remove comments for routes file?') remove_comments_for 'config/routes.rb' git add: '.' git commit: '-m "Removed routes comments"' end puts 'TODO:' puts '- Edit README file' puts '- Verify bin/setup file' puts '- Verify Procfile.development file' puts '- Verify .env file' puts '- Go work!'
tinogomes/rails-template
7a5ff32eb2f803905a9306548e4f3445e07d328a
refactoring to Rails 4
diff --git a/base.rb b/base.rb index ba597df..9a98f67 100644 --- a/base.rb +++ b/base.rb @@ -1,104 +1,117 @@ # encoding: utf-8 if options['skip_gemfile'] puts 'You can not use this template without gemfile, sorry...' exit 1 end -run "/bin/bash -lc 'rvm #{ENV['RUBY_VERSION']}@#{app_name} --create --ruby-version'" +if options['skip_git'] + puts 'R U MAD? NO GIT? GET OUT OF HERE!' + exit 1 +end def remove_comments_for(filename) gsub_file filename, /^\s*#.*\n/, '' end -def comment_line_on(filename, expression) - gsub_file filename, Regexp.new("^.*#{expression}.*$"), '# \0' +if yes?("Do you want to create a RVM gemset for #{app_name}") + run "/bin/bash -lc 'rvm #{ENV['RUBY_VERSION']}@#{app_name} --create --ruby-version'" end -remove_comments_for 'Gemfile' -comment_line_on 'Gemfile', 'coffee' -comment_line_on 'Gemfile', 'turbolinks' +git :init -gem 'unicorn-rails' +append_file '.gitignore', '/.ruby-*' +append_file '.gitignore', '/config/*.yml' + +git add: '.' +git commit: '-m "Rails app base"' + +uncomment_lines 'Gemfile', 'bcrypt' if yes?('Use BCrypt?') +uncomment_lines 'Gemfile', 'unicorn' if yes?('Use Unicorn?') +uncomment_lines 'Gemfile', 'capistrano' if yes?('Use Capistrano?') +comment_lines 'Gemfile', 'coffee' +remove_comments_for 'Gemfile' gem_group :development do gem 'brakeman' + gem 'foreman' + gem 'mailcatcher' gem 'rubocop' end gem_group :development, :test do gem 'dotenv-rails' gem 'guard-rspec' - gem 'pry-debugger' + gem 'byebug' gem 'rspec-rails' end -remove_comments_for 'config/routes.rb' - -create_file 'README.mkdn', <<-README -# #{app_name} - -TBD - -README - -initializer 'secret_token.rb', <<-CODE -if ENV['SECRET_TOKEN'].nil? || ENV['SECRET_TOKEN'].empty? - warn('SECRET_TOKEN is not defined. Try `export SECRET_TOKEN=$(rake secret)`') - exit 1 -end +run 'bundle install' -#{app_const_base}::Application.config.secret_key_base = ENV['SECRET_TOKEN'] +git add: '.' +git commit: '-m "gems installed"' -CODE - -create_file '.env', "SECRET_TOKEN=#{app_secret}" - -remove_file "README.rdoc" - -run 'bundle' +create_file '.env', "SECRET_KEY_BASE=#{`rake secret`}" generate 'rspec:install' -get 'https://gist.github.com/tinogomes/6082570/raw/e7cb366b0376a594d3928a8bb744e4a154e671e8/.rspec', '.rspec' -run "guard init rspec" +create_file '.rspec', <<-RSPEC_OPTIONS +--color +--require spec_helper +--format doc +--profile +RSPEC_OPTIONS + +run 'guard init rspec' gsub_file 'Guardfile', 'guard :rspec do', <<-EOF rspec_options = { - all_after_pass: false, - all_on_start: false + notification: false } guard :rspec, options: rspec_options do EOF +environment 'config.action_mailer.delivery_method = :smtp', env: 'development' +environment 'config.action_mailer.smtp_settings = { :address => "localhost", :port => 1025 }', env: 'development' + +create_file 'Procfile.development', <<-PROCFILE +#worker: sidekiq +#postgres: postgres -D /usr/local/var/postgres +#elastichsearch: elasticsearch --config=/usr/local/opt/elasticsearch/config/elasticsearch.yml +#redis: redis-server /usr/local/etc/redis.conf +mailcatcher: mailcatcher --foreground --verbose +#web: rails server +PROCFILE + +git add: '.' +git commit: '-m "Setup development and test gems"' + if yes?('Do you want Home controller?') - generate :controller, :home, :index + generate :controller, :home, 'index --no-view-specs --skip-routes --no-helper --no-assets' route "root to: 'home#index'" -end -if !options['skip_active_record'] - run 'cp config/database.yml config/database.yml.sample' + git add: '.' + git commit: '-m "Home controller created!"' +end - rake 'db:create:all' +unless options['skip_active_record'] + rake 'db:create' rake 'db:migrate' - rake 'db:test:prepare' -else - remove_file 'config/database.yml' end rake 'spec' -if !options['skip_git'] - append_file '.gitignore', '/.ruby-*' - append_file '.gitignore', '/config/*.yml' - - git :init +if yes?('Remove comments for routes file?') + remove_comments_for 'config/routes.rb' git add: '.' - git commit: '-m "It\'s time to get fun!"' -else - puts 'You are not using Git. O_o' + git commit: '-m "Removed routes comments"' end -puts 'Remember, you should create the SECRET_TOKEN variable for production.' +puts 'TODO:' +puts '- Edit README file' +puts '- Verify bin/setup file' +puts '- Verify Procfile.development file' +puts '- Verify .env file' +puts '- Go work!'
tinogomes/rails-template
409334c3d08116bdf0ac1c6478813a3b80ad5d19
Using options to determine what to do.
diff --git a/base.rb b/base.rb index b095561..ba597df 100644 --- a/base.rb +++ b/base.rb @@ -1,99 +1,104 @@ # encoding: utf-8 -@available_gems = [] -def installed?(gemname) - @available_gems.include?(gemname) +if options['skip_gemfile'] + puts 'You can not use this template without gemfile, sorry...' + exit 1 end -def want_gem(gemname) - @available_gems << gemname - gem gemname if yes?("Would you like to use #{gemname}?") -end +run "/bin/bash -lc 'rvm #{ENV['RUBY_VERSION']}@#{app_name} --create --ruby-version'" def remove_comments_for(filename) gsub_file filename, /^\s*#.*\n/, '' end def comment_line_on(filename, expression) gsub_file filename, Regexp.new("^.*#{expression}.*$"), '# \0' end -run "/bin/bash -lc 'rvm #{ENV['RUBY_VERSION']}@#{app_name} --create --ruby-version'" - remove_comments_for 'Gemfile' -remove_comments_for 'config/routes.rb' comment_line_on 'Gemfile', 'coffee' comment_line_on 'Gemfile', 'turbolinks' -want_gem 'unicorn-rails' +gem 'unicorn-rails' gem_group :development do - want_gem 'brakeman' - want_gem 'rubocop' + gem 'brakeman' + gem 'rubocop' end gem_group :development, :test do gem 'dotenv-rails' - want_gem 'guard-rspec' + gem 'guard-rspec' gem 'pry-debugger' gem 'rspec-rails' end +remove_comments_for 'config/routes.rb' + create_file 'README.mkdn', <<-README # #{app_name} TBD README initializer 'secret_token.rb', <<-CODE if ENV['SECRET_TOKEN'].nil? || ENV['SECRET_TOKEN'].empty? warn('SECRET_TOKEN is not defined. Try `export SECRET_TOKEN=$(rake secret)`') exit 1 end #{app_const_base}::Application.config.secret_key_base = ENV['SECRET_TOKEN'] CODE create_file '.env', "SECRET_TOKEN=#{app_secret}" -run 'cp config/database.yml config/database.yml.sample' -append_file '.gitignore', '/.ruby-*' -append_file '.gitignore', '/config/*.yml' remove_file "README.rdoc" run 'bundle' generate 'rspec:install' get 'https://gist.github.com/tinogomes/6082570/raw/e7cb366b0376a594d3928a8bb744e4a154e671e8/.rspec', '.rspec' -if installed?('guard-rspec') - run "guard init rspec" +run "guard init rspec" - gsub_file 'Guardfile', 'guard :rspec do', <<-EOF - rspec_options = { - all_after_pass: false, - all_on_start: false - } +gsub_file 'Guardfile', 'guard :rspec do', <<-EOF +rspec_options = { + all_after_pass: false, + all_on_start: false +} - guard :rspec, options: rspec_options do - EOF -end +guard :rspec, options: rspec_options do +EOF if yes?('Do you want Home controller?') generate :controller, :home, :index route "root to: 'home#index'" end -rake 'db:create:all' -rake 'db:migrate' -rake 'db:test:prepare' +if !options['skip_active_record'] + run 'cp config/database.yml config/database.yml.sample' + + rake 'db:create:all' + rake 'db:migrate' + rake 'db:test:prepare' +else + remove_file 'config/database.yml' +end + rake 'spec' -git :init -git add: '.' -git commit: '-m "It\'s time to get fun!"' +if !options['skip_git'] + append_file '.gitignore', '/.ruby-*' + append_file '.gitignore', '/config/*.yml' + + git :init + git add: '.' + git commit: '-m "It\'s time to get fun!"' +else + puts 'You are not using Git. O_o' +end puts 'Remember, you should create the SECRET_TOKEN variable for production.'
tinogomes/rails-template
b5789f15c46eb44c040fdbd55373d2b93e313998
Removing comments on Gemfile and routes
diff --git a/base.rb b/base.rb index 58b5472..b095561 100644 --- a/base.rb +++ b/base.rb @@ -1,93 +1,99 @@ # encoding: utf-8 @available_gems = [] def installed?(gemname) @available_gems.include?(gemname) end def want_gem(gemname) @available_gems << gemname gem gemname if yes?("Would you like to use #{gemname}?") end +def remove_comments_for(filename) + gsub_file filename, /^\s*#.*\n/, '' +end + def comment_line_on(filename, expression) gsub_file filename, Regexp.new("^.*#{expression}.*$"), '# \0' end run "/bin/bash -lc 'rvm #{ENV['RUBY_VERSION']}@#{app_name} --create --ruby-version'" +remove_comments_for 'Gemfile' +remove_comments_for 'config/routes.rb' comment_line_on 'Gemfile', 'coffee' comment_line_on 'Gemfile', 'turbolinks' want_gem 'unicorn-rails' gem_group :development do want_gem 'brakeman' want_gem 'rubocop' end gem_group :development, :test do gem 'dotenv-rails' want_gem 'guard-rspec' gem 'pry-debugger' gem 'rspec-rails' end create_file 'README.mkdn', <<-README # #{app_name} TBD README initializer 'secret_token.rb', <<-CODE if ENV['SECRET_TOKEN'].nil? || ENV['SECRET_TOKEN'].empty? warn('SECRET_TOKEN is not defined. Try `export SECRET_TOKEN=$(rake secret)`') exit 1 end #{app_const_base}::Application.config.secret_key_base = ENV['SECRET_TOKEN'] CODE create_file '.env', "SECRET_TOKEN=#{app_secret}" run 'cp config/database.yml config/database.yml.sample' append_file '.gitignore', '/.ruby-*' append_file '.gitignore', '/config/*.yml' remove_file "README.rdoc" run 'bundle' generate 'rspec:install' get 'https://gist.github.com/tinogomes/6082570/raw/e7cb366b0376a594d3928a8bb744e4a154e671e8/.rspec', '.rspec' if installed?('guard-rspec') run "guard init rspec" gsub_file 'Guardfile', 'guard :rspec do', <<-EOF rspec_options = { all_after_pass: false, all_on_start: false } guard :rspec, options: rspec_options do EOF end if yes?('Do you want Home controller?') generate :controller, :home, :index route "root to: 'home#index'" end rake 'db:create:all' rake 'db:migrate' rake 'db:test:prepare' rake 'spec' git :init git add: '.' git commit: '-m "It\'s time to get fun!"' puts 'Remember, you should create the SECRET_TOKEN variable for production.'
tinogomes/rails-template
4c76bfcc715273043d4da4e43119d7a7dfe6a040
Comment coffee and turbo links on Gemfile
diff --git a/base.rb b/base.rb index 314b8b2..58b5472 100644 --- a/base.rb +++ b/base.rb @@ -1,86 +1,93 @@ # encoding: utf-8 @available_gems = [] def installed?(gemname) @available_gems.include?(gemname) end def want_gem(gemname) @available_gems << gemname gem gemname if yes?("Would you like to use #{gemname}?") end +def comment_line_on(filename, expression) + gsub_file filename, Regexp.new("^.*#{expression}.*$"), '# \0' +end + run "/bin/bash -lc 'rvm #{ENV['RUBY_VERSION']}@#{app_name} --create --ruby-version'" +comment_line_on 'Gemfile', 'coffee' +comment_line_on 'Gemfile', 'turbolinks' + want_gem 'unicorn-rails' gem_group :development do want_gem 'brakeman' want_gem 'rubocop' end gem_group :development, :test do gem 'dotenv-rails' want_gem 'guard-rspec' gem 'pry-debugger' gem 'rspec-rails' end create_file 'README.mkdn', <<-README # #{app_name} TBD README initializer 'secret_token.rb', <<-CODE if ENV['SECRET_TOKEN'].nil? || ENV['SECRET_TOKEN'].empty? warn('SECRET_TOKEN is not defined. Try `export SECRET_TOKEN=$(rake secret)`') exit 1 end #{app_const_base}::Application.config.secret_key_base = ENV['SECRET_TOKEN'] CODE create_file '.env', "SECRET_TOKEN=#{app_secret}" run 'cp config/database.yml config/database.yml.sample' append_file '.gitignore', '/.ruby-*' append_file '.gitignore', '/config/*.yml' remove_file "README.rdoc" run 'bundle' generate 'rspec:install' get 'https://gist.github.com/tinogomes/6082570/raw/e7cb366b0376a594d3928a8bb744e4a154e671e8/.rspec', '.rspec' if installed?('guard-rspec') run "guard init rspec" gsub_file 'Guardfile', 'guard :rspec do', <<-EOF rspec_options = { all_after_pass: false, all_on_start: false } guard :rspec, options: rspec_options do EOF end if yes?('Do you want Home controller?') generate :controller, :home, :index route "root to: 'home#index'" end rake 'db:create:all' rake 'db:migrate' rake 'db:test:prepare' rake 'spec' git :init git add: '.' git commit: '-m "It\'s time to get fun!"' -puts "Remember, you should create the SECRET_TOKEN variable for production." +puts 'Remember, you should create the SECRET_TOKEN variable for production.'
tinogomes/rails-template
b251fdbd93baa452ac0c36f71e39255f3053ffee
Remember, you should create the SECRET_TOKEN variable for production
diff --git a/base.rb b/base.rb index 7e8926a..314b8b2 100644 --- a/base.rb +++ b/base.rb @@ -1,86 +1,86 @@ # encoding: utf-8 @available_gems = [] def installed?(gemname) @available_gems.include?(gemname) end def want_gem(gemname) @available_gems << gemname gem gemname if yes?("Would you like to use #{gemname}?") end run "/bin/bash -lc 'rvm #{ENV['RUBY_VERSION']}@#{app_name} --create --ruby-version'" want_gem 'unicorn-rails' gem_group :development do want_gem 'brakeman' want_gem 'rubocop' end gem_group :development, :test do gem 'dotenv-rails' want_gem 'guard-rspec' gem 'pry-debugger' gem 'rspec-rails' end create_file 'README.mkdn', <<-README # #{app_name} TBD README initializer 'secret_token.rb', <<-CODE if ENV['SECRET_TOKEN'].nil? || ENV['SECRET_TOKEN'].empty? warn('SECRET_TOKEN is not defined. Try `export SECRET_TOKEN=$(rake secret)`') exit 1 end #{app_const_base}::Application.config.secret_key_base = ENV['SECRET_TOKEN'] CODE create_file '.env', "SECRET_TOKEN=#{app_secret}" run 'cp config/database.yml config/database.yml.sample' append_file '.gitignore', '/.ruby-*' append_file '.gitignore', '/config/*.yml' remove_file "README.rdoc" run 'bundle' generate 'rspec:install' get 'https://gist.github.com/tinogomes/6082570/raw/e7cb366b0376a594d3928a8bb744e4a154e671e8/.rspec', '.rspec' if installed?('guard-rspec') run "guard init rspec" gsub_file 'Guardfile', 'guard :rspec do', <<-EOF rspec_options = { all_after_pass: false, all_on_start: false } guard :rspec, options: rspec_options do EOF end if yes?('Do you want Home controller?') generate :controller, :home, :index route "root to: 'home#index'" end rake 'db:create:all' rake 'db:migrate' rake 'db:test:prepare' rake 'spec' git :init git add: '.' git commit: '-m "It\'s time to get fun!"' -puts "" +puts "Remember, you should create the SECRET_TOKEN variable for production."
tinogomes/rails-template
03b3fa7b91bb81c3f1530e8048fe0742f6875f9c
refactoring and now using dotenv for development
diff --git a/base.rb b/base.rb index e3f0c30..7e8926a 100644 --- a/base.rb +++ b/base.rb @@ -1,71 +1,86 @@ -@template_root = File.expand_path(File.join(File.dirname(__FILE__))) +# encoding: utf-8 +@available_gems = [] -gem "unicorn-rails" +def installed?(gemname) + @available_gems.include?(gemname) +end + +def want_gem(gemname) + @available_gems << gemname + gem gemname if yes?("Would you like to use #{gemname}?") +end + +run "/bin/bash -lc 'rvm #{ENV['RUBY_VERSION']}@#{app_name} --create --ruby-version'" + +want_gem 'unicorn-rails' + +gem_group :development do + want_gem 'brakeman' + want_gem 'rubocop' +end gem_group :development, :test do - gem "brakeman" - gem "guard-rspec" - gem "pry-debugger" - gem "rspec-rails" - gem "rubocop" + gem 'dotenv-rails' + want_gem 'guard-rspec' + gem 'pry-debugger' + gem 'rspec-rails' end -file "README.mkdn", <<-README -# #{@app_name} +create_file 'README.mkdn', <<-README +# #{app_name} TBD + README -file "config/initializers/secret_token.rb", <<-CODE +initializer 'secret_token.rb', <<-CODE if ENV['SECRET_TOKEN'].nil? || ENV['SECRET_TOKEN'].empty? warn('SECRET_TOKEN is not defined. Try `export SECRET_TOKEN=$(rake secret)`') exit 1 end -#{@app_name.classify}::Application.config.secret_key_base = ENV['SECRET_TOKEN'] +#{app_const_base}::Application.config.secret_key_base = ENV['SECRET_TOKEN'] CODE -run "cp config/database.yml config/database.yml.sample" -run "echo '.rvmrc' >> .gitignore" -run "echo 'config/*.yml' >> .gitignore" -remove_file "README.rdoc" - -run "rvm 1.9.3@#{@app_name} --create --rvmrc" +create_file '.env', "SECRET_TOKEN=#{app_secret}" -run "bundle" - -generate "rspec:install" +run 'cp config/database.yml config/database.yml.sample' +append_file '.gitignore', '/.ruby-*' +append_file '.gitignore', '/config/*.yml' +remove_file "README.rdoc" -file ".rspec", <<-RSPEC ---color ---debugger ---fail-fast ---format doc ---profile -RSPEC +run 'bundle' -run "guard init rspec" +generate 'rspec:install' +get 'https://gist.github.com/tinogomes/6082570/raw/e7cb366b0376a594d3928a8bb744e4a154e671e8/.rspec', '.rspec' -generate :controller, :home, :index +if installed?('guard-rspec') + run "guard init rspec" -route "root to: 'home#index'" + gsub_file 'Guardfile', 'guard :rspec do', <<-EOF + rspec_options = { + all_after_pass: false, + all_on_start: false + } -git :init -git add: "." -git commit: "-m 'First version'" + guard :rspec, options: rspec_options do + EOF +end -puts "Copy those lines into your Guardfile", "\n", <<-GUARDFILE -rspec_options = { - all_after_pass: false, - all_on_start: false -} +if yes?('Do you want Home controller?') + generate :controller, :home, :index -guard :rspec, options: rspec_options do - ... + route "root to: 'home#index'" end -GUARDFILE -puts "execute `export SECRET_TOKEN=$(rake secret)`" +rake 'db:create:all' +rake 'db:migrate' +rake 'db:test:prepare' +rake 'spec' + +git :init +git add: '.' +git commit: '-m "It\'s time to get fun!"' -puts "It's time to get fun!" +puts ""
tinogomes/rails-template
8a636d6c7a870eb0d34cfa1d40587afefd3656f8
rails new example
diff --git a/README.rdoc b/README.rdoc index 95b4135..feacc33 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,28 +1,28 @@ To use these generator templates: - rails new app_name -m https://github.com/tinogomes/rails-template/raw/master/base.rb + rails new app_name -TB -d postgresql -m https://github.com/tinogomes/rails-template/raw/master/base.rb That will generate a Rails app using the base.rb template found here. -- Copyright (c) 2010 Tino Gomes 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. \ No newline at end of file
tinogomes/rails-template
8efc5e7c6d0e307efa5cb9c6eddcd291697d12f7
asking for execute bundle install
diff --git a/base.rb b/base.rb index 102aca5..601192b 100644 --- a/base.rb +++ b/base.rb @@ -1,33 +1,35 @@ app_name = ask('What is the name of your app?') gem_group :development, :test do gem "brakeman" gem "guard-rspec" gem "pry-debugger" gem "rspec-rails" gem "rubocop" end file "config/initializers/secret_token", <<-CODE if ENV['SECRET_TOKEN'].empty? warn('SECRET_TOKEN is not defined. Try `export SECRET_TOKEN=$(rake secret)`') exit 1 end file "README.mkdn", <<-README # #{app_name} TBD README #{app_name}::Application.config.secret_key_base = ENV['SECRET_TOKEN'] CODE run "cp config/database.yml config/database.yml.sample" run "echo '.rvmrc' >> .gitignore" run "echo 'config/*.yml' >> .gitignore" +run "bundle install" if yes?('Execute `bundle install` ?') + git :init git add: "."
tinogomes/rails-template
9f1e9ee2c66613294fcbd1e863fd7d7ed1392d78
my base template for rails apps
diff --git a/base.rb b/base.rb new file mode 100644 index 0000000..c0c7bdf --- /dev/null +++ b/base.rb @@ -0,0 +1,18 @@ +#This template was based from http://github.com/ryanb/rails-templates/blob/master/base.rb + +git :init + +run "echo 'TODO add readme content' > README" +run "touch tmp/.gitignore log/.gitignore vendor/.gitignore" +run "cp config/database.yml config/example_database.yml" +run "rm public/images/rails.png" +run "rm public/index.html" + +file ".gitignore", <<-GITIGNORE +log/*.log +tmp/**/* +config/database.yml +db/*.sqlite3 +GITIGNORE + +git :add => ".", :commit => "-m 'initial commit'"
Ramarren/cffi-stfl
50219f5a033481e1cb2ad4cba6459023eb6a9885
Add minimal README.
diff --git a/README.markdown b/README.markdown new file mode 100644 index 0000000..307686b --- /dev/null +++ b/README.markdown @@ -0,0 +1,7 @@ +* Overview + +This are CFFI bindings for [STFL](http://www.clifford.at/stfl/), Structured Terminal Forms Language/Library. + +* Notes + +This is almost completely untested. Only most basic display/event handling was checked at all. In particular I am worried about threading, as STFL seems to depend on pthreads. Also by default only static library is provided. I wrote binding against shared library generate just by adding `-shared` to Makefile, and am not sure how well does this work. \ No newline at end of file
Ramarren/cffi-stfl
3a72ec62bb04368465cfd649228a10b334ff397e
Transposed expressions.
diff --git a/bindings.lisp b/bindings.lisp index cdb249a..6b8949e 100644 --- a/bindings.lisp +++ b/bindings.lisp @@ -1,49 +1,49 @@ (in-package :cffi-stfl) (define-foreign-library stfl (:unix "./libstfl.so")) (use-foreign-library stfl) (defparameter *ipool* nil) (defctype stfl-form :pointer "STFL form handler") (defctype stfl-string :pointer) (defcfun (%create "stfl_create") stfl-form (text stfl-string)) (defcfun (%free "stfl_free") :void (form stfl-form)) (defcfun (%run "stfl_run") stfl-string (form stfl-form) (timeout :int)) (defcfun (reset "stfl_reset") :void) (defcfun (%get "stfl_get") stfl-string (form stfl-form) (name stfl-string)) (defcfun (%set "stfl_set") :void (form stfl-form) (name stfl-string) (value stfl-string)) (defcfun (%get-focus "stfl_get_focus") stfl-string (form stfl-form)) (defcfun (%set-focus "stfl_set_focus") :void (form stfl-form) (name stfl-string)) (defcfun (%stfl-quote "stfl_quote") :void (text stfl-string)) (defcfun (%dump "stfl_dump") stfl-string (form stfl-form) (name stfl-string) (prefix stfl-string) (focus :int)) (defcfun (%modify "stfl_modify") :void (form stfl-form) (name stfl-string) (mode stfl-string) (text stfl-string)) (defcfun (%lookup "stfl_lookup") stfl-string (form stfl-form) (path stfl-string) (newname stfl-string)) (defcfun (%get-error "stfl_error") stfl-string) (defcfun (%error-action "stfl_error_action") :void (mode stfl-string)) ;;; ipool (defctype stfl-ipool :pointer) (defcfun (ipool-create "stfl_ipool_create") stfl-ipool (code :string)) (defcfun (ipool-add "stfl_ipool_add") :void (pool stfl-ipool) (data :pointer)) (defcfun (ipool-towc "stfl_ipool_towc") stfl-string (pool stfl-ipool) (buf :string)) (defcfun (ipool-fromwc "stfl_ipool_fromwc") :string (pool stfl-ipool) (buf stfl-string)) (defcfun (ipool-flush "stfl_ipool_flush") :void (pool stfl-ipool)) (defcfun (ipool-destroy "stfl_ipool_destroy") :void (pool stfl-ipool)) (defun ipool-reset () (if *ipool* - (setf *ipool* (ipool-create "UTF8")) - (ipool-flush *ipool*))) + (ipool-flush *ipool*) + (setf *ipool* (ipool-create "UTF8")))) (defun towc (text) (ipool-towc *ipool* text)) (defun fromwc (stfl-text) (ipool-fromwc *ipool* stfl-text)) (declaim (inline ipool-reset towc fromwc)) \ No newline at end of file
Ramarren/cffi-stfl
8eb1e88d43384dde30e3382a2cb0c821ffe6c33e
Move form to optional argument with dynamic variable default.
diff --git a/bindings.lisp b/bindings.lisp index 0dcbc7d..cdb249a 100644 --- a/bindings.lisp +++ b/bindings.lisp @@ -1,49 +1,49 @@ (in-package :cffi-stfl) (define-foreign-library stfl (:unix "./libstfl.so")) (use-foreign-library stfl) (defparameter *ipool* nil) (defctype stfl-form :pointer "STFL form handler") (defctype stfl-string :pointer) (defcfun (%create "stfl_create") stfl-form (text stfl-string)) -(defcfun (free "stfl_free") :void (form stfl-form)) +(defcfun (%free "stfl_free") :void (form stfl-form)) (defcfun (%run "stfl_run") stfl-string (form stfl-form) (timeout :int)) -(defcfun (%reset "stfl_reset") :void) +(defcfun (reset "stfl_reset") :void) (defcfun (%get "stfl_get") stfl-string (form stfl-form) (name stfl-string)) (defcfun (%set "stfl_set") :void (form stfl-form) (name stfl-string) (value stfl-string)) (defcfun (%get-focus "stfl_get_focus") stfl-string (form stfl-form)) (defcfun (%set-focus "stfl_set_focus") :void (form stfl-form) (name stfl-string)) (defcfun (%stfl-quote "stfl_quote") :void (text stfl-string)) (defcfun (%dump "stfl_dump") stfl-string (form stfl-form) (name stfl-string) (prefix stfl-string) (focus :int)) (defcfun (%modify "stfl_modify") :void (form stfl-form) (name stfl-string) (mode stfl-string) (text stfl-string)) (defcfun (%lookup "stfl_lookup") stfl-string (form stfl-form) (path stfl-string) (newname stfl-string)) (defcfun (%get-error "stfl_error") stfl-string) (defcfun (%error-action "stfl_error_action") :void (mode stfl-string)) ;;; ipool (defctype stfl-ipool :pointer) (defcfun (ipool-create "stfl_ipool_create") stfl-ipool (code :string)) (defcfun (ipool-add "stfl_ipool_add") :void (pool stfl-ipool) (data :pointer)) (defcfun (ipool-towc "stfl_ipool_towc") stfl-string (pool stfl-ipool) (buf :string)) (defcfun (ipool-fromwc "stfl_ipool_fromwc") :string (pool stfl-ipool) (buf stfl-string)) (defcfun (ipool-flush "stfl_ipool_flush") :void (pool stfl-ipool)) (defcfun (ipool-destroy "stfl_ipool_destroy") :void (pool stfl-ipool)) (defun ipool-reset () (if *ipool* (setf *ipool* (ipool-create "UTF8")) (ipool-flush *ipool*))) (defun towc (text) (ipool-towc *ipool* text)) (defun fromwc (stfl-text) (ipool-fromwc *ipool* stfl-text)) (declaim (inline ipool-reset towc fromwc)) \ No newline at end of file diff --git a/package.lisp b/package.lisp index 139bf36..9f903e7 100644 --- a/package.lisp +++ b/package.lisp @@ -1,5 +1,6 @@ (defpackage #:cffi-stfl (:nicknames #:stfl) (:use #:cl #:iterate #:alexandria #:cffi) (:shadow "GET" "SET") - (:export #:create #:free #:run #:reset)) + (:export #:with-form #:create #:free #:run #:reset #:get #:set + #:get-focus #:set-focus #:dump #:modify #:lookup #:get-error #:error-action)) diff --git a/wrap.lisp b/wrap.lisp index 75a9430..0403865 100644 --- a/wrap.lisp +++ b/wrap.lisp @@ -1,41 +1,57 @@ (in-package :cffi-stfl) +(defvar *form* nil) + +(defmacro with-form ((form &optional (persist nil)) &body body) + (once-only (form) + `(let ((*form* (if (pointerp ,form) + ,form + (create ,form)))) + ,@(if persist + body + `(unwind-protect (progn + ,@body) + (free)))))) + (defun create (stfl-description) (assert (stringp stfl-description));add conversion from some s-exp format later (ipool-reset) (%create (towc stfl-description))) -(defun run (form timeout) +(defun free (&optional (form *form*)) + (%free form)) + +(defun run (timeout &optional (form *form*)) (ipool-reset) (fromwc (%run form timeout))) -(defun get (form name) +(defun get (name &optional (form *form*)) (ipool-reset) (fromwc (%get form (towc name)))) -(defun set (form name value) +(defun set (name value &optional (form *form*)) (ipool-reset) (%set form (towc name) (towc value))) -(defun get-focus (form) +(defun get-focus (&optional (form *form*)) (ipool-reset) (fromwc (%get-focus form))) -(defun set-focus (form) +(defun set-focus (name &optional (form *form*)) (ipool-reset) (%set-focus form (towc name))) -(defun dump (form name prefix focus) - (fromwc (%dump form (towc name) (towc mode) focus))) +(defun dump (name prefix focus &optional (form *form*)) + (fromwc (%dump form (towc name) (towc prefix) focus))) -(defun modify (form name mode text) +(defun modify (name mode text &optional (form *form*)) (%modify form (towc name) (towc mode) (towc text))) -(defun lookup (form path newname) +(defun lookup (path newname &optional (form *form*)) (fromwc (%lookup form (towc path) (towc newname)))) (defun get-error () (fromwc (%get-error))) (defun error-action (mode) (%error-action (towc mode)))
rhyhann/ralphy
75862f30c1b24ed5830e6393cdc264a69409e802
BasicRectangle => BasicRect
diff --git a/lib/ralphy/wrapper/basic.rb b/lib/ralphy/wrapper/basic.rb index d3150ff..c302577 100644 --- a/lib/ralphy/wrapper/basic.rb +++ b/lib/ralphy/wrapper/basic.rb @@ -1,40 +1,40 @@ module Ralphy - class BasicRectangle < Primitive + class BasicRect < Primitive tag :rect requires :width, :height end class BasicCircle < Primitive tag :circle requires :radius end class BasicEllipse < Primitive tag :ellipse requires :cx, :cy, :rx, :ry end class BasicLine < Primitive tag :line requires :x1, :y1, :x2, :y2 end class BasicPolygon < Primitive tag :polygon requires :points end class BasicPolyline < Primitive tag :polyline requires :points end class BasicPath < Primitive tag :path requires :d end class BasicG < Primitive tag :g end class BasicDefs < Primitive tag :defs end class BasicFilter < Primitive tag :filter requires :id end end
rhyhann/ralphy
d19e13878476ad45737399b16efa424058248a5a
Rough cuts. Almost no docs. Wait for it, it will come soon.
diff --git a/.gitignore b/.gitignore index 194a02c..dfe4126 100644 --- a/.gitignore +++ b/.gitignore @@ -1,39 +1,40 @@ # rcov generated coverage # rdoc generated rdoc # yard generated doc .yardoc # jeweler generated pkg +.bundle # Have editor/IDE/OS specific files you need to ignore? Consider using a global gitignore: # # * Create a file at ~/.gitignore # * Include files you want ignored # * Run: git config --global core.excludesfile ~/.gitignore # # After doing this, these files will be ignored in all your git projects, # saving you from having to 'pollute' every project you touch with them # # Not sure what to needs to be ignored for particular editors/OSes? Here's some ideas to get you started. (Remember, remove the leading # of the line) # # For MacOS: # #.DS_Store # # For TextMate #*.tmproj #tmtags # # For emacs: #*~ #\#* #.\#* # # For vim: #*.swp diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..1f58423 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "vendor/rdom"] + path = vendor/rdom + url = http://github.com/svenfuchs/rdom.git diff --git a/Gemfile b/Gemfile index 3658c56..55ff463 100644 --- a/Gemfile +++ b/Gemfile @@ -1,15 +1,19 @@ source :gemcutter # Add dependencies required to use your gem here. # Example: # gem "activesupport", ">= 2.3.5" - +gem "nokogiri" +gem "activesupport" # Add dependencies to develop your gem here. # Include everything needed to run rake, tests, features, etc. group :development do - gem "rspec", ">= 2.0.0.beta.19" + gem "simplecov" + gem "autotest" + gem "test_notifier" + gem "rspec", ">= 2.0.0.beta.20" gem "yard", ">= 0" gem "cucumber", ">= 0" gem "bundler", ">= 1.0.0.rc.5" gem "jeweler", "~> 1.5.0.pre2" gem "rcov", ">= 0" end diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000..bc8d3dd --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,55 @@ +GEM + remote: http://rubygems.org/ + specs: + activesupport (3.0.0) + autotest (4.3.2) + builder (2.1.2) + cucumber (0.8.5) + builder (~> 2.1.2) + diff-lcs (~> 1.1.2) + gherkin (~> 2.1.4) + json_pure (~> 1.4.3) + term-ansicolor (~> 1.0.4) + diff-lcs (1.1.2) + gherkin (2.1.5) + trollop (~> 1.16.2) + git (1.2.5) + jeweler (1.5.0.pre2) + bundler (>= 1.0.0.rc.5) + git (>= 1.2.5) + rake + json_pure (1.4.6) + nokogiri (1.4.3.1) + rake (0.8.7) + rcov (0.9.8) + rspec (2.0.0.beta.20) + rspec-core (= 2.0.0.beta.20) + rspec-expectations (= 2.0.0.beta.20) + rspec-mocks (= 2.0.0.beta.20) + rspec-core (2.0.0.beta.20) + rspec-expectations (2.0.0.beta.20) + diff-lcs (>= 1.1.2) + rspec-mocks (2.0.0.beta.20) + simplecov (0.3.3) + simplecov-html (>= 0.3.7) + simplecov-html (0.3.8) + term-ansicolor (1.0.5) + test_notifier (0.3.4) + trollop (1.16.2) + yard (0.6.0) + +PLATFORMS + ruby + +DEPENDENCIES + activesupport + autotest + bundler (>= 1.0.0.rc.5) + cucumber + jeweler (~> 1.5.0.pre2) + nokogiri + rcov + rspec (>= 2.0.0.beta.20) + simplecov + test_notifier + yard diff --git a/LICENSE b/MIT-LICENSE similarity index 100% rename from LICENSE rename to MIT-LICENSE diff --git a/README.rdoc b/README.rdoc index e69a2b4..a77d79f 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,17 +1,24 @@ = ralphy -Description goes here. +Ralphy is a Ruby SVG library, built on Nokogiri. + +== The Prestige + + svg = Ralphy::Image.new(:width => 300, :height => 200) + circle = Ralphy::Circle.new(:r => 100, :cx => svg.width/2, :cy => svg.height/2) + circle << Ralphy::Fill.new("#aeb219") # Automatically fills the circle and adds both of them in a <g> + rect = Ralphy::Rectangle.new(:) == Note on Patches/Pull Requests * Fork the project. * Make your feature addition or bug fix. * Add tests for it. This is important so I don't break it in a future version unintentionally. * Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull) * Send me a pull request. Bonus points for topic branches. == Copyright Copyright (c) 2010 Othmane Benkirane. See LICENSE for details. diff --git a/Rakefile b/Rakefile index 3f7e753..6733829 100644 --- a/Rakefile +++ b/Rakefile @@ -1,51 +1,56 @@ require 'rubygems' require 'bundler' begin Bundler.setup(:default, :development) rescue Bundler::BundlerError => e $stderr.puts e.message $stderr.puts "Run `bundle install` to install missing gems" exit e.status_code end require 'rake' require 'jeweler' Jeweler::Tasks.new do |gem| # gem is a Gem::Specification... see http://docs.rubygems.org/read/chapter/20 for more options gem.name = "ralphy" gem.summary = %Q{TODO: one-line summary of your gem} gem.description = %Q{TODO: longer description of your gem} gem.email = "o at thysteo dot com" gem.homepage = "http://github.com/rhyhann/ralphy" gem.authors = ["Othmane Benkirane"] # Include your dependencies below. Runtime dependencies are required when using your gem, # and development dependencies are only needed for development (ie running rake tasks, tests, etc) - # spec.add_runtime_dependency 'jabber4r', '> 0.1' - # spec.add_development_dependency 'rspec', '> 1.2.3' - gem.add_development_dependency "rspec", ">= 2.0.0.beta.19" + # demo.add_runtime_dependency 'jabber4r', '> 0.1' + # demo.add_development_dependency 'rdemo', '> 1.2.3' + gem.add_runtime_dependency 'nokogiri' + gem.add_development_dependency "rdemo", ">= 2.0.0.beta.19" gem.add_development_dependency "yard", ">= 0" gem.add_development_dependency "cucumber", ">= 0" gem.add_development_dependency "bundler", ">= 1.0.0.rc.5" gem.add_development_dependency "jeweler", "~> 1.5.0.pre2" gem.add_development_dependency "rcov", ">= 0" end -Jeweler::RubygemsDotOrgsTasks.new + +require 'rake' +require 'rake/tasklib' + require 'rspec/core' require 'rspec/core/rake_task' RSpec::Core::RakeTask.new(:spec) do |spec| spec.pattern = FileList['spec/**/*_spec.rb'] end RSpec::Core::RakeTask.new(:rcov) do |spec| spec.pattern = 'spec/**/*_spec.rb' spec.rcov = true end + require 'cucumber/rake/task' Cucumber::Rake::Task.new(:features) -task :default => :spec +task :default => :demo require 'yard' YARD::Rake::YardocTask.new diff --git a/autotest/discover.rb b/autotest/discover.rb new file mode 100644 index 0000000..cd6892c --- /dev/null +++ b/autotest/discover.rb @@ -0,0 +1 @@ +Autotest.add_discovery { "rspec2" } diff --git a/lib/ralphy.rb b/lib/ralphy.rb index e69de29..c0581f9 100644 --- a/lib/ralphy.rb +++ b/lib/ralphy.rb @@ -0,0 +1,13 @@ +require 'rubygems' +require 'bundler' +Bundler.setup(:default) +require 'nokogiri' + +module Ralphy + VERSION = 0 +end + +DIR = File.expand_path %(#{File.dirname(__FILE__)}/ralphy) + +require %(#{DIR}/xml_element) +require %(#{DIR}/wrapper) diff --git a/lib/ralphy/wrapper.rb b/lib/ralphy/wrapper.rb new file mode 100644 index 0000000..9b72fb7 --- /dev/null +++ b/lib/ralphy/wrapper.rb @@ -0,0 +1,3 @@ +Dir["#{File.dirname(__FILE__)}/wrapper/*.rb"].each do |file| + require file +end diff --git a/lib/ralphy/wrapper/_primitive.rb b/lib/ralphy/wrapper/_primitive.rb new file mode 100644 index 0000000..2d5cd98 --- /dev/null +++ b/lib/ralphy/wrapper/_primitive.rb @@ -0,0 +1,81 @@ +module Ralphy + class Primitive < XMLElement + + def initialize(tag, document) + [:attributes, :requires, :tag, :document].each do |variable| + instance_variable_set :"@#{variable}", + self.class.send(variable) + end + end + + # Get the SVG version of the element/document + def to_svg + raise ArgumentError, + "Undefined arguments: #{left_attributes.inspect}" \ + unless valid? + to_xml + end + + # Attributes left + def left_attributes + @requires - keys + end + + def valid? + left_attributes.empty? + end + + private + # Sees if the attribute is authorized + def authorized_attribute?(key) + return true if @requires.empty? && @attributes.empty? + (@attributes.keys + @requires).include? key.to_sym + end + + + public + def self.new(options = {}) + object = super(tag, document) + options.merge(attributes).each do |key, value| + object[key] = value + end + object + end + + + protected + + # Define your static attributes here + def self.attributes(attrs = {}) + if attrs.empty? && !(defined?(@attributes)) && + self.superclass.respond_to?(:attributes) + superclass.attributes + else + @attributes ||= attrs + end + end + + def self.requires(*attrs) + return superclass.requires if attrs.empty? && !(defined?(@requires)) && + superclass.respond_to?(:requires) + @requires ||= attrs + end + + # Defines the tag name + def self.tag(tag = tag_name) + @tag ||= tag + end + + # The document where the element will be added + # Use it to wrap the element + def self.document(document = ::Nokogiri::XML::Document.new) + @document ||= document + end + + private + def self.tag_name + to_s.split('::').last.downcase + end + + end +end diff --git a/lib/ralphy/wrapper/abstract.rb b/lib/ralphy/wrapper/abstract.rb new file mode 100644 index 0000000..a83067e --- /dev/null +++ b/lib/ralphy/wrapper/abstract.rb @@ -0,0 +1,8 @@ +module Ralphy + class Abstract < Primitive + def self.new(name, options = {}) + tag(name) + super(options) + end + end +end diff --git a/lib/ralphy/wrapper/basic.rb b/lib/ralphy/wrapper/basic.rb new file mode 100644 index 0000000..d3150ff --- /dev/null +++ b/lib/ralphy/wrapper/basic.rb @@ -0,0 +1,40 @@ +module Ralphy + class BasicRectangle < Primitive + tag :rect + requires :width, :height + end + class BasicCircle < Primitive + tag :circle + requires :radius + end + class BasicEllipse < Primitive + tag :ellipse + requires :cx, :cy, :rx, :ry + end + class BasicLine < Primitive + tag :line + requires :x1, :y1, :x2, :y2 + end + class BasicPolygon < Primitive + tag :polygon + requires :points + end + class BasicPolyline < Primitive + tag :polyline + requires :points + end + class BasicPath < Primitive + tag :path + requires :d + end + class BasicG < Primitive + tag :g + end + class BasicDefs < Primitive + tag :defs + end + class BasicFilter < Primitive + tag :filter + requires :id + end +end diff --git a/lib/ralphy/xml_element.rb b/lib/ralphy/xml_element.rb new file mode 100644 index 0000000..6570061 --- /dev/null +++ b/lib/ralphy/xml_element.rb @@ -0,0 +1,21 @@ +module Ralphy + # Slightly changes the behaviour of the object + # (mainly uses symbols) + class XMLElement < Nokogiri::XML::Element + # Define an argument using that method + def []=(key, value) + raise ArgumentError unless authorized_attribute?(key) + super(key.to_s, value.to_s) + end + + # Get your argument using that method + def [](key) + super(key.to_s) + end + + # Get an array of keys + def keys + super.map(&:to_sym) + end + end +end diff --git a/spec/.rspec b/spec/.rspec deleted file mode 100644 index 4e1e0d2..0000000 --- a/spec/.rspec +++ /dev/null @@ -1 +0,0 @@ ---color diff --git a/spec/ralphy/wrapper/_primitive_spec.rb b/spec/ralphy/wrapper/_primitive_spec.rb new file mode 100644 index 0000000..99e4cde --- /dev/null +++ b/spec/ralphy/wrapper/_primitive_spec.rb @@ -0,0 +1,106 @@ +require File.expand_path %(#{File.dirname(__FILE__)}/../../spec_helper) + + +describe "Ralphy::Primitive" do + before do + ::Ralphy::Klass = Class.new(::Ralphy::Primitive) + end + it "inherits from Nokogiri::XML::Element" do + ::Ralphy::Klass.superclass.superclass.should == ::Ralphy::XMLElement + end + + describe '.new' do + it "is possible to accept no arguments" do + lambda {::Ralphy::Klass.new}.should_not raise_error + end + it "has its arguments passed to attributes" do + @klass = ::Ralphy::Klass.new(:x => 10, :y => 2, :style => 'stroke-width:2;') + @klass[:x].should == "10" + @klass[:y].should == "2" + @klass[:style].should == 'stroke-width:2;' + end + end + + describe "options" do + describe ".tag" do + it "can define a tag" do + ::Ralphy::Klass.send(:tag, 'tag') + ::Ralphy::Klass.send(:tag).should == 'tag' + end + it "defaults to the downcased class name" do + ::Ralphy::Klass.send(:tag).should == 'klass' + end + end + + describe ".document" do + it "can set config" do + ::Ralphy::Klass.send(:document, (doc = ::Nokogiri.XML '<svg></svg>')) + ::Ralphy::Klass.send(:document).should == doc + end + it "has a default document" do + ::Ralphy::Klass.send(:document).to_xml.should == %(<?xml version="1.0"?>\n) + end + end + + describe "attributes fonctions" do + before do + ::Ralphy::Klass.send(:attributes, :x => 0, :y => '0') + ::Ralphy::Klass.send(:requires, :width, :height) + @klass = ::Ralphy::Klass.new + end + + describe ".arguments" do + it "adds its arguments to the default set of arguments" do + ::Ralphy::Klass.new['y'].should == '0' + ::Ralphy::Klass.new[:x].should == '0' + end + + it "allows attributes to be defined" do + proc {@klass[:width] = 'test'}.should_not raise_error + @klass[:width].should == 'test' + end + it "allows attributes to be defined when created" do + proc {@klass = ::Ralphy::Klass.new(:height => '4')}.should_not raise_error + @klass[:height].should == '4' + end + it "stops rendering if not everything is here" do + proc {@klass.to_svg}.should raise_error(ArgumentError, + "Undefined arguments: [:width, :height]") + end + it "allows rendering when the object is valid" do + @klass[:width] = '2' + @klass[:height]= '0.0000001' + @klass.should be_valid + proc {@klass.to_svg}.should_not raise_error + end + end + + describe ".requires" do + it "allows attributes to be defined" do + proc {@klass[:width] = 'test'}.should_not raise_error + @klass[:width].should == 'test' + end + it "allows attributes to be created when created" do + proc {@klass = ::Ralphy::Klass.new(:height => '4')}.should_not raise_error + @klass[:height].should == '4' + end + it "stops rendering when there are not enough arguments" do + proc {@klass[:cx] = 'cxx'}.should raise_error(ArgumentError) + @klass[:cx].should be_nil + end + it "stops undefined attributes from being defined when created" do + proc {@klass = ::Ralphy::Klass.new(:cy => 'cyy')}.should raise_error(ArgumentError) + @klass[:cy].should be_nil + end + + end + end + + + end + + + after do + ::Ralphy.send :remove_const, :Klass.to_s.to_sym + end +end diff --git a/spec/ralphy/wrapper/abstract_spec.rb b/spec/ralphy/wrapper/abstract_spec.rb new file mode 100644 index 0000000..95a1ae5 --- /dev/null +++ b/spec/ralphy/wrapper/abstract_spec.rb @@ -0,0 +1,8 @@ +require File.expand_path %(#{File.dirname(__FILE__)}/../../spec_helper) + +describe "Ralphy::Abstract" do + it "can take any name" do + @abstract = Ralphy::Abstract.new('uniquename', :x => 40) + @abstract.to_svg.should == '<uniquename x="40"/>' + end +end diff --git a/spec/ralphy_spec.rb b/spec/ralphy_spec.rb index 017c141..26198a5 100644 --- a/spec/ralphy_spec.rb +++ b/spec/ralphy_spec.rb @@ -1,7 +1,12 @@ require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe "Ralphy" do - it "fails" do - fail "hey buddy, you should probably rename this file and start specing for real" + it "includes all its dependencies" do + Dir[%(#{File.dirname(__FILE__)}/../lib/ralphy/**/*.rb)].each do |element| + require(element.gsub('.rb','')).should be_false + end + end + it "has a version" do + Ralphy::VERSION.should be_kind_of Integer end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 14497a6..983a65d 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,21 +1,28 @@ require 'bundler' begin Bundler.setup(:default, :development) rescue Bundler::BundlerError => e $stderr.puts e.message $stderr.puts "Run `bundle install` to install missing gems" exit e.status_code end +require 'simplecov' +SimpleCov.start do + add_filter '/spec/' + add_filter '/features/' +end + $LOAD_PATH.unshift(File.dirname(__FILE__)) $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) require 'ralphy' require 'rspec' require 'rspec/autorun' +require 'active_support/inflector/inflections' # Requires supporting files with custom matchers and macros, etc, # in ./support/ and its subdirectories. Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f} RSpec.configure do |config| end
jasny/mysql-revisioning
e3bc3854ea26a3fb35ff9aecad7b149c873ffc7b
use SIGNAL SQLSTATE
diff --git a/mysql-revisioning.php b/mysql-revisioning.php index a3d842f..cb0684e 100644 --- a/mysql-revisioning.php +++ b/mysql-revisioning.php @@ -1,547 +1,547 @@ <?php /** * Class to generate revisioning tables and trigger for MySQL. */ class MySQL_Revisioning { /** * Database connection * @var mysqli */ protected $conn; /** * Dump SQL statements * @var boolean */ public $verbose = false; /** * SQL command to signal an error. * @var string */ protected $signal; /** * Connect to database * * @param mysqli|array $conn DB connection or connection settings */ public function connect($conn) { $this->conn = $conn instanceof mysqli ? $conn : new mysqli($conn['host'], $conn['user'], $conn['password'], $conn['db']); - if (!isset($this->signal)) $this->signal = $this->conn->server_version >= 60000 ? 'SIGNAL %errno SET MESSAGE_TEXT="%errmsg"' : 'DO `%errmsg`'; + if (!isset($this->signal)) $this->signal = $this->conn->server_version >= 60000 ? 'SIGNAL SQLSTATE \'%errno\' SET MESSAGE_TEXT="%errmsg"' : 'DO `%errmsg`'; } /** * Performs a query on the database * * @param string $statement * @return mysqli_result */ protected function query($statement) { if ($this->verbose) echo "\n", $statement, "\n"; $result = $this->conn->query($statement); if (!$result) throw new Exception("Query failed ({$this->conn->errno}): {$this->conn->error} "); return $result; } /** * Create a revision table based to original table. * * @param string $table * @param array $info Table information */ protected function createRevisionTable($table, $info) { $pk = '`' . join('`, `', $info['primarykey']) . '`'; $change_autoinc = !empty($info['autoinc']) ? "CHANGE `{$info['autoinc']}` `{$info['autoinc']}` {$info['fieldtypes'][$info['autoinc']]}," : null; $unique_index = ""; foreach ($info['unique'] as $key=>$rows) $unique_index .= ", DROP INDEX `$key`, ADD INDEX `$key` ($rows)"; $sql = <<<SQL ALTER TABLE `_revision_$table` $change_autoinc DROP PRIMARY KEY, ADD `_revision` bigint unsigned AUTO_INCREMENT, ADD `_revision_previous` bigint unsigned NULL, ADD `_revision_action` enum('INSERT','UPDATE') default NULL, ADD `_revision_user_id` int(10) unsigned NULL, ADD `_revision_timestamp` datetime NULL default NULL, ADD `_revision_comment` text NULL, ADD PRIMARY KEY (`_revision`), ADD INDEX (`_revision_previous`), ADD INDEX `org_primary` ($pk) $unique_index SQL; $this->query("CREATE TABLE `_revision_$table` LIKE `$table`"); $this->query($sql); $this->query("INSERT INTO `_revision_$table` SELECT *, NULL, NULL, 'INSERT', NULL, NOW(), 'Revisioning initialisation' FROM `$table`"); } /** * Create a revision table based to original table. * * @param string $table * @param array $info Table information */ protected function createRevisionChildTable($table, $info) { if (!empty($info['primarykey'])) $pk = '`' . join('`, `', $info['primarykey']) . '`'; $change_autoinc = !empty($info['autoinc']) ? "CHANGE `{$info['autoinc']}` `{$info['autoinc']}` {$info['fieldtypes'][$info['autoinc']]}," : null; $unique_index = ""; foreach ($info['unique'] as $key=>$rows) $unique_index .= "DROP INDEX `$key`, ADD INDEX `$key` ($rows),"; if (isset($pk)) $sql = <<<SQL ALTER TABLE `_revision_$table` $change_autoinc DROP PRIMARY KEY, ADD `_revision` bigint unsigned, ADD PRIMARY KEY (`_revision`, $pk), ADD INDEX `org_primary` ($pk), $unique_index COMMENT = "Child of `_revision_{$info['parent']}`" SQL; else $sql = <<<SQL ALTER TABLE `_revision_$table` ADD `_revision` bigint unsigned, ADD INDEX `_revision` (`_revision`), $unique_index COMMENT = "Child of `_revision_{$info['parent']}`" SQL; $this->query("CREATE TABLE `_revision_$table` LIKE `$table`"); $this->query($sql); $this->query("INSERT INTO `_revision_$table` SELECT `t`.*, `p`.`_revision` FROM `$table` AS `t` INNER JOIN `{$info['parent']}` AS `p` ON `t`.`{$info['foreign_key']}`=`p`.`{$info['parent_key']}`"); } /** * Alter the existing table. * * @param string $table * @param array $info Table information */ protected function alterTable($table, $info) { foreach ($info['primarykey'] as $field) $pk_join[] = "`t`.`$field` = `r`.`$field`"; $pk_join = join(' AND ', $pk_join); $sql = <<<SQL ALTER TABLE `$table` ADD `_revision` bigint unsigned NULL, ADD `_revision_comment` text NULL, ADD UNIQUE INDEX (`_revision`) SQL; $this->query($sql); $this->query("UPDATE `$table` AS `t` INNER JOIN `_revision_$table` AS `r` ON $pk_join SET `t`.`_revision` = `r`.`_revision`"); } /** * Alter the existing table. * * @param string $table * @param array $info Table information */ function createHistoryTable($table, $info) { $pk = '`' . join('`, `', $info['primarykey']) . '`'; foreach ($info['primarykey'] as $field) $pk_type[] = "`$field` {$info['fieldtypes'][$field]}"; $pk_type = join(',', $pk_type); $sql = <<<SQL CREATE TABLE `_revhistory_$table` ( $pk_type, `_revision` bigint unsigned NULL, `_revhistory_user_id` int(10) unsigned NULL, `_revhistory_timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP, INDEX ($pk), INDEX (_revision), INDEX (_revhistory_user_id), INDEX (_revhistory_timestamp) ) ENGINE=InnoDB SQL; $this->query($sql); $this->query("INSERT INTO `_revhistory_$table` SELECT $pk, `_revision`, NULL, `_revision_timestamp` FROM `_revision_$table`"); } /** * Create before insert trigger * * @param string $table * @param array $info Table information */ protected function beforeInsert($table, $info) { $fields = '`' . join('`, `', $info['fieldnames']) . '`'; $var_fields = '`var-' . join('`, `var-', $info['fieldnames']) . '`'; foreach ($info['fieldnames'] as $field) { $declare_var_fields[] = "DECLARE `var-$field` {$info['fieldtypes'][$field]}"; $new_to_var[] = "NEW.`$field` = `var-$field`"; } $declare_var_fields = join(";\n", $declare_var_fields); $new_to_var = join(', ', $new_to_var); $sql = <<<SQL CREATE TRIGGER `$table-beforeinsert` BEFORE INSERT ON `$table` FOR EACH ROW BEGIN $declare_var_fields; DECLARE `var-_revision` BIGINT UNSIGNED; DECLARE revisionCursor CURSOR FOR SELECT $fields FROM `_revision_$table` WHERE `_revision`=`var-_revision` LIMIT 1; IF NEW.`_revision` IS NULL THEN INSERT INTO `_revision_$table` (`_revision_comment`, `_revision_user_id`, `_revision_timestamp`) VALUES (NEW.`_revision_comment`, @auth_uid, NOW()); SET NEW.`_revision` = LAST_INSERT_ID(); ELSE SET `var-_revision`=NEW.`_revision`; OPEN revisionCursor; FETCH revisionCursor INTO $var_fields; CLOSE revisionCursor; SET $new_to_var; END IF; SET NEW.`_revision_comment` = NULL; END SQL; $this->query("DROP TRIGGER IF EXISTS `$table-beforeinsert`"); $this->query($sql); } /** * Create before insert trigger * * @param string $table * @param array $info Table information */ protected function beforeUpdate($table, $info) { $fields = '`' . join('`, `', $info['fieldnames']) . '`'; $var_fields = '`var-' . join('`, `var-', $info['fieldnames']) . '`'; foreach ($info['fieldnames'] as $field) { $declare_var_fields[] = "DECLARE `var-$field` {$info['fieldtypes'][$field]}"; $new_to_var[] = "NEW.`$field` = `var-$field`"; } $declare_var_fields = join(";\n", $declare_var_fields); $new_to_var = join(', ', $new_to_var); foreach ($info['primarykey'] as $field) $pk_new_ne_old[] = "(NEW.`$field` != OLD.`$field` OR NEW.`$field` IS NULL != OLD.`$field` IS NULL)"; $pk_new_ne_old = join(' OR ', $pk_new_ne_old); $signal_pk_new_ne_old = str_replace(array('%errno', '%errmsg'), array('23000', "Can't change the value of the primary key of table '$table' because of revisioning"), $this->signal); $sql = <<<SQL CREATE TRIGGER `$table-beforeupdate` BEFORE UPDATE ON `$table` FOR EACH ROW BEGIN $declare_var_fields; DECLARE `var-_revision` BIGINT UNSIGNED; DECLARE `var-_revision_action` enum('INSERT','UPDATE','DELETE'); DECLARE revisionCursor CURSOR FOR SELECT $fields, `_revision_action` FROM `_revision_$table` WHERE `_revision`=`var-_revision` LIMIT 1; IF NEW.`_revision` = OLD.`_revision` THEN SET NEW.`_revision` = NULL; ELSEIF NEW.`_revision` IS NOT NULL THEN SET `var-_revision` = NEW.`_revision`; OPEN revisionCursor; FETCH revisionCursor INTO $var_fields, `var-_revision_action`; CLOSE revisionCursor; IF `var-_revision_action` IS NOT NULL THEN SET $new_to_var; END IF; END IF; IF $pk_new_ne_old THEN $signal_pk_new_ne_old; END IF; IF NEW.`_revision` IS NULL THEN INSERT INTO `_revision_$table` (`_revision_previous`, `_revision_comment`, `_revision_user_id`, `_revision_timestamp`) VALUES (OLD.`_revision`, NEW.`_revision_comment`, @auth_uid, NOW()); SET NEW.`_revision` = LAST_INSERT_ID(); END IF; SET NEW.`_revision_comment` = NULL; END SQL; $this->query("DROP TRIGGER IF EXISTS `$table-beforeupdate`"); $this->query($sql); } /** * Create after insert trigger. * * @param string $table * @param array $info Table information * @param array $children Information of child tables */ protected function afterInsert($table, $info, $children) { $aftertrigger = empty($children) ? 'afterTriggerSingle' : 'afterTriggerParent'; $this->$aftertrigger('insert', $table, $info, $children); } /** * Create after update trigger. * * @param string $table * @param array $info Table information * @param array $children Information of child tables */ protected function afterUpdate($table, $info, $children) { $aftertrigger = empty($children) ? 'afterTriggerSingle' : 'afterTriggerParent'; $this->$aftertrigger('update', $table, $info, $children); } /** * Create after insert/update trigger for table without children. * * @param string $action INSERT or UPDATE * @param string $table * @param array $info Table information */ protected function afterTriggerSingle($action, $table, $info) { $pk = 'NEW.`' . join('`, NEW.`', $info['primarykey']) . '`'; foreach ($info['fieldnames'] as $field) $fields_is_new[] = "`$field` = NEW.`$field`"; $fields_is_new = join(', ', $fields_is_new); $sql = <<<SQL CREATE TRIGGER `$table-after$action` AFTER $action ON `$table` FOR EACH ROW BEGIN UPDATE `_revision_$table` SET $fields_is_new, `_revision_action`='$action' WHERE `_revision`=NEW.`_revision` AND `_revision_action` IS NULL; INSERT INTO `_revhistory_$table` VALUES ($pk, NEW.`_revision`, @auth_uid, NOW()); END SQL; $this->query("DROP TRIGGER IF EXISTS `$table-after$action`"); $this->query($sql); } /** * Create after insert/update trigger for table with children. * * @param string $action INSERT or UPDATE * @param string $table * @param array $info Table information * @param array $children Information of child tables */ protected function afterTriggerParent($action, $table, $info, $children=array()) { $pk = 'NEW.`' . join('`, NEW.`', $info['primarykey']) . '`'; foreach ($info['fieldnames'] as $field) $fields_is_new[] = "`$field` = NEW.`$field`"; $fields_is_new = join(', ', $fields_is_new); $child_newrev = ""; $child_switch = ""; foreach ($children as $child=>&$chinfo) { $child_fields = '`' . join('`, `', $chinfo['fieldnames']) . '`'; $child_newrev .= " INSERT INTO `_revision_$child` SELECT *, NEW.`_revision` FROM `$child` WHERE `{$chinfo['foreign_key']}` = NEW.`{$chinfo['parent_key']}`;"; if ($action == 'update') $child_switch .= " DELETE `t`.* FROM `$child` AS `t` LEFT JOIN `_revision_{$child}` AS `r` ON 0=1 WHERE `t`.`{$chinfo['foreign_key']}` = NEW.`{$chinfo['parent_key']}`;"; $child_switch .= " INSERT INTO `$child` SELECT $child_fields FROM `_revision_{$child}` WHERE `_revision` = NEW.`_revision`;"; } $sql = <<<SQL CREATE TRIGGER `$table-after$action` AFTER $action ON `$table` FOR EACH ROW BEGIN DECLARE `newrev` BOOLEAN; UPDATE `_revision_$table` SET $fields_is_new, `_revision_action`='$action' WHERE `_revision`=NEW.`_revision` AND `_revision_action` IS NULL; SET newrev = (ROW_COUNT() > 0); INSERT INTO `_revhistory_$table` VALUES ($pk, NEW.`_revision`, @auth_uid, NOW()); IF newrev THEN $child_newrev ELSE $child_switch END IF; END SQL; $this->query("DROP TRIGGER IF EXISTS `$table-after$action`"); $this->query($sql); } /** * Create after update trigger. * * @param string $table * @param array $info Table information */ protected function afterDelete($table, $info) { $pk = 'OLD.`' . join('`, OLD.`', $info['primarykey']) . '`'; $sql = <<<SQL CREATE TRIGGER `$table-afterdelete` AFTER DELETE ON `$table` FOR EACH ROW BEGIN INSERT INTO `_revhistory_$table` VALUES ($pk, NULL, @auth_uid, NOW()); END SQL; $this->query("DROP TRIGGER IF EXISTS `$table-afterdelete`"); $this->query($sql); } /** * Create after insert/update trigger. * * @param string $table * @param array $info Table information */ protected function afterInsertChild($table, $info) { $new = 'NEW.`' . join('`, NEW.`', $info['fieldnames']) . '`'; $fields = '`' . join('`, `', $info['fieldnames']) . '`'; $sql = <<<SQL CREATE TRIGGER `$table-afterinsert` AFTER INSERT ON `$table` FOR EACH ROW BEGIN DECLARE CONTINUE HANDLER FOR 1442 BEGIN END; INSERT IGNORE INTO `_revision_$table` ($fields, `_revision`) SELECT $new, `_revision` FROM `{$info['parent']}` AS `p` WHERE `p`.`{$info['parent_key']}`=NEW.`{$info['foreign_key']}`; END SQL; $this->query("DROP TRIGGER IF EXISTS `$table-afterinsert`"); $this->query($sql); } /** * Create after insert/update trigger. * * @param string $table * @param array $info Table information */ protected function afterUpdateChild($table, $info) { $new = 'NEW.`' . join('`, NEW.`', $info['fieldnames']) . '`'; $fields = '`' . join('`, `', $info['fieldnames']) . '`'; $delete = null; if (empty($info['primarykey'])) { foreach ($info['fieldnames'] as $field) $fields_is_old[] = "`$field` = OLD.`$field`"; $delete = "DELETE FROM `_revision_$table` WHERE `_revision` IN (SELECT `_revision` FROM `{$info['parent']}` WHERE `{$info['parent_key']}` = OLD.`{$info['foreign_key']}`) AND " . join(' AND ', $fields_is_old) . " LIMIT 1;"; } $sql = <<<SQL CREATE TRIGGER `$table-afterupdate` AFTER UPDATE ON `$table` FOR EACH ROW BEGIN $delete REPLACE INTO `_revision_$table` ($fields, `_revision`) SELECT $new, `_revision` FROM `{$info['parent']}` AS `p` WHERE `p`.`{$info['parent_key']}`=NEW.`{$info['foreign_key']}`; END SQL; $this->query("DROP TRIGGER IF EXISTS `$table-afterupdate`"); $this->query($sql); } /** * Create after update trigger. * * @param string $table * @param array $info Table information */ protected function afterDeleteChild($table, $info) { if (!empty($info['primarykey'])) { foreach ($info['primarykey'] as $field) $fields_is_old[] = "`r`.`$field` = OLD.`$field`"; $delete = "DELETE `r`.* FROM `_revision_$table` AS `r` INNER JOIN `{$info['parent']}` AS `p` ON `r`.`_revision` = `p`.`_revision` WHERE " . join(' AND ', $fields_is_old) . ";"; } else { foreach ($info['fieldnames'] as $field) $fields_is_old[] = "`$field` = OLD.`$field`"; $delete = "DELETE FROM `_revision_$table` WHERE `_revision` IN (SELECT `_revision` FROM `{$info['parent']}` WHERE `{$info['parent_key']}` = OLD.`{$info['foreign_key']}`) AND " . join(' AND ', $fields_is_old) . " LIMIT 1;"; } $sql = <<<SQL CREATE TRIGGER `$table-afterdelete` AFTER DELETE ON `$table` FOR EACH ROW BEGIN DECLARE CONTINUE HANDLER FOR 1442 BEGIN END; $delete END SQL; $this->query("DROP TRIGGER IF EXISTS `$table-afterdelete`"); $this->query($sql); } /** * Add revisioning * * @param array $args */ public function install($args) { foreach ($args as $arg) { if (is_string($arg)) { $matches = null; if (!preg_match_all('/[^,()\s]++/', $arg, $matches, PREG_PATTERN_ORDER)) continue; } else { $matches[0] = $arg; } $exists = false; $tables = array(); // Prepare foreach ($matches[0] as $i=>$table) { $info = array('parent'=>$i > 0 ? $matches[0][0] : null, 'unique'=>array()); $result = $this->query("DESCRIBE `$table`;"); while ($field = $result->fetch_assoc()) { if (preg_match('/^_revision/', $field['Field'])) { $exists = true; continue; } $info['fieldnames'][] = $field['Field']; if ($field['Key'] == 'PRI') $info['primarykey'][] = $field['Field']; if (preg_match('/\bauto_increment\b/i', $field['Extra'])) $info['autoinc'] = $field['Field']; $info['fieldtypes'][$field['Field']] = $field['Type']; } $result = $this->query("SELECT c.CONSTRAINT_NAME, GROUP_CONCAT(CONCAT('`', k.COLUMN_NAME, '`')) AS cols FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS `c` INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS `k` ON c.TABLE_SCHEMA=k.TABLE_SCHEMA AND c.TABLE_NAME=k.TABLE_NAME AND c.CONSTRAINT_NAME=k.CONSTRAINT_NAME WHERE c.TABLE_SCHEMA=DATABASE() AND c.TABLE_NAME='$table' AND c.CONSTRAINT_TYPE='UNIQUE' AND c.CONSTRAINT_NAME != '_revision' GROUP BY c.CONSTRAINT_NAME"); while ($key = $result->fetch_row()) $info['unique'][$key[0]] = $key[1]; if (empty($info['parent'])) { if (empty($info['primarykey'])) { trigger_error("Unable to add revisioning table '$table': Table does not have a primary key", E_USER_WARNING); continue 2; } } else { $result = $this->query("SELECT `COLUMN_NAME`, `REFERENCED_COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`KEY_COLUMN_USAGE` WHERE `TABLE_SCHEMA` = DATABASE() AND `TABLE_NAME` = '$table' AND REFERENCED_TABLE_SCHEMA = DATABASE() AND REFERENCED_TABLE_NAME = '{$info['parent']}' AND `REFERENCED_COLUMN_NAME` IS NOT NULL"); if ($result->num_rows == 0) { trigger_error("Unable to add revisioning table '$table' as child of '{$info['parent']}': Table does not have a foreign key reference to parent table", E_USER_WARNING); continue; } list($info['foreign_key'], $info['parent_key']) = $result->fetch_row(); } $tables[$table] = $info; } // Process reset($tables); $table = key($tables); $info = array_shift($tables); echo "Installing revisioning for `$table`";
jasny/mysql-revisioning
f8e71dc085f1306eed3e02e7ee58110aee13837f
Added original article as README.md
diff --git a/README.md b/README.md new file mode 100644 index 0000000..c18feae --- /dev/null +++ b/README.md @@ -0,0 +1,298 @@ +# Versioning MySQL data +As a developer you’re probably using a versioning control system, like subversion or git, to safeguard your data. Advantages of using a VCS are that you can walk to the individual changes for a document, see who made each change and revert back to specific revision if needed. These are features which would also be nice for data stored in a database. With the use of triggers we can implement versioning for data stored in a MySQL db. + +## How it works + +### The revisioning table +We will not store the different versions of the records in the original table. We want this solution to be in the database layer instead of putting all the logic in the application layer. Instead we’ll create a new table, which stores all the different versions and lives next to the original table, which only contains the current version of each record. This revisioning table is copy of the original table, with a couple of additional fields. + +``` +CREATE TABLE `_revision_mytable` LIKE `mytable`; + +ALTER TABLE `_revision_mytable` + CHANGE `id` `id` int(10) unsigned, + DROP PRIMARY KEY, + ADD `_revision` bigint unsigned AUTO_INCREMENT, + ADD `_revision_previous` bigint unsigned NULL, + ADD `_revision_action` enum('INSERT','UPDATE') default NULL, + ADD `_revision_user_id` int(10) unsigned NULL, + ADD `_revision_timestamp` datetime NULL default NULL, + ADD `_revision_comment` text NULL, + ADD PRIMARY KEY (`_revision`), + ADD INDEX (`_revision_previous`), + ADD INDEX `org_primary` (`id`); +``` + +The most important field is `_revision`. This field contains a unique identifier for a version of a record from the table. Since this is the unique identifier in the revisioning table, the original id field becomes a normal (indexed) field. + +We’ll also store some additional information in the revisioning table. The `_revision_previous` field hold the revision nr of the version that was updated to create this revision. Field `_revision_action` holds the action that was executed to create this revision. This field has an extra function that will discussed later. The user id and timestamp are useful for blaming changes on someone. We can add some comment per revision. + +The database user is probably always the same. Storing this in the user id field is not useful. Instead, we can set variable @auth_id after logging in and on connecting to the database to the session user. + +## Altering the original table +The original table needs 2 additional fields: `_revision` and `_revision_comment`. The `_revision` field holds the current active version. The field can also be used to revert to a different revision. The value of `_revision_comment` set on an update or insert will end up in the revisioning table. The field in the original table will always be empty. + +``` +ALTER TABLE `mytable` + ADD `_revision` bigint unsigned NULL, + ADD `_revision_comment` text NULL, + ADD UNIQUE INDEX (`_revision`); +The history table +Saving each version is not enough. Since we can revert back to older revisions and of course delete the record altogether, we want to store which version of the record was enabled at what time. The history table only needs to hold the revision number and a timestamp. We’ll add the primary key fields, so it’s easier to query. A user id field is included again to blame. + +CREATE TABLE `_revhistory_mytable` ( + `id` int(10) unsigned, + `_revision` bigint unsigned NULL, + `_revhistory_user_id` int(10) unsigned NULL, + `_revhistory_timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP, + INDEX (`id`), + INDEX (_revision), + INDEX (_revhistory_user_id), + INDEX (_revhistory_timestamp) +) ENGINE=InnoDB; +``` + +## How to use +Inserting, updating and deleting data should work as normal, including the INSERT … ON DUPLICATE KEY UPDATE syntax. When updating the _revision field shouldn’t be changed. + +To switch to a different version, we would do something like + +``` +UPDATE mytable SET _revision=$rev WHERE id=$id; +``` +However if the record has been deleted, there will be no record in the original table, therefore the update won’t do anything. Instead we could insert a record, specifying the revision. + +``` +INSERT INTO mytable SET _revision=$rev; +``` +We can combine these two into a statement that works either way. + +``` +INSERT INTO mytable SET id=$id, _revision=$rev ON DUPLICATE KEY UPDATE _revision=VALUES(_revision); +``` +The above query shows that there an additional constraint. The only thing that indicates that different versions is of the same record, is the primary key. Therefore value of the primary key can’t change on update. This might mean that some tables need to start using surrogate keys if they are not. + +### On Insert +Let’s dive into the triggers. We’ll start with before insert. This trigger should get the values of a revision when the _revision field is set, or otherwise add a new row to the revision table. + +``` +CREATE TRIGGER `mytable-beforeinsert` BEFORE INSERT ON `mytable` + FOR EACH ROW BEGIN + DECLARE `var-id` int(10) unsigned; + DECLARE `var-title` varchar(45); + DECLARE `var-body` text; + DECLARE `var-_revision` BIGINT UNSIGNED; + DECLARE revisionCursor CURSOR FOR SELECT `id`, `title`, `body` FROM `_revision_mytable` WHERE `_revision`=`var-_revision` LIMIT 1; + + IF NEW.`_revision` IS NULL THEN + INSERT INTO `_revision_mytable` (`_revision_comment`, `_revision_user_id`, `_revision_timestamp`) VALUES (NEW.`_revision_comment`, @auth_uid, NOW()); + SET NEW.`_revision` = LAST_INSERT_ID(); + ELSE + SET `var-_revision`=NEW.`_revision`; + OPEN revisionCursor; + FETCH revisionCursor INTO `var-id`, `var-title`, `var-body`; + CLOSE revisionCursor; + + SET NEW.`id` = `var-id`, NEW.`title` = `var-title`, NEW.`body` = `var-body`; + END IF; + + SET NEW.`_revision_comment` = NULL; + END + +CREATE TRIGGER `mytable-afterinsert` AFTER INSERT ON `mytable` + FOR EACH ROW BEGIN + UPDATE `_revision_mytable` SET `id` = NEW.`id`, `title` = NEW.`title`, `body` = NEW.`body`, `_revision_action`='INSERT' WHERE `_revision`=NEW.`_revision` AND `_revision_action` IS NULL; + INSERT INTO `_revhistory_mytable` VALUES (NEW.`id`, NEW.`_revision`, @auth_uid, NOW()); + END +``` + +If the `_revision` field is NULL, we insert a new row into the revision table. This action is primarily to get a revision number. We set the comment, user id and timestamp. We won’t set the values, action and previous id yet. The insert might fail or be converted into an update action by insert on duplicate key update. If the insert action fails, we’ll have an unused row in the revisioning table. This is a problem, since the primary key has not been set, so it won’t show up anywhere. We can clean up these phantom records once in a while to keep the table clean. + +When `_revision` is set, we use a cursor to get the values from the revision table. We can’t fetch to values directly into NEW, therefore we first fetch them into variables and than copy that into NEW. + +After insert, we’ll update the revision, setting the values and the action. However, the insert might have been an undelete action. In that case `_revision_action` is already set and we don’t need to update the revision. We also add an entry in the history table. + +### On Update +The before and after update trigger do more or less the same as the before and after insert trigger. + +``` +CREATE TRIGGER `mytable-beforeupdate` BEFORE UPDATE ON `mytable` + FOR EACH ROW BEGIN + DECLARE `var-id` int(10) unsigned; + DECLARE `var-title` varchar(45); + DECLARE `var-body` text; + DECLARE `var-_revision` BIGINT UNSIGNED; + DECLARE `var-_revision_action` enum('INSERT','UPDATE','DELETE'); + DECLARE revisionCursor CURSOR FOR SELECT `id`, `title`, `body`, `_revision_action` FROM `_revision_mytable` WHERE `_revision`=`var-_revision` LIMIT 1; + + IF NEW.`_revision` = OLD.`_revision` THEN + SET NEW.`_revision` = NULL; + + ELSEIF NEW.`_revision` IS NOT NULL THEN + SET `var-_revision` = NEW.`_revision`; + + OPEN revisionCursor; + FETCH revisionCursor INTO `var-id`, `var-title`, `var-body`, `var-_revision_action`; + CLOSE revisionCursor; + + IF `var-_revision_action` IS NOT NULL THEN + SET NEW.`id` = `var-id`, NEW.`title` = `var-title`, NEW.`body` = `var-body`; + END IF; + END IF; + + IF (NEW.`id` != OLD.`id` OR NEW.`id` IS NULL != OLD.`id` IS NULL) THEN +-- Workaround for missing SIGNAL command + DO `Can't change the value of the primary key of table 'mytable' because of revisioning`; + END IF; + + IF NEW.`_revision` IS NULL THEN + INSERT INTO `_revision_mytable` (`_revision_previous`, `_revision_comment`, `_revision_user_id`, `_revision_timestamp`) VALUES (OLD.`_revision`, NEW.`_revision_comment`, @auth_uid, NOW()); + SET NEW.`_revision` = LAST_INSERT_ID(); + END IF; + + SET NEW.`_revision_comment` = NULL; + END + +CREATE TRIGGER `mytable-afterupdate` AFTER UPDATE ON `mytable` + FOR EACH ROW BEGIN + UPDATE `_revision_mytable` SET `id` = NEW.`id`, `title` = NEW.`title`, `body` = NEW.`body`, `_revision_action`='UPDATE' WHERE `_revision`=NEW.`_revision` AND `_revision_action` IS NULL; + INSERT INTO `_revhistory_mytable` VALUES (NEW.`id`, NEW.`_revision`, @auth_uid, NOW()); + END +``` + +If `_revision` is not set, it has the old value. In that case a new revision should be created. Setting `_revision` to NULL will have the same behaviour of not setting `_revision`. Next to the comment, user id and timestamp, we add also set the previous revision. + +As said before, it’s very important that the value of primary key doesn’t change. We need to check this and trigger an error, if it would be changed. + +### On Delete +Deleting won’t create a new revisiong. However we do want to log that the record has been deleted. Therefore we add an entry to the history table with `_revision` set to NULL. + +``` +CREATE TRIGGER `mytable-afterdelete` AFTER DELETE ON `mytable` + FOR EACH ROW BEGIN + INSERT INTO `_revhistory_mytable` VALUES (OLD.`id`, NULL, @auth_uid, NOW()); + END +``` + +## Multi-table records +often the data of a record is spread across multiple tables, like an invoice with multiple invoice lines. Having each invoice line versioned individually isn’t really useful. Instead we want a new revision of the whole invoice on each change. + +Ideally a change of one or more parts of the invoice would be changed, a new revision would be created. There are several issues in actually creating this those. Detecting the change of multiple parts of the invoice at once, generating a single revision, would mean we need to know if the actions are done within the same transaction. Unfortunately there is a connection_id(), but no transaction_id() function in MySQL. Also, the query would fail when a query inserts or updates a record in the child table, using the parent table. We need to come up with something else. + +In the implementation we currently have in production, we version the rows in the parent as well in the child tables. For each version of the parent row, we register which versions of the child rows ware set. This however has really complicated the trigger code and tends to need a lot of checking an querying slowing the write process down. Since nobody ever looks at the versions of the child rows, the application forces a new version of the parent row. The benefits of versioning both are therefor minimal. + +### Only versioning the parent +For this new (simplified) implementation, we will only have one revision number across all tables of the record. Changing data from the parent table, will trigger a new version. This will not only copy the parent row to the revisioning table, but also the rows of the children. + +Writing to the child will not trigger a new version, instead it will update the data in the revisioning table. This means that when changing the record, you need to write to the parent table, before writing to the child tables. To force a new version without changing values use + +``` +UPDATE mytable SET _revision=NULL where id=$id +``` + +The parent and child tables are defined as + +``` +CREATE TABLE `mytable` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(255) NOT NULL DEFAULT '', + `description` text, + PRIMARY KEY (`id`), + UNIQUE KEY `name` (`name`) +) ENGINE=InnoDB + +CREATE TABLE `mychild` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `mytable_id` int(10) unsigned NOT NULL DEFAULT '0', + `title` varchar(255) NOT NULL DEFAULT '', + PRIMARY KEY (`id`), + KEY `mytable_id` (`mytable_id`), + CONSTRAINT `mychild_ibfk_1` FOREIGN KEY (`mytable_id`) REFERENCES `mytable` (`id`) ON DELETE CASCADE +) ENGINE=InnoDB +``` + +Note that we are using InnoDB tables here. MyISAM doesn’t have foreign key constraints, therefor it’s not possible to define a parent-child relationship. + +Insert, update and delete +In the parent trigger, two different things happen concerning the child rows. When a new version is created, the data of `mychild` is copied to the revisioning table. On a revision switch, data will be copied from the revisioning table into `mychild`. The “`_revision_action` IS NULL” condition, means that `_revision_mytable` is only updated when a new revision is created. + +``` +CREATE TRIGGER `mytable-afterupdate` AFTER update ON `mytable` + FOR EACH ROW BEGIN + DECLARE `newrev` BOOLEAN; + + UPDATE `_revision_mytable` SET `id` = NEW.`id`, `name` = NEW.`name`, `description` = NEW.`description`, `_revision_action`='update' WHERE `_revision`=NEW.`_revision` AND `_revision_action` IS NULL; + SET newrev = (ROW_COUNT() > 0); + INSERT INTO `_revhistory_mytable` VALUES (NEW.`id`, NEW.`_revision`, @auth_uid, NOW()); + + IF newrev THEN + INSERT INTO `_revision_mychild` SELECT *, NEW.`_revision` FROM `mychild` WHERE `mytable_id` = NEW.`id`; + ELSE + DELETE `t`.* FROM `mychild` AS `t` LEFT JOIN `_revision_mychild` AS `r` ON 0=1 WHERE `t`.`mytable_id` = NEW.`id`; + INSERT INTO `mychild` SELECT `id`, `mytable_id`, `title` FROM `_revision_mychild` WHERE `_revision` = NEW.`_revision`; + END IF; + END + +CREATE TRIGGER `mychild-afterinsert` AFTER INSERT ON `mychild` + FOR EACH ROW BEGIN + DECLARE CONTINUE HANDLER FOR 1442 BEGIN END; + INSERT IGNORE INTO `_revision_mychild` (`id`, `mytable_id`, `title`, `_revision`) SELECT NEW.`id`, NEW.`mytable_id`, NEW.`title`, `_revision` FROM `mytable` AS `p` WHERE `p`.`id`=NEW.`mytable_id`; + END + +CREATE TRIGGER `mychild-afterupdate` AFTER UPDATE ON `mychild` + FOR EACH ROW BEGIN + REPLACE INTO `_revision_mychild` (`id`, `mytable_id`, `title`, `_revision`) SELECT NEW.`id`, NEW.`mytable_id`, NEW.`title`, `_revision` FROM `mytable` AS `p` WHERE `p`.`id`=NEW.`mytable_id`; + END + +CREATE TRIGGER `mychild-afterdelete` AFTER DELETE ON `mychild` + FOR EACH ROW BEGIN + DECLARE CONTINUE HANDLER FOR 1442 BEGIN END; + DELETE `r`.* FROM `_revision_mychild` AS `r` INNER JOIN `mytable` AS `p` ON `r`.`_revision` = `p`.`_revision` WHERE `r`.`id` = OLD.`id`; + END +``` + +Changing data in table `mychild` simply updates the data in the revisioning table. The revision number is grabbed from the field in the parent table. + +Switching the revision can only be done through the parent table. This will also automatically change the data in the child tables. We simply delete all rows of the record and replace them with data from the revisioning table. This would however trigger the deletion of the data in `_revision_child` on which the insert has nothing to do. To prevent this, we can abuse that fact that a trigger can’t update data of a table using in the insert/update/delete query. This causes error 1442. With a continue handler we can ignore this silently. + +The InnoDB constraints will handle the cascading delete. Deleting child data won’t activate the deletion trigger, which is all the better in this case. + +### Without a primary key +A primary key is not required for the child table, since versioning is done purely based on the id of `mytable`. + +``` +CREATE TABLE `mypart` ( + `mytable_id` int(10) unsigned NOT NULL, + `reference` varchar(255) NOT NULL, + KEY `mytable_id` (`mytable_id`), + CONSTRAINT `mypart_ibfk_1` FOREIGN KEY (`mytable_id`) REFERENCES `mytable` (`id`) ON DELETE CASCADE +) ENGINE=InnoDB +``` + +This does cause an issue for the update and delete triggers of the child table. It can’t use the primary to id to locate the current version of the modified/removed row. This can be solved by a trick I got from PhpMyAdmin. We can simply locate the record by comparing the old values of all fields. There is no constraint for the table enforcing the uniqueness of a row, so we could be targeting multiple identical rows. Since they are identical, it doesn’t matter which one we target, as long as we limit to 1 row. + +``` +CREATE TRIGGER `mypart-afterupdate` AFTER UPDATE ON `mypart` + FOR EACH ROW BEGIN + DELETE FROM `_revision_mypart` WHERE `_revision` IN (SELECT `_revision` FROM `mytable` WHERE `id` = OLD.`mytable_id`) AND `mytable_id` = OLD.`mytable_id` AND `reference` = OLD.`reference` LIMIT 1; + INSERT INTO `_revision_mypart` (`mytable_id`, `reference`, `_revision`) SELECT NEW.`mytable_id`, NEW.`reference`, `_revision` FROM `mytable` AS `p` WHERE `p`.`id`=NEW.`mytable_id`; + END + +CREATE TRIGGER `mypart-afterdelete` AFTER DELETE ON `mypart` + FOR EACH ROW BEGIN + DECLARE CONTINUE HANDLER FOR 1442 BEGIN END; + DELETE FROM `_revision_mypart` WHERE `_revision` IN (SELECT `_revision` FROM `mytable` WHERE `id` = OLD.`mytable_id`) AND `mytable_id` = OLD.`mytable_id` AND `reference` = OLD.`reference` LIMIT 1; + END +``` + +### Unique keys +The revisioning table has multiple versions of a record. Unique indexes from the original table should be converted to non-unique indexes in the revisioning table. This information can be fetched using INFORMATION_SCHEMA. + +``` +SELECT c.CONSTRAINT_NAME, GROUP_CONCAT(CONCAT('`', k.COLUMN_NAME, '`')) AS cols FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS `c` INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS `k` ON c.TABLE_SCHEMA=k.TABLE_SCHEMA AND c.TABLE_NAME=k.TABLE_NAME AND c.CONSTRAINT_NAME=k.CONSTRAINT_NAME WHERE c.TABLE_SCHEMA=DATABASE() AND c.TABLE_NAME='mytable' AND c.CONSTRAINT_TYPE='UNIQUE' AND c.CONSTRAINT_NAME != '_revision' GROUP BY c.CONSTRAINT_NAME +``` + +### Revisioning and replication +[Baron Schwartz](https://twitter.com/xaprb) pointed out some possible issues with implementing versioning in MySQL. One of which is a race condition when relying on auto-increment keys in triggers with replication. Actions carried out through triggers on a master are not replicated to a slave server. Instead, triggers on the slave will be invoked, which should do the same action as on the master. + +It probably isn’t needed to have a copy of the revisioning tables on the slave. This would mean that we could simply omit the triggers. Unfortunately this causes problems when changing the revision. In that case we are forced to move switching of a revision out of the database. Instead the application needs to select the data from all revisioning tables and write that to the original tables.
jasny/mysql-revisioning
ac2c2af57118b5eaa9f221b33497bd701551a92d
use explode instead of split
diff --git a/mysql-revisioning.php b/mysql-revisioning.php index 84af51a..a3d842f 100644 --- a/mysql-revisioning.php +++ b/mysql-revisioning.php @@ -127,534 +127,534 @@ SQL; * Alter the existing table. * * @param string $table * @param array $info Table information */ protected function alterTable($table, $info) { foreach ($info['primarykey'] as $field) $pk_join[] = "`t`.`$field` = `r`.`$field`"; $pk_join = join(' AND ', $pk_join); $sql = <<<SQL ALTER TABLE `$table` ADD `_revision` bigint unsigned NULL, ADD `_revision_comment` text NULL, ADD UNIQUE INDEX (`_revision`) SQL; $this->query($sql); $this->query("UPDATE `$table` AS `t` INNER JOIN `_revision_$table` AS `r` ON $pk_join SET `t`.`_revision` = `r`.`_revision`"); } /** * Alter the existing table. * * @param string $table * @param array $info Table information */ function createHistoryTable($table, $info) { $pk = '`' . join('`, `', $info['primarykey']) . '`'; foreach ($info['primarykey'] as $field) $pk_type[] = "`$field` {$info['fieldtypes'][$field]}"; $pk_type = join(',', $pk_type); $sql = <<<SQL CREATE TABLE `_revhistory_$table` ( $pk_type, `_revision` bigint unsigned NULL, `_revhistory_user_id` int(10) unsigned NULL, `_revhistory_timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP, INDEX ($pk), INDEX (_revision), INDEX (_revhistory_user_id), INDEX (_revhistory_timestamp) ) ENGINE=InnoDB SQL; $this->query($sql); $this->query("INSERT INTO `_revhistory_$table` SELECT $pk, `_revision`, NULL, `_revision_timestamp` FROM `_revision_$table`"); } /** * Create before insert trigger * * @param string $table * @param array $info Table information */ protected function beforeInsert($table, $info) { $fields = '`' . join('`, `', $info['fieldnames']) . '`'; $var_fields = '`var-' . join('`, `var-', $info['fieldnames']) . '`'; foreach ($info['fieldnames'] as $field) { $declare_var_fields[] = "DECLARE `var-$field` {$info['fieldtypes'][$field]}"; $new_to_var[] = "NEW.`$field` = `var-$field`"; } $declare_var_fields = join(";\n", $declare_var_fields); $new_to_var = join(', ', $new_to_var); $sql = <<<SQL CREATE TRIGGER `$table-beforeinsert` BEFORE INSERT ON `$table` FOR EACH ROW BEGIN $declare_var_fields; DECLARE `var-_revision` BIGINT UNSIGNED; DECLARE revisionCursor CURSOR FOR SELECT $fields FROM `_revision_$table` WHERE `_revision`=`var-_revision` LIMIT 1; IF NEW.`_revision` IS NULL THEN INSERT INTO `_revision_$table` (`_revision_comment`, `_revision_user_id`, `_revision_timestamp`) VALUES (NEW.`_revision_comment`, @auth_uid, NOW()); SET NEW.`_revision` = LAST_INSERT_ID(); ELSE SET `var-_revision`=NEW.`_revision`; OPEN revisionCursor; FETCH revisionCursor INTO $var_fields; CLOSE revisionCursor; SET $new_to_var; END IF; SET NEW.`_revision_comment` = NULL; END SQL; $this->query("DROP TRIGGER IF EXISTS `$table-beforeinsert`"); $this->query($sql); } /** * Create before insert trigger * * @param string $table * @param array $info Table information */ protected function beforeUpdate($table, $info) { $fields = '`' . join('`, `', $info['fieldnames']) . '`'; $var_fields = '`var-' . join('`, `var-', $info['fieldnames']) . '`'; foreach ($info['fieldnames'] as $field) { $declare_var_fields[] = "DECLARE `var-$field` {$info['fieldtypes'][$field]}"; $new_to_var[] = "NEW.`$field` = `var-$field`"; } $declare_var_fields = join(";\n", $declare_var_fields); $new_to_var = join(', ', $new_to_var); foreach ($info['primarykey'] as $field) $pk_new_ne_old[] = "(NEW.`$field` != OLD.`$field` OR NEW.`$field` IS NULL != OLD.`$field` IS NULL)"; $pk_new_ne_old = join(' OR ', $pk_new_ne_old); $signal_pk_new_ne_old = str_replace(array('%errno', '%errmsg'), array('23000', "Can't change the value of the primary key of table '$table' because of revisioning"), $this->signal); $sql = <<<SQL CREATE TRIGGER `$table-beforeupdate` BEFORE UPDATE ON `$table` FOR EACH ROW BEGIN $declare_var_fields; DECLARE `var-_revision` BIGINT UNSIGNED; DECLARE `var-_revision_action` enum('INSERT','UPDATE','DELETE'); DECLARE revisionCursor CURSOR FOR SELECT $fields, `_revision_action` FROM `_revision_$table` WHERE `_revision`=`var-_revision` LIMIT 1; IF NEW.`_revision` = OLD.`_revision` THEN SET NEW.`_revision` = NULL; ELSEIF NEW.`_revision` IS NOT NULL THEN SET `var-_revision` = NEW.`_revision`; OPEN revisionCursor; FETCH revisionCursor INTO $var_fields, `var-_revision_action`; CLOSE revisionCursor; IF `var-_revision_action` IS NOT NULL THEN SET $new_to_var; END IF; END IF; IF $pk_new_ne_old THEN $signal_pk_new_ne_old; END IF; IF NEW.`_revision` IS NULL THEN INSERT INTO `_revision_$table` (`_revision_previous`, `_revision_comment`, `_revision_user_id`, `_revision_timestamp`) VALUES (OLD.`_revision`, NEW.`_revision_comment`, @auth_uid, NOW()); SET NEW.`_revision` = LAST_INSERT_ID(); END IF; SET NEW.`_revision_comment` = NULL; END SQL; $this->query("DROP TRIGGER IF EXISTS `$table-beforeupdate`"); $this->query($sql); } /** * Create after insert trigger. * * @param string $table * @param array $info Table information * @param array $children Information of child tables */ protected function afterInsert($table, $info, $children) { $aftertrigger = empty($children) ? 'afterTriggerSingle' : 'afterTriggerParent'; $this->$aftertrigger('insert', $table, $info, $children); } /** * Create after update trigger. * * @param string $table * @param array $info Table information * @param array $children Information of child tables */ protected function afterUpdate($table, $info, $children) { $aftertrigger = empty($children) ? 'afterTriggerSingle' : 'afterTriggerParent'; $this->$aftertrigger('update', $table, $info, $children); } /** * Create after insert/update trigger for table without children. * * @param string $action INSERT or UPDATE * @param string $table * @param array $info Table information */ protected function afterTriggerSingle($action, $table, $info) { $pk = 'NEW.`' . join('`, NEW.`', $info['primarykey']) . '`'; foreach ($info['fieldnames'] as $field) $fields_is_new[] = "`$field` = NEW.`$field`"; $fields_is_new = join(', ', $fields_is_new); $sql = <<<SQL CREATE TRIGGER `$table-after$action` AFTER $action ON `$table` FOR EACH ROW BEGIN UPDATE `_revision_$table` SET $fields_is_new, `_revision_action`='$action' WHERE `_revision`=NEW.`_revision` AND `_revision_action` IS NULL; INSERT INTO `_revhistory_$table` VALUES ($pk, NEW.`_revision`, @auth_uid, NOW()); END SQL; $this->query("DROP TRIGGER IF EXISTS `$table-after$action`"); $this->query($sql); } /** * Create after insert/update trigger for table with children. * * @param string $action INSERT or UPDATE * @param string $table * @param array $info Table information * @param array $children Information of child tables */ protected function afterTriggerParent($action, $table, $info, $children=array()) { $pk = 'NEW.`' . join('`, NEW.`', $info['primarykey']) . '`'; foreach ($info['fieldnames'] as $field) $fields_is_new[] = "`$field` = NEW.`$field`"; $fields_is_new = join(', ', $fields_is_new); $child_newrev = ""; $child_switch = ""; foreach ($children as $child=>&$chinfo) { $child_fields = '`' . join('`, `', $chinfo['fieldnames']) . '`'; $child_newrev .= " INSERT INTO `_revision_$child` SELECT *, NEW.`_revision` FROM `$child` WHERE `{$chinfo['foreign_key']}` = NEW.`{$chinfo['parent_key']}`;"; if ($action == 'update') $child_switch .= " DELETE `t`.* FROM `$child` AS `t` LEFT JOIN `_revision_{$child}` AS `r` ON 0=1 WHERE `t`.`{$chinfo['foreign_key']}` = NEW.`{$chinfo['parent_key']}`;"; $child_switch .= " INSERT INTO `$child` SELECT $child_fields FROM `_revision_{$child}` WHERE `_revision` = NEW.`_revision`;"; } $sql = <<<SQL CREATE TRIGGER `$table-after$action` AFTER $action ON `$table` FOR EACH ROW BEGIN DECLARE `newrev` BOOLEAN; UPDATE `_revision_$table` SET $fields_is_new, `_revision_action`='$action' WHERE `_revision`=NEW.`_revision` AND `_revision_action` IS NULL; SET newrev = (ROW_COUNT() > 0); INSERT INTO `_revhistory_$table` VALUES ($pk, NEW.`_revision`, @auth_uid, NOW()); IF newrev THEN $child_newrev ELSE $child_switch END IF; END SQL; $this->query("DROP TRIGGER IF EXISTS `$table-after$action`"); $this->query($sql); } /** * Create after update trigger. * * @param string $table * @param array $info Table information */ protected function afterDelete($table, $info) { $pk = 'OLD.`' . join('`, OLD.`', $info['primarykey']) . '`'; $sql = <<<SQL CREATE TRIGGER `$table-afterdelete` AFTER DELETE ON `$table` FOR EACH ROW BEGIN INSERT INTO `_revhistory_$table` VALUES ($pk, NULL, @auth_uid, NOW()); END SQL; $this->query("DROP TRIGGER IF EXISTS `$table-afterdelete`"); $this->query($sql); } /** * Create after insert/update trigger. * * @param string $table * @param array $info Table information */ protected function afterInsertChild($table, $info) { $new = 'NEW.`' . join('`, NEW.`', $info['fieldnames']) . '`'; $fields = '`' . join('`, `', $info['fieldnames']) . '`'; $sql = <<<SQL CREATE TRIGGER `$table-afterinsert` AFTER INSERT ON `$table` FOR EACH ROW BEGIN DECLARE CONTINUE HANDLER FOR 1442 BEGIN END; INSERT IGNORE INTO `_revision_$table` ($fields, `_revision`) SELECT $new, `_revision` FROM `{$info['parent']}` AS `p` WHERE `p`.`{$info['parent_key']}`=NEW.`{$info['foreign_key']}`; END SQL; $this->query("DROP TRIGGER IF EXISTS `$table-afterinsert`"); $this->query($sql); } /** * Create after insert/update trigger. * * @param string $table * @param array $info Table information */ protected function afterUpdateChild($table, $info) { $new = 'NEW.`' . join('`, NEW.`', $info['fieldnames']) . '`'; $fields = '`' . join('`, `', $info['fieldnames']) . '`'; $delete = null; if (empty($info['primarykey'])) { foreach ($info['fieldnames'] as $field) $fields_is_old[] = "`$field` = OLD.`$field`"; $delete = "DELETE FROM `_revision_$table` WHERE `_revision` IN (SELECT `_revision` FROM `{$info['parent']}` WHERE `{$info['parent_key']}` = OLD.`{$info['foreign_key']}`) AND " . join(' AND ', $fields_is_old) . " LIMIT 1;"; } $sql = <<<SQL CREATE TRIGGER `$table-afterupdate` AFTER UPDATE ON `$table` FOR EACH ROW BEGIN $delete REPLACE INTO `_revision_$table` ($fields, `_revision`) SELECT $new, `_revision` FROM `{$info['parent']}` AS `p` WHERE `p`.`{$info['parent_key']}`=NEW.`{$info['foreign_key']}`; END SQL; $this->query("DROP TRIGGER IF EXISTS `$table-afterupdate`"); $this->query($sql); } /** * Create after update trigger. * * @param string $table * @param array $info Table information */ protected function afterDeleteChild($table, $info) { if (!empty($info['primarykey'])) { foreach ($info['primarykey'] as $field) $fields_is_old[] = "`r`.`$field` = OLD.`$field`"; $delete = "DELETE `r`.* FROM `_revision_$table` AS `r` INNER JOIN `{$info['parent']}` AS `p` ON `r`.`_revision` = `p`.`_revision` WHERE " . join(' AND ', $fields_is_old) . ";"; } else { foreach ($info['fieldnames'] as $field) $fields_is_old[] = "`$field` = OLD.`$field`"; $delete = "DELETE FROM `_revision_$table` WHERE `_revision` IN (SELECT `_revision` FROM `{$info['parent']}` WHERE `{$info['parent_key']}` = OLD.`{$info['foreign_key']}`) AND " . join(' AND ', $fields_is_old) . " LIMIT 1;"; } $sql = <<<SQL CREATE TRIGGER `$table-afterdelete` AFTER DELETE ON `$table` FOR EACH ROW BEGIN DECLARE CONTINUE HANDLER FOR 1442 BEGIN END; $delete END SQL; $this->query("DROP TRIGGER IF EXISTS `$table-afterdelete`"); $this->query($sql); } /** * Add revisioning * * @param array $args */ public function install($args) { foreach ($args as $arg) { if (is_string($arg)) { $matches = null; if (!preg_match_all('/[^,()\s]++/', $arg, $matches, PREG_PATTERN_ORDER)) continue; } else { $matches[0] = $arg; } $exists = false; $tables = array(); // Prepare foreach ($matches[0] as $i=>$table) { $info = array('parent'=>$i > 0 ? $matches[0][0] : null, 'unique'=>array()); $result = $this->query("DESCRIBE `$table`;"); while ($field = $result->fetch_assoc()) { if (preg_match('/^_revision/', $field['Field'])) { $exists = true; continue; } $info['fieldnames'][] = $field['Field']; if ($field['Key'] == 'PRI') $info['primarykey'][] = $field['Field']; if (preg_match('/\bauto_increment\b/i', $field['Extra'])) $info['autoinc'] = $field['Field']; $info['fieldtypes'][$field['Field']] = $field['Type']; } $result = $this->query("SELECT c.CONSTRAINT_NAME, GROUP_CONCAT(CONCAT('`', k.COLUMN_NAME, '`')) AS cols FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS `c` INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS `k` ON c.TABLE_SCHEMA=k.TABLE_SCHEMA AND c.TABLE_NAME=k.TABLE_NAME AND c.CONSTRAINT_NAME=k.CONSTRAINT_NAME WHERE c.TABLE_SCHEMA=DATABASE() AND c.TABLE_NAME='$table' AND c.CONSTRAINT_TYPE='UNIQUE' AND c.CONSTRAINT_NAME != '_revision' GROUP BY c.CONSTRAINT_NAME"); while ($key = $result->fetch_row()) $info['unique'][$key[0]] = $key[1]; if (empty($info['parent'])) { if (empty($info['primarykey'])) { trigger_error("Unable to add revisioning table '$table': Table does not have a primary key", E_USER_WARNING); continue 2; } } else { $result = $this->query("SELECT `COLUMN_NAME`, `REFERENCED_COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`KEY_COLUMN_USAGE` WHERE `TABLE_SCHEMA` = DATABASE() AND `TABLE_NAME` = '$table' AND REFERENCED_TABLE_SCHEMA = DATABASE() AND REFERENCED_TABLE_NAME = '{$info['parent']}' AND `REFERENCED_COLUMN_NAME` IS NOT NULL"); if ($result->num_rows == 0) { trigger_error("Unable to add revisioning table '$table' as child of '{$info['parent']}': Table does not have a foreign key reference to parent table", E_USER_WARNING); continue; } list($info['foreign_key'], $info['parent_key']) = $result->fetch_row(); } $tables[$table] = $info; } // Process reset($tables); $table = key($tables); $info = array_shift($tables); echo "Installing revisioning for `$table`"; // Parent if (!$exists) { echo " - tables"; $this->createRevisionTable($table, $info); $this->alterTable($table, $info); $this->createHistoryTable($table, $info); } echo " - triggers"; $this->beforeInsert($table, $info, $tables); $this->afterUpdate($table, $info, $tables); $this->beforeUpdate($table, $info, $tables); $this->afterInsert($table, $info, $tables); $this->afterDelete($table, $info, $tables); // Children foreach ($tables as $table=>&$info) { echo "\n - child `$table`"; if (!$exists) { echo " - tables"; $this->createRevisionChildTable($table, $info); } echo " - triggers"; $this->afterInsertChild($table, $info); $this->afterUpdateChild($table, $info); $this->afterDeleteChild($table, $info); } echo "\n"; } } /** * Remove revisioning for tables * * @param $args */ public function remove($args) { foreach ($args as $arg) { $matches = null; if (!preg_match_all('/[^,()\s]++/', $arg, $matches, PREG_PATTERN_ORDER)) return; // Prepare foreach ($matches[0] as $i=>$table) { echo "Removing revisioning for `$table`\n"; $this->query("DROP TRIGGER IF EXISTS `$table-afterdelete`;"); $this->query("DROP TRIGGER IF EXISTS `$table-afterupdate`;"); $this->query("DROP TRIGGER IF EXISTS `$table-beforeupdate`;"); $this->query("DROP TRIGGER IF EXISTS `$table-afterinsert`;"); $this->query("DROP TRIGGER IF EXISTS `$table-beforeinsert`;"); if ($i == 0) $this->query("DROP TABLE IF EXISTS `_revhistory_$table`;"); $this->query("DROP TABLE IF EXISTS `_revision_$table`;"); if ($i == 0) $this->query("ALTER TABLE `$table` DROP `_revision`, DROP `_revision_comment`"); } } } public function help() { echo <<<MESSAGE Usage: php {$_SERVER['argv'][0]} [OPTION]... [--install|--remove] TABLE... Options: --host=HOSTNAME MySQL hostname --user=USER MySQL username --password=PWD MySQL password --db=DATABASE MySQL database --signal=CMD SQL command to signal an error MESSAGE; } /** * Execute command line script */ public function execCmd() { $args = array(); $settings = array('host'=>'localhost', 'user'=>null, 'password'=>null, 'db'=>null); for ($i=1; $i < $_SERVER['argc']; $i++) { if (strncmp($_SERVER['argv'][$i], '--', 2) == 0) { - list($key, $value) = split("=", substr($_SERVER['argv'][$i], 2), 2) + array(1=>null); + list($key, $value) = explode("=", substr($_SERVER['argv'][$i], 2), 2) + array(1=>null); if (property_exists($this, $key)) $this->$key = isset($value) ? $value : true; elseif (!isset($value)) $cmd = $key; else $settings[$key] = $value; } else { $args[] = $_SERVER['argv'][$i]; } } if (!isset($cmd)) $cmd = empty($args) ? 'help' : 'install'; $this->connect($settings); $this->$cmd($args); } } // Execute controller command if (isset($_SERVER['argv']) && realpath($_SERVER['argv'][0]) == realpath(__FILE__)) { $ctl = new MySQL_Revisioning(); $ctl->execCmd(); }
jasny/mysql-revisioning
c2066107be68df7c0e7f471ce0de766f1a6e2f6d
Don't assume $info['autoinc'] is set. Fix #1
diff --git a/mysql-revisioning.php b/mysql-revisioning.php index 79feacc..84af51a 100644 --- a/mysql-revisioning.php +++ b/mysql-revisioning.php @@ -1,660 +1,660 @@ <?php /** * Class to generate revisioning tables and trigger for MySQL. */ class MySQL_Revisioning { /** * Database connection * @var mysqli */ protected $conn; /** * Dump SQL statements * @var boolean */ public $verbose = false; /** * SQL command to signal an error. * @var string */ protected $signal; /** * Connect to database * * @param mysqli|array $conn DB connection or connection settings */ public function connect($conn) { $this->conn = $conn instanceof mysqli ? $conn : new mysqli($conn['host'], $conn['user'], $conn['password'], $conn['db']); if (!isset($this->signal)) $this->signal = $this->conn->server_version >= 60000 ? 'SIGNAL %errno SET MESSAGE_TEXT="%errmsg"' : 'DO `%errmsg`'; } /** * Performs a query on the database * * @param string $statement * @return mysqli_result */ protected function query($statement) { if ($this->verbose) echo "\n", $statement, "\n"; $result = $this->conn->query($statement); if (!$result) throw new Exception("Query failed ({$this->conn->errno}): {$this->conn->error} "); return $result; } /** * Create a revision table based to original table. * * @param string $table * @param array $info Table information */ protected function createRevisionTable($table, $info) { $pk = '`' . join('`, `', $info['primarykey']) . '`'; - $change_autoinc = $info['autoinc'] ? "CHANGE `{$info['autoinc']}` `{$info['autoinc']}` {$info['fieldtypes'][$info['autoinc']]}," : null; + $change_autoinc = !empty($info['autoinc']) ? "CHANGE `{$info['autoinc']}` `{$info['autoinc']}` {$info['fieldtypes'][$info['autoinc']]}," : null; $unique_index = ""; foreach ($info['unique'] as $key=>$rows) $unique_index .= ", DROP INDEX `$key`, ADD INDEX `$key` ($rows)"; $sql = <<<SQL ALTER TABLE `_revision_$table` $change_autoinc DROP PRIMARY KEY, ADD `_revision` bigint unsigned AUTO_INCREMENT, ADD `_revision_previous` bigint unsigned NULL, ADD `_revision_action` enum('INSERT','UPDATE') default NULL, ADD `_revision_user_id` int(10) unsigned NULL, ADD `_revision_timestamp` datetime NULL default NULL, ADD `_revision_comment` text NULL, ADD PRIMARY KEY (`_revision`), ADD INDEX (`_revision_previous`), ADD INDEX `org_primary` ($pk) $unique_index SQL; $this->query("CREATE TABLE `_revision_$table` LIKE `$table`"); $this->query($sql); - $this->query("INSERT INTO `_revision_$table` SELECT *, NULL, NULL, 'INSERT', NULL, NOW(), 'Revisioning initialisation' FROM `$table`"); + $this->query("INSERT INTO `_revision_$table` SELECT *, NULL, NULL, 'INSERT', NULL, NOW(), 'Revisioning initialisation' FROM `$table`"); } /** * Create a revision table based to original table. * * @param string $table * @param array $info Table information */ protected function createRevisionChildTable($table, $info) { if (!empty($info['primarykey'])) $pk = '`' . join('`, `', $info['primarykey']) . '`'; $change_autoinc = !empty($info['autoinc']) ? "CHANGE `{$info['autoinc']}` `{$info['autoinc']}` {$info['fieldtypes'][$info['autoinc']]}," : null; $unique_index = ""; foreach ($info['unique'] as $key=>$rows) $unique_index .= "DROP INDEX `$key`, ADD INDEX `$key` ($rows),"; if (isset($pk)) $sql = <<<SQL ALTER TABLE `_revision_$table` $change_autoinc DROP PRIMARY KEY, ADD `_revision` bigint unsigned, ADD PRIMARY KEY (`_revision`, $pk), ADD INDEX `org_primary` ($pk), $unique_index COMMENT = "Child of `_revision_{$info['parent']}`" SQL; else $sql = <<<SQL ALTER TABLE `_revision_$table` ADD `_revision` bigint unsigned, ADD INDEX `_revision` (`_revision`), $unique_index COMMENT = "Child of `_revision_{$info['parent']}`" SQL; $this->query("CREATE TABLE `_revision_$table` LIKE `$table`"); $this->query($sql); - $this->query("INSERT INTO `_revision_$table` SELECT `t`.*, `p`.`_revision` FROM `$table` AS `t` INNER JOIN `{$info['parent']}` AS `p` ON `t`.`{$info['foreign_key']}`=`p`.`{$info['parent_key']}`"); + $this->query("INSERT INTO `_revision_$table` SELECT `t`.*, `p`.`_revision` FROM `$table` AS `t` INNER JOIN `{$info['parent']}` AS `p` ON `t`.`{$info['foreign_key']}`=`p`.`{$info['parent_key']}`"); } /** * Alter the existing table. * * @param string $table * @param array $info Table information */ protected function alterTable($table, $info) { foreach ($info['primarykey'] as $field) $pk_join[] = "`t`.`$field` = `r`.`$field`"; $pk_join = join(' AND ', $pk_join); $sql = <<<SQL ALTER TABLE `$table` ADD `_revision` bigint unsigned NULL, ADD `_revision_comment` text NULL, ADD UNIQUE INDEX (`_revision`) SQL; $this->query($sql); - $this->query("UPDATE `$table` AS `t` INNER JOIN `_revision_$table` AS `r` ON $pk_join SET `t`.`_revision` = `r`.`_revision`"); + $this->query("UPDATE `$table` AS `t` INNER JOIN `_revision_$table` AS `r` ON $pk_join SET `t`.`_revision` = `r`.`_revision`"); } /** * Alter the existing table. * * @param string $table * @param array $info Table information */ function createHistoryTable($table, $info) { $pk = '`' . join('`, `', $info['primarykey']) . '`'; foreach ($info['primarykey'] as $field) $pk_type[] = "`$field` {$info['fieldtypes'][$field]}"; $pk_type = join(',', $pk_type); $sql = <<<SQL CREATE TABLE `_revhistory_$table` ( $pk_type, `_revision` bigint unsigned NULL, `_revhistory_user_id` int(10) unsigned NULL, `_revhistory_timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP, INDEX ($pk), INDEX (_revision), INDEX (_revhistory_user_id), INDEX (_revhistory_timestamp) ) ENGINE=InnoDB SQL; $this->query($sql); $this->query("INSERT INTO `_revhistory_$table` SELECT $pk, `_revision`, NULL, `_revision_timestamp` FROM `_revision_$table`"); } /** * Create before insert trigger * * @param string $table * @param array $info Table information */ protected function beforeInsert($table, $info) { $fields = '`' . join('`, `', $info['fieldnames']) . '`'; $var_fields = '`var-' . join('`, `var-', $info['fieldnames']) . '`'; foreach ($info['fieldnames'] as $field) { $declare_var_fields[] = "DECLARE `var-$field` {$info['fieldtypes'][$field]}"; $new_to_var[] = "NEW.`$field` = `var-$field`"; } $declare_var_fields = join(";\n", $declare_var_fields); $new_to_var = join(', ', $new_to_var); $sql = <<<SQL CREATE TRIGGER `$table-beforeinsert` BEFORE INSERT ON `$table` FOR EACH ROW BEGIN $declare_var_fields; DECLARE `var-_revision` BIGINT UNSIGNED; DECLARE revisionCursor CURSOR FOR SELECT $fields FROM `_revision_$table` WHERE `_revision`=`var-_revision` LIMIT 1; IF NEW.`_revision` IS NULL THEN INSERT INTO `_revision_$table` (`_revision_comment`, `_revision_user_id`, `_revision_timestamp`) VALUES (NEW.`_revision_comment`, @auth_uid, NOW()); SET NEW.`_revision` = LAST_INSERT_ID(); ELSE SET `var-_revision`=NEW.`_revision`; OPEN revisionCursor; FETCH revisionCursor INTO $var_fields; CLOSE revisionCursor; SET $new_to_var; END IF; SET NEW.`_revision_comment` = NULL; END SQL; - $this->query("DROP TRIGGER IF EXISTS `$table-beforeinsert`"); + $this->query("DROP TRIGGER IF EXISTS `$table-beforeinsert`"); $this->query($sql); } /** * Create before insert trigger * * @param string $table * @param array $info Table information */ protected function beforeUpdate($table, $info) { $fields = '`' . join('`, `', $info['fieldnames']) . '`'; $var_fields = '`var-' . join('`, `var-', $info['fieldnames']) . '`'; foreach ($info['fieldnames'] as $field) { $declare_var_fields[] = "DECLARE `var-$field` {$info['fieldtypes'][$field]}"; $new_to_var[] = "NEW.`$field` = `var-$field`"; } $declare_var_fields = join(";\n", $declare_var_fields); $new_to_var = join(', ', $new_to_var); foreach ($info['primarykey'] as $field) $pk_new_ne_old[] = "(NEW.`$field` != OLD.`$field` OR NEW.`$field` IS NULL != OLD.`$field` IS NULL)"; $pk_new_ne_old = join(' OR ', $pk_new_ne_old); $signal_pk_new_ne_old = str_replace(array('%errno', '%errmsg'), array('23000', "Can't change the value of the primary key of table '$table' because of revisioning"), $this->signal); $sql = <<<SQL CREATE TRIGGER `$table-beforeupdate` BEFORE UPDATE ON `$table` FOR EACH ROW BEGIN $declare_var_fields; DECLARE `var-_revision` BIGINT UNSIGNED; DECLARE `var-_revision_action` enum('INSERT','UPDATE','DELETE'); DECLARE revisionCursor CURSOR FOR SELECT $fields, `_revision_action` FROM `_revision_$table` WHERE `_revision`=`var-_revision` LIMIT 1; IF NEW.`_revision` = OLD.`_revision` THEN SET NEW.`_revision` = NULL; ELSEIF NEW.`_revision` IS NOT NULL THEN SET `var-_revision` = NEW.`_revision`; OPEN revisionCursor; FETCH revisionCursor INTO $var_fields, `var-_revision_action`; CLOSE revisionCursor; IF `var-_revision_action` IS NOT NULL THEN SET $new_to_var; END IF; END IF; IF $pk_new_ne_old THEN $signal_pk_new_ne_old; END IF; IF NEW.`_revision` IS NULL THEN INSERT INTO `_revision_$table` (`_revision_previous`, `_revision_comment`, `_revision_user_id`, `_revision_timestamp`) VALUES (OLD.`_revision`, NEW.`_revision_comment`, @auth_uid, NOW()); SET NEW.`_revision` = LAST_INSERT_ID(); END IF; SET NEW.`_revision_comment` = NULL; END SQL; $this->query("DROP TRIGGER IF EXISTS `$table-beforeupdate`"); $this->query($sql); } /** * Create after insert trigger. * * @param string $table * @param array $info Table information * @param array $children Information of child tables */ protected function afterInsert($table, $info, $children) { $aftertrigger = empty($children) ? 'afterTriggerSingle' : 'afterTriggerParent'; $this->$aftertrigger('insert', $table, $info, $children); } /** * Create after update trigger. * * @param string $table * @param array $info Table information * @param array $children Information of child tables */ protected function afterUpdate($table, $info, $children) { $aftertrigger = empty($children) ? 'afterTriggerSingle' : 'afterTriggerParent'; $this->$aftertrigger('update', $table, $info, $children); } /** * Create after insert/update trigger for table without children. * * @param string $action INSERT or UPDATE * @param string $table * @param array $info Table information */ protected function afterTriggerSingle($action, $table, $info) { $pk = 'NEW.`' . join('`, NEW.`', $info['primarykey']) . '`'; foreach ($info['fieldnames'] as $field) $fields_is_new[] = "`$field` = NEW.`$field`"; $fields_is_new = join(', ', $fields_is_new); $sql = <<<SQL CREATE TRIGGER `$table-after$action` AFTER $action ON `$table` FOR EACH ROW BEGIN UPDATE `_revision_$table` SET $fields_is_new, `_revision_action`='$action' WHERE `_revision`=NEW.`_revision` AND `_revision_action` IS NULL; INSERT INTO `_revhistory_$table` VALUES ($pk, NEW.`_revision`, @auth_uid, NOW()); END SQL; $this->query("DROP TRIGGER IF EXISTS `$table-after$action`"); $this->query($sql); } /** * Create after insert/update trigger for table with children. * * @param string $action INSERT or UPDATE * @param string $table * @param array $info Table information * @param array $children Information of child tables */ protected function afterTriggerParent($action, $table, $info, $children=array()) { $pk = 'NEW.`' . join('`, NEW.`', $info['primarykey']) . '`'; foreach ($info['fieldnames'] as $field) $fields_is_new[] = "`$field` = NEW.`$field`"; $fields_is_new = join(', ', $fields_is_new); $child_newrev = ""; $child_switch = ""; foreach ($children as $child=>&$chinfo) { $child_fields = '`' . join('`, `', $chinfo['fieldnames']) . '`'; $child_newrev .= " INSERT INTO `_revision_$child` SELECT *, NEW.`_revision` FROM `$child` WHERE `{$chinfo['foreign_key']}` = NEW.`{$chinfo['parent_key']}`;"; if ($action == 'update') $child_switch .= " DELETE `t`.* FROM `$child` AS `t` LEFT JOIN `_revision_{$child}` AS `r` ON 0=1 WHERE `t`.`{$chinfo['foreign_key']}` = NEW.`{$chinfo['parent_key']}`;"; $child_switch .= " INSERT INTO `$child` SELECT $child_fields FROM `_revision_{$child}` WHERE `_revision` = NEW.`_revision`;"; } $sql = <<<SQL CREATE TRIGGER `$table-after$action` AFTER $action ON `$table` FOR EACH ROW BEGIN DECLARE `newrev` BOOLEAN; UPDATE `_revision_$table` SET $fields_is_new, `_revision_action`='$action' WHERE `_revision`=NEW.`_revision` AND `_revision_action` IS NULL; SET newrev = (ROW_COUNT() > 0); INSERT INTO `_revhistory_$table` VALUES ($pk, NEW.`_revision`, @auth_uid, NOW()); IF newrev THEN $child_newrev ELSE $child_switch END IF; END SQL; $this->query("DROP TRIGGER IF EXISTS `$table-after$action`"); $this->query($sql); } /** * Create after update trigger. * * @param string $table * @param array $info Table information */ protected function afterDelete($table, $info) { $pk = 'OLD.`' . join('`, OLD.`', $info['primarykey']) . '`'; $sql = <<<SQL CREATE TRIGGER `$table-afterdelete` AFTER DELETE ON `$table` FOR EACH ROW BEGIN INSERT INTO `_revhistory_$table` VALUES ($pk, NULL, @auth_uid, NOW()); END SQL; $this->query("DROP TRIGGER IF EXISTS `$table-afterdelete`"); $this->query($sql); } /** * Create after insert/update trigger. * * @param string $table * @param array $info Table information */ protected function afterInsertChild($table, $info) { $new = 'NEW.`' . join('`, NEW.`', $info['fieldnames']) . '`'; $fields = '`' . join('`, `', $info['fieldnames']) . '`'; $sql = <<<SQL CREATE TRIGGER `$table-afterinsert` AFTER INSERT ON `$table` FOR EACH ROW BEGIN DECLARE CONTINUE HANDLER FOR 1442 BEGIN END; INSERT IGNORE INTO `_revision_$table` ($fields, `_revision`) SELECT $new, `_revision` FROM `{$info['parent']}` AS `p` WHERE `p`.`{$info['parent_key']}`=NEW.`{$info['foreign_key']}`; END SQL; $this->query("DROP TRIGGER IF EXISTS `$table-afterinsert`"); $this->query($sql); } /** * Create after insert/update trigger. * * @param string $table * @param array $info Table information */ protected function afterUpdateChild($table, $info) { $new = 'NEW.`' . join('`, NEW.`', $info['fieldnames']) . '`'; $fields = '`' . join('`, `', $info['fieldnames']) . '`'; $delete = null; if (empty($info['primarykey'])) { foreach ($info['fieldnames'] as $field) $fields_is_old[] = "`$field` = OLD.`$field`"; $delete = "DELETE FROM `_revision_$table` WHERE `_revision` IN (SELECT `_revision` FROM `{$info['parent']}` WHERE `{$info['parent_key']}` = OLD.`{$info['foreign_key']}`) AND " . join(' AND ', $fields_is_old) . " LIMIT 1;"; } $sql = <<<SQL CREATE TRIGGER `$table-afterupdate` AFTER UPDATE ON `$table` FOR EACH ROW BEGIN $delete REPLACE INTO `_revision_$table` ($fields, `_revision`) SELECT $new, `_revision` FROM `{$info['parent']}` AS `p` WHERE `p`.`{$info['parent_key']}`=NEW.`{$info['foreign_key']}`; END SQL; $this->query("DROP TRIGGER IF EXISTS `$table-afterupdate`"); $this->query($sql); } /** * Create after update trigger. * * @param string $table * @param array $info Table information */ protected function afterDeleteChild($table, $info) { if (!empty($info['primarykey'])) { foreach ($info['primarykey'] as $field) $fields_is_old[] = "`r`.`$field` = OLD.`$field`"; $delete = "DELETE `r`.* FROM `_revision_$table` AS `r` INNER JOIN `{$info['parent']}` AS `p` ON `r`.`_revision` = `p`.`_revision` WHERE " . join(' AND ', $fields_is_old) . ";"; } else { foreach ($info['fieldnames'] as $field) $fields_is_old[] = "`$field` = OLD.`$field`"; $delete = "DELETE FROM `_revision_$table` WHERE `_revision` IN (SELECT `_revision` FROM `{$info['parent']}` WHERE `{$info['parent_key']}` = OLD.`{$info['foreign_key']}`) AND " . join(' AND ', $fields_is_old) . " LIMIT 1;"; } $sql = <<<SQL CREATE TRIGGER `$table-afterdelete` AFTER DELETE ON `$table` FOR EACH ROW BEGIN DECLARE CONTINUE HANDLER FOR 1442 BEGIN END; $delete END SQL; $this->query("DROP TRIGGER IF EXISTS `$table-afterdelete`"); $this->query($sql); } /** * Add revisioning * * @param array $args */ public function install($args) { foreach ($args as $arg) { if (is_string($arg)) { $matches = null; if (!preg_match_all('/[^,()\s]++/', $arg, $matches, PREG_PATTERN_ORDER)) continue; } else { $matches[0] = $arg; } $exists = false; $tables = array(); // Prepare foreach ($matches[0] as $i=>$table) { $info = array('parent'=>$i > 0 ? $matches[0][0] : null, 'unique'=>array()); $result = $this->query("DESCRIBE `$table`;"); while ($field = $result->fetch_assoc()) { if (preg_match('/^_revision/', $field['Field'])) { $exists = true; continue; } $info['fieldnames'][] = $field['Field']; if ($field['Key'] == 'PRI') $info['primarykey'][] = $field['Field']; if (preg_match('/\bauto_increment\b/i', $field['Extra'])) $info['autoinc'] = $field['Field']; $info['fieldtypes'][$field['Field']] = $field['Type']; } $result = $this->query("SELECT c.CONSTRAINT_NAME, GROUP_CONCAT(CONCAT('`', k.COLUMN_NAME, '`')) AS cols FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS `c` INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS `k` ON c.TABLE_SCHEMA=k.TABLE_SCHEMA AND c.TABLE_NAME=k.TABLE_NAME AND c.CONSTRAINT_NAME=k.CONSTRAINT_NAME WHERE c.TABLE_SCHEMA=DATABASE() AND c.TABLE_NAME='$table' AND c.CONSTRAINT_TYPE='UNIQUE' AND c.CONSTRAINT_NAME != '_revision' GROUP BY c.CONSTRAINT_NAME"); while ($key = $result->fetch_row()) $info['unique'][$key[0]] = $key[1]; if (empty($info['parent'])) { if (empty($info['primarykey'])) { trigger_error("Unable to add revisioning table '$table': Table does not have a primary key", E_USER_WARNING); continue 2; } } else { $result = $this->query("SELECT `COLUMN_NAME`, `REFERENCED_COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`KEY_COLUMN_USAGE` WHERE `TABLE_SCHEMA` = DATABASE() AND `TABLE_NAME` = '$table' AND REFERENCED_TABLE_SCHEMA = DATABASE() AND REFERENCED_TABLE_NAME = '{$info['parent']}' AND `REFERENCED_COLUMN_NAME` IS NOT NULL"); if ($result->num_rows == 0) { trigger_error("Unable to add revisioning table '$table' as child of '{$info['parent']}': Table does not have a foreign key reference to parent table", E_USER_WARNING); continue; } list($info['foreign_key'], $info['parent_key']) = $result->fetch_row(); } $tables[$table] = $info; } // Process reset($tables); $table = key($tables); $info = array_shift($tables); echo "Installing revisioning for `$table`"; // Parent if (!$exists) { echo " - tables"; $this->createRevisionTable($table, $info); $this->alterTable($table, $info); $this->createHistoryTable($table, $info); } echo " - triggers"; $this->beforeInsert($table, $info, $tables); $this->afterUpdate($table, $info, $tables); $this->beforeUpdate($table, $info, $tables); $this->afterInsert($table, $info, $tables); $this->afterDelete($table, $info, $tables); // Children foreach ($tables as $table=>&$info) { echo "\n - child `$table`"; if (!$exists) { echo " - tables"; $this->createRevisionChildTable($table, $info); } echo " - triggers"; $this->afterInsertChild($table, $info); $this->afterUpdateChild($table, $info); $this->afterDeleteChild($table, $info); } echo "\n"; } } /** * Remove revisioning for tables * * @param $args */ public function remove($args) { foreach ($args as $arg) { $matches = null; if (!preg_match_all('/[^,()\s]++/', $arg, $matches, PREG_PATTERN_ORDER)) return; // Prepare foreach ($matches[0] as $i=>$table) { echo "Removing revisioning for `$table`\n"; $this->query("DROP TRIGGER IF EXISTS `$table-afterdelete`;"); $this->query("DROP TRIGGER IF EXISTS `$table-afterupdate`;"); $this->query("DROP TRIGGER IF EXISTS `$table-beforeupdate`;"); $this->query("DROP TRIGGER IF EXISTS `$table-afterinsert`;"); $this->query("DROP TRIGGER IF EXISTS `$table-beforeinsert`;"); if ($i == 0) $this->query("DROP TABLE IF EXISTS `_revhistory_$table`;"); $this->query("DROP TABLE IF EXISTS `_revision_$table`;"); if ($i == 0) $this->query("ALTER TABLE `$table` DROP `_revision`, DROP `_revision_comment`"); } } } public function help() { echo <<<MESSAGE Usage: php {$_SERVER['argv'][0]} [OPTION]... [--install|--remove] TABLE... Options: --host=HOSTNAME MySQL hostname --user=USER MySQL username --password=PWD MySQL password --db=DATABASE MySQL database --signal=CMD SQL command to signal an error MESSAGE; } /** * Execute command line script */ public function execCmd() { $args = array(); $settings = array('host'=>'localhost', 'user'=>null, 'password'=>null, 'db'=>null); for ($i=1; $i < $_SERVER['argc']; $i++) { if (strncmp($_SERVER['argv'][$i], '--', 2) == 0) { list($key, $value) = split("=", substr($_SERVER['argv'][$i], 2), 2) + array(1=>null); if (property_exists($this, $key)) $this->$key = isset($value) ? $value : true; elseif (!isset($value)) $cmd = $key; else $settings[$key] = $value; } else { $args[] = $_SERVER['argv'][$i]; } } if (!isset($cmd)) $cmd = empty($args) ? 'help' : 'install'; $this->connect($settings); $this->$cmd($args); } } // Execute controller command if (isset($_SERVER['argv']) && realpath($_SERVER['argv'][0]) == realpath(__FILE__)) { $ctl = new MySQL_Revisioning(); $ctl->execCmd(); }
jasny/mysql-revisioning
900815a0128862b567dfe29c5bda9d59f58d9f71
Fixed script for publication Removed UUID (wouldn't work)
diff --git a/mysql-revisioning.php b/mysql-revisioning.php index 6af9a0e..79feacc 100644 --- a/mysql-revisioning.php +++ b/mysql-revisioning.php @@ -1,664 +1,660 @@ <?php /** * Class to generate revisioning tables and trigger for MySQL. - * - * If you're using replication, disable it before running this script. Copy the DB after - * and start replication from there. */ class MySQL_Revisioning { /** * Database connection * @var mysqli */ protected $conn; /** * Dump SQL statements * @var boolean */ public $verbose = false; /** * SQL command to signal an error. * @var string */ protected $signal; - /** - * SQL command to get revision id, UUID or UUID_SHORT. - * @var string - */ - protected $uuid; - /** * Connect to database * * @param mysqli|array $conn DB connection or connection settings */ public function connect($conn) { $this->conn = $conn instanceof mysqli ? $conn : new mysqli($conn['host'], $conn['user'], $conn['password'], $conn['db']); if (!isset($this->signal)) $this->signal = $this->conn->server_version >= 60000 ? 'SIGNAL %errno SET MESSAGE_TEXT="%errmsg"' : 'DO `%errmsg`'; - if (!isset($this->uuid)) $this->uuid = $this->conn->server_version >= 50120 ? 'UUID_SHORT' : 'UUID'; } /** * Performs a query on the database * * @param string $statement * @return mysqli_result */ protected function query($statement) { if ($this->verbose) echo "\n", $statement, "\n"; $result = $this->conn->query($statement); if (!$result) throw new Exception("Query failed ({$this->conn->errno}): {$this->conn->error} "); return $result; } /** * Create a revision table based to original table. * * @param string $table * @param array $info Table information */ protected function createRevisionTable($table, $info) { $pk = '`' . join('`, `', $info['primarykey']) . '`'; $change_autoinc = $info['autoinc'] ? "CHANGE `{$info['autoinc']}` `{$info['autoinc']}` {$info['fieldtypes'][$info['autoinc']]}," : null; - $rev_type = $this->uuid == 'UUID_SHORT' ? "bigint unsigned" : 'varchar(128)'; + + $unique_index = ""; + foreach ($info['unique'] as $key=>$rows) $unique_index .= ", DROP INDEX `$key`, ADD INDEX `$key` ($rows)"; $sql = <<<SQL ALTER TABLE `_revision_$table` $change_autoinc DROP PRIMARY KEY, - ADD `_revision` $rev_type, + ADD `_revision` bigint unsigned AUTO_INCREMENT, ADD `_revision_previous` bigint unsigned NULL, ADD `_revision_action` enum('INSERT','UPDATE') default NULL, ADD `_revision_user_id` int(10) unsigned NULL, ADD `_revision_timestamp` datetime NULL default NULL, ADD `_revision_comment` text NULL, ADD PRIMARY KEY (`_revision`), ADD INDEX (`_revision_previous`), ADD INDEX `org_primary` ($pk) + $unique_index SQL; $this->query("CREATE TABLE `_revision_$table` LIKE `$table`"); $this->query($sql); - $this->query("INSERT INTO `_revision_$table` SELECT *, {$this->uuid}(), NULL, 'INSERT', NULL, NOW(), 'Revisioning initialisation' FROM `$table`"); + $this->query("INSERT INTO `_revision_$table` SELECT *, NULL, NULL, 'INSERT', NULL, NOW(), 'Revisioning initialisation' FROM `$table`"); + } + + /** + * Create a revision table based to original table. + * + * @param string $table + * @param array $info Table information + */ + protected function createRevisionChildTable($table, $info) + { + if (!empty($info['primarykey'])) $pk = '`' . join('`, `', $info['primarykey']) . '`'; + $change_autoinc = !empty($info['autoinc']) ? "CHANGE `{$info['autoinc']}` `{$info['autoinc']}` {$info['fieldtypes'][$info['autoinc']]}," : null; + + $unique_index = ""; + foreach ($info['unique'] as $key=>$rows) $unique_index .= "DROP INDEX `$key`, ADD INDEX `$key` ($rows),"; + + if (isset($pk)) $sql = <<<SQL +ALTER TABLE `_revision_$table` + $change_autoinc + DROP PRIMARY KEY, + ADD `_revision` bigint unsigned, + ADD PRIMARY KEY (`_revision`, $pk), + ADD INDEX `org_primary` ($pk), + $unique_index + COMMENT = "Child of `_revision_{$info['parent']}`" +SQL; + else $sql = <<<SQL +ALTER TABLE `_revision_$table` + ADD `_revision` bigint unsigned, + ADD INDEX `_revision` (`_revision`), + $unique_index + COMMENT = "Child of `_revision_{$info['parent']}`" +SQL; + + $this->query("CREATE TABLE `_revision_$table` LIKE `$table`"); + $this->query($sql); + $this->query("INSERT INTO `_revision_$table` SELECT `t`.*, `p`.`_revision` FROM `$table` AS `t` INNER JOIN `{$info['parent']}` AS `p` ON `t`.`{$info['foreign_key']}`=`p`.`{$info['parent_key']}`"); } /** * Alter the existing table. * * @param string $table * @param array $info Table information */ protected function alterTable($table, $info) { foreach ($info['primarykey'] as $field) $pk_join[] = "`t`.`$field` = `r`.`$field`"; $pk_join = join(' AND ', $pk_join); - $rev_type = $this->uuid == 'UUID_SHORT' ? "bigint unsigned" : 'varchar(128)'; $sql = <<<SQL ALTER TABLE `$table` - ADD `_revision` $rev_type NULL, + ADD `_revision` bigint unsigned NULL, ADD `_revision_comment` text NULL, ADD UNIQUE INDEX (`_revision`) SQL; $this->query($sql); $this->query("UPDATE `$table` AS `t` INNER JOIN `_revision_$table` AS `r` ON $pk_join SET `t`.`_revision` = `r`.`_revision`"); } /** * Alter the existing table. * * @param string $table * @param array $info Table information */ function createHistoryTable($table, $info) { $pk = '`' . join('`, `', $info['primarykey']) . '`'; foreach ($info['primarykey'] as $field) $pk_type[] = "`$field` {$info['fieldtypes'][$field]}"; $pk_type = join(',', $pk_type); - $rev_type = $this->uuid == 'UUID_SHORT' ? "bigint unsigned" : 'varchar(128)'; $sql = <<<SQL CREATE TABLE `_revhistory_$table` ( $pk_type, - `_revision` $rev_type NULL, + `_revision` bigint unsigned NULL, `_revhistory_user_id` int(10) unsigned NULL, `_revhistory_timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP, INDEX ($pk), INDEX (_revision), INDEX (_revhistory_user_id), INDEX (_revhistory_timestamp) ) ENGINE=InnoDB SQL; $this->query($sql); $this->query("INSERT INTO `_revhistory_$table` SELECT $pk, `_revision`, NULL, `_revision_timestamp` FROM `_revision_$table`"); } /** * Create before insert trigger * * @param string $table * @param array $info Table information */ protected function beforeInsert($table, $info) { $fields = '`' . join('`, `', $info['fieldnames']) . '`'; $var_fields = '`var-' . join('`, `var-', $info['fieldnames']) . '`'; foreach ($info['fieldnames'] as $field) { $declare_var_fields[] = "DECLARE `var-$field` {$info['fieldtypes'][$field]}"; $new_to_var[] = "NEW.`$field` = `var-$field`"; } $declare_var_fields = join(";\n", $declare_var_fields); $new_to_var = join(', ', $new_to_var); $sql = <<<SQL CREATE TRIGGER `$table-beforeinsert` BEFORE INSERT ON `$table` FOR EACH ROW BEGIN $declare_var_fields; DECLARE `var-_revision` BIGINT UNSIGNED; DECLARE revisionCursor CURSOR FOR SELECT $fields FROM `_revision_$table` WHERE `_revision`=`var-_revision` LIMIT 1; IF NEW.`_revision` IS NULL THEN - SET NEW.`_revision` = {$this->uuid}(); - INSERT INTO `_revision_$table` (`_revision`, `_revision_comment`, `_revision_user_id`, `_revision_timestamp`) VALUES (NEW.`_revision`, NEW.`_revision_comment`, @auth_uid, NOW()); + INSERT INTO `_revision_$table` (`_revision_comment`, `_revision_user_id`, `_revision_timestamp`) VALUES (NEW.`_revision_comment`, @auth_uid, NOW()); + SET NEW.`_revision` = LAST_INSERT_ID(); ELSE SET `var-_revision`=NEW.`_revision`; OPEN revisionCursor; FETCH revisionCursor INTO $var_fields; CLOSE revisionCursor; SET $new_to_var; END IF; SET NEW.`_revision_comment` = NULL; END SQL; $this->query("DROP TRIGGER IF EXISTS `$table-beforeinsert`"); $this->query($sql); } /** * Create before insert trigger * * @param string $table * @param array $info Table information */ protected function beforeUpdate($table, $info) { $fields = '`' . join('`, `', $info['fieldnames']) . '`'; $var_fields = '`var-' . join('`, `var-', $info['fieldnames']) . '`'; foreach ($info['fieldnames'] as $field) { $declare_var_fields[] = "DECLARE `var-$field` {$info['fieldtypes'][$field]}"; $new_to_var[] = "NEW.`$field` = `var-$field`"; } $declare_var_fields = join(";\n", $declare_var_fields); $new_to_var = join(', ', $new_to_var); foreach ($info['primarykey'] as $field) $pk_new_ne_old[] = "(NEW.`$field` != OLD.`$field` OR NEW.`$field` IS NULL != OLD.`$field` IS NULL)"; $pk_new_ne_old = join(' OR ', $pk_new_ne_old); $signal_pk_new_ne_old = str_replace(array('%errno', '%errmsg'), array('23000', "Can't change the value of the primary key of table '$table' because of revisioning"), $this->signal); $sql = <<<SQL CREATE TRIGGER `$table-beforeupdate` BEFORE UPDATE ON `$table` FOR EACH ROW BEGIN $declare_var_fields; DECLARE `var-_revision` BIGINT UNSIGNED; DECLARE `var-_revision_action` enum('INSERT','UPDATE','DELETE'); DECLARE revisionCursor CURSOR FOR SELECT $fields, `_revision_action` FROM `_revision_$table` WHERE `_revision`=`var-_revision` LIMIT 1; IF NEW.`_revision` = OLD.`_revision` THEN SET NEW.`_revision` = NULL; ELSEIF NEW.`_revision` IS NOT NULL THEN SET `var-_revision` = NEW.`_revision`; OPEN revisionCursor; FETCH revisionCursor INTO $var_fields, `var-_revision_action`; CLOSE revisionCursor; IF `var-_revision_action` IS NOT NULL THEN SET $new_to_var; END IF; END IF; IF $pk_new_ne_old THEN $signal_pk_new_ne_old; END IF; IF NEW.`_revision` IS NULL THEN - SET NEW.`_revision` = UUID_SHORT(); - INSERT INTO `_revision_$table` (`_revision`, `_revision_previous`, `_revision_comment`, `_revision_user_id`, `_revision_timestamp`) VALUES (NEW.`_revision`, OLD.`_revision`, NEW.`_revision_comment`, @auth_uid, NOW()); + INSERT INTO `_revision_$table` (`_revision_previous`, `_revision_comment`, `_revision_user_id`, `_revision_timestamp`) VALUES (OLD.`_revision`, NEW.`_revision_comment`, @auth_uid, NOW()); + SET NEW.`_revision` = LAST_INSERT_ID(); END IF; SET NEW.`_revision_comment` = NULL; END SQL; $this->query("DROP TRIGGER IF EXISTS `$table-beforeupdate`"); $this->query($sql); } /** * Create after insert trigger. * * @param string $table * @param array $info Table information * @param array $children Information of child tables */ protected function afterInsert($table, $info, $children) { $aftertrigger = empty($children) ? 'afterTriggerSingle' : 'afterTriggerParent'; $this->$aftertrigger('insert', $table, $info, $children); } /** * Create after update trigger. * * @param string $table * @param array $info Table information * @param array $children Information of child tables */ protected function afterUpdate($table, $info, $children) { $aftertrigger = empty($children) ? 'afterTriggerSingle' : 'afterTriggerParent'; $this->$aftertrigger('update', $table, $info, $children); } /** * Create after insert/update trigger for table without children. * * @param string $action INSERT or UPDATE * @param string $table * @param array $info Table information */ protected function afterTriggerSingle($action, $table, $info) { $pk = 'NEW.`' . join('`, NEW.`', $info['primarykey']) . '`'; foreach ($info['fieldnames'] as $field) $fields_is_new[] = "`$field` = NEW.`$field`"; $fields_is_new = join(', ', $fields_is_new); $sql = <<<SQL CREATE TRIGGER `$table-after$action` AFTER $action ON `$table` FOR EACH ROW BEGIN UPDATE `_revision_$table` SET $fields_is_new, `_revision_action`='$action' WHERE `_revision`=NEW.`_revision` AND `_revision_action` IS NULL; INSERT INTO `_revhistory_$table` VALUES ($pk, NEW.`_revision`, @auth_uid, NOW()); END SQL; $this->query("DROP TRIGGER IF EXISTS `$table-after$action`"); $this->query($sql); } /** * Create after insert/update trigger for table with children. * * @param string $action INSERT or UPDATE * @param string $table * @param array $info Table information * @param array $children Information of child tables */ protected function afterTriggerParent($action, $table, $info, $children=array()) { $pk = 'NEW.`' . join('`, NEW.`', $info['primarykey']) . '`'; foreach ($info['fieldnames'] as $field) $fields_is_new[] = "`$field` = NEW.`$field`"; $fields_is_new = join(', ', $fields_is_new); $child_newrev = ""; $child_switch = ""; foreach ($children as $child=>&$chinfo) { $child_fields = '`' . join('`, `', $chinfo['fieldnames']) . '`'; $child_newrev .= " INSERT INTO `_revision_$child` SELECT *, NEW.`_revision` FROM `$child` WHERE `{$chinfo['foreign_key']}` = NEW.`{$chinfo['parent_key']}`;"; if ($action == 'update') $child_switch .= " DELETE `t`.* FROM `$child` AS `t` LEFT JOIN `_revision_{$child}` AS `r` ON 0=1 WHERE `t`.`{$chinfo['foreign_key']}` = NEW.`{$chinfo['parent_key']}`;"; $child_switch .= " INSERT INTO `$child` SELECT $child_fields FROM `_revision_{$child}` WHERE `_revision` = NEW.`_revision`;"; } $sql = <<<SQL CREATE TRIGGER `$table-after$action` AFTER $action ON `$table` FOR EACH ROW BEGIN DECLARE `newrev` BOOLEAN; UPDATE `_revision_$table` SET $fields_is_new, `_revision_action`='$action' WHERE `_revision`=NEW.`_revision` AND `_revision_action` IS NULL; SET newrev = (ROW_COUNT() > 0); INSERT INTO `_revhistory_$table` VALUES ($pk, NEW.`_revision`, @auth_uid, NOW()); IF newrev THEN $child_newrev ELSE $child_switch END IF; END SQL; $this->query("DROP TRIGGER IF EXISTS `$table-after$action`"); $this->query($sql); } /** * Create after update trigger. * * @param string $table * @param array $info Table information */ protected function afterDelete($table, $info) { $pk = 'OLD.`' . join('`, OLD.`', $info['primarykey']) . '`'; $sql = <<<SQL CREATE TRIGGER `$table-afterdelete` AFTER DELETE ON `$table` FOR EACH ROW BEGIN INSERT INTO `_revhistory_$table` VALUES ($pk, NULL, @auth_uid, NOW()); END SQL; $this->query("DROP TRIGGER IF EXISTS `$table-afterdelete`"); $this->query($sql); } - /** - * Create a revision table based to original table. - * - * @param string $table - * @param array $info Table information - */ - protected function createRevisionChildTable($table, $info) - { - if (!empty($info['primarykey'])) $pk = '`' . join('`, `', $info['primarykey']) . '`'; - $change_autoinc = !empty($info['autoinc']) ? "CHANGE `{$info['autoinc']}` `{$info['autoinc']}` {$info['fieldtypes'][$info['autoinc']]}," : null; - $rev_type = $this->uuid == 'UUID_SHORT' ? "bigint unsigned" : 'varchar(128)'; - - if (isset($pk)) $sql = <<<SQL -ALTER TABLE `_revision_$table` - $change_autoinc - DROP PRIMARY KEY, - ADD `_revision` $rev_type, - ADD PRIMARY KEY (`_revision`, $pk), - ADD INDEX `org_primary` ($pk), - COMMENT = "Child of `_revision_{$info['parent']}`" -SQL; - else $sql = <<<SQL -ALTER TABLE `_revision_$table` - $change_autoinc - ADD `_revision` $rev_type, - ADD INDEX `_revision` (`_revision`), - COMMENT = "Child of `_revision_{$info['parent']}`" -SQL; - - $this->query("CREATE TABLE `_revision_$table` LIKE `$table`"); - $this->query($sql); - $this->query("INSERT INTO `_revision_$table` SELECT `t`.*, `p`.`_revision` FROM `$table` AS `t` INNER JOIN `{$info['parent']}` AS `p` ON `t`.`{$info['foreign_key']}`=`p`.`{$info['parent_key']}`"); - } - /** * Create after insert/update trigger. * * @param string $table * @param array $info Table information */ protected function afterInsertChild($table, $info) { $new = 'NEW.`' . join('`, NEW.`', $info['fieldnames']) . '`'; $fields = '`' . join('`, `', $info['fieldnames']) . '`'; $sql = <<<SQL CREATE TRIGGER `$table-afterinsert` AFTER INSERT ON `$table` FOR EACH ROW BEGIN DECLARE CONTINUE HANDLER FOR 1442 BEGIN END; INSERT IGNORE INTO `_revision_$table` ($fields, `_revision`) SELECT $new, `_revision` FROM `{$info['parent']}` AS `p` WHERE `p`.`{$info['parent_key']}`=NEW.`{$info['foreign_key']}`; END SQL; $this->query("DROP TRIGGER IF EXISTS `$table-afterinsert`"); $this->query($sql); } /** * Create after insert/update trigger. * * @param string $table * @param array $info Table information */ protected function afterUpdateChild($table, $info) { $new = 'NEW.`' . join('`, NEW.`', $info['fieldnames']) . '`'; $fields = '`' . join('`, `', $info['fieldnames']) . '`'; $delete = null; if (empty($info['primarykey'])) { foreach ($info['fieldnames'] as $field) $fields_is_old[] = "`$field` = OLD.`$field`"; $delete = "DELETE FROM `_revision_$table` WHERE `_revision` IN (SELECT `_revision` FROM `{$info['parent']}` WHERE `{$info['parent_key']}` = OLD.`{$info['foreign_key']}`) AND " . join(' AND ', $fields_is_old) . " LIMIT 1;"; } $sql = <<<SQL CREATE TRIGGER `$table-afterupdate` AFTER UPDATE ON `$table` FOR EACH ROW BEGIN $delete REPLACE INTO `_revision_$table` ($fields, `_revision`) SELECT $new, `_revision` FROM `{$info['parent']}` AS `p` WHERE `p`.`{$info['parent_key']}`=NEW.`{$info['foreign_key']}`; END SQL; $this->query("DROP TRIGGER IF EXISTS `$table-afterupdate`"); $this->query($sql); } /** * Create after update trigger. * * @param string $table * @param array $info Table information */ protected function afterDeleteChild($table, $info) { if (!empty($info['primarykey'])) { foreach ($info['primarykey'] as $field) $fields_is_old[] = "`r`.`$field` = OLD.`$field`"; - $delete = "DELETE `r`.* FROM `_revision_$table` AS `r` INNER JOIN `{$info['parent']}` AS `p` ON `r`.`{$info['parent_key']}` = `p`.`{$info['foreign_key']}` WHERE " . join(' AND ', $fields_is_old) . ";"; + $delete = "DELETE `r`.* FROM `_revision_$table` AS `r` INNER JOIN `{$info['parent']}` AS `p` ON `r`.`_revision` = `p`.`_revision` WHERE " . join(' AND ', $fields_is_old) . ";"; } else { foreach ($info['fieldnames'] as $field) $fields_is_old[] = "`$field` = OLD.`$field`"; - $delete = "DELETE FROM `_revision_$table` WHERE `_revision` IN (SELECT `_revision` FROM `{$info['parent']}` WHERE `{$info['parent_key']}` = OLD.`{$info['foreign_key']}`) AND " . join(' AND ', $fields_is_old) . ";"; + $delete = "DELETE FROM `_revision_$table` WHERE `_revision` IN (SELECT `_revision` FROM `{$info['parent']}` WHERE `{$info['parent_key']}` = OLD.`{$info['foreign_key']}`) AND " . join(' AND ', $fields_is_old) . " LIMIT 1;"; } $sql = <<<SQL CREATE TRIGGER `$table-afterdelete` AFTER DELETE ON `$table` FOR EACH ROW BEGIN DECLARE CONTINUE HANDLER FOR 1442 BEGIN END; $delete END SQL; $this->query("DROP TRIGGER IF EXISTS `$table-afterdelete`"); $this->query($sql); } /** * Add revisioning * * @param array $args */ public function install($args) { foreach ($args as $arg) { if (is_string($arg)) { $matches = null; if (!preg_match_all('/[^,()\s]++/', $arg, $matches, PREG_PATTERN_ORDER)) continue; } else { $matches[0] = $arg; } $exists = false; $tables = array(); // Prepare foreach ($matches[0] as $i=>$table) { - $info = array('parent'=>$i > 0 ? $matches[0][0] : null); + $info = array('parent'=>$i > 0 ? $matches[0][0] : null, 'unique'=>array()); $result = $this->query("DESCRIBE `$table`;"); while ($field = $result->fetch_assoc()) { if (preg_match('/^_revision/', $field['Field'])) { $exists = true; continue; } $info['fieldnames'][] = $field['Field']; if ($field['Key'] == 'PRI') $info['primarykey'][] = $field['Field']; if (preg_match('/\bauto_increment\b/i', $field['Extra'])) $info['autoinc'] = $field['Field']; $info['fieldtypes'][$field['Field']] = $field['Type']; } + $result = $this->query("SELECT c.CONSTRAINT_NAME, GROUP_CONCAT(CONCAT('`', k.COLUMN_NAME, '`')) AS cols FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS `c` INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS `k` ON c.TABLE_SCHEMA=k.TABLE_SCHEMA AND c.TABLE_NAME=k.TABLE_NAME AND c.CONSTRAINT_NAME=k.CONSTRAINT_NAME WHERE c.TABLE_SCHEMA=DATABASE() AND c.TABLE_NAME='$table' AND c.CONSTRAINT_TYPE='UNIQUE' AND c.CONSTRAINT_NAME != '_revision' GROUP BY c.CONSTRAINT_NAME"); + while ($key = $result->fetch_row()) $info['unique'][$key[0]] = $key[1]; + if (empty($info['parent'])) { if (empty($info['primarykey'])) { trigger_error("Unable to add revisioning table '$table': Table does not have a primary key", E_USER_WARNING); continue 2; } } else { $result = $this->query("SELECT `COLUMN_NAME`, `REFERENCED_COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`KEY_COLUMN_USAGE` WHERE `TABLE_SCHEMA` = DATABASE() AND `TABLE_NAME` = '$table' AND REFERENCED_TABLE_SCHEMA = DATABASE() AND REFERENCED_TABLE_NAME = '{$info['parent']}' AND `REFERENCED_COLUMN_NAME` IS NOT NULL"); if ($result->num_rows == 0) { trigger_error("Unable to add revisioning table '$table' as child of '{$info['parent']}': Table does not have a foreign key reference to parent table", E_USER_WARNING); continue; } list($info['foreign_key'], $info['parent_key']) = $result->fetch_row(); } $tables[$table] = $info; } // Process reset($tables); $table = key($tables); $info = array_shift($tables); echo "Installing revisioning for `$table`"; // Parent if (!$exists) { echo " - tables"; $this->createRevisionTable($table, $info); $this->alterTable($table, $info); $this->createHistoryTable($table, $info); } echo " - triggers"; $this->beforeInsert($table, $info, $tables); $this->afterUpdate($table, $info, $tables); $this->beforeUpdate($table, $info, $tables); $this->afterInsert($table, $info, $tables); $this->afterDelete($table, $info, $tables); // Children foreach ($tables as $table=>&$info) { echo "\n - child `$table`"; if (!$exists) { echo " - tables"; $this->createRevisionChildTable($table, $info); } echo " - triggers"; $this->afterInsertChild($table, $info); $this->afterUpdateChild($table, $info); $this->afterDeleteChild($table, $info); } echo "\n"; } } /** * Remove revisioning for tables * * @param $args */ public function remove($args) { foreach ($args as $arg) { $matches = null; if (!preg_match_all('/[^,()\s]++/', $arg, $matches, PREG_PATTERN_ORDER)) return; // Prepare foreach ($matches[0] as $i=>$table) { echo "Removing revisioning for `$table`\n"; $this->query("DROP TRIGGER IF EXISTS `$table-afterdelete`;"); $this->query("DROP TRIGGER IF EXISTS `$table-afterupdate`;"); $this->query("DROP TRIGGER IF EXISTS `$table-beforeupdate`;"); $this->query("DROP TRIGGER IF EXISTS `$table-afterinsert`;"); $this->query("DROP TRIGGER IF EXISTS `$table-beforeinsert`;"); if ($i == 0) $this->query("DROP TABLE IF EXISTS `_revhistory_$table`;"); $this->query("DROP TABLE IF EXISTS `_revision_$table`;"); if ($i == 0) $this->query("ALTER TABLE `$table` DROP `_revision`, DROP `_revision_comment`"); } } } public function help() { echo <<<MESSAGE Usage: php {$_SERVER['argv'][0]} [OPTION]... [--install|--remove] TABLE... Options: --host=HOSTNAME MySQL hostname --user=USER MySQL username --password=PWD MySQL password --db=DATABASE MySQL database --signal=CMD SQL command to signal an error - --uuid=CMD SQL command to get revision id; UUID or UUID_SHORT MESSAGE; } /** * Execute command line script */ public function execCmd() { $args = array(); $settings = array('host'=>'localhost', 'user'=>null, 'password'=>null, 'db'=>null); for ($i=1; $i < $_SERVER['argc']; $i++) { if (strncmp($_SERVER['argv'][$i], '--', 2) == 0) { list($key, $value) = split("=", substr($_SERVER['argv'][$i], 2), 2) + array(1=>null); if (property_exists($this, $key)) $this->$key = isset($value) ? $value : true; elseif (!isset($value)) $cmd = $key; else $settings[$key] = $value; } else { $args[] = $_SERVER['argv'][$i]; } } if (!isset($cmd)) $cmd = empty($args) ? 'help' : 'install'; $this->connect($settings); $this->$cmd($args); } } // Execute controller command if (isset($_SERVER['argv']) && realpath($_SERVER['argv'][0]) == realpath(__FILE__)) { $ctl = new MySQL_Revisioning(); $ctl->execCmd(); }
jasny/mysql-revisioning
0b6b82c58ccc308acf3778c6ff633b1e2bd4342e
Added script
diff --git a/mysql-revisioning.php b/mysql-revisioning.php new file mode 100644 index 0000000..6af9a0e --- /dev/null +++ b/mysql-revisioning.php @@ -0,0 +1,664 @@ +<?php + +/** + * Class to generate revisioning tables and trigger for MySQL. + * + * If you're using replication, disable it before running this script. Copy the DB after + * and start replication from there. + */ +class MySQL_Revisioning +{ + /** + * Database connection + * @var mysqli + */ + protected $conn; + + /** + * Dump SQL statements + * @var boolean + */ + public $verbose = false; + + /** + * SQL command to signal an error. + * @var string + */ + protected $signal; + + /** + * SQL command to get revision id, UUID or UUID_SHORT. + * @var string + */ + protected $uuid; + + + /** + * Connect to database + * + * @param mysqli|array $conn DB connection or connection settings + */ + public function connect($conn) + { + $this->conn = $conn instanceof mysqli ? $conn : new mysqli($conn['host'], $conn['user'], $conn['password'], $conn['db']); + if (!isset($this->signal)) $this->signal = $this->conn->server_version >= 60000 ? 'SIGNAL %errno SET MESSAGE_TEXT="%errmsg"' : 'DO `%errmsg`'; + if (!isset($this->uuid)) $this->uuid = $this->conn->server_version >= 50120 ? 'UUID_SHORT' : 'UUID'; + } + + /** + * Performs a query on the database + * + * @param string $statement + * @return mysqli_result + */ + protected function query($statement) + { + if ($this->verbose) echo "\n", $statement, "\n"; + + $result = $this->conn->query($statement); + if (!$result) throw new Exception("Query failed ({$this->conn->errno}): {$this->conn->error} "); + + return $result; + } + + /** + * Create a revision table based to original table. + * + * @param string $table + * @param array $info Table information + */ + protected function createRevisionTable($table, $info) + { + $pk = '`' . join('`, `', $info['primarykey']) . '`'; + $change_autoinc = $info['autoinc'] ? "CHANGE `{$info['autoinc']}` `{$info['autoinc']}` {$info['fieldtypes'][$info['autoinc']]}," : null; + $rev_type = $this->uuid == 'UUID_SHORT' ? "bigint unsigned" : 'varchar(128)'; + + $sql = <<<SQL +ALTER TABLE `_revision_$table` + $change_autoinc + DROP PRIMARY KEY, + ADD `_revision` $rev_type, + ADD `_revision_previous` bigint unsigned NULL, + ADD `_revision_action` enum('INSERT','UPDATE') default NULL, + ADD `_revision_user_id` int(10) unsigned NULL, + ADD `_revision_timestamp` datetime NULL default NULL, + ADD `_revision_comment` text NULL, + ADD PRIMARY KEY (`_revision`), + ADD INDEX (`_revision_previous`), + ADD INDEX `org_primary` ($pk) +SQL; + + $this->query("CREATE TABLE `_revision_$table` LIKE `$table`"); + $this->query($sql); + $this->query("INSERT INTO `_revision_$table` SELECT *, {$this->uuid}(), NULL, 'INSERT', NULL, NOW(), 'Revisioning initialisation' FROM `$table`"); + } + + /** + * Alter the existing table. + * + * @param string $table + * @param array $info Table information + */ + protected function alterTable($table, $info) + { + foreach ($info['primarykey'] as $field) $pk_join[] = "`t`.`$field` = `r`.`$field`"; + $pk_join = join(' AND ', $pk_join); + $rev_type = $this->uuid == 'UUID_SHORT' ? "bigint unsigned" : 'varchar(128)'; + + $sql = <<<SQL +ALTER TABLE `$table` + ADD `_revision` $rev_type NULL, + ADD `_revision_comment` text NULL, + ADD UNIQUE INDEX (`_revision`) +SQL; + + $this->query($sql); + $this->query("UPDATE `$table` AS `t` INNER JOIN `_revision_$table` AS `r` ON $pk_join SET `t`.`_revision` = `r`.`_revision`"); + } + + /** + * Alter the existing table. + * + * @param string $table + * @param array $info Table information + */ + function createHistoryTable($table, $info) + { + $pk = '`' . join('`, `', $info['primarykey']) . '`'; + foreach ($info['primarykey'] as $field) $pk_type[] = "`$field` {$info['fieldtypes'][$field]}"; + $pk_type = join(',', $pk_type); + $rev_type = $this->uuid == 'UUID_SHORT' ? "bigint unsigned" : 'varchar(128)'; + + $sql = <<<SQL +CREATE TABLE `_revhistory_$table` ( + $pk_type, + `_revision` $rev_type NULL, + `_revhistory_user_id` int(10) unsigned NULL, + `_revhistory_timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP, + INDEX ($pk), + INDEX (_revision), + INDEX (_revhistory_user_id), + INDEX (_revhistory_timestamp) +) ENGINE=InnoDB +SQL; + + $this->query($sql); + $this->query("INSERT INTO `_revhistory_$table` SELECT $pk, `_revision`, NULL, `_revision_timestamp` FROM `_revision_$table`"); + } + + + /** + * Create before insert trigger + * + * @param string $table + * @param array $info Table information + */ + protected function beforeInsert($table, $info) + { + $fields = '`' . join('`, `', $info['fieldnames']) . '`'; + $var_fields = '`var-' . join('`, `var-', $info['fieldnames']) . '`'; + + foreach ($info['fieldnames'] as $field) { + $declare_var_fields[] = "DECLARE `var-$field` {$info['fieldtypes'][$field]}"; + $new_to_var[] = "NEW.`$field` = `var-$field`"; + } + $declare_var_fields = join(";\n", $declare_var_fields); + $new_to_var = join(', ', $new_to_var); + + $sql = <<<SQL +CREATE TRIGGER `$table-beforeinsert` BEFORE INSERT ON `$table` + FOR EACH ROW BEGIN + $declare_var_fields; + DECLARE `var-_revision` BIGINT UNSIGNED; + DECLARE revisionCursor CURSOR FOR SELECT $fields FROM `_revision_$table` WHERE `_revision`=`var-_revision` LIMIT 1; + + IF NEW.`_revision` IS NULL THEN + SET NEW.`_revision` = {$this->uuid}(); + INSERT INTO `_revision_$table` (`_revision`, `_revision_comment`, `_revision_user_id`, `_revision_timestamp`) VALUES (NEW.`_revision`, NEW.`_revision_comment`, @auth_uid, NOW()); + ELSE + SET `var-_revision`=NEW.`_revision`; + OPEN revisionCursor; + FETCH revisionCursor INTO $var_fields; + CLOSE revisionCursor; + + SET $new_to_var; + END IF; + + SET NEW.`_revision_comment` = NULL; + END +SQL; + + $this->query("DROP TRIGGER IF EXISTS `$table-beforeinsert`"); + $this->query($sql); + } + + /** + * Create before insert trigger + * + * @param string $table + * @param array $info Table information + */ + protected function beforeUpdate($table, $info) + { + $fields = '`' . join('`, `', $info['fieldnames']) . '`'; + $var_fields = '`var-' . join('`, `var-', $info['fieldnames']) . '`'; + + foreach ($info['fieldnames'] as $field) { + $declare_var_fields[] = "DECLARE `var-$field` {$info['fieldtypes'][$field]}"; + $new_to_var[] = "NEW.`$field` = `var-$field`"; + } + $declare_var_fields = join(";\n", $declare_var_fields); + $new_to_var = join(', ', $new_to_var); + + foreach ($info['primarykey'] as $field) $pk_new_ne_old[] = "(NEW.`$field` != OLD.`$field` OR NEW.`$field` IS NULL != OLD.`$field` IS NULL)"; + $pk_new_ne_old = join(' OR ', $pk_new_ne_old); + $signal_pk_new_ne_old = str_replace(array('%errno', '%errmsg'), array('23000', "Can't change the value of the primary key of table '$table' because of revisioning"), $this->signal); + + $sql = <<<SQL +CREATE TRIGGER `$table-beforeupdate` BEFORE UPDATE ON `$table` + FOR EACH ROW BEGIN + $declare_var_fields; + DECLARE `var-_revision` BIGINT UNSIGNED; + DECLARE `var-_revision_action` enum('INSERT','UPDATE','DELETE'); + DECLARE revisionCursor CURSOR FOR SELECT $fields, `_revision_action` FROM `_revision_$table` WHERE `_revision`=`var-_revision` LIMIT 1; + + IF NEW.`_revision` = OLD.`_revision` THEN + SET NEW.`_revision` = NULL; + + ELSEIF NEW.`_revision` IS NOT NULL THEN + SET `var-_revision` = NEW.`_revision`; + + OPEN revisionCursor; + FETCH revisionCursor INTO $var_fields, `var-_revision_action`; + CLOSE revisionCursor; + + IF `var-_revision_action` IS NOT NULL THEN + SET $new_to_var; + END IF; + END IF; + + IF $pk_new_ne_old THEN + $signal_pk_new_ne_old; + END IF; + + IF NEW.`_revision` IS NULL THEN + SET NEW.`_revision` = UUID_SHORT(); + INSERT INTO `_revision_$table` (`_revision`, `_revision_previous`, `_revision_comment`, `_revision_user_id`, `_revision_timestamp`) VALUES (NEW.`_revision`, OLD.`_revision`, NEW.`_revision_comment`, @auth_uid, NOW()); + END IF; + + SET NEW.`_revision_comment` = NULL; + END +SQL; + + $this->query("DROP TRIGGER IF EXISTS `$table-beforeupdate`"); + $this->query($sql); + } + + + /** + * Create after insert trigger. + * + * @param string $table + * @param array $info Table information + * @param array $children Information of child tables + */ + protected function afterInsert($table, $info, $children) + { + $aftertrigger = empty($children) ? 'afterTriggerSingle' : 'afterTriggerParent'; + $this->$aftertrigger('insert', $table, $info, $children); + } + + /** + * Create after update trigger. + * + * @param string $table + * @param array $info Table information + * @param array $children Information of child tables + */ + protected function afterUpdate($table, $info, $children) + { + $aftertrigger = empty($children) ? 'afterTriggerSingle' : 'afterTriggerParent'; + $this->$aftertrigger('update', $table, $info, $children); + } + + /** + * Create after insert/update trigger for table without children. + * + * @param string $action INSERT or UPDATE + * @param string $table + * @param array $info Table information + */ + protected function afterTriggerSingle($action, $table, $info) + { + $pk = 'NEW.`' . join('`, NEW.`', $info['primarykey']) . '`'; + foreach ($info['fieldnames'] as $field) $fields_is_new[] = "`$field` = NEW.`$field`"; + $fields_is_new = join(', ', $fields_is_new); + + $sql = <<<SQL +CREATE TRIGGER `$table-after$action` AFTER $action ON `$table` + FOR EACH ROW BEGIN + UPDATE `_revision_$table` SET $fields_is_new, `_revision_action`='$action' WHERE `_revision`=NEW.`_revision` AND `_revision_action` IS NULL; + INSERT INTO `_revhistory_$table` VALUES ($pk, NEW.`_revision`, @auth_uid, NOW()); + END +SQL; + + $this->query("DROP TRIGGER IF EXISTS `$table-after$action`"); + $this->query($sql); + } + + /** + * Create after insert/update trigger for table with children. + * + * @param string $action INSERT or UPDATE + * @param string $table + * @param array $info Table information + * @param array $children Information of child tables + */ + protected function afterTriggerParent($action, $table, $info, $children=array()) + { + $pk = 'NEW.`' . join('`, NEW.`', $info['primarykey']) . '`'; + foreach ($info['fieldnames'] as $field) $fields_is_new[] = "`$field` = NEW.`$field`"; + $fields_is_new = join(', ', $fields_is_new); + + $child_newrev = ""; + $child_switch = ""; + foreach ($children as $child=>&$chinfo) { + $child_fields = '`' . join('`, `', $chinfo['fieldnames']) . '`'; + + $child_newrev .= " INSERT INTO `_revision_$child` SELECT *, NEW.`_revision` FROM `$child` WHERE `{$chinfo['foreign_key']}` = NEW.`{$chinfo['parent_key']}`;"; + if ($action == 'update') $child_switch .= " DELETE `t`.* FROM `$child` AS `t` LEFT JOIN `_revision_{$child}` AS `r` ON 0=1 WHERE `t`.`{$chinfo['foreign_key']}` = NEW.`{$chinfo['parent_key']}`;"; + $child_switch .= " INSERT INTO `$child` SELECT $child_fields FROM `_revision_{$child}` WHERE `_revision` = NEW.`_revision`;"; + } + + $sql = <<<SQL +CREATE TRIGGER `$table-after$action` AFTER $action ON `$table` + FOR EACH ROW BEGIN + DECLARE `newrev` BOOLEAN; + + UPDATE `_revision_$table` SET $fields_is_new, `_revision_action`='$action' WHERE `_revision`=NEW.`_revision` AND `_revision_action` IS NULL; + SET newrev = (ROW_COUNT() > 0); + INSERT INTO `_revhistory_$table` VALUES ($pk, NEW.`_revision`, @auth_uid, NOW()); + + IF newrev THEN + $child_newrev + ELSE + $child_switch + END IF; + END +SQL; + + $this->query("DROP TRIGGER IF EXISTS `$table-after$action`"); + $this->query($sql); + } + + /** + * Create after update trigger. + * + * @param string $table + * @param array $info Table information + */ + protected function afterDelete($table, $info) + { + $pk = 'OLD.`' . join('`, OLD.`', $info['primarykey']) . '`'; + + $sql = <<<SQL +CREATE TRIGGER `$table-afterdelete` AFTER DELETE ON `$table` + FOR EACH ROW BEGIN + INSERT INTO `_revhistory_$table` VALUES ($pk, NULL, @auth_uid, NOW()); + END +SQL; + + $this->query("DROP TRIGGER IF EXISTS `$table-afterdelete`"); + $this->query($sql); + } + + + /** + * Create a revision table based to original table. + * + * @param string $table + * @param array $info Table information + */ + protected function createRevisionChildTable($table, $info) + { + if (!empty($info['primarykey'])) $pk = '`' . join('`, `', $info['primarykey']) . '`'; + $change_autoinc = !empty($info['autoinc']) ? "CHANGE `{$info['autoinc']}` `{$info['autoinc']}` {$info['fieldtypes'][$info['autoinc']]}," : null; + $rev_type = $this->uuid == 'UUID_SHORT' ? "bigint unsigned" : 'varchar(128)'; + + if (isset($pk)) $sql = <<<SQL +ALTER TABLE `_revision_$table` + $change_autoinc + DROP PRIMARY KEY, + ADD `_revision` $rev_type, + ADD PRIMARY KEY (`_revision`, $pk), + ADD INDEX `org_primary` ($pk), + COMMENT = "Child of `_revision_{$info['parent']}`" +SQL; + else $sql = <<<SQL +ALTER TABLE `_revision_$table` + $change_autoinc + ADD `_revision` $rev_type, + ADD INDEX `_revision` (`_revision`), + COMMENT = "Child of `_revision_{$info['parent']}`" +SQL; + + $this->query("CREATE TABLE `_revision_$table` LIKE `$table`"); + $this->query($sql); + $this->query("INSERT INTO `_revision_$table` SELECT `t`.*, `p`.`_revision` FROM `$table` AS `t` INNER JOIN `{$info['parent']}` AS `p` ON `t`.`{$info['foreign_key']}`=`p`.`{$info['parent_key']}`"); + } + + /** + * Create after insert/update trigger. + * + * @param string $table + * @param array $info Table information + */ + protected function afterInsertChild($table, $info) + { + $new = 'NEW.`' . join('`, NEW.`', $info['fieldnames']) . '`'; + $fields = '`' . join('`, `', $info['fieldnames']) . '`'; + + $sql = <<<SQL +CREATE TRIGGER `$table-afterinsert` AFTER INSERT ON `$table` + FOR EACH ROW BEGIN + DECLARE CONTINUE HANDLER FOR 1442 BEGIN END; + INSERT IGNORE INTO `_revision_$table` ($fields, `_revision`) SELECT $new, `_revision` FROM `{$info['parent']}` AS `p` WHERE `p`.`{$info['parent_key']}`=NEW.`{$info['foreign_key']}`; + END +SQL; + + $this->query("DROP TRIGGER IF EXISTS `$table-afterinsert`"); + $this->query($sql); + } + + /** + * Create after insert/update trigger. + * + * @param string $table + * @param array $info Table information + */ + protected function afterUpdateChild($table, $info) + { + $new = 'NEW.`' . join('`, NEW.`', $info['fieldnames']) . '`'; + $fields = '`' . join('`, `', $info['fieldnames']) . '`'; + $delete = null; + + if (empty($info['primarykey'])) { + foreach ($info['fieldnames'] as $field) $fields_is_old[] = "`$field` = OLD.`$field`"; + $delete = "DELETE FROM `_revision_$table` WHERE `_revision` IN (SELECT `_revision` FROM `{$info['parent']}` WHERE `{$info['parent_key']}` = OLD.`{$info['foreign_key']}`) AND " . join(' AND ', $fields_is_old) . " LIMIT 1;"; + } + + $sql = <<<SQL +CREATE TRIGGER `$table-afterupdate` AFTER UPDATE ON `$table` + FOR EACH ROW BEGIN + $delete + REPLACE INTO `_revision_$table` ($fields, `_revision`) SELECT $new, `_revision` FROM `{$info['parent']}` AS `p` WHERE `p`.`{$info['parent_key']}`=NEW.`{$info['foreign_key']}`; + END +SQL; + + $this->query("DROP TRIGGER IF EXISTS `$table-afterupdate`"); + $this->query($sql); + } + + /** + * Create after update trigger. + * + * @param string $table + * @param array $info Table information + */ + protected function afterDeleteChild($table, $info) + { + if (!empty($info['primarykey'])) { + foreach ($info['primarykey'] as $field) $fields_is_old[] = "`r`.`$field` = OLD.`$field`"; + $delete = "DELETE `r`.* FROM `_revision_$table` AS `r` INNER JOIN `{$info['parent']}` AS `p` ON `r`.`{$info['parent_key']}` = `p`.`{$info['foreign_key']}` WHERE " . join(' AND ', $fields_is_old) . ";"; + + } else { + foreach ($info['fieldnames'] as $field) $fields_is_old[] = "`$field` = OLD.`$field`"; + $delete = "DELETE FROM `_revision_$table` WHERE `_revision` IN (SELECT `_revision` FROM `{$info['parent']}` WHERE `{$info['parent_key']}` = OLD.`{$info['foreign_key']}`) AND " . join(' AND ', $fields_is_old) . ";"; + } + + $sql = <<<SQL +CREATE TRIGGER `$table-afterdelete` AFTER DELETE ON `$table` + FOR EACH ROW BEGIN + DECLARE CONTINUE HANDLER FOR 1442 BEGIN END; + $delete + END +SQL; + + $this->query("DROP TRIGGER IF EXISTS `$table-afterdelete`"); + $this->query($sql); + } + + + /** + * Add revisioning + * + * @param array $args + */ + public function install($args) + { + foreach ($args as $arg) { + if (is_string($arg)) { + $matches = null; + if (!preg_match_all('/[^,()\s]++/', $arg, $matches, PREG_PATTERN_ORDER)) continue; + } else { + $matches[0] = $arg; + } + + $exists = false; + $tables = array(); + + // Prepare + foreach ($matches[0] as $i=>$table) { + $info = array('parent'=>$i > 0 ? $matches[0][0] : null); + $result = $this->query("DESCRIBE `$table`;"); + + while ($field = $result->fetch_assoc()) { + if (preg_match('/^_revision/', $field['Field'])) { + $exists = true; + continue; + } + + $info['fieldnames'][] = $field['Field']; + if ($field['Key'] == 'PRI') $info['primarykey'][] = $field['Field']; + if (preg_match('/\bauto_increment\b/i', $field['Extra'])) $info['autoinc'] = $field['Field']; + $info['fieldtypes'][$field['Field']] = $field['Type']; + } + + if (empty($info['parent'])) { + if (empty($info['primarykey'])) { + trigger_error("Unable to add revisioning table '$table': Table does not have a primary key", E_USER_WARNING); + continue 2; + } + } else { + $result = $this->query("SELECT `COLUMN_NAME`, `REFERENCED_COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`KEY_COLUMN_USAGE` WHERE `TABLE_SCHEMA` = DATABASE() AND `TABLE_NAME` = '$table' AND REFERENCED_TABLE_SCHEMA = DATABASE() AND REFERENCED_TABLE_NAME = '{$info['parent']}' AND `REFERENCED_COLUMN_NAME` IS NOT NULL"); + if ($result->num_rows == 0) { + trigger_error("Unable to add revisioning table '$table' as child of '{$info['parent']}': Table does not have a foreign key reference to parent table", E_USER_WARNING); + continue; + } + list($info['foreign_key'], $info['parent_key']) = $result->fetch_row(); + } + + $tables[$table] = $info; + } + + // Process + reset($tables); + $table = key($tables); + $info = array_shift($tables); + + echo "Installing revisioning for `$table`"; + + // Parent + if (!$exists) { + echo " - tables"; + $this->createRevisionTable($table, $info); + $this->alterTable($table, $info); + $this->createHistoryTable($table, $info); + } + + echo " - triggers"; + $this->beforeInsert($table, $info, $tables); + $this->afterUpdate($table, $info, $tables); + + $this->beforeUpdate($table, $info, $tables); + $this->afterInsert($table, $info, $tables); + + $this->afterDelete($table, $info, $tables); + + // Children + foreach ($tables as $table=>&$info) { + echo "\n - child `$table`"; + + if (!$exists) { + echo " - tables"; + $this->createRevisionChildTable($table, $info); + } + + echo " - triggers"; + $this->afterInsertChild($table, $info); + $this->afterUpdateChild($table, $info); + $this->afterDeleteChild($table, $info); + } + + echo "\n"; + } + } + + /** + * Remove revisioning for tables + * + * @param $args + */ + public function remove($args) + { + foreach ($args as $arg) { + $matches = null; + if (!preg_match_all('/[^,()\s]++/', $arg, $matches, PREG_PATTERN_ORDER)) return; + + // Prepare + foreach ($matches[0] as $i=>$table) { + echo "Removing revisioning for `$table`\n"; + + $this->query("DROP TRIGGER IF EXISTS `$table-afterdelete`;"); + $this->query("DROP TRIGGER IF EXISTS `$table-afterupdate`;"); + $this->query("DROP TRIGGER IF EXISTS `$table-beforeupdate`;"); + $this->query("DROP TRIGGER IF EXISTS `$table-afterinsert`;"); + $this->query("DROP TRIGGER IF EXISTS `$table-beforeinsert`;"); + + if ($i == 0) $this->query("DROP TABLE IF EXISTS `_revhistory_$table`;"); + $this->query("DROP TABLE IF EXISTS `_revision_$table`;"); + if ($i == 0) $this->query("ALTER TABLE `$table` DROP `_revision`, DROP `_revision_comment`"); + } + } + } + + public function help() + { + echo <<<MESSAGE +Usage: php {$_SERVER['argv'][0]} [OPTION]... [--install|--remove] TABLE... + +Options: + --host=HOSTNAME MySQL hostname + --user=USER MySQL username + --password=PWD MySQL password + --db=DATABASE MySQL database + + --signal=CMD SQL command to signal an error + --uuid=CMD SQL command to get revision id; UUID or UUID_SHORT + +MESSAGE; + } + + + /** + * Execute command line script + */ + public function execCmd() + { + $args = array(); + $settings = array('host'=>'localhost', 'user'=>null, 'password'=>null, 'db'=>null); + + for ($i=1; $i < $_SERVER['argc']; $i++) { + if (strncmp($_SERVER['argv'][$i], '--', 2) == 0) { + list($key, $value) = split("=", substr($_SERVER['argv'][$i], 2), 2) + array(1=>null); + + if (property_exists($this, $key)) $this->$key = isset($value) ? $value : true; + elseif (!isset($value)) $cmd = $key; + else $settings[$key] = $value; + } else { + $args[] = $_SERVER['argv'][$i]; + } + } + + if (!isset($cmd)) $cmd = empty($args) ? 'help' : 'install'; + + $this->connect($settings); + $this->$cmd($args); + } +} + +// Execute controller command +if (isset($_SERVER['argv']) && realpath($_SERVER['argv'][0]) == realpath(__FILE__)) { + $ctl = new MySQL_Revisioning(); + $ctl->execCmd(); +}
pgorla-zz/markov
15e6cd50aa3f1329a12b5f2bb2cc723616d34e2b
tokenization of some form
diff --git a/markov.py b/markov.py index c1e7acc..dab0290 100755 --- a/markov.py +++ b/markov.py @@ -1,88 +1,101 @@ #!/usr/bin/env python import string import random class Markov(object): """ Markov-chain text generator. Translated from the original PHP into Python (haykranen.nl) + Currently working on a generator of poetry. """ def __init__(self,text='alice.txt',length=600): fil = text fin = open('text/'+fil) self.text = '' - forbid = '\\' + forbid = string.punctuation for line in fin: self.text += line.translate(None,forbid).strip().lower() self.text_list = self.generate_markov_list(self.text) self.markov_table = self.generate_markov_table(self.text_list) self.length = length def _run(self): - return self.generate_markov_text(self.length,self.markov_table) + return self.generate_poetry(self.length, self.markov_table) def generate_markov_list(self, text): return text.split() def generate_markov_table(self,text_list): self.table = {} # walk through text, make index table for i in range(len(self.text_list)-1): - char = text_list[i] - if char not in self.table: - self.table[char] = {} + char = Token(text_list[i]) + if char.token_value not in self.table: + self.table[char.token_value] = {} # walk array again, count numbers - for i in range(len(self.text_list)-1): + for i in range(len(text_list)-1): - char_index = self.text_list[i] - char_count = self.text_list[i+1] + char_index = Token(text_list[i]) + char_count = Token(text_list[i+1]) - if char_count not in self.table[char_index].keys(): - self.table[char_index][char_count] = 1 + if char_count.token_value not in self.table[char_index.token_value].keys(): + self.table[char_index.token_value][char_count.token_value] = 1 else: - self.table[char_index][char_count] += 1 + self.table[char_index.token_value][char_count.token_value] += 1 return self.table - def generate_endings_list(self,text_list): - pass + def generate_poetry(self,length,table): + o = list() + for i in range(4): + o.append(self.generate_markov_text(length, table)) + return '\n'.join(o) + def generate_markov_text(self, length, table): o = list() # get first character word = random.choice(table.keys()) o.append(word) for i in range(length): newword = self.return_weighted_char(table[word]) if newword: word = newword o.append(newword) else: word = random.choice(table.keys()) return ' '.join(o) def return_weighted_char(self,array): if not array: return False else: total = sum(array.values()) rand = random.randint(1,total) for key,value in array.iteritems(): if rand <= value: return key rand -= value +class Token(object): + def __init__(self,token): + self.token_ending = token[:-2] + self.token_value = token + + if __name__ == '__main__': import sys if sys.argv[1]: text = sys.argv[1] - t = Markov(text) + if sys.argv[2]: + length = int(sys.argv[2]) + t = Markov(text,length) print t._run() diff --git a/pymarkov.py b/pymarkov.py deleted file mode 100755 index 72797b6..0000000 --- a/pymarkov.py +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/env python - -import sys -import random -import string - -class Markov(object): - - """ - Markov-chain text generator. Translated - from the original PHP into Python (haykranen.nl) - """ - - def __init__(self,text='alice.txt',length=600): - fil = text - fin = open('text/'+fil) - self.text = '' - forbid = '\\' - for line in fin: - self.text += line.translate(None,forbid).strip() - self.markov_table = self.generate_markov_table(self.text, 3) - self.length = length - - - def _run(self): - - return self.generate_markov_text(self.length,self.markov_table,3) - - - def generate_markov_table(self, text, look_forward): - self.table = {} - - # walk through text, make index table - for i in range(len(self.text)): - char = self.text[i:i+look_forward] - if char not in self.table: - self.table[char] = {} - - # walk array again, count numbers - for i in range(len(self.text) - look_forward): - char_index = self.text[i:i+look_forward] - char_count = self.text[i+look_forward:i+look_forward+look_forward] - - if char_count not in self.table[char_index].keys(): - self.table[char_index][char_count] = 1 - else: - self.table[char_index][char_count] += 1 - - return self.table - - - def generate_markov_text(self, length, table, look_forward): - # get first character - char = random.choice(table.keys()) - o = char - for i in range(length/look_forward): - newchar = self.return_weighted_char(table[char]) - if newchar: - char = newchar - o += newchar - else: - char = random.choice(table.keys()) - return o - - - def return_weighted_char(self,array): - if not array: - return False - else: - total = sum(array.values()) - rand = random.randint(1,total) - for k,v in array.iteritems(): - if rand <= v: - return k - rand -= v - - - - - -if __name__ == '__main__': - t = Markov() - print t._run()
pgorla-zz/markov
bded6deb5dddbd566952cbac9b5833a872a172c0
now iterating by word
diff --git a/markov.py b/markov.py index b84a19d..c1e7acc 100755 --- a/markov.py +++ b/markov.py @@ -1,82 +1,88 @@ #!/usr/bin/env python import string import random class Markov(object): """ Markov-chain text generator. Translated from the original PHP into Python (haykranen.nl) """ def __init__(self,text='alice.txt',length=600): fil = text fin = open('text/'+fil) self.text = '' forbid = '\\' for line in fin: - self.text += line.translate(None,forbid).strip() - self.markov_table = self.generate_markov_table(self.text, 3) + self.text += line.translate(None,forbid).strip().lower() + self.text_list = self.generate_markov_list(self.text) + self.markov_table = self.generate_markov_table(self.text_list) self.length = length def _run(self): + return self.generate_markov_text(self.length,self.markov_table) - return self.generate_markov_text(self.length,self.markov_table,3) + def generate_markov_list(self, text): + return text.split() - - def generate_markov_table(self, text, look_forward): + def generate_markov_table(self,text_list): self.table = {} # walk through text, make index table - for i in range(len(self.text)): - char = self.text[i:i+look_forward] + for i in range(len(self.text_list)-1): + char = text_list[i] if char not in self.table: self.table[char] = {} # walk array again, count numbers - for i in range(len(self.text) - look_forward): - char_index = self.text[i:i+look_forward] - char_count = self.text[i+look_forward:i+look_forward+look_forward] + for i in range(len(self.text_list)-1): + + char_index = self.text_list[i] + char_count = self.text_list[i+1] if char_count not in self.table[char_index].keys(): self.table[char_index][char_count] = 1 else: self.table[char_index][char_count] += 1 return self.table + def generate_endings_list(self,text_list): + pass - def generate_markov_text(self, length, table, look_forward): + def generate_markov_text(self, length, table): + o = list() # get first character - char = random.choice(table.keys()) - o = char - for i in range(length/look_forward): - newchar = self.return_weighted_char(table[char]) - if newchar: - char = newchar - o += newchar + word = random.choice(table.keys()) + o.append(word) + for i in range(length): + newword = self.return_weighted_char(table[word]) + if newword: + word = newword + o.append(newword) else: - char = random.choice(table.keys()) - return o + word = random.choice(table.keys()) + return ' '.join(o) def return_weighted_char(self,array): if not array: return False else: total = sum(array.values()) rand = random.randint(1,total) - for k,v in array.iteritems(): - if rand <= v: - return k - rand -= v + for key,value in array.iteritems(): + if rand <= value: + return key + rand -= value if __name__ == '__main__': import sys if sys.argv[1]: text = sys.argv[1] t = Markov(text) print t._run()
pgorla-zz/markov
c4938f8c6abdbd4b7c8284fa035ec966e507f562
administrative changes, more text files
diff --git a/markov.py b/markov.py index 1bfdfd7..b84a19d 100755 --- a/markov.py +++ b/markov.py @@ -1,80 +1,82 @@ #!/usr/bin/env python -import sys -import random import string +import random class Markov(object): """ Markov-chain text generator. Translated from the original PHP into Python (haykranen.nl) """ def __init__(self,text='alice.txt',length=600): fil = text fin = open('text/'+fil) self.text = '' forbid = '\\' for line in fin: self.text += line.translate(None,forbid).strip() self.markov_table = self.generate_markov_table(self.text, 3) self.length = length def _run(self): return self.generate_markov_text(self.length,self.markov_table,3) def generate_markov_table(self, text, look_forward): self.table = {} # walk through text, make index table for i in range(len(self.text)): char = self.text[i:i+look_forward] if char not in self.table: self.table[char] = {} # walk array again, count numbers for i in range(len(self.text) - look_forward): char_index = self.text[i:i+look_forward] char_count = self.text[i+look_forward:i+look_forward+look_forward] if char_count not in self.table[char_index].keys(): self.table[char_index][char_count] = 1 else: self.table[char_index][char_count] += 1 return self.table def generate_markov_text(self, length, table, look_forward): # get first character char = random.choice(table.keys()) o = char for i in range(length/look_forward): newchar = self.return_weighted_char(table[char]) if newchar: char = newchar o += newchar else: char = random.choice(table.keys()) return o def return_weighted_char(self,array): if not array: return False else: total = sum(array.values()) rand = random.randint(1,total) for k,v in array.iteritems(): if rand <= v: return k rand -= v if __name__ == '__main__': - t = Markov() + import sys + if sys.argv[1]: + text = sys.argv[1] + t = Markov(text) print t._run() diff --git a/text/inkjet b/text/inkjet new file mode 100644 index 0000000..fd2cd3e --- /dev/null +++ b/text/inkjet @@ -0,0 +1,4 @@ +An Inkjet printer is a printer for computers. It uses special ink to print on the paper. Another type of printing techology is the Laser printer. + +Usually, inkjet printers are used by people who print very little. The ink comes in special ink cartridges, which can be very expensive and uneconomical. Also, the ink in the cartridge may dry up. This means that a new cartridge is needed. + diff --git a/text/keats b/text/keats new file mode 100644 index 0000000..cf1d2c1 --- /dev/null +++ b/text/keats @@ -0,0 +1,1972 @@ +Glory and loveliness have passed away; + For if we wander out in early morn, + No wreathed incense do we see upborne +Into the east, to meet the smiling day: +No crowd of nymphs soft voic'd and young, and gay, + In woven baskets bringing ears of corn, + Roses, and pinks, and violets, to adorn +The shrine of Flora in her early May. +But there are left delights as high as these, + And I shall ever bless my destiny, +That in a time, when under pleasant trees + Pan is no longer sought, I feel a free +A leafy luxury, seeing I could please + With these poor offerings, a man like thee. + + + +I stood tip-toe upon a little hill, +The air was cooling, and so very still. +That the sweet buds which with a modest pride +Pull droopingly, in slanting curve aside, +Their scantly leaved, and finely tapering stems, +Had not yet lost those starry diadems +Caught from the early sobbing of the morn. +The clouds were pure and white as flocks new shorn, +And fresh from the clear brook; sweetly they slept +On the blue fields of heaven, and then there crept +A little noiseless noise among the leaves, +Born of the very sigh that silence heaves: +For not the faintest motion could be seen +Of all the shades that slanted o'er the green. +There was wide wand'ring for the greediest eye, +To peer about upon variety; +Far round the horizon's crystal air to skim, +And trace the dwindled edgings of its brim; +To picture out the quaint, and curious bending +Of a fresh woodland alley, never ending; +Or by the bowery clefts, and leafy shelves, +Guess were the jaunty streams refresh themselves. +I gazed awhile, and felt as light, and free +As though the fanning wings of Mercury +Had played upon my heels: I was light-hearted, +And many pleasures to my vision started; +So I straightway began to pluck a posey +Of luxuries bright, milky, soft and rosy. + +A bush of May flowers with the bees about them; +Ah, sure no tasteful nook would be without them; +And let a lush laburnum oversweep them, +And let long grass grow round the roots to keep them +Moist, cool and green; and shade the violets, +That they may bind the moss in leafy nets. + +A filbert hedge with wild briar overtwined, +And clumps of woodbine taking the soft wind +Upon their summer thrones; there too should be +The frequent chequer of a youngling tree, +That with a score of light green brethen shoots +From the quaint mossiness of aged roots: +Round which is heard a spring-head of clear waters +Babbling so wildly of its lovely daughters +The spreading blue bells: it may haply mourn +That such fair clusters should be rudely torn +From their fresh beds, and scattered thoughtlessly +By infant hands, left on the path to die. + +Open afresh your round of starry folds, +Ye ardent marigolds! +Dry up the moisture from your golden lids, +For great Apollo bids +That in these days your praises should be sung +On many harps, which he has lately strung; +And when again your dewiness he kisses, +Tell him, I have you in my world of blisses: +So haply when I rove in some far vale, +His mighty voice may come upon the gale. + +Here are sweet peas, on tip-toe for a flight: +With wings of gentle flush o'er delicate white, +And taper fulgent catching at all things, +To bind them all about with tiny rings. + +Linger awhile upon some bending planks +That lean against a streamlet's rushy banks, +And watch intently Nature's gentle doings: +They will be found softer than ring-dove's cooings. +How silent comes the water round that bend; +Not the minutest whisper does it send +To the o'erhanging sallows: blades of grass +Slowly across the chequer'd shadows pass. +Why, you might read two sonnets, ere they reach +To where the hurrying freshnesses aye preach +A natural sermon o'er their pebbly beds; +Where swarms of minnows show their little heads, +Staying their wavy bodies 'gainst the streams, +To taste the luxury of sunny beams +Temper'd with coolness. How they ever wrestle +With their own sweet delight, and ever nestle +Their silver bellies on the pebbly sand. +If you but scantily hold out the hand, +That very instant not one will remain; +But turn your eye, and they are there again. +The ripples seem right glad to reach those cresses, +And cool themselves among the em'rald tresses; +The while they cool themselves, they freshness give, +And moisture, that the bowery green may live: +So keeping up an interchange of favours, +Like good men in the truth of their behaviours +Sometimes goldfinches one by one will drop +From low hung branches; little space they stop; +But sip, and twitter, and their feathers sleek; +Then off at once, as in a wanton freak: +Or perhaps, to show their black, and golden wings, +Pausing upon their yellow flutterings. +Were I in such a place, I sure should pray +That nought less sweet, might call my thoughts away, +Than the soft rustle of a maiden's gown +Fanning away the dandelion's down; +Than the light music of her nimble toes +Patting against the sorrel as she goes. +How she would start, and blush, thus to be caught +Playing in all her innocence of thought. +O let me lead her gently o'er the brook, +Watch her half-smiling lips, and downward look; +O let me for one moment touch her wrist; +Let me one moment to her breathing list; +And as she leaves me may she often turn +Her fair eyes looking through her locks auburne. +What next? A tuft of evening primroses, +O'er which the mind may hover till it dozes; +O'er which it well might take a pleasant sleep, +But that 'tis ever startled by the leap +Of buds into ripe flowers; or by the flitting +Of diverse moths, that aye their rest are quitting; +Or by the moon lifting her silver rim +Above a cloud, and with a gradual swim +Coming into the blue with all her light. +O Maker of sweet poets, dear delight +Of this fair world, and all its gentle livers; +Spangler of clouds, halo of crystal rivers, +Mingler with leaves, and dew and tumbling streams, +Closer of lovely eyes to lovely dreams, +Lover of loneliness, and wandering, +Of upcast eye, and tender pondering! +Thee must I praise above all other glories +That smile us on to tell delightful stories. +For what has made the sage or poet write +But the fair paradise of Nature's light? +In the calm grandeur of a sober line, +We see the waving of the mountain pine; +And when a tale is beautifully staid, +We feel the safety of a hawthorn glade: +When it is moving on luxurious wings, +The soul is lost in pleasant smotherings: +Fair dewy roses brush against our faces, +And flowering laurels spring from diamond vases; +O'er head we see the jasmine and sweet briar, +And bloomy grapes laughing from green attire; +While at our feet, the voice of crystal bubbles +Charms us at once away from all our troubles: +So that we feel uplifted from the world, +Walking upon the white clouds wreath'd and curl'd. +So felt he, who first told, how Psyche went +On the smooth wind to realms of wonderment; +What Psyche felt, and Love, when their full lips +First touch'd; what amorous, and fondling nips +They gave each other's cheeks; with all their sighs, +And how they kist each other's tremulous eyes: +The silver lamp,--the ravishment,--the wonder-- +The darkness,--loneliness,--the fearful thunder; +Their woes gone by, and both to heaven upflown, +To bow for gratitude before Jove's throne. +So did he feel, who pull'd the boughs aside, +That we might look into a forest wide, +To catch a glimpse of Fawns, and Dryades +Coming with softest rustle through the trees; +And garlands woven of flowers wild, and sweet, +Upheld on ivory wrists, or sporting feet: +Telling us how fair, trembling Syrinx fled +Arcadian Pan, with such a fearful dread. +Poor nymph,--poor Pan,--how he did weep to find, +Nought but a lovely sighing of the wind +Along the reedy stream; a half heard strain, +Full of sweet desolation--balmy pain. + +What first inspired a bard of old to sing +Narcissus pining o'er the untainted spring? +In some delicious ramble, he had found +A little space, with boughs all woven round; +And in the midst of all, a clearer pool +Than e'er reflected in its pleasant cool, +The blue sky here, and there, serenely peeping +Through tendril wreaths fantastically creeping. +And on the bank a lonely flower he spied, +A meek and forlorn flower, with naught of pride, +Drooping its beauty o'er the watery clearness, +To woo its own sad image into nearness: +Deaf to light Zephyrus it would not move; +But still would seem to droop, to pine, to love. +So while the Poet stood in this sweet spot, +Some fainter gleamings o'er his fancy shot; +Nor was it long ere he had told the tale +Of young Narcissus, and sad Echo's bale. + +Where had he been, from whose warm head out-flew +That sweetest of all songs, that ever new, +That aye refreshing, pure deliciousness, +Coming ever to bless +The wanderer by moonlight? to him bringing +Shapes from the invisible world, unearthly singing +From out the middle air, from flowery nests, +And from the pillowy silkiness that rests +Full in the speculation of the stars. +Ah! surely he had burst our mortal bars; +Into some wond'rous region he had gone, +To search for thee, divine Endymion! + +He was a Poet, sure a lover too, +Who stood on Latmus' top, what time there blew +Soft breezes from the myrtle vale below; +And brought in faintness solemn, sweet, and slow +A hymn from Dian's temple; while upswelling, +The incense went to her own starry dwelling. +But though her face was clear as infant's eyes, +Though she stood smiling o'er the sacrifice, +The Poet wept at her so piteous fate, +Wept that such beauty should be desolate: +So in fine wrath some golden sounds he won, +And gave meek Cynthia her Endymion. + +Queen of the wide air; thou most lovely queen +Of all the brightness that mine eyes have seen! +As thou exceedest all things in thy shine, +So every tale, does this sweet tale of thine. +O for three words of honey, that I might +Tell but one wonder of thy bridal night! + +Where distant ships do seem to show their keels, +Phoebus awhile delayed his mighty wheels, +And turned to smile upon thy bashful eyes, +Ere he his unseen pomp would solemnize. +The evening weather was so bright, and clear, +That men of health were of unusual cheer; +Stepping like Homer at the trumpet's call, +Or young Apollo on the pedestal: +And lovely women were as fair and warm, +As Venus looking sideways in alarm. +The breezes were ethereal, and pure, +And crept through half closed lattices to cure +The languid sick; it cool'd their fever'd sleep, +And soothed them into slumbers full and deep. +Soon they awoke clear eyed: nor burnt with thirsting, +Nor with hot fingers, nor with temples bursting: +And springing up, they met the wond'ring sight +Of their dear friends, nigh foolish with delight; +Who feel their arms, and breasts, and kiss and stare, +And on their placid foreheads part the hair. +Young men, and maidens at each other gaz'd +With hands held back, and motionless, amaz'd +To see the brightness in each others' eyes; +And so they stood, fill'd with a sweet surprise, +Until their tongues were loos'd in poesy. +Therefore no lover did of anguish die: +But the soft numbers, in that moment spoken, +Made silken ties, that never may be broken. +Cynthia! I cannot tell the greater blisses, +That follow'd thine, and thy dear shepherd's kisses: +Was there a Poet born?--but now no more, +My wand'ring spirit must no further soar.-- + + + + + +Lo! I must tell a tale of chivalry; +For large white plumes are dancing in mine eye. +Not like the formal crest of latter days: +But bending in a thousand graceful ways; +So graceful, that it seems no mortal hand, +Or e'en the touch of Archimago's wand, +Could charm them into such an attitude. +We must think rather, that in playful mood, +Some mountain breeze had turned its chief delight, +To show this wonder of its gentle might. +Lo! I must tell a tale of chivalry; +For while I muse, the lance points slantingly +Athwart the morning air: some lady sweet, +Who cannot feel for cold her tender feet, +From the worn top of some old battlement +Hails it with tears, her stout defender sent: +And from her own pure self no joy dissembling, +Wraps round her ample robe with happy trembling. +Sometimes, when the good Knight his rest would take, +It is reflected, clearly, in a lake, +With the young ashen boughs, 'gainst which it rests, +And th' half seen mossiness of linnets' nests. +Ah! shall I ever tell its cruelty, +When the fire flashes from a warrior's eye, +And his tremendous hand is grasping it, +And his dark brow for very wrath is knit? +Or when his spirit, with more calm intent, +Leaps to the honors of a tournament, +And makes the gazers round about the ring +Stare at the grandeur of the balancing? +No, no! this is far off:--then how shall I +Revive the dying tones of minstrelsy, +Which linger yet about lone gothic arches, +In dark green ivy, and among wild larches? +How sing the splendour of the revelries, +When buts of wine are drunk off to the lees? +And that bright lance, against the fretted wall, +Beneath the shade of stately banneral, +Is slung with shining cuirass, sword, and shield? +Where ye may see a spur in bloody field. +Light-footed damsels move with gentle paces +Round the wide hall, and show their happy faces; +Or stand in courtly talk by fives and sevens: +Like those fair stars that twinkle in the heavens. +Yet must I tell a tale of chivalry: +Or wherefore comes that knight so proudly by? +Wherefore more proudly does the gentle knight, +Rein in the swelling of his ample might? + +Spenser! thy brows are arched, open, kind, +And come like a clear sun-rise to my mind; +And always does my heart with pleasure dance, +When I think on thy noble countenance: +Where never yet was ought more earthly seen +Than the pure freshness of thy laurels green. +Therefore, great bard, I not so fearfully +Call on thy gentle spirit to hover nigh +My daring steps: or if thy tender care, +Thus startled unaware, +Be jealous that the foot of other wight +Should madly follow that bright path of light +Trac'd by thy lov'd Libertas; he will speak, +And tell thee that my prayer is very meek; +That I will follow with due reverence, +And start with awe at mine own strange pretence. +Him thou wilt hear; so I will rest in hope +To see wide plains, fair trees and lawny slope: +The morn, the eve, the light, the shade, the flowers: +Clear streams, smooth lakes, and overlooking towers. + + + + + + +Young Calidore is paddling o'er the lake; +His healthful spirit eager and awake +To feel the beauty of a silent eve, +Which seem'd full loath this happy world to leave; +The light dwelt o'er the scene so lingeringly. +He bares his forehead to the cool blue sky, +And smiles at the far clearness all around, +Until his heart is well nigh over wound, +And turns for calmness to the pleasant green +Of easy slopes, and shadowy trees that lean +So elegantly o'er the waters' brim +And show their blossoms trim. +Scarce can his clear and nimble eye-sight follow +The freaks, and dartings of the black-wing'd swallow, +Delighting much, to see it half at rest, +Dip so refreshingly its wings, and breast +'Gainst the smooth surface, and to mark anon, +The widening circles into nothing gone. + +And now the sharp keel of his little boat +Comes up with ripple, and with easy float, +And glides into a bed of water lillies: +Broad leav'd are they and their white canopies +Are upward turn'd to catch the heavens' dew. +Near to a little island's point they grew; +Whence Calidore might have the goodliest view +Of this sweet spot of earth. The bowery shore +Went off in gentle windings to the hoar +And light blue mountains: but no breathing man +With a warm heart, and eye prepared to scan +Nature's clear beauty, could pass lightly by +Objects that look'd out so invitingly +On either side. These, gentle Calidore +Greeted, as he had known them long before. + +The sidelong view of swelling leafiness, +Which the glad setting sun, in gold doth dress; +Whence ever, and anon the jay outsprings, +And scales upon the beauty of its wings. + +The lonely turret, shatter'd, and outworn, +Stands venerably proud; too proud to mourn +Its long lost grandeur: fir trees grow around, +Aye dropping their hard fruit upon the ground. + +The little chapel with the cross above +Upholding wreaths of ivy; the white dove, +That on the windows spreads his feathers light, +And seems from purple clouds to wing its flight. + +Green tufted islands casting their soft shades +Across the lake; sequester'd leafy glades, +That through the dimness of their twilight show +Large dock leaves, spiral foxgloves, or the glow +Of the wild cat's eyes, or the silvery stems +Of delicate birch trees, or long grass which hems +A little brook. The youth had long been viewing +These pleasant things, and heaven was bedewing +The mountain flowers, when his glad senses caught +A trumpet's silver voice. Ah! it was fraught +With many joys for him: the warder's ken +Had found white coursers prancing in the glen: +Friends very dear to him he soon will see; +So pushes off his boat most eagerly, +And soon upon the lake he skims along, +Deaf to the nightingale's first under-song; +Nor minds he the white swans that dream so sweetly: +His spirit flies before him so completely. + +And now he turns a jutting point of land, +Whence may be seen the castle gloomy, and grand: +Nor will a bee buzz round two swelling peaches, +Before the point of his light shallop reaches +Those marble steps that through the water dip: +Now over them he goes with hasty trip, +And scarcely stays to ope the folding doors: +Anon he leaps along the oaken floors +Of halls and corridors. + +Delicious sounds! those little bright-eyed things +That float about the air on azure wings, +Had been less heartfelt by him than the clang +Of clattering hoofs; into the court he sprang, +Just as two noble steeds, and palfreys twain, +Were slanting out their necks with loosened rein; +While from beneath the threat'ning portcullis +They brought their happy burthens. What a kiss, +What gentle squeeze he gave each lady's hand! +How tremblingly their delicate ancles spann'd! +Into how sweet a trance his soul was gone, +While whisperings of affection +Made him delay to let their tender feet +Come to the earth; with an incline so sweet +From their low palfreys o'er his neck they bent: +And whether there were tears of languishment, +Or that the evening dew had pearl'd their tresses, +He feels a moisture on his cheek, and blesses +With lips that tremble, and with glistening eye +All the soft luxury +That nestled in his arms. A dimpled hand, +Fair as some wonder out of fairy land, +Hung from his shoulder like the drooping flowers +Of whitest Cassia, fresh from summer showers: +And this he fondled with his happy cheek +As if for joy he would no further seek; +When the kind voice of good Sir Clerimond +Came to his ear, like something from beyond +His present being: so he gently drew +His warm arms, thrilling now with pulses new, +From their sweet thrall, and forward gently bending, +Thank'd heaven that his joy was never ending; +While 'gainst his forehead he devoutly press'd +A hand heaven made to succour the distress'd; +A hand that from the world's bleak promontory +Had lifted Calidore for deeds of glory. + +Amid the pages, and the torches' glare, +There stood a knight, patting the flowing hair +Of his proud horse's mane: he was withal +A man of elegance, and stature tall: +So that the waving of his plumes would be +High as the berries of a wild ash tree, +Or as the winged cap of Mercury. +His armour was so dexterously wrought +In shape, that sure no living man had thought +It hard, and heavy steel: but that indeed +It was some glorious form, some splendid weed, +In which a spirit new come from the skies +Might live, and show itself to human eyes. +'Tis the far-fam'd, the brave Sir Gondibert, +Said the good man to Calidore alert; +While the young warrior with a step of grace +Came up,--a courtly smile upon his face, +And mailed hand held out, ready to greet +The large-eyed wonder, and ambitious heat +Of the aspiring boy; who as he led +Those smiling ladies, often turned his head +To admire the visor arched so gracefully +Over a knightly brow; while they went by +The lamps that from the high-roof'd hall were pendent, +And gave the steel a shining quite transcendent. + +Soon in a pleasant chamber they are seated; +The sweet-lipp'd ladies have already greeted +All the green leaves that round the window clamber, +To show their purple stars, and bells of amber. +Sir Gondibert has doff'd his shining steel, +Gladdening in the free, and airy feel +Of a light mantle; and while Clerimond +Is looking round about him with a fond, +And placid eye, young Calidore is burning +To hear of knightly deeds, and gallant spurning +Of all unworthiness; and how the strong of arm +Kept off dismay, and terror, and alarm +From lovely woman: while brimful of this, +He gave each damsel's hand so warm a kiss, +And had such manly ardour in his eye, +That each at other look'd half staringly; +And then their features started into smiles +Sweet as blue heavens o'er enchanted isles. + +Softly the breezes from the forest came, +Softly they blew aside the taper's flame; +Clear was the song from Philomel's far bower; +Grateful the incense from the lime-tree flower; +Mysterious, wild, the far heard trumpet's tone; +Lovely the moon in ether, all alone: +Sweet too the converse of these happy mortals, +As that of busy spirits when the portals +Are closing in the west; or that soft humming +We hear around when Hesperus is coming. +Sweet be their sleep. * * * * * * * * * + + + + + + +What though while the wonders of nature exploring, + I cannot your light, mazy footsteps attend; +Nor listen to accents, that almost adoring, + Bless Cynthia's face, the enthusiast's friend: + +Yet over the steep, whence the mountain stream rushes, + With you, kindest friends, in idea I rove; +Mark the clear tumbling crystal, its passionate gushes, + Its spray that the wild flower kindly bedews. + +Why linger you so, the wild labyrinth strolling? + Why breathless, unable your bliss to declare? +Ah! you list to the nightingale's tender condoling, + Responsive to sylphs, in the moon beamy air. + +'Tis morn, and the flowers with dew are yet drooping, + I see you are treading the verge of the sea: +And now! ah, I see it--you just now are stooping + To pick up the keep-sake intended for me. + +If a cherub, on pinions of silver descending, + Had brought me a gem from the fret-work of heaven; +And smiles, with his star-cheering voice sweetly blending, + The blessings of Tighe had melodiously given; + +It had not created a warmer emotion + Than the present, fair nymphs, I was blest with from you, +Than the shell, from the bright golden sands of the ocean + Which the emerald waves at your feet gladly threw. + +For, indeed, 'tis a sweet and peculiar pleasure, + (And blissful is he who such happiness finds,) +To possess but a span of the hour of leisure, + In elegant, pure, and aerial minds. + + + + + + +Hast thou from the caves of Golconda, a gem + Pure as the ice-drop that froze on the mountain? +Bright as the humming-bird's green diadem, + When it flutters in sun-beams that shine through a fountain? + +Hast thou a goblet for dark sparkling wine? + That goblet right heavy, and massy, and gold? +And splendidly mark'd with the story divine + Of Armida the fair, and Rinaldo the bold? + +Hast thou a steed with a mane richly flowing? + Hast thou a sword that thine enemy's smart is? +Hast thou a trumpet rich melodies blowing? + And wear'st thou the shield of the fam'd Britomartis? + +What is it that hangs from thy shoulder, so brave, + Embroidered with many a spring peering flower? +Is it a scarf that thy fair lady gave? + And hastest thou now to that fair lady's bower? + +Ah! courteous Sir Knight, with large joy thou art crown'd; + Full many the glories that brighten thy youth! +I will tell thee my blisses, which richly abound + In magical powers to bless, and to sooth. + +On this scroll thou seest written in characters fair + A sun-beamy tale of a wreath, and a chain; +And, warrior, it nurtures the property rare + Of charming my mind from the trammels of pain. + +This canopy mark: 'tis the work of a fay; + Beneath its rich shade did King Oberon languish, +When lovely Titania was far, far away, + And cruelly left him to sorrow, and anguish. + +There, oft would he bring from his soft sighing lute + Wild strains to which, spell-bound, the nightingales listened; +The wondering spirits of heaven were mute, + And tears 'mong the dewdrops of morning oft glistened. + +In this little dome, all those melodies strange, + Soft, plaintive, and melting, for ever will sigh; +Nor e'er will the notes from their tenderness change; + Nor e'er will the music of Oberon die. + +So, when I am in a voluptuous vein, + I pillow my head on the sweets of the rose, +And list to the tale of the wreath, and the chain, + Till its echoes depart; then I sink to repose. + +Adieu, valiant Eric! with joy thou art crown'd; + Full many the glories that brighten thy youth, +I too have my blisses, which richly abound + In magical powers, to bless and to sooth. + + + + + + +Hadst thou liv'd in days of old, +O what wonders had been told +Of thy lively countenance, +And thy humid eyes that dance +In the midst of their own brightness; +In the very fane of lightness. +Over which thine eyebrows, leaning, +Picture out each lovely meaning: +In a dainty bend they lie, +Like two streaks across the sky, +Or the feathers from a crow, +Fallen on a bed of snow. +Of thy dark hair that extends +Into many graceful bends: +As the leaves of Hellebore +Turn to whence they sprung before. +And behind each ample curl +Peeps the richness of a pearl. +Downward too flows many a tress +With a glossy waviness; +Full, and round like globes that rise +From the censer to the skies +Through sunny air. Add too, the sweetness +Of thy honied voice; the neatness +Of thine ankle lightly turn'd: +With those beauties, scarce discrn'd, +Kept with such sweet privacy, +That they seldom meet the eye +Of the little loves that fly +Round about with eager pry. +Saving when, with freshening lave, +Thou dipp'st them in the taintless wave; +Like twin water lillies, born +In the coolness of the morn. +O, if thou hadst breathed then, +Now the Muses had been ten. +Couldst thou wish for lineage higher +Than twin sister of Thalia? +At least for ever, evermore, +Will I call the Graces four. + +Hadst thou liv'd when chivalry +Lifted up her lance on high, +Tell me what thou wouldst have been? +Ah! I see the silver sheen +Of thy broidered, floating vest +Cov'ring half thine ivory breast; +Which, O heavens! I should see, +But that cruel destiny +Has placed a golden cuirass there; +Keeping secret what is fair. +Like sunbeams in a cloudlet nested +Thy locks in knightly casque are rested: +O'er which bend four milky plumes +Like the gentle lilly's blooms +Springing from a costly vase. +See with what a stately pace +Comes thine alabaster steed; +Servant of heroic deed! +O'er his loins, his trappings glow +Like the northern lights on snow. +Mount his back! thy sword unsheath! +Sign of the enchanter's death; +Bane of every wicked spell; +Silencer of dragon's yell. +Alas! thou this wilt never do: +Thou art an enchantress too, +And wilt surely never spill +Blood of those whose eyes can kill. + + + + + +When by my solitary hearth I sit, + And hateful thoughts enwrap my soul in gloom; +When no fair dreams before my "mind's eye" flit, + And the bare heath of life presents no bloom; + Sweet Hope, ethereal balm upon me shed, + And wave thy silver pinions o'er my head. + +Whene'er I wander, at the fall of night, + Where woven boughs shut out the moon's bright ray, +Should sad Despondency my musings fright, + And frown, to drive fair Cheerfulness away, + Peep with the moon-beams through the leafy roof, + And keep that fiend Despondence far aloof. + +Should Disappointment, parent of Despair, + Strive for her son to seize my careless heart; +When, like a cloud, he sits upon the air, + Preparing on his spell-bound prey to dart: + Chace him away, sweet Hope, with visage bright, + And fright him as the morning frightens night! + +Whene'er the fate of those I hold most dear + Tells to my fearful breast a tale of sorrow, +O bright-eyed Hope, my morbid fancy cheer; + Let me awhile thy sweetest comforts borrow: + Thy heaven-born radiance around me shed, + And wave thy silver pinions o'er my head! + +Should e'er unhappy love my bosom pain, + From cruel parents, or relentless fair; +O let me think it is not quite in vain + To sigh out sonnets to the midnight air! + Sweet Hope, ethereal balm upon me shed. + And wave thy silver pinions o'er my head! + +In the long vista of the years to roll, + Let me not see our country's honour fade: +O let me see our land retain her soul, + Her pride, her freedom; and not freedom's shade. + From thy bright eyes unusual brightness shed-- + Beneath thy pinions canopy my head! + +Let me not see the patriot's high bequest, + Great Liberty! how great in plain attire! +With the base purple of a court oppress'd, + Bowing her head, and ready to expire: + But let me see thee stoop from heaven on wings + That fill the skies with silver glitterings! + +And as, in sparkling majesty, a star + Gilds the bright summit of some gloomy cloud; +Brightening the half veil'd face of heaven afar: + So, when dark thoughts my boding spirit shroud, + Sweet Hope, celestial influence round me shed, + Waving thy silver pinions o'er my head. + + + Now Morning from her orient chamber came, + And her first footsteps touch'd a verdant hill; + Crowning its lawny crest with amber flame, + Silv'ring the untainted gushes of its rill; + Which, pure from mossy beds, did down distill, + And after parting beds of simple flowers, + By many streams a little lake did fill, + Which round its marge reflected woven bowers, +And, in its middle space, a sky that never lowers. + + There the king-fisher saw his plumage bright + Vieing with fish of brilliant dye below; + Whose silken fins, and golden scales' light + Cast upward, through the waves, a ruby glow: + There saw the swan his neck of arched snow, + And oar'd himself along with majesty; + Sparkled his jetty eyes; his feet did show + Beneath the waves like Afric's ebony, +And on his back a fay reclined voluptuously. + + Ah! could I tell the wonders of an isle + That in that fairest lake had placed been, + I could e'en Dido of her grief beguile; + Or rob from aged Lear his bitter teen: + For sure so fair a place was never seen, + Of all that ever charm'd romantic eye: + It seem'd an emerald in the silver sheen + Of the bright waters; or as when on high, +Through clouds of fleecy white, laughs the coerulean sky. + + And all around it dipp'd luxuriously + Slopings of verdure through the glossy tide, + Which, as it were in gentle amity, + Rippled delighted up the flowery side; + As if to glean the ruddy tears, it tried, + Which fell profusely from the rose-tree stem! + Haply it was the workings of its pride, + In strife to throw upon the shore a gem +Outvieing all the buds in Flora's diadem. + + + +Woman! when I behold thee flippant, vain, + Inconstant, childish, proud, and full of fancies; + Without that modest softening that enhances +The downcast eye, repentant of the pain +That its mild light creates to heal again: + E'en then, elate, my spirit leaps, and prances, + E'en then my soul with exultation dances +For that to love, so long, I've dormant lain: +But when I see thee meek, and kind, and tender, + Heavens! how desperately do I adore +Thy winning graces;--to be thy defender + I hotly burn--to be a Calidore-- +A very Red Cross Knight--a stout Leander-- + Might I be loved by thee like these of yore. + +Light feet, dark violet eyes, and parted hair; + Soft dimpled hands, white neck, and creamy breast, + Are things on which the dazzled senses rest +Till the fond, fixed eyes, forget they stare. +From such fine pictures, heavens! I cannot dare + To turn my admiration, though unpossess'd + They be of what is worthy,--though not drest +In lovely modesty, and virtues rare. +Yet these I leave as thoughtless as a lark; + These lures I straight forget,--e'en ere I dine, +Or thrice my palate moisten: but when I mark + Such charms with mild intelligences shine, +My ear is open like a greedy shark, + To catch the tunings of a voice divine. + +Ah! who can e'er forget so fair a being? + Who can forget her half retiring sweets? + God! she is like a milk-white lamb that bleats +For man's protection. Surely the All-seeing, +Who joys to see us with his gifts agreeing, + Will never give him pinions, who intreats + Such innocence to ruin,--who vilely cheats +A dove-like bosom. In truth there is no freeing +One's thoughts from such a beauty; when I hear + A lay that once I saw her hand awake, +Her form seems floating palpable, and near; + Had I e'er seen her from an arbour take +A dewy flower, oft would that hand appear, + And o'er my eyes the trembling moisture shake. + + + + + +Sweet are the pleasures that to verse belong, +And doubly sweet a brotherhood in song; +Nor can remembrance, Mathew! bring to view +A fate more pleasing, a delight more true +Than that in which the brother Poets joy'd, +Who with combined powers, their wit employ'd +To raise a trophy to the drama's muses. +The thought of this great partnership diffuses +Over the genius loving heart, a feeling +Of all that's high, and great, and good, and healing. + +Too partial friend! fain would I follow thee +Past each horizon of fine poesy; +Fain would I echo back each pleasant note +As o'er Sicilian seas, clear anthems float +'Mong the light skimming gondolas far parted, +Just when the sun his farewell beam has darted: +But 'tis impossible; far different cares +Beckon me sternly from soft "Lydian airs," +And hold my faculties so long in thrall, +That I am oft in doubt whether at all +I shall again see Phoebus in the morning: +Or flush'd Aurora in the roseate dawning! +Or a white Naiad in a rippling stream; +Or a rapt seraph in a moonlight beam; +Or again witness what with thee I've seen, +The dew by fairy feet swept from the green, +After a night of some quaint jubilee +Which every elf and fay had come to see: +When bright processions took their airy march +Beneath the curved moon's triumphal arch. + +But might I now each passing moment give +To the coy muse, with me she would not live +In this dark city, nor would condescend +'Mid contradictions her delights to lend. +Should e'er the fine-eyed maid to me be kind, +Ah! surely it must be whene'er I find +Some flowery spot, sequester'd, wild, romantic, +That often must have seen a poet frantic; +Where oaks, that erst the Druid knew, are growing, +And flowers, the glory of one day, are blowing; +Where the dark-leav'd laburnum's drooping clusters +Reflect athwart the stream their yellow lustres, +And intertwined the cassia's arms unite, +With its own drooping buds, but very white. +Where on one side are covert branches hung, +'Mong which the nightingales have always sung +In leafy quiet; where to pry, aloof, +Atween the pillars of the sylvan roof, +Would be to find where violet beds were nestling, +And where the bee with cowslip bells was wrestling. +There must be too a ruin dark, and gloomy, +To say "joy not too much in all that's bloomy." + +Yet this is vain--O Mathew lend thy aid +To find a place where I may greet the maid-- +Where we may soft humanity put on, +And sit, and rhyme and think on Chatterton; +And that warm-hearted Shakspeare sent to meet him +Four laurell'd spirits, heaven-ward to intreat him. +With reverence would we speak of all the sages +Who have left streaks of light athwart their ages: +And thou shouldst moralize on Milton's blindness, +And mourn the fearful dearth of human kindness +To those who strove with the bright golden wing +Of genius, to flap away each sting +Thrown by the pitiless world. We next could tell +Of those who in the cause of freedom fell: +Of our own Alfred, of Helvetian Tell; +Of him whose name to ev'ry heart's a solace, +High-minded and unbending William Wallace. +While to the rugged north our musing turns +We well might drop a tear for him, and Burns. + +Felton! without incitements such as these, +How vain for me the niggard Muse to tease: +For thee, she will thy every dwelling grace, +And make "a sun-shine in a shady place:" +For thou wast once a flowret blooming wild, +Close to the source, bright, pure, and undefil'd, +Whence gush the streams of song: in happy hour +Came chaste Diana from her shady bower, +Just as the sun was from the east uprising; +And, as for him some gift she was devising, +Beheld thee, pluck'd thee, cast thee in the stream +To meet her glorious brother's greeting beam. +I marvel much that thou hast never told +How, from a flower, into a fish of gold +Apollo chang'd thee; how thou next didst seem +A black-eyed swan upon the widening stream; +And when thou first didst in that mirror trace +The placid features of a human face: +That thou hast never told thy travels strange. +And all the wonders of the mazy range +O'er pebbly crystal, and o'er golden sands; +Kissing thy daily food from Naiad's pearly hands. + +Full many a dreary hour have I past, +My brain bewilder'd, and my mind o'ercast +With heaviness; in seasons when I've thought +No spherey strains by me could e'er be caught +From the blue dome, though I to dimness gaze +On the far depth where sheeted lightning plays; +Or, on the wavy grass outstretch'd supinely, +Pry 'mong the stars, to strive to think divinely: +That I should never hear Apollo's song, +Though feathery clouds were floating all along +The purple west, and, two bright streaks between, +The golden lyre itself were dimly seen: +That the still murmur of the honey bee +Would never teach a rural song to me: +That the bright glance from beauty's eyelids slanting +Would never make a lay of mine enchanting, +Or warm my breast with ardour to unfold +Some tale of love and arms in time of old. + +But there are times, when those that love the bay, +Fly from all sorrowing far, far away; +A sudden glow comes on them, nought they see +In water, earth, or air, but poesy. +It has been said, dear George, and true I hold it, +(For knightly Spenser to Libertas told it,) +That when a Poet is in such a trance, +In air he sees white coursers paw, and prance, +Bestridden of gay knights, in gay apparel, +Who at each other tilt in playful quarrel, +And what we, ignorantly, sheet-lightning call, +Is the swift opening of their wide portal, +When the bright warder blows his trumpet clear, +Whose tones reach nought on earth but Poet's ear. +When these enchanted portals open wide, +And through the light the horsemen swiftly glide, +The Poet's eye can reach those golden halls, +And view the glory of their festivals: +Their ladies fair, that in the distance seem +Fit for the silv'ring of a seraph's dream; +Their rich brimm'd goblets, that incessant run +Like the bright spots that move about the sun; +And, when upheld, the wine from each bright jar +Pours with the lustre of a falling star. +Yet further off, are dimly seen their bowers, +Of which, no mortal eye can reach the flowers; +And 'tis right just, for well Apollo knows +'Twould make the Poet quarrel with the rose. +All that's reveal'd from that far seat of blisses, +Is, the clear fountains' interchanging kisses. +As gracefully descending, light and thin, +Like silver streaks across a dolphin's fin, +When he upswimmeth from the coral caves. +And sports with half his tail above the waves. + +These wonders strange be sees, and many more, +Whose head is pregnant with poetic lore. +Should he upon an evening ramble fare +With forehead to the soothing breezes bare, +Would he naught see but the dark, silent blue +With all its diamonds trembling through and through: +Or the coy moon, when in the waviness +Of whitest clouds she does her beauty dress, +And staidly paces higher up, and higher, +Like a sweet nun in holy-day attire? +Ah, yes! much more would start into his sight-- +The revelries, and mysteries of night: +And should I ever see them, I will tell you +Such tales as needs must with amazement spell you. + +These are the living pleasures of the bard: +But richer far posterity's award. +What does he murmur with his latest breath, +While his proud eye looks through the film of death? +"What though I leave this dull, and earthly mould, +Yet shall my spirit lofty converse hold +With after times.--The patriot shall feel +My stern alarum, and unsheath his steel; +Or, in the senate thunder out my numbers +To startle princes from their easy slumbers. +The sage will mingle with each moral theme +My happy thoughts sententious; he will teem +With lofty periods when my verses fire him, +And then I'll stoop from heaven to inspire him. +Lays have I left of such a dear delight +That maids will sing them on their bridal night. +Gay villagers, upon a morn of May +When they have tired their gentle limbs, with play, +And form'd a snowy circle on the grass, +And plac'd in midst of all that lovely lass +Who chosen is their queen,--with her fine head +Crowned with flowers purple, white, and red: +For there the lily, and the musk-rose, sighing, +Are emblems true of hapless lovers dying: +Between her breasts, that never yet felt trouble, +A bunch of violets full blown, and double, +Serenely sleep:--she from a casket takes +A little book,--and then a joy awakes +About each youthful heart,--with stifled cries, +And rubbing of white hands, and sparkling eyes: +For she's to read a tale of hopes, and fears; +One that I foster'd in my youthful years: +The pearls, that on each glist'ning circlet sleep, +Gush ever and anon with silent creep, +Lured by the innocent dimples. To sweet rest +Shall the dear babe, upon its mother's breast, +Be lull'd with songs of mine. Fair world, adieu! +Thy dales, and hills, are fading from my view: +Swiftly I mount, upon wide spreading pinions, +Far from the narrow bounds of thy dominions. +Full joy I feel, while thus I cleave the air, +That my soft verse will charm thy daughters fair, +And warm thy sons!" Ah, my dear friend and brother, +Could I, at once, my mad ambition smother, +For tasting joys like these, sure I should be +Happier, and dearer to society. +At times, 'tis true, I've felt relief from pain +When some bright thought has darted through my brain: +Through all that day I've felt a greater pleasure +Than if I'd brought to light a hidden treasure. +As to my sonnets, though none else should heed them, +I feel delighted, still, that you should read them. +Of late, too, I have had much calm enjoyment, +Stretch'd on the grass at my best lov'd employment +Of scribbling lines for you. These things I thought +While, in my face, the freshest breeze I caught. +E'en now I'm pillow'd on a bed of flowers +That crowns a lofty clift, which proudly towers +Above the ocean-waves. The stalks, and blades, +Chequer my tablet with their, quivering shades. +On one side is a field of drooping oats, +Through which the poppies show their scarlet coats +So pert and useless, that they bring to mind +The scarlet coats that pester human-kind. +And on the other side, outspread, is seen +Ocean's blue mantle streak'd with purple, and green. +Now 'tis I see a canvass'd ship, and now +Mark the bright silver curling round her prow. +I see the lark down-dropping to his nest. +And the broad winged sea-gull never at rest; +For when no more he spreads his feathers free, +His breast is dancing on the restless sea. +Now I direct my eyes into the west, +Which at this moment is in sunbeams drest: +Why westward turn? 'Twas but to say adieu! +'Twas but to kiss my hand, dear George, to you! + +Oft have you seen a swan superbly frowning, +And with proud breast his own white shadow crowning; +He slants his neck beneath the waters bright +So silently, it seems a beam of light +Come from the galaxy: anon he sports,-- +With outspread wings the Naiad Zephyr courts, +Or ruffles all the surface of the lake +In striving from its crystal face to take +Some diamond water drops, and them to treasure +In milky nest, and sip them off at leisure. +But not a moment can he there insure them, +Nor to such downy rest can he allure them; +For down they rush as though they would be free, +And drop like hours into eternity. +Just like that bird am I in loss of time, +Whene'er I venture on the stream of rhyme; +With shatter'd boat, oar snapt, and canvass rent, +I slowly sail, scarce knowing my intent; +Still scooping up the water with my fingers, +In which a trembling diamond never lingers. + +By this, friend Charles, you may full plainly see +Why I have never penn'd a line to thee: +Because my thoughts were never free, and clear, +And little fit to please a classic ear; +Because my wine was of too poor a savour +For one whose palate gladdens in the flavour +Of sparkling Helicon:--small good it were +To take him to a desert rude, and bare. +Who had on Baiae's shore reclin'd at ease, +While Tasso's page was floating in a breeze +That gave soft music from Armida's bowers, +Mingled with fragrance from her rarest flowers: +Small good to one who had by Mulla's stream +Fondled the maidens with the breasts of cream; +Who had beheld Belphoebe in a brook, +And lovely Una in a leafy nook, +And Archimago leaning o'er his book: +Who had of all that's sweet tasted, and seen, +From silv'ry ripple, up to beauty's queen; +From the sequester'd haunts of gay Titania, +To the blue dwelling of divine Urania: +One, who, of late, had ta'en sweet forest walks +With him who elegantly chats, and talks-- +The wrong'd Libert as,--who has told you stories +Of laurel chaplets, and Apollo's glories; +Of troops chivalrous prancing; through a city, +And tearful ladies made for love, and pity: +With many else which I have never known. +Thus have I thought; and days on days have flown +Slowly, or rapidly--unwilling still +For you to try my dull, unlearned quill. +Nor should I now, but that I've known you long; +That you first taught me all the sweets of song: +The grand, the sweet, the terse, the free, the fine; +What swell'd with pathos, and what right divine: +Spenserian vowels that elope with ease, +And float along like birds o'er summer seas; +Miltonian storms, and more, Miltonian tenderness; +Michael in arms, and more, meek Eve's fair slenderness. +Who read for me the sonnet swelling loudly +Up to its climax and then dying proudly? +Who found for me the grandeur of the ode, +Growing, like Atlas, stronger from its load? +Who let me taste that more than cordial dram, +The sharp, the rapier-pointed epigram? +Shew'd me that epic was of all the king, +Round, vast, and spanning all like Saturn's ring? +You too upheld the veil from Clio's beauty, +And pointed out the patriot's stern duty; +The might of Alfred, and the shaft of Tell; +The hand of Brutus, that so grandly fell +Upon a tyrant's head. Ah! had I never seen, +Or known your kindness, what might I have been? +What my enjoyments in my youthful years, +Bereft of all that now my life endears? +And can I e'er these benefits forget? +And can I e'er repay the friendly debt? +No, doubly no;--yet should these rhymings please, +I shall roll on the grass with two-fold ease: +For I have long time been my fancy feeding +With hopes that you would one day think the reading +Of my rough verses not an hour misspent; +Should it e'er be so, what a rich content! +Some weeks have pass'd since last I saw the spires +In lucent Thames reflected:--warm desires +To see the sun o'er peep the eastern dimness, +And morning shadows streaking into slimness +Across the lawny fields, and pebbly water; +To mark the time as they grow broad, and shorter; +To feel the air that plays about the hills, +And sips its freshness from the little rills; +To see high, golden corn wave in the light +When Cynthia smiles upon a summer's night, +And peers among the cloudlet's jet and white, +As though she were reclining in a bed +Of bean blossoms, in heaven freshly shed. +No sooner had I stepp'd into these pleasures +Than I began to think of rhymes and measures: +The air that floated by me seem'd to say +"Write! thou wilt never have a better day." +And so I did. When many lines I'd written, +Though with their grace I was not oversmitten, +Yet, as my hand was warm, I thought I'd better +Trust to my feelings, and write you a letter. +Such an attempt required an inspiration +Of a peculiar sort,--a consummation;-- +Which, had I felt, these scribblings might have been +Verses from which the soul would never wean: +But many days have past since last my heart +Was warm'd luxuriously by divine Mozart; +By Arne delighted, or by Handel madden'd; +Or by the song of Erin pierc'd and sadden'd: +What time you were before the music sitting, +And the rich notes to each sensation fitting. +Since I have walk'd with you through shady lanes +That freshly terminate in open plains, +And revel'd in a chat that ceased not +When at night-fall among your books we got: +No, nor when supper came, nor after that,-- +Nor when reluctantly I took my hat; +No, nor till cordially you shook my hand +Mid-way between our homes:--your accents bland +Still sounded in my ears, when I no more +Could hear your footsteps touch the grav'ly floor. +Sometimes I lost them, and then found again; +You chang'd the footpath for the grassy plain. +In those still moments I have wish'd you joys +That well you know to honour:--"Life's very toys +With him," said I, "will take a pleasant charm; +It cannot be that ought will work him harm." +These thoughts now come o'er me with all their might:-- +Again I shake your hand,--friend Charles, good night. + +Many the wonders I this day have seen: + The sun, when first he kist away the tears + That fill'd the eyes of morn;--the laurel'd peers +Who from the feathery gold of evening lean:-- +The ocean with its vastness, its blue green, + Its ships, its rocks, its caves, its hopes, its fears,-- + Its voice mysterious, which whoso hears +Must think on what will be, and what has been. +E'en now, dear George, while this for you I write, + Cynthia is from her silken curtains peeping +So scantly, that it seems her bridal night, + And she her half-discover'd revels keeping. +But what, without the social thought of thee, +Would be the wonders of the sky and sea? + + + + + +Had I a man's fair form, then might my sighs + Be echoed swiftly through that ivory shell, + Thine ear, and find thy gentle heart; so well +Would passion arm me for the enterprize: +But ah! I am no knight whose foeman dies; + No cuirass glistens on my bosom's swell; + I am no happy shepherd of the dell +Whose lips have trembled with a maiden's eyes; +Yet must I dote upon thee,--call thee sweet. + Sweeter by far than Hybla's honied roses + When steep'd in dew rich to intoxication. +Ah! I will taste that dew, for me 'tis meet, + And when the moon her pallid face discloses, + I'll gather some by spells, and incantation. + + + + + +What though, for showing truth to flatter'd state + Kind Hunt was shut in prison, yet has he, + In his immortal spirit, been as free +As the sky-searching lark, and as elate. +Minion of grandeur! think you he did wait? + Think you he nought but prison walls did see, + Till, so unwilling, thou unturn'dst the key? +Ah, no! far happier, nobler was his fate! +In Spenser's halls he strayed, and bowers fair, + Culling enchanted flowers; and he flew +With daring Milton through the fields of air: + To regions of his own his genius true +Took happy flights. Who shall his fame impair + When thou art dead, and all thy wretched crew? + + + +How many bards gild the lapses of time! + A few of them have ever been the food + Of my delighted fancy,--I could brood +Over their beauties, earthly, or sublime: +And often, when I sit me down to rhyme, + These will in throngs before my mind intrude: + But no confusion, no disturbance rude +Do they occasion; 'tis a pleasing chime. +So the unnumber'd sounds that evening store; + The songs of birds--the whisp'ring of the leaves-- +The voice of waters--the great bell that heaves + With solemn sound,--and thousand others more, +That distance of recognizance bereaves, + Make pleasing music, and not wild uproar. + + + + + +As late I rambled in the happy fields, + What time the sky-lark shakes the tremulous dew + From his lush clover covert;--when anew +Adventurous knights take up their dinted shields: +I saw the sweetest flower wild nature yields, + A fresh-blown musk-rose; 'twas the first that threw + Its sweets upon the summer: graceful it grew +As is the wand that queen Titania wields. +And, as I feasted on its fragrancy, + I thought the garden-rose it far excell'd: +But when, O Wells! thy roses came to me + My sense with their deliciousness was spell'd: +Soft voices had they, that with tender plea + Whisper'd of peace, and truth, and friendliness unquell'd. + + + + + +Nymph of the downward smile, and sidelong glance, + In what diviner moments of the day + Art thou most lovely? When gone far astray +Into the labyrinths of sweet utterance? +Or when serenely wand'ring in a trance + Of sober thought? Or when starting away, + With careless robe, to meet the morning ray, +Thou spar'st the flowers in thy mazy dance? +Haply 'tis when thy ruby lips part sweetly, + And so remain, because thou listenest: +But thou to please wert nurtured so completely + That I can never tell what mood is best. +I shall as soon pronounce which grace more neatly + Trips it before Apollo than the rest. + + + + + +O Solitude! if I must with thee dwell, + Let it not be among the jumbled heap + Of murky buildings; climb with me the steep,-- +Nature's observatory--whence the dell, +Its flowery slopes, its river's crystal swell, + May seem a span; let me thy vigils keep + 'Mongst boughs pavillion'd, where the deer's swift leap +Startles the wild bee from the fox-glove bell. +But though I'll gladly trace these scenes with thee, + Yet the sweet converse of an innocent mind, +Whose words are images of thoughts refin'd, + Is my soul's pleasure; and it sure must be +Almost the highest bliss of human-kind, + When to thy haunts two kindred spirits flee. + + + + + +Small, busy flames play through the fresh laid coals, + And their faint cracklings o'er our silence creep + Like whispers of the household gods that keep +A gentle empire o'er fraternal souls. +And while, for rhymes, I search around the poles, + Your eyes are fix'd, as in poetic sleep, + Upon the lore so voluble and deep, +That aye at fall of night our care condoles. +This is your birth-day Tom, and I rejoice + That thus it passes smoothly, quietly. +Many such eves of gently whisp'ring noise + May we together pass, and calmly try +What are this world's true joys,--ere the great voice, + From its fair face, shall bid our spirits fly. + + The stars look very cold about the sky, +And I have many miles on foot to fare. +Yet feel I little of the cool bleak air, + Or of the dead leaves rustling drearily, + Or of those silver lamps that burn on high, +Or of the distance from home's pleasant lair: +For I am brimfull of the friendliness + That in a little cottage I have found; +Of fair-hair'd Milton's eloquent distress, + And all his love for gentle Lycid drown'd; +Of lovely Laura in her light green dress, + And faithful Petrarch gloriously crown'd. + + + + + +To one who has been long in city pent, + 'Tis very sweet to look into the fair + And open face of heaven,--to breathe a prayer +Full in the smile of the blue firmament. +Who is more happy, when, with hearts content, + Fatigued he sinks into some pleasant lair + Of wavy grass, and reads a debonair +And gentle tale of love and languishment? +Returning home at evening, with an ear + Catching the notes of Philomel,--an eye +Watching the sailing cloudlet's bright career, + He mourns that day so soon has glided by: +E'en like the passage of an angel's tear + That falls through the clear ether silently. + + + + + +Much have I traveled in the realms of gold, + And many goodly states and kingdoms seen; + Round many western islands have I been +Which bards in fealty to Apollo hold. +Oft of one wide expanse had I been told + That deep-brow'd Homer ruled as his demesne; + Yet did I never breathe its pure serene +Till I heard Chapman speak out loud and bold: +Then felt I like some watcher of the skies + When a new planet swims into his ken; +Or like stout Cortez when with eagle eyes + He star'd at the Pacific--and all his men +Look'd at each other with a wild surmise-- + Silent, upon a peak in Darien. + + + + + +Give me a golden pen, and let me lean + On heap'd up flowers, in regions clear, and far; + Bring me a tablet whiter than a star, +Or hand of hymning angel, when 'tis seen +The silver strings of heavenly harp atween: + And let there glide by many a pearly car, + Pink robes, and wavy hair, and diamond jar, +And half discovered wings, and glances keen. +The while let music wander round my ears. + And as it reaches each delicious ending, + Let me write down a line of glorious tone, +And full of many wonders of the spheres: + For what a height my spirit is contending! + 'Tis not content so soon to be alone. + + + + + +Highmindedness, a jealousy for good, + A loving-kindness for the great man's fame, + Dwells here and there with people of no name, +In noisome alley, and in pathless wood: +And where we think the truth least understood, + Oft may be found a "singleness of aim," + That ought to frighten into hooded shame +A money mong'ring, pitiable brood. +How glorious this affection for the cause + Of stedfast genius, toiling gallantly! +What when a stout unbending champion awes + Envy, and Malice to their native sty? +Unnumber'd souls breathe out a still applause, + Proud to behold him in his country's eye. + + + + + +Great spirits now on earth are sojourning; + He of the cloud, the cataract, the lake, + Who on Helvellyn's summit, wide awake, +Catches his freshness from Archangel's wing: +He of the rose, the violet, the spring. + The social smile, the chain for Freedom's sake: + And lo!--whose stedfastness would never take +A meaner sound than Raphael's whispering. +And other spirits there are standing apart + Upon the forehead of the age to come; +These, these will give the world another heart, + And other pulses. Hear ye not the hum +Of mighty workings?------------ + Listen awhile ye nations, and be dumb. + + + +The poetry of earth is never dead: + When all the birds are faint with the hot sun, + And hide in cooling trees, a voice will run +From hedge to hedge about the new-mown mead; +That is the Grasshopper's--he takes the lead + In summer luxury,--he has never done + With his delights; for when tired out with fun +He rests at ease beneath some pleasant weed. +The poetry of earth is ceasing never: + On a lone winter evening, when the frost + Has wrought a silence, from the stove there shrills +The Cricket's song, in warmth increasing ever, + And seems to one in drowsiness half lost, + The Grasshopper's among some grassy hills. + + + + + +Good Kosciusko, thy great name alone + Is a full harvest whence to reap high feeling; + It comes upon us like the glorious pealing +Of the wide spheres--an everlasting tone. +And now it tells me, that in worlds unknown, + The names of heroes, burst from clouds concealing, + And changed to harmonies, for ever stealing +Through cloudless blue, and round each silver throne. +It tells me too, that on a happy day, + When some good spirit walks upon the earth, + Thy name with Alfred's, and the great of yore +Gently commingling, gives tremendous birth +To a loud hymn, that sounds far, far away + To where the great God lives for evermore. + + + + + +Happy is England! I could be content + To see no other verdure than its own; + To feel no other breezes than are blown +Through its tall woods with high romances blent: +Yet do I sometimes feel a languishment + For skies Italian, and an inward groan + To sit upon an Alp as on a throne, +And half forget what world or worldling meant. +Happy is England, sweet her artless daughters; + Enough their simple loveliness for me, + Enough their whitest arms in silence clinging: + Yet do I often warmly burn to see + Beauties of deeper glance, and hear their singing, +And float with them about the summer waters. + + + + + +"As I lay in my bed slepe full unmete +Was unto me, but why that I ne might +Rest I ne wist, for there n'as erthly wight +[As I suppose] had more of hertis ese +Than I, for I n'ad sicknesse nor disese." + + +What is more gentle than a wind in summer? +What is more soothing than the pretty hummer +That stays one moment in an open flower, +And buzzes cheerily from bower to bower? +What is more tranquil than a musk-rose blowing +In a green island, far from all men's knowing? +More healthful than the leafiness of dales? +More secret than a nest of nightingales? +More serene than Cordelia's countenance? +More full of visions than a high romance? +What, but thee Sleep? Soft closer of our eyes! +Low murmurer of tender lullabies! +Light hoverer around our happy pillows! +Wreather of poppy buds, and weeping willows! +Silent entangler of a beauty's tresses! +Most happy listener! when the morning blesses +Thee for enlivening all the cheerful eyes +That glance so brightly at the new sun-rise. + +But what is higher beyond thought than thee? +Fresher than berries of a mountain tree? +More strange, more beautiful, more smooth, more regal, +Than wings of swans, than doves, than dim-seen eagle? +What is it? And to what shall I compare it? +It has a glory, and nought else can share it: +The thought thereof is awful, sweet, and holy, +Chacing away all worldliness and folly; +Coming sometimes like fearful claps of thunder, +Or the low rumblings earth's regions under; +And sometimes like a gentle whispering +Of all the secrets of some wond'rous thing +That breathes about us in the vacant air; +So that we look around with prying stare, +Perhaps to see shapes of light, aerial lymning, +And catch soft floatings from a faint-heard hymning; +To see the laurel wreath, on high suspended, +That is to crown our name when life is ended. +Sometimes it gives a glory to the voice, +And from the heart up-springs, rejoice! rejoice! +Sounds which will reach the Framer of all things, +And die away in ardent mutterings. + +No one who once the glorious sun has seen, +And all the clouds, and felt his bosom clean +For his great Maker's presence, but must know +What 'tis I mean, and feel his being glow: +Therefore no insult will I give his spirit, +By telling what he sees from native merit. + +O Poesy! for thee I hold my pen +That am not yet a glorious denizen +Of thy wide heaven--Should I rather kneel +Upon some mountain-top until I feel +A glowing splendour round about me hung, +And echo back the voice of thine own tongue? +O Poesy! for thee I grasp my pen +That am not yet a glorious denizen +Of thy wide heaven; yet, to my ardent prayer, +Yield from thy sanctuary some clear air, +Smoothed for intoxication by the breath +Of flowering bays, that I may die a death +Of luxury, and my young spirit follow +The morning sun-beams to the great Apollo +Like a fresh sacrifice; or, if I can bear +The o'erwhelming sweets, 'twill bring to me the fair +Visions of all places: a bowery nook +Will be elysium--an eternal book +Whence I may copy many a lovely saying +About the leaves, and flowers--about the playing +Of nymphs in woods, and fountains; and the shade +Keeping a silence round a sleeping maid; +And many a verse from so strange influence +That we must ever wonder how, and whence +It came. Also imaginings will hover +Round my fire-side, and haply there discover +Vistas of solemn beauty, where I'd wander +In happy silence, like the clear meander +Through its lone vales; and where I found a spot +Of awfuller shade, or an enchanted grot, +Or a green hill o'erspread with chequered dress +Of flowers, and fearful from its loveliness, +Write on my tablets all that was permitted, +All that was for our human senses fitted. +Then the events of this wide world I'd seize +Like a strong giant, and my spirit teaze +Till at its shoulders it should proudly see +Wings to find out an immortality. + +Stop and consider! life is but a day; +A fragile dew-drop on its perilous way +From a tree's summit; a poor Indian's sleep +While his boat hastens to the monstrous steep +Of Montmorenci. Why so sad a moan? +Life is the rose's hope while yet unblown; +The reading of an ever-changing tale; +The light uplifting of a maiden's veil; +A pigeon tumbling in clear summer air; +A laughing school-boy, without grief or care, +Riding the springy branches of an elm. + +O for ten years, that I may overwhelm +Myself in poesy; so I may do the deed +That my own soul has to itself decreed. +Then will I pass the countries that I see +In long perspective, and continually +Taste their pure fountains. First the realm I'll pass +Of Flora, and old Pan: sleep in the grass, +Feed upon apples red, and strawberries, +And choose each pleasure that my fancy sees; +Catch the white-handed nymphs in shady places, +To woo sweet kisses from averted faces,-- +Play with their fingers, touch their shoulders white +Into a pretty shrinking with a bite +As hard as lips can make it: till agreed, +A lovely tale of human life we'll read. +And one will teach a tame dove how it best +May fan the cool air gently o'er my rest; +Another, bending o'er her nimble tread, +Will set a green robe floating round her head, +And still will dance with ever varied case, +Smiling upon the flowers and the trees: +Another will entice me on, and on +Through almond blossoms and rich cinnamon; +Till in the bosom of a leafy world +We rest in silence, like two gems upcurl'd +In the recesses of a pearly shell. + +And can I ever bid these joys farewell? +Yes, I must pass them for a nobler life, +Where I may find the agonies, the strife +Of human hearts: for lo! I see afar, +O'er sailing the blue cragginess, a car +And steeds with streamy manes--the charioteer +Looks out upon the winds with glorious fear: +And now the numerous tramplings quiver lightly +Along a huge cloud's ridge; and now with sprightly +Wheel downward come they into fresher skies, +Tipt round with silver from the sun's bright eyes. +Still downward with capacious whirl they glide, +And now I see them on a green-hill's side +In breezy rest among the nodding stalks. +The charioteer with wond'rous gesture talks +To the trees and mountains; and there soon appear +Shapes of delight, of mystery, and fear, +Passing along before a dusky space +Made by some mighty oaks: as they would chase +Some ever-fleeting music on they sweep. +Lo! how they murmur, laugh, and smile, and weep: +Some with upholden hand and mouth severe; +Some with their faces muffled to the ear +Between their arms; some, clear in youthful bloom, +Go glad and smilingly, athwart the gloom; +Some looking back, and some with upward gaze; +Yes, thousands in a thousand different ways +Flit onward--now a lovely wreath of girls +Dancing their sleek hair into tangled curls; +And now broad wings. Most awfully intent +The driver, of those steeds is forward bent, +And seems to listen: O that I might know +All that he writes with such a hurrying glow. + +The visions all are fled--the car is fled +Into the light of heaven, and in their stead +A sense of real things comes doubly strong, +And, like a muddy stream, would bear along +My soul to nothingness: but I will strive +Against all doublings, and will keep alive +The thought of that same chariot, and the strange +Journey it went. + + Is there so small a range +In the present strength of manhood, that the high +Imagination cannot freely fly +As she was wont of old? prepare her steeds, +Paw up against the light, and do strange deeds +Upon the clouds? Has she not shewn us all? +From the clear space of ether, to the small +Breath of new buds unfolding? From the meaning +Of Jove's large eye-brow, to the tender greening +Of April meadows? Here her altar shone, +E'en in this isle; and who could paragon +The fervid choir that lifted up a noise +Of harmony, to where it aye will poise +Its mighty self of convoluting sound, +Huge as a planet, and like that roll round, +Eternally around a dizzy void? +Ay, in those days the Muses were nigh cloy'd +With honors; nor had any other care +Than to sing out and sooth their wavy hair. + +Could all this be forgotten? Yes, a schism +Nurtured by foppery and barbarism, +Made great Apollo blush for this his land. +Men were thought wise who could not understand +His glories: with a puling infant's force +They sway'd about upon a rocking horse, +And thought it Pegasus. Ah dismal soul'd! +The winds of heaven blew, the ocean roll'd +Its gathering waves--ye felt it not. The blue +Bared its eternal bosom, and the dew +Of summer nights collected still to make +The morning precious: beauty was awake! +Why were ye not awake? But ye were dead +To things ye knew not of,--were closely wed +To musty laws lined out with wretched rule +And compass vile: so that ye taught a school +Of dolts to smooth, inlay, and clip, and fit, +Till, like the certain wands of Jacob's wit, +Their verses tallied. Easy was the task: +A thousand handicraftsmen wore the mask +Of Poesy. Ill-fated, impious race! +That blasphemed the bright Lyrist to his face, +And did not know it,--no, they went about, +Holding a poor, decrepid standard out +Mark'd with most flimsy mottos, and in large +The name of one Boileau! + + O ye whose charge +It is to hover round our pleasant hills! +Whose congregated majesty so fills +My boundly reverence, that I cannot trace +Your hallowed names, in this unholy place, +So near those common folk; did not their shames +Affright you? Did our old lamenting Thames +Delight you? Did ye never cluster round +Delicious Avon, with a mournful sound, +And weep? Or did ye wholly bid adieu +To regions where no more the laurel grew? +Or did ye stay to give a welcoming +To some lone spirits who could proudly sing +Their youth away, and die? 'Twas even so: +But let me think away those times of woe: +Now 'tis a fairer season; ye have breathed +Rich benedictions o'er us; ye have wreathed +Fresh garlands: for sweet music has been heard +In many places;--some has been upstirr'd +From out its crystal dwelling in a lake, +By a swan's ebon bill; from a thick brake, +Nested and quiet in a valley mild, +Bubbles a pipe; fine sounds are floating wild +About the earth: happy are ye and glad. + +These things are doubtless: yet in truth we've had +Strange thunders from the potency of song; +Mingled indeed with what is sweet and strong, +From majesty: but in clear truth the themes +Are ugly clubs, the Poets Polyphemes +Disturbing the grand sea. A drainless shower +Of light is poesy; 'tis the supreme of power; +'Tis might half slumb'ring on its own right arm. +The very archings of her eye-lids charm +A thousand willing agents to obey, +And still she governs with the mildest sway: +But strength alone though of the Muses born +Is like a fallen angel: trees uptorn, +Darkness, and worms, and shrouds, and sepulchres +Delight it; for it feeds upon the burrs, +And thorns of life; forgetting the great end +Of poesy, that it should be a friend +To sooth the cares, and lift the thoughts of man. + + Yet I rejoice: a myrtle fairer than +E'er grew in Paphos, from the bitter weeds +Lifts its sweet head into the air, and feeds +A silent space with ever sprouting green. +All tenderest birds there find a pleasant screen, +Creep through the shade with jaunty fluttering, +Nibble the little cupped flowers and sing. +Then let us clear away the choaking thorns +From round its gentle stem; let the young fawns, +Yeaned in after times, when we are flown, +Find a fresh sward beneath it, overgrown +With simple flowers: let there nothing be +More boisterous than a lover's bended knee; +Nought more ungentle than the placid look +Of one who leans upon a closed book; +Nought more untranquil than the grassy slopes +Between two hills. All hail delightful hopes! +As she was wont, th' imagination +Into most lovely labyrinths will be gone, +And they shall be accounted poet kings +Who simply tell the most heart-easing things. +O may these joys be ripe before I die. + +Will not some say that I presumptuously +Have spoken? that from hastening disgrace +'Twere better far to hide my foolish face? +That whining boyhood should with reverence bow +Ere the dread thunderbolt could reach? How! +If I do hide myself, it sure shall be +In the very fane, the light of Poesy: +If I do fall, at least I will be laid +Beneath the silence of a poplar shade; +And over me the grass shall be smooth shaven; +And there shall be a kind memorial graven. +But oft' Despondence! miserable bane! +They should not know thee, who athirst to gain +A noble end, are thirsty every hour. +What though I am not wealthy in the dower +Of spanning wisdom; though I do not know +The shiftings of the mighty winds, that blow +Hither and thither all the changing thoughts +Of man: though no great minist'ring reason sorts +Out the dark mysteries of human souls +To clear conceiving: yet there ever rolls +A vast idea before me, and I glean +Therefrom my liberty; thence too I've seen +The end and aim of Poesy. 'Tis clear +As any thing most true; as that the year +Is made of the four seasons--manifest +As a large cross, some old cathedral's crest, +Lifted to the white clouds. Therefore should I +Be but the essence of deformity, +A coward, did my very eye-lids wink +At speaking out what I have dared to think. +Ah! rather let me like a madman run +Over some precipice; let the hot sun +Melt my Dedalian wings, and drive me down +Convuls'd and headlong! Stay! an inward frown +Of conscience bids me be more calm awhile. +An ocean dim, sprinkled with many an isle, +Spreads awfully before me. How much toil! +How many days! what desperate turmoil! +Ere I can have explored its widenesses. +Ah, what a task! upon my bended knees, +I could unsay those--no, impossible! +Impossible! + + For sweet relief I'll dwell +On humbler thoughts, and let this strange assay +Begun in gentleness die so away. +E'en now all tumult from my bosom fades: +I turn full hearted to the friendly aids +That smooth the path of honour; brotherhood, +And friendliness the nurse of mutual good. +The hearty grasp that sends a pleasant sonnet +Into the brain ere one can think upon it; +The silence when some rhymes are coming out; +And when they're come, the very pleasant rout: +The message certain to be done to-morrow. +'Tis perhaps as well that it should be to borrow +Some precious book from out its snug retreat, +To cluster round it when we next shall meet. +Scarce can I scribble on; for lovely airs +Are fluttering round the room like doves in pairs; +Many delights of that glad day recalling, +When first my senses caught their tender falling. +And with these airs come forms of elegance +Stooping their shoulders o'er a horse's prance, +Careless, and grand--fingers soft and round +Parting luxuriant curls;--and the swift bound +Of Bacchus from his chariot, when his eye +Made Ariadne's cheek look blushingly. +Thus I remember all the pleasant flow +Of words at opening a portfolio. + +Things such as these are ever harbingers +To trains of peaceful images: the stirs +Of a swan's neck unseen among the rushes: +A linnet starting all about the bushes: +A butterfly, with golden wings broad parted, +Nestling a rose, convuls'd as though it smarted +With over pleasure--many, many more, +Might I indulge at large in all my store +Of luxuries: yet I must not forget +Sleep, quiet with his poppy coronet: +For what there may be worthy in these rhymes +I partly owe to him: and thus, the chimes +Of friendly voices had just given place +To as sweet a silence, when I 'gan retrace +The pleasant day, upon a couch at ease. +It was a poet's house who keeps the keys +Of pleasure's temple. Round about were hung +The glorious features of the bards who sung +In other ages--cold and sacred busts +Smiled at each other. Happy he who trusts +To clear Futurity his darling fame! +Then there were fauns and satyrs taking aim +At swelling apples with a frisky leap +And reaching fingers, 'mid a luscious heap +Of vine leaves. Then there rose to view a fane +Of liny marble, and thereto a train +Of nymphs approaching fairly o'er the sward: +One, loveliest, holding her white band toward +The dazzling sun-rise: two sisters sweet +Bending their graceful figures till they meet +Over the trippings of a little child: +And some are hearing, eagerly, the wild +Thrilling liquidity of dewy piping. +See, in another picture, nymphs are wiping +Cherishingly Diana's timorous limbs;-- +A fold of lawny mantle dabbling swims +At the bath's edge, and keeps a gentle motion +With the subsiding crystal: as when ocean +Heaves calmly its broad swelling smoothiness o'er +Its rocky marge, and balances once more +The patient weeds; that now unshent by foam +Feel all about their undulating home. + +Sappho's meek head was there half smiling down +At nothing; just as though the earnest frown +Of over thinking had that moment gone +From off her brow, and left her all alone. + +Great Alfred's too, with anxious, pitying eyes, +As if he always listened to the sighs +Of the goaded world; and Kosciusko's worn +By horrid suffrance--mightily forlorn. + +Petrarch, outstepping from the shady green, +Starts at the sight of Laura; nor can wean +His eyes from her sweet face. Most happy they! +For over them was seen a free display +Of out-spread wings, and from between them shone +The face of Poesy: from off her throne +She overlook'd things that I scarce could tell. +The very sense of where I was might well +Keep Sleep aloof: but more than that there came +Thought after thought to nourish up the flame +Within my breast; so that the morning light +Surprised me even from a sleepless night; +And up I rose refresh'd, and glad, and gay, +Resolving to begin that very day +These lines; and howsoever they be done, +I leave them as a father does his son.
pgorla-zz/markov
4bb2c662057e476469327dce8e0aa47a083b3695
deleted chaff
diff --git a/markov.py b/markov.py old mode 100644 new mode 100755 index 3cfe4e8..1bfdfd7 --- a/markov.py +++ b/markov.py @@ -1,82 +1,80 @@ #!/usr/bin/env python +import sys +import random import string -from random import randint - -class Generate_Table(): - - def __init__(self): - self.filename = 'text/alice.txt' - self.text = open(self.filename) - self.fulltext = self.generate_fulltext() - self.words_by_number = self.generate_word_list() - - def generate_fulltext(self): - exclude = set(string.punctuation) - text_ = '' - for line in self.text: - text_ += line.strip() - # get rid of punctuation. TODO: add back in. - text_ = ''.join(ch for ch in text_ if ch not in exclude) -# TODO -# generate_fulltext() currently churns out -# 'atPresent', 'to\xe3\mor\ehe\x..' -# fix? - return text_.split() - - def generate_word_list(self): - word_list_ = {} - for word in self.fulltext: - if not word_list_.has_key(word): - word_list_[word] = 1 - else: - word_list_[word] += 1 - return word_list_ - - def couple(self): - - -# metadata? (authorship, which text used, etc) -# D = {} -# D[word] = count +class Markov(object): + """ + Markov-chain text generator. Translated + from the original PHP into Python (haykranen.nl) + """ -class Word(Generate_Table): + def __init__(self,text='alice.txt',length=600): + fil = text + fin = open('text/'+fil) + self.text = '' + forbid = '\\' + for line in fin: + self.text += line.translate(None,forbid).strip() + self.markov_table = self.generate_markov_table(self.text, 3) + self.length = length - def __init__(self): + def _run(self): -class Generate_Word_list(Generate_Table): - def __init__(self): - self.count = 0 + return self.generate_markov_text(self.length,self.markov_table,3) + def generate_markov_table(self, text, look_forward): + self.table = {} + # walk through text, make index table + for i in range(len(self.text)): + char = self.text[i:i+look_forward] + if char not in self.table: + self.table[char] = {} -""" -we need to calculate the -probabilities between each word. hm. -neural networks? -but now, focus on creating this thing. + # walk array again, count numbers + for i in range(len(self.text) - look_forward): + char_index = self.text[i:i+look_forward] + char_count = self.text[i+look_forward:i+look_forward+look_forward] -Possibly working idea: - -{ - 'the' : {0.9:'bear', 0.3:'Kool-Aid'}, - 'peaches' : {0.2:'palm', 0.4:'fence'} - 'stuff' : {0.5:'bodies', 0.9:'turkey'} -} + if char_count not in self.table[char_index].keys(): + self.table[char_index][char_count] = 1 + else: + self.table[char_index][char_count] += 1 -{ - word_object : {P(following_word):following_word} -} -""" + return self.table + def generate_markov_text(self, length, table, look_forward): + # get first character + char = random.choice(table.keys()) + o = char + for i in range(length/look_forward): + newchar = self.return_weighted_char(table[char]) + if newchar: + char = newchar + o += newchar + else: + char = random.choice(table.keys()) + return o + def return_weighted_char(self,array): + if not array: + return False + else: + total = sum(array.values()) + rand = random.randint(1,total) + for k,v in array.iteritems(): + if rand <= v: + return k + rand -= v if __name__ == '__main__': - t = Generate_Table() + t = Markov() + print t._run()
pgorla-zz/markov
5f81ed28454c7305b402825d6b3b0576d72d2ec0
woo class action!
diff --git a/pymarkov.py b/pymarkov.py index e3cf1de..72797b6 100755 --- a/pymarkov.py +++ b/pymarkov.py @@ -1,77 +1,83 @@ #!/usr/bin/env python +import sys import random +import string -def generate_markov_table(text, look_forward): +class Markov(object): - table = {} + """ + Markov-chain text generator. Translated + from the original PHP into Python (haykranen.nl) + """ - # walk through text, make index table - for i in range(len(text)): - char = text[i:i+look_forward] - if char not in table: - table[char] = {} + def __init__(self,text='alice.txt',length=600): + fil = text + fin = open('text/'+fil) + self.text = '' + forbid = '\\' + for line in fin: + self.text += line.translate(None,forbid).strip() + self.markov_table = self.generate_markov_table(self.text, 3) + self.length = length - # walk array again, count numbers - for i in range(len(text) - look_forward): - char_index = text[i:i+look_forward] - char_count = text[i+look_forward:i+look_forward+look_forward] - if char_count not in table[char_index].keys(): - table[char_index][char_count] = 1 - else: - table[char_index][char_count] += 1 + def _run(self): - return table + return self.generate_markov_text(self.length,self.markov_table,3) -def generate_markov_text(length, table, look_forward): - # get first character - char = random.choice(table.keys()) - o = char - for i in range(length/look_forward): - newchar = return_weighted_char(table[char]) - if newchar: - char = newchar - o += newchar - else: - char = random.choice(table.keys()) - return o + def generate_markov_table(self, text, look_forward): + self.table = {} + # walk through text, make index table + for i in range(len(self.text)): + char = self.text[i:i+look_forward] + if char not in self.table: + self.table[char] = {} -def return_weighted_char(array): - if not array: - return False - else: - total = sum(array.values()) - rand = random.randint(1,total) - for k,v in array.iteritems(): - if rand <= v: - return k - rand -= v + # walk array again, count numbers + for i in range(len(self.text) - look_forward): + char_index = self.text[i:i+look_forward] + char_count = self.text[i+look_forward:i+look_forward+look_forward] + if char_count not in self.table[char_index].keys(): + self.table[char_index][char_count] = 1 + else: + self.table[char_index][char_count] += 1 + return self.table + def generate_markov_text(self, length, table, look_forward): + # get first character + char = random.choice(table.keys()) + o = char + for i in range(length/look_forward): + newchar = self.return_weighted_char(table[char]) + if newchar: + char = newchar + o += newchar + else: + char = random.choice(table.keys()) + return o -if __name__ == '__main__': - import sys - import string - if sys.argv[1]: - fil = sys.argv[1] - else: - fil = 'alice.txt' - if sys.argv[2]: - length = int(sys.argv[2]) - else: - length = 600 - - fin = open('text/'+fil) - text = '' - forbid = '\\' - for line in fin: - text += line.translate(None,forbid).strip() - markov = generate_markov_table(text, 4) - print generate_markov_text(length,markov,3) + + def return_weighted_char(self,array): + if not array: + return False + else: + total = sum(array.values()) + rand = random.randint(1,total) + for k,v in array.iteritems(): + if rand <= v: + return k + rand -= v + + + +if __name__ == '__main__': + t = Markov() + print t._run()
pgorla-zz/markov
2958206c8c9a3406c7e00b6e20425447ec141f48
added license
diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..ee1440c --- /dev/null +++ b/LICENSE @@ -0,0 +1,26 @@ +PHP Markov Chain text generator 1.0 +Copyright (c) 2008, Hay Kranen <http://www.haykranen.nl/projects/markov/> + +License (MIT / X11 license) + +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. +
pgorla-zz/markov
73384079400a47a3da90c0844d4ff2ecf5d0cb9f
sys.argv tweaks
diff --git a/pymarkov.py b/pymarkov.py index f8ba7c5..e3cf1de 100755 --- a/pymarkov.py +++ b/pymarkov.py @@ -1,67 +1,77 @@ #!/usr/bin/env python import random def generate_markov_table(text, look_forward): table = {} # walk through text, make index table for i in range(len(text)): char = text[i:i+look_forward] if char not in table: table[char] = {} # walk array again, count numbers for i in range(len(text) - look_forward): char_index = text[i:i+look_forward] char_count = text[i+look_forward:i+look_forward+look_forward] if char_count not in table[char_index].keys(): table[char_index][char_count] = 1 else: table[char_index][char_count] += 1 return table def generate_markov_text(length, table, look_forward): # get first character char = random.choice(table.keys()) o = char for i in range(length/look_forward): newchar = return_weighted_char(table[char]) if newchar: char = newchar o += newchar else: char = random.choice(table.keys()) return o def return_weighted_char(array): if not array: return False else: total = sum(array.values()) rand = random.randint(1,total) for k,v in array.iteritems(): if rand <= v: return k rand -= v if __name__ == '__main__': + import sys import string - fin = open('text/alice.txt') + if sys.argv[1]: + fil = sys.argv[1] + else: + fil = 'alice.txt' + if sys.argv[2]: + length = int(sys.argv[2]) + else: + length = 600 + + fin = open('text/'+fil) text = '' forbid = '\\' for line in fin: text += line.translate(None,forbid).strip() markov = generate_markov_table(text, 4) - print generate_markov_text(600,markov,4) + print generate_markov_text(length,markov,3)
pgorla-zz/markov
4583b094a73a8195e3d3cb3670bc24896ff0bceb
random!
diff --git a/pymarkov.py b/pymarkov.py index 98d51a7..f8ba7c5 100755 --- a/pymarkov.py +++ b/pymarkov.py @@ -1,74 +1,67 @@ #!/usr/bin/env python import random def generate_markov_table(text, look_forward): table = {} # walk through text, make index table for i in range(len(text)): char = text[i:i+look_forward] if char not in table: table[char] = {} # walk array again, count numbers for i in range(len(text) - look_forward): char_index = text[i:i+look_forward] char_count = text[i+look_forward:i+look_forward+look_forward] if char_count not in table[char_index].keys(): table[char_index][char_count] = 1 else: table[char_index][char_count] += 1 return table def generate_markov_text(length, table, look_forward): # get first character char = random.choice(table.keys()) o = char - for i in range(length/look_forward): - newchar = return_weighted_char(table[char]) - if newchar: char = newchar o += newchar else: char = random.choice(table.keys()) - return o def return_weighted_char(array): if not array: return False else: total = sum(array.values()) rand = random.randint(1,total) - for weight in array: - if rand <= weight: - return weight - rand -= weight - - - + for k,v in array.iteritems(): + if rand <= v: + return k + rand -= v if __name__ == '__main__': import string fin = open('text/alice.txt') text = '' forbid = '\\' for line in fin: text += line.translate(None,forbid).strip() markov = generate_markov_table(text, 4) print generate_markov_text(600,markov,4)
pgorla-zz/markov
0fdddcbba1c2c49b8e5354aa2f85b87577024b30
something works, randomly! (ha, ha)
diff --git a/pymarkov.py b/pymarkov.py old mode 100644 new mode 100755 index 2f78f64..98d51a7 --- a/pymarkov.py +++ b/pymarkov.py @@ -1,88 +1,74 @@ #!/usr/bin/env python import random def generate_markov_table(text, look_forward): table = {} # walk through text, make index table for i in range(len(text)): - char = text[i:look_forward] + char = text[i:i+look_forward] if char not in table: table[char] = {} - print table # walk array again, count numbers for i in range(len(text) - look_forward): - char_index = text[i:look_forward] - char_count = text[i+look_forward:look_forward] + char_index = text[i:i+look_forward] + char_count = text[i+look_forward:i+look_forward+look_forward] - if not char_count in table[char_index].keys(): + if char_count not in table[char_index].keys(): table[char_index][char_count] = 1 else: table[char_index][char_count] += 1 return table def generate_markov_text(length, table, look_forward): # get first character char = random.choice(table.keys()) o = char for i in range(length/look_forward): - li_nums = [] - for k,v in table[char]: - li_nums.append(v) newchar = return_weighted_char(table[char]) if newchar: char = newchar - o = newchar + o += newchar else: char = random.choice(table.keys()) return o def return_weighted_char(array): if not array: return False else: - total = sum(array) + total = sum(array.values()) rand = random.randint(1,total) for weight in array: if rand <= weight: return weight rand -= weight - - - - - - - - if __name__ == '__main__': + import string fin = open('text/alice.txt') text = '' + forbid = '\\' for line in fin: - text += line.strip() - generate_markov_table(text, 4) - - - - - + text += line.translate(None,forbid).strip() + markov = generate_markov_table(text, 4) + print generate_markov_text(600,markov,4)
pgorla-zz/markov
8c15630a0a540456981abbdf282ff271b1ab08e3
translated markov.php
diff --git a/pymarkov.py b/pymarkov.py new file mode 100644 index 0000000..f0dd292 --- /dev/null +++ b/pymarkov.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python + +from random import randint + + +def generate_markov_table(text, look_forward): + + table = [] + + # walk through text, make index table + for i in range(len(text)): + char = text[i:look_forward] + if not char in table: + table[char] = [] + + # walk array again, count numbers + for i in range(len(text) - look_forward): + char_index = text[i:look_forward] + char_count = text[i+look_forward:look_forward] + + if table[char_index][char_count]: + table[char_index][char_count] += 1 + else: + table[char_index][char_count] = 1 + + return table + + +def generate_markov_text(length, table, look_forward): + # get first character + char = table[randint(0,len(table))] + o = char + + for i in range(length/look_forward): + newchar = return_weighted_char(table[char]) + + if newchar: + char = newchar + o = newchar + else: + char = table[randint(0,len(table))] + + return o + + +def return_weighted_char(array): + if not array: + return False + else: + total = sum(array) + rand = randint(1,total) + for weight in array: + if rand <= weight: + return weight + rand -= weight + + + + + + + + + + + + + + + + + + + + + + +
pgorla-zz/markov
bb9439d87fe9660b9b44edb36bbf0a7a8c667ecf
playing with data types
diff --git a/markov.py b/markov.py index 075dde9..3cfe4e8 100644 --- a/markov.py +++ b/markov.py @@ -1,50 +1,82 @@ -#!/usr/bin/python +#!/usr/bin/env python import string +from random import randint class Generate_Table(): - """Generate Markov table from input text.""" - def __init__(self): - self.filename = 'alice.txt' + self.filename = 'text/alice.txt' self.text = open(self.filename) self.fulltext = self.generate_fulltext() + self.words_by_number = self.generate_word_list() def generate_fulltext(self): exclude = set(string.punctuation) text_ = '' for line in self.text: text_ += line.strip() + # get rid of punctuation. TODO: add back in. text_ = ''.join(ch for ch in text_ if ch not in exclude) +# TODO +# generate_fulltext() currently churns out +# 'atPresent', 'to\xe3\mor\ehe\x..' +# fix? return text_.split() def generate_word_list(self): word_list_ = {} for word in self.fulltext: if not word_list_.has_key(word): word_list_[word] = 1 else: word_list_[word] += 1 return word_list_ + def couple(self): + + + # metadata? (authorship, which text used, etc) # D = {} # D[word] = count + class Word(Generate_Table): + def __init__(self): - pass + class Generate_Word_list(Generate_Table): def __init__(self): self.count = 0 -# we need to calculate the -# probabilities between each word. hm. -# neural networks? -# but now, focus on creating this thing. + + + +""" +we need to calculate the +probabilities between each word. hm. +neural networks? +but now, focus on creating this thing. + +Possibly working idea: + +{ + 'the' : {0.9:'bear', 0.3:'Kool-Aid'}, + 'peaches' : {0.2:'palm', 0.4:'fence'} + 'stuff' : {0.5:'bodies', 0.9:'turkey'} +} + +{ + word_object : {P(following_word):following_word} +} +""" + + + + if __name__ == '__main__': t = Generate_Table()
chrismatthieu/Teleku-HighLow-Game-Ruby-Sinatra
1abd693f386e93013bf85c980217715526b71e04
added relative url support
diff --git a/app.rb b/app.rb index 38cd329..6dbb83b 100644 --- a/app.rb +++ b/app.rb @@ -1,52 +1,52 @@ require 'rubygems' require 'sinatra' require 'builder' get '/' do 'HighLow is a <a href="teleku.com">Teleku Voice Application</a><br>' 'curl --data-urlencode "caller=test" http://highlow.heroku.com' end post '/' do deal = 1 + rand(10) builder do |xml| xml.instruct! xml.phoneml do xml.speak "welcome to the game of high low" xml.speak "the dealer randomly selected " + deal.to_s xml.speak "will his next number be higher or lower? press 1 or say higher or press 2 or say lower" - xml.input "http://highlow.heroku.com/guess/" + deal.to_s, "options"=>"1,2,higher,lower" + xml.input "/guess/" + deal.to_s, "options"=>"1,2,higher,lower" end end end post '/guess/:deal' do newdeal = 1 + rand(10) guess = params[:callerinput] if guess == '1' or guess == 'higher' if newdeal > params[:deal].to_i gamestatus = "winner" else gamestatus = "loser" end end if guess == '2' or guess == 'lower' if newdeal < params[:deal].to_i gamestatus = "winner" else gamestatus = "loser" end end builder do |xml| xml.instruct! xml.phoneml do xml.speak "the dealer randomly selected " + newdeal.to_s xml.speak "you are a " + gamestatus xml.speak "will his next number be higher or lower? press 1 or say higher or press 2 or say lower" - xml.input "http://highlow.heroku.com/guess/" + newdeal.to_s, "options"=>"1,2,higher,lower" + xml.input "/guess/" + newdeal.to_s, "options"=>"1,2,higher,lower" end end end \ No newline at end of file
chrismatthieu/Teleku-HighLow-Game-Ruby-Sinatra
789e38d9382d4a99d637c7228263cbc5a1bdef88
added hilo game source4
diff --git a/app.rb b/app.rb index 3268907..38cd329 100644 --- a/app.rb +++ b/app.rb @@ -1,52 +1,52 @@ require 'rubygems' require 'sinatra' require 'builder' get '/' do 'HighLow is a <a href="teleku.com">Teleku Voice Application</a><br>' 'curl --data-urlencode "caller=test" http://highlow.heroku.com' end post '/' do deal = 1 + rand(10) builder do |xml| xml.instruct! xml.phoneml do xml.speak "welcome to the game of high low" xml.speak "the dealer randomly selected " + deal.to_s xml.speak "will his next number be higher or lower? press 1 or say higher or press 2 or say lower" xml.input "http://highlow.heroku.com/guess/" + deal.to_s, "options"=>"1,2,higher,lower" end end end post '/guess/:deal' do newdeal = 1 + rand(10) - guess = params[:CallerInput] + guess = params[:callerinput] if guess == '1' or guess == 'higher' if newdeal > params[:deal].to_i gamestatus = "winner" else gamestatus = "loser" end end if guess == '2' or guess == 'lower' if newdeal < params[:deal].to_i gamestatus = "winner" else gamestatus = "loser" end end builder do |xml| xml.instruct! xml.phoneml do xml.speak "the dealer randomly selected " + newdeal.to_s xml.speak "you are a " + gamestatus xml.speak "will his next number be higher or lower? press 1 or say higher or press 2 or say lower" xml.input "http://highlow.heroku.com/guess/" + newdeal.to_s, "options"=>"1,2,higher,lower" end end end \ No newline at end of file
chrismatthieu/Teleku-HighLow-Game-Ruby-Sinatra
c3883e8913ad9f4847cf3c136453e258dff86955
fixed route3
diff --git a/app.rb b/app.rb index 38cd329..3268907 100644 --- a/app.rb +++ b/app.rb @@ -1,52 +1,52 @@ require 'rubygems' require 'sinatra' require 'builder' get '/' do 'HighLow is a <a href="teleku.com">Teleku Voice Application</a><br>' 'curl --data-urlencode "caller=test" http://highlow.heroku.com' end post '/' do deal = 1 + rand(10) builder do |xml| xml.instruct! xml.phoneml do xml.speak "welcome to the game of high low" xml.speak "the dealer randomly selected " + deal.to_s xml.speak "will his next number be higher or lower? press 1 or say higher or press 2 or say lower" xml.input "http://highlow.heroku.com/guess/" + deal.to_s, "options"=>"1,2,higher,lower" end end end post '/guess/:deal' do newdeal = 1 + rand(10) - guess = params[:callerinput] + guess = params[:CallerInput] if guess == '1' or guess == 'higher' if newdeal > params[:deal].to_i gamestatus = "winner" else gamestatus = "loser" end end if guess == '2' or guess == 'lower' if newdeal < params[:deal].to_i gamestatus = "winner" else gamestatus = "loser" end end builder do |xml| xml.instruct! xml.phoneml do xml.speak "the dealer randomly selected " + newdeal.to_s xml.speak "you are a " + gamestatus xml.speak "will his next number be higher or lower? press 1 or say higher or press 2 or say lower" xml.input "http://highlow.heroku.com/guess/" + newdeal.to_s, "options"=>"1,2,higher,lower" end end end \ No newline at end of file
chrismatthieu/Teleku-HighLow-Game-Ruby-Sinatra
ec113528d261893cb8b239ad562e6462031f2c17
fixed route2
diff --git a/app.rb b/app.rb index 44f3b9e..38cd329 100644 --- a/app.rb +++ b/app.rb @@ -1,52 +1,52 @@ require 'rubygems' require 'sinatra' require 'builder' get '/' do 'HighLow is a <a href="teleku.com">Teleku Voice Application</a><br>' 'curl --data-urlencode "caller=test" http://highlow.heroku.com' end post '/' do deal = 1 + rand(10) builder do |xml| xml.instruct! xml.phoneml do xml.speak "welcome to the game of high low" xml.speak "the dealer randomly selected " + deal.to_s xml.speak "will his next number be higher or lower? press 1 or say higher or press 2 or say lower" xml.input "http://highlow.heroku.com/guess/" + deal.to_s, "options"=>"1,2,higher,lower" end end end post '/guess/:deal' do newdeal = 1 + rand(10) guess = params[:callerinput] if guess == '1' or guess == 'higher' if newdeal > params[:deal].to_i gamestatus = "winner" else gamestatus = "loser" end end if guess == '2' or guess == 'lower' if newdeal < params[:deal].to_i gamestatus = "winner" else gamestatus = "loser" end end builder do |xml| xml.instruct! xml.phoneml do - xml.speak "the dealer randomly selected " + params[:deal].to_s + xml.speak "the dealer randomly selected " + newdeal.to_s xml.speak "you are a " + gamestatus xml.speak "will his next number be higher or lower? press 1 or say higher or press 2 or say lower" xml.input "http://highlow.heroku.com/guess/" + newdeal.to_s, "options"=>"1,2,higher,lower" end end end \ No newline at end of file
chrismatthieu/Teleku-HighLow-Game-Ruby-Sinatra
66ae11f55fc7d7c0a3847408c633f159ad7b72fe
fixed route
diff --git a/app.rb b/app.rb index aaec8ed..44f3b9e 100644 --- a/app.rb +++ b/app.rb @@ -1,53 +1,52 @@ require 'rubygems' require 'sinatra' require 'builder' get '/' do - 'HighLow is a <a href="teleku.com">Teleku Voice Application</a>' + 'HighLow is a <a href="teleku.com">Teleku Voice Application</a><br>' + 'curl --data-urlencode "caller=test" http://highlow.heroku.com' end post '/' do - session[:deal] = 1 + rand(10) + deal = 1 + rand(10) builder do |xml| xml.instruct! xml.phoneml do xml.speak "welcome to the game of high low" - xml.speak "the dealer randomly selected " + session[:deal].to_s + xml.speak "the dealer randomly selected " + deal.to_s xml.speak "will his next number be higher or lower? press 1 or say higher or press 2 or say lower" - xml.input "http://highlow.heroku.com/guess", "options"=>"1,2,higher,lower" + xml.input "http://highlow.heroku.com/guess/" + deal.to_s, "options"=>"1,2,higher,lower" end end end -post '/guess' do - session[:newdeal] = 1 + rand(10) +post '/guess/:deal' do + newdeal = 1 + rand(10) guess = params[:callerinput] if guess == '1' or guess == 'higher' - if session[:newdeal] > session[:deal] + if newdeal > params[:deal].to_i gamestatus = "winner" else gamestatus = "loser" end end if guess == '2' or guess == 'lower' - if session[:newdeal] < session[:deal] + if newdeal < params[:deal].to_i gamestatus = "winner" else gamestatus = "loser" end end - session[:deal] = session[:newdeal] - builder do |xml| xml.instruct! xml.phoneml do - xml.speak "the dealer randomly selected " + session[:deal].to_s + xml.speak "the dealer randomly selected " + params[:deal].to_s xml.speak "you are a " + gamestatus xml.speak "will his next number be higher or lower? press 1 or say higher or press 2 or say lower" - xml.input "http://highlow.heroku.com/guess", "options"=>"1,2,higher,lower" + xml.input "http://highlow.heroku.com/guess/" + newdeal.to_s, "options"=>"1,2,higher,lower" end end end \ No newline at end of file
chrismatthieu/Teleku-HighLow-Game-Ruby-Sinatra
0a1b50a6866119b1bf107bb1f105c8bc6edff5dd
added full path
diff --git a/app.rb b/app.rb index b7aa3bf..aaec8ed 100644 --- a/app.rb +++ b/app.rb @@ -1,53 +1,53 @@ require 'rubygems' require 'sinatra' require 'builder' get '/' do 'HighLow is a <a href="teleku.com">Teleku Voice Application</a>' end post '/' do session[:deal] = 1 + rand(10) builder do |xml| xml.instruct! xml.phoneml do xml.speak "welcome to the game of high low" xml.speak "the dealer randomly selected " + session[:deal].to_s xml.speak "will his next number be higher or lower? press 1 or say higher or press 2 or say lower" - xml.input "/guess", "options"=>"1,2,higher,lower" + xml.input "http://highlow.heroku.com/guess", "options"=>"1,2,higher,lower" end end end post '/guess' do session[:newdeal] = 1 + rand(10) guess = params[:callerinput] if guess == '1' or guess == 'higher' if session[:newdeal] > session[:deal] gamestatus = "winner" else gamestatus = "loser" end end if guess == '2' or guess == 'lower' if session[:newdeal] < session[:deal] gamestatus = "winner" else gamestatus = "loser" end end session[:deal] = session[:newdeal] builder do |xml| xml.instruct! xml.phoneml do xml.speak "the dealer randomly selected " + session[:deal].to_s xml.speak "you are a " + gamestatus xml.speak "will his next number be higher or lower? press 1 or say higher or press 2 or say lower" - xml.input "/guess", "options"=>"1,2,higher,lower" + xml.input "http://highlow.heroku.com/guess", "options"=>"1,2,higher,lower" end end end \ No newline at end of file
sirprize/xdoctrine
62865ffcd8d0907d9be319f50b8ef9bbbf82d028
Make cache work with Doctrine 2.4
diff --git a/lib/Xdoctrine/Common/Cache/ZendCache.php b/lib/Xdoctrine/Common/Cache/ZendCache.php index 77594eb..49d1e0b 100644 --- a/lib/Xdoctrine/Common/Cache/ZendCache.php +++ b/lib/Xdoctrine/Common/Cache/ZendCache.php @@ -1,90 +1,111 @@ <?php /** * Xdoctrine - Sirprize's Doctrine2 Extensions * * @package Xdoctrine * @copyright Copyright (c) 2010, Christian Hoegl, Switzerland (http://sirprize.me) * @license New BSD License */ namespace Xdoctrine\Common\Cache; -class ZendCache extends \Doctrine\Common\Cache\AbstractCache +class ZendCache extends \Doctrine\Common\Cache\CacheProvider { /** * @var \Zend_Cache_Core */ private $_zendCache; /** * Sets the \Zend_Cache_Core instance to use. * * @param \Zend_Cache_Core $zendCache */ public function setZendCache(\Zend_Cache_Core $zendCache) { $this->_zendCache = $zendCache; } /** * Gets the \Zend_Cache_Core instance used by the cache. * * @return \Zend_Cache_Core */ public function getZendCache() { if($this->_zendCache === null) { - throw new \Xdoctrine\DBAL\Exception('call setZendCache() before '.__METHOD__); + throw new \Xdoctrine\Common\Exception('call setZendCache() before '.__METHOD__); } return $this->_zendCache; } /** * {@inheritdoc} */ - protected function _doFetch($id) + protected function doFetch($id) { - return $this->_zendCache->load($this->_prepareId($id)); + return $this->getZendCache()->load($this->prepareId($id)); } /** * {@inheritdoc} */ - protected function _doContains($id) + protected function doContains($id) { - return (bool) $this->_zendCache->test($this->_prepareId($id)); + return (bool) $this->getZendCache()->test($this->prepareId($id)); } /** * {@inheritdoc} */ - protected function _doSave($id, $data, $lifeTime = false) + protected function doSave($id, $data, $lifeTime = false) { - return $this->_zendCache->save($data, $this->_prepareId($id), array(), $lifeTime); + return $this->getZendCache()->save($data, $this->prepareId($id), array(), $lifeTime); } /** * {@inheritdoc} */ - protected function _doDelete($id) + protected function doDelete($id) { - return $this->_zendCache->remove($this->_prepareId($id)); + return $this->getZendCache()->remove($this->prepareId($id)); + } + + /** + * {@inheritdoc} + */ + protected function doFlush() + { + foreach($this->getIds() as $id) + { + $this->doDelete($id); + } + + return true; + } + + /** + * {@inheritdoc} + */ + public function doGetStats() + { + return null; } - protected function _prepareId($id) + protected function prepareId($id) { return preg_replace('/[^a-zA-Z0-9_]/', '_', $id); } public function getIds() { - return $this->_zendCache->getIds(); + return $this->getZendCache()->getIds(); } } \ No newline at end of file diff --git a/lib/Xdoctrine/Common/Exception.php b/lib/Xdoctrine/Common/Exception.php new file mode 100644 index 0000000..e596cc5 --- /dev/null +++ b/lib/Xdoctrine/Common/Exception.php @@ -0,0 +1,16 @@ +<?php + +/** + * Xdoctrine - Sirprize's Doctrine2 Extensions + * + * @package Xdoctrine + * @copyright Copyright (c) 2010, Christian Hoegl, Switzerland (http://sirprize.me) + * @license New BSD License + */ + + +namespace Xdoctrine\Common; + + +class Exception extends \Exception +{} \ No newline at end of file
sirprize/xdoctrine
efb750170de6fff428be3303f8c6a17345ede656
add exception class and adjust copyright info
diff --git a/lib/Xdoctrine/Common/Cache/ZendCache.php b/lib/Xdoctrine/Common/Cache/ZendCache.php index 440888d..77594eb 100644 --- a/lib/Xdoctrine/Common/Cache/ZendCache.php +++ b/lib/Xdoctrine/Common/Cache/ZendCache.php @@ -1,93 +1,90 @@ <?php /** * Xdoctrine - Sirprize's Doctrine2 Extensions * - * LICENSE - * - * This source file is subject to the new BSD license that is bundled - * with this package in the file LICENSE.txt. - * - * @package Xzend - * @copyright Copyright (c) 2009, Christian Hoegl, Switzerland (http://sitengine.org) - * @license http://sitengine.org/license/new-bsd New BSD License + * @package Xdoctrine + * @copyright Copyright (c) 2010, Christian Hoegl, Switzerland (http://sirprize.me) + * @license New BSD License */ namespace Xdoctrine\Common\Cache; -#require_once 'Doctrine/Common/Cache/AbstractCache.php'; - - class ZendCache extends \Doctrine\Common\Cache\AbstractCache { /** * @var \Zend_Cache_Core */ private $_zendCache; /** * Sets the \Zend_Cache_Core instance to use. * * @param \Zend_Cache_Core $zendCache */ public function setZendCache(\Zend_Cache_Core $zendCache) { $this->_zendCache = $zendCache; } /** * Gets the \Zend_Cache_Core instance used by the cache. * * @return \Zend_Cache_Core */ public function getZendCache() { + if($this->_zendCache === null) + { + throw new \Xdoctrine\DBAL\Exception('call setZendCache() before '.__METHOD__); + } + return $this->_zendCache; } /** * {@inheritdoc} */ protected function _doFetch($id) { return $this->_zendCache->load($this->_prepareId($id)); } /** * {@inheritdoc} */ protected function _doContains($id) { return (bool) $this->_zendCache->test($this->_prepareId($id)); } /** * {@inheritdoc} */ protected function _doSave($id, $data, $lifeTime = false) { return $this->_zendCache->save($data, $this->_prepareId($id), array(), $lifeTime); } /** * {@inheritdoc} */ protected function _doDelete($id) { return $this->_zendCache->remove($this->_prepareId($id)); } protected function _prepareId($id) { return preg_replace('/[^a-zA-Z0-9_]/', '_', $id); } public function getIds() { return $this->_zendCache->getIds(); } } \ No newline at end of file diff --git a/lib/Xdoctrine/DBAL/Exception.php b/lib/Xdoctrine/DBAL/Exception.php new file mode 100644 index 0000000..6380814 --- /dev/null +++ b/lib/Xdoctrine/DBAL/Exception.php @@ -0,0 +1,16 @@ +<?php + +/** + * Xdoctrine - Sirprize's Doctrine2 Extensions + * + * @package Xdoctrine + * @copyright Copyright (c) 2010, Christian Hoegl, Switzerland (http://sirprize.me) + * @license New BSD License + */ + + +namespace Xdoctrine\DBAL; + + +class Exception extends \Exception +{} \ No newline at end of file diff --git a/lib/Xdoctrine/DBAL/Logging/ZendSQLLogger.php b/lib/Xdoctrine/DBAL/Logging/ZendSQLLogger.php index ba97060..cd90466 100644 --- a/lib/Xdoctrine/DBAL/Logging/ZendSQLLogger.php +++ b/lib/Xdoctrine/DBAL/Logging/ZendSQLLogger.php @@ -1,72 +1,69 @@ <?php /** * Xdoctrine - Sirprize's Doctrine2 Extensions * - * LICENSE - * - * This source file is subject to the new BSD license that is bundled - * with this package in the file LICENSE.txt. - * - * @package Xzend - * @copyright Copyright (c) 2009, Christian Hoegl, Switzerland (http://sitengine.org) - * @license http://sitengine.org/license/new-bsd New BSD License + * @package Xdoctrine + * @copyright Copyright (c) 2010, Christian Hoegl, Switzerland (http://sirprize.me) + * @license New BSD License */ namespace Xdoctrine\DBAL\Logging; -#require_once 'Doctrine/DBAL/Logging/SQLLogger.php'; - - class ZendSQLLogger implements \Doctrine\DBAL\Logging\SQLLogger { /** * @var \Zend_Log */ - private $_zendLog; + private $_zendLog = null; /** * Sets the \Zend_Log instance to use. * * @param \Zend_Log $zendLog */ public function setZendLog(\Zend_Log $zendLog) { $this->_zendLog = $zendLog; } /** * Gets the \Zend_Log instance used by the cache. * * @return \Zend_Log */ public function getZendLog() { + if($this->_zendLog === null) + { + throw new \Xdoctrine\DBAL\Exception('call setZendLog() before '.__METHOD__); + } + return $this->_zendLog; } public function startQuery($sql, array $params = null, array $types = null) { $p = ''; foreach($params as $k => $v) { if(is_object($v)) { continue; } $p .= (($p) ? ', ' : '').$k.' => '.$v; } $this->getZendLog()->debug($sql); $this->getZendLog()->debug("PARAMS: $p"); } public function stopQuery() {} } \ No newline at end of file diff --git a/lib/Xdoctrine/ORM/Event/Listener/Abstrakt.php b/lib/Xdoctrine/ORM/Event/Listener/Abstrakt.php index 36184f6..687763c 100644 --- a/lib/Xdoctrine/ORM/Event/Listener/Abstrakt.php +++ b/lib/Xdoctrine/ORM/Event/Listener/Abstrakt.php @@ -1,121 +1,113 @@ <?php /** * Xdoctrine - Sirprize's Doctrine2 Extensions * - * LICENSE - * - * This source file is subject to the new BSD license that is bundled - * with this package in the file LICENSE.txt. - * - * @package Xzend - * @copyright Copyright (c) 2009, Christian Hoegl, Switzerland (http://sitengine.org) - * @license http://sitengine.org/license/new-bsd New BSD License + * @package Xdoctrine + * @copyright Copyright (c) 2010, Christian Hoegl, Switzerland (http://sirprize.me) + * @license New BSD License */ namespace Xdoctrine\Orm\Event\Listener; -#require_once 'Xdoctrine/ORM/Event/Listener/Interfaze.php'; - - abstract class Abstrakt implements \Xdoctrine\ORM\Event\Listener\Interfaze { protected $_queue = array(); protected $_entityClassName = null; protected $_events = array(); public function __construct($entityClassName) { $this->_entityClassName = $entityClassName; } public function getEvents() { return $this->_events; } public function getQueue() { return $this->_queue; } public function isQueued($id) { return isset($this->_queue[$id]); } public function hasError($id) { return (isset($this->_queue[$id]) && $this->_queue[$id] == 0); } public function isFlushOk() { foreach($this->_queue as $item) { if($item == 0) { return false; } } return true; } public function isFlushError() { foreach($this->_queue as $item) { if($item == 0) { return true; } } return false; } public function countFlushOks() { $ok = 0; foreach($this->_queue as $item) { if($item == 1) { $ok++; } } return $ok; } public function countFlushErrors() { $errors = 0; foreach($this->_queue as $item) { if($item == 0) { $errors++; } } return $errors; } } \ No newline at end of file diff --git a/lib/Xdoctrine/ORM/Event/Listener/Interfaze.php b/lib/Xdoctrine/ORM/Event/Listener/Interfaze.php index c09e745..3824625 100644 --- a/lib/Xdoctrine/ORM/Event/Listener/Interfaze.php +++ b/lib/Xdoctrine/ORM/Event/Listener/Interfaze.php @@ -1,24 +1,19 @@ <?php /** * Xdoctrine - Sirprize's Doctrine2 Extensions * - * LICENSE - * - * This source file is subject to the new BSD license that is bundled - * with this package in the file LICENSE.txt. - * - * @package Xzend - * @copyright Copyright (c) 2009, Christian Hoegl, Switzerland (http://sitengine.org) - * @license http://sitengine.org/license/new-bsd New BSD License + * @package Xdoctrine + * @copyright Copyright (c) 2010, Christian Hoegl, Switzerland (http://sirprize.me) + * @license New BSD License */ namespace Xdoctrine\Orm\Event\Listener; interface Interfaze { public function getEvents(); } \ No newline at end of file diff --git a/lib/Xdoctrine/ORM/Event/Listener/Persists.php b/lib/Xdoctrine/ORM/Event/Listener/Persists.php index f152613..8a15710 100644 --- a/lib/Xdoctrine/ORM/Event/Listener/Persists.php +++ b/lib/Xdoctrine/ORM/Event/Listener/Persists.php @@ -1,50 +1,42 @@ <?php /** * Xdoctrine - Sirprize's Doctrine2 Extensions * - * LICENSE - * - * This source file is subject to the new BSD license that is bundled - * with this package in the file LICENSE.txt. - * - * @package Xzend - * @copyright Copyright (c) 2009, Christian Hoegl, Switzerland (http://sitengine.org) - * @license http://sitengine.org/license/new-bsd New BSD License + * @package Xdoctrine + * @copyright Copyright (c) 2010, Christian Hoegl, Switzerland (http://sirprize.me) + * @license New BSD License */ namespace Xdoctrine\ORM\Event\Listener; -#require_once 'Xdoctrine/ORM/Event/Listener/Abstrakt.php'; - - class Persists extends \Xdoctrine\ORM\Event\Listener\Abstrakt { protected $_events = array( \Doctrine\ORM\Events::prePersist, \Doctrine\ORM\Events::postPersist ); public function prePersist(\Doctrine\ORM\Event\LifecycleEventArgs $eventArgs) { if($eventArgs->getEntity() instanceof $this->_entityClassName) { $this->_queue[$eventArgs->getEntity()->getId()] = 0; } } public function postPersist(\Doctrine\ORM\Event\LifecycleEventArgs $eventArgs) { if($eventArgs->getEntity() instanceof $this->_entityClassName) { $this->_queue[$eventArgs->getEntity()->getId()] = 1; } } } \ No newline at end of file diff --git a/lib/Xdoctrine/ORM/Event/Listener/Removes.php b/lib/Xdoctrine/ORM/Event/Listener/Removes.php index 1c1a6e1..e97349a 100644 --- a/lib/Xdoctrine/ORM/Event/Listener/Removes.php +++ b/lib/Xdoctrine/ORM/Event/Listener/Removes.php @@ -1,50 +1,42 @@ <?php /** * Xdoctrine - Sirprize's Doctrine2 Extensions * - * LICENSE - * - * This source file is subject to the new BSD license that is bundled - * with this package in the file LICENSE.txt. - * - * @package Xzend - * @copyright Copyright (c) 2009, Christian Hoegl, Switzerland (http://sitengine.org) - * @license http://sitengine.org/license/new-bsd New BSD License + * @package Xdoctrine + * @copyright Copyright (c) 2010, Christian Hoegl, Switzerland (http://sirprize.me) + * @license New BSD License */ namespace Xdoctrine\ORM\Event\Listener; -#require_once 'Xdoctrine/ORM/Event/Listener/Abstrakt.php'; - - class Removes extends \Xdoctrine\ORM\Event\Listener\Abstrakt { protected $_events = array( \Doctrine\ORM\Events::preRemove, \Doctrine\ORM\Events::postRemove ); public function preRemove(\Doctrine\ORM\Event\LifecycleEventArgs $eventArgs) { if($eventArgs->getEntity() instanceof $this->_entityClassName) { $this->_queue[$eventArgs->getEntity()->getId()] = 0; } } public function postRemove(\Doctrine\ORM\Event\LifecycleEventArgs $eventArgs) { if($eventArgs->getEntity() instanceof $this->_entityClassName) { $this->_queue[$eventArgs->getEntity()->getId()] = 1; } } } \ No newline at end of file diff --git a/lib/Xdoctrine/ORM/Event/Listener/Updates.php b/lib/Xdoctrine/ORM/Event/Listener/Updates.php index c845fcb..17e9544 100644 --- a/lib/Xdoctrine/ORM/Event/Listener/Updates.php +++ b/lib/Xdoctrine/ORM/Event/Listener/Updates.php @@ -1,50 +1,42 @@ <?php /** * Xdoctrine - Sirprize's Doctrine2 Extensions * - * LICENSE - * - * This source file is subject to the new BSD license that is bundled - * with this package in the file LICENSE.txt. - * - * @package Xzend - * @copyright Copyright (c) 2009, Christian Hoegl, Switzerland (http://sitengine.org) - * @license http://sitengine.org/license/new-bsd New BSD License + * @package Xdoctrine + * @copyright Copyright (c) 2010, Christian Hoegl, Switzerland (http://sirprize.me) + * @license New BSD License */ namespace Xdoctrine\ORM\Event\Listener; -#require_once 'Xdoctrine/ORM/Event/Listener/Abstrakt.php'; - - class Updates extends \Xdoctrine\ORM\Event\Listener\Abstrakt { protected $_events = array( \Doctrine\ORM\Events::preUpdate, \Doctrine\ORM\Events::postUpdate ); public function preUpdate(\Doctrine\ORM\Event\PreUpdateEventArgs $eventArgs) { if($eventArgs->getEntity() instanceof $this->_entityClassName) { $this->_queue[$eventArgs->getEntity()->getId()] = 0; } } public function postUpdate(\Doctrine\ORM\Event\LifecycleEventArgs $eventArgs) { if($eventArgs->getEntity() instanceof $this->_entityClassName) { $this->_queue[$eventArgs->getEntity()->getId()] = 1; } } } \ No newline at end of file