text:
make[1]: Entering directory `/home/john/Dropbox/workspace/twig.js'

Twig.js Control Structures ->

if tag ->

should parse the contents of the if block if the expression is true

var test_template = twig({data: '{% if test %}true{% endif%}'});
test_template.render({test: true}).should.equal("true" );
test_template.render({test: false}).should.equal("" );

should call the if or else blocks based on the expression result

var test_template = twig({data: '{% if test %}true{% endif%}'});
test_template.render({test: true}).should.equal("true" );
test_template.render({test: false}).should.equal("" );

should support elseif

var test_template = twig({data: '{% if test %}1{% elseif other %}2{%else%}3{% endif%}'});
test_template.render({test: true, other:false}).should.equal("1" );
test_template.render({test: true, other:true}).should.equal("1" );
test_template.render({test: false, other:true}).should.equal("2" );
test_template.render({test: false, other:false}).should.equal("3" );

should be able to nest

var test_template = twig({data: '{% if test %}{% if test2 %}true{% else %}false{% endif%}{% else %}not{% endif%}'});
test_template.render({test: true, test2: true}).should.equal("true" );
test_template.render({test: true, test2: false}).should.equal("false" );
test_template.render({test: false, test2: true}).should.equal("not" );
test_template.render({test: false, test2: false}).should.equal("not" );

for tag ->

should provide value only for array input

var test_template = twig({data: '{% for value in test %}{{ value }}{% endfor %}'});
test_template.render({test: [1,2,3,4]}).should.equal("1234" );
test_template.render({test: []}).should.equal("" );

should provide both key and value for array input

var test_template = twig({data: '{% for key,value in test %}{{key}}:{{ value }}{% endfor %}'});
test_template.render({test: [1,2,3,4]}).should.equal("0:11:22:33:4" );
test_template.render({test: []}).should.equal("" );

should provide value only for object input

var test_template = twig({data: '{% for value in test %}{{ value }}{% endfor %}'});
test_template.render({test: {one: 1, two: 2, three: 3}}).should.equal("123" );
test_template.render({test: {}}).should.equal("" );

should provide both key and value for object input

var test_template = twig({data: '{% for key, value in test %}{{key}}:{{ value }}{% endfor %}'});
test_template.render({test: {one: 1, two: 2, three: 3}}).should.equal("one:1two:2three:3" );
test_template.render({test: {}}).should.equal("" );

should support else if the input is empty

var test_template = twig({data: '{% for key,value in test %}{{ value }}{% else %}else{% endfor %}'});
test_template.render({test: [1,2,3,4]}).should.equal("1234" );
test_template.render({test: []}).should.equal("else" );

should be able to nest

var test_template = twig({data: '{% for key,list in test %}{% for val in list %}{{ val }}{%endfor %}.{% else %}else{% endfor %}'});
test_template.render({test: [[1,2],[3,4],[5,6]]}).should.equal("12.34.56." );
test_template.render({test: []}).should.equal("else" );

should have a loop context item available for arrays

var test_template = twig({data: '{% for key,value in test %}{{ loop.index }}{% endfor %}'});
test_template.render({test: [1,2,3,4]}).should.equal("1234" );
test_template = twig({data: '{% for key,value in test %}{{ loop.index0 }}{% endfor %}'});
test_template.render({test: [1,2,3,4]}).should.equal("0123" );
test_template = twig({data: '{% for key,value in test %}{{ loop.revindex }}{% endfor %}'});
test_template.render({test: [1,2,3,4]}).should.equal("4321" );
test_template = twig({data: '{% for key,value in test %}{{ loop.revindex0 }}{% endfor %}'});
test_template.render({test: [1,2,3,4]}).should.equal("3210" );
test_template = twig({data: '{% for key,value in test %}{{ loop.length }}{% endfor %}'});
test_template.render({test: [1,2,3,4]}).should.equal("4444" );
test_template = twig({data: '{% for key,value in test %}{{ loop.first }}{% endfor %}'});
test_template.render({test: [1,2,3,4]}).should.equal("truefalsefalsefalse" );
test_template = twig({data: '{% for key,value in test %}{{ loop.last }}{% endfor %}'});
test_template.render({test: [1,2,3,4]}).should.equal("falsefalsefalsetrue" );

should have a loop context item available for objects

var test_template = twig({data: '{% for key,value in test %}{{ loop.index }}{% endfor %}'});
test_template.render({test: {a:1,b:2,c:3,d:4}}).should.equal("1234" );
test_template = twig({data: '{% for key,value in test %}{{ loop.index0 }}{% endfor %}'});
test_template.render({test: {a:1,b:2,c:3,d:4}}).should.equal("0123" );
test_template = twig({data: '{% for key,value in test %}{{ loop.revindex }}{% endfor %}'});
test_template.render({test: {a:1,b:2,c:3,d:4}}).should.equal("4321" );
test_template = twig({data: '{% for key,value in test %}{{ loop.revindex0 }}{% endfor %}'});
test_template.render({test: {a:1,b:2,c:3,d:4}}).should.equal("3210" );
test_template = twig({data: '{% for key,value in test %}{{ loop.length }}{% endfor %}'});
test_template.render({test: {a:1,b:2,c:3,d:4}}).should.equal("4444" );
test_template = twig({data: '{% for key,value in test %}{{ loop.first }}{% endfor %}'});
test_template.render({test: {a:1,b:2,c:3,d:4}}).should.equal("truefalsefalsefalse" );
test_template = twig({data: '{% for key,value in test %}{{ loop.last }}{% endfor %}'});
test_template.render({test: {a:1,b:2,c:3,d:4}}).should.equal("falsefalsefalsetrue" );

Twig.js Core ->

should save and load a template by reference

        // Define and save a template
        twig({
            id:   'test',
            data: '{{ "test" }}'
        });

        // Load and render the template
        twig({ref: 'test'}).render()
                .should.equal("test");

should be able to parse output tags with tag ends in strings

// Really all we care about here is not throwing exceptions.
twig({data: '{{ "test" }}'}).render().should.equal("test");
twig({data: '{{ " }} " }}'}).render().should.equal(" }} ");
twig({data: '{{ " \\"}} " }}'}).render().should.equal(' "}} ');
twig({data: "{{ ' }} ' }}"}).render().should.equal(" }} ");
twig({data: "{{ ' \\'}} ' }}"}).render().should.equal(" '}} ");

twig({data: '{{ " \'}} " }}'}).render().should.equal(" '}} ");
twig({data: "{{ ' \"}} ' }}"}).render().should.equal(' "}} ');

should be able to output numbers

twig({data: '{{ 12 }}'}).render().should.equal( "12" );
twig({data: '{{ 12.64 }}'}).render().should.equal( "12.64" );
twig({data: '{{ 0.64 }}'}).render().should.equal("0.64" );

should be able to output booleans

twig({data: '{{ true }}'}).render().should.equal( "true" );
twig({data: '{{ false }}'}).render().should.equal( "false" );

should be able to output strings

twig({data: '{{ "double" }}'}).render().should.equal("double");
twig({data: "{{ 'single' }}"}).render().should.equal('single');
twig({data: '{{ "dou\'ble" }}'}).render().should.equal("dou'ble");
twig({data: "{{ 'sin\"gle' }}"}).render().should.equal('sin"gle');
twig({data: '{{ "dou\\"ble" }}'}).render().should.equal("dou\"ble");
twig({data: "{{ 'sin\\'gle' }}"}).render().should.equal("sin'gle");

should be able to output arrays

twig({data: '{{ [1] }}'}).render().should.equal("1" );
twig({data: '{{ [1,2 ,3 ] }}'}).render().should.equal("1,2,3" );
twig({data: '{{ [1,2 ,3 , val ] }}'}).render({val: 4}).should.equal("1,2,3,4" );
twig({data: '{{ ["[to",\'the\' ,"string]" ] }}'}).render().should.equal('[to,the,string]' );
twig({data: '{{ ["[to",\'the\' ,"str\\"ing]" ] }}'}).render().should.equal('[to,the,str"ing]' );

should be able to output parse expressions in an array

twig({data: '{{ [1,2 ,1+2 ] }}'}).render().should.equal("1,2,3" );
twig({data: '{{ [1,2 ,3 , "-", [4,5, 6] ] }}'}).render({val: 4}).should.equal("1,2,3,-,4,5,6" );
twig({data: '{{ [a,b ,(1+2) * a ] }}'}).render({a:1,b:2}).should.equal("1,2,3" );

should be able to output variables

twig({data: '{{ orp }}'}).render({ orp: "test"}).should.equal("test");
twig({data: '{{ val }}'}).render({ val: function() {
                                              return "test"
                                          }}).should.equal("test");

should recognize null

twig({data: '{{ null == val }}'}).render({val: null}).should.equal( "true" );
twig({data: '{{ null == val }}'}).render({val: undefined}).should.equal( "true" );

twig({data: '{{ null == val }}'}).render({val: "test"}).should.equal( "false" );
twig({data: '{{ null == val }}'}).render({val: 0}).should.equal( "false" );
twig({data: '{{ null == val }}'}).render({val: false}).should.equal( "false" );

should recognize null in an object

twig({data: '{% set at = {"foo": null} %}{{ at.foo == val }}'}).render({val: null}).should.equal( "true" );

Key Notation ->

should support dot key notation

twig({data: '{{ key.value }} {{ key.sub.test }}'}).render({
    key: {
        value: "test",
        sub: {
            test: "value"
        }
    }
}).should.equal("test value");

should support square bracket key notation

twig({data: '{{ key["value"] }} {{ key[\'sub\']["test"] }}'}).render({
    key: {
        value: "test",
        sub: {
            test: "value"
        }
    }
}).should.equal("test value");

should support mixed dot and bracket key notation

twig({data: '{{ key["value"] }} {{ key.sub[key.value] }} {{ s.t["u"].v["w"] }}'}).render({
    key: {
        value: "test",
        sub: {
            test: "value"
        }
    },
    s: { t: { u: { v: { w: 'x' } } } }
}).should.equal("test value x" );

should support dot key notation after a function

var test_template = twig({data: '{{ key.fn().value }}'});
var output = test_template.render({
    key: {
        fn: function() {
            return {
                value: "test"
            }
        }
    }
});
output.should.equal("test");

should support bracket key notation after a function

var test_template = twig({data: '{{ key.fn()["value"] }}'});
var output = test_template.render({
    key: {
        fn: function() {
            return {
                value: "test 2"
            }
        }
    }
});
output.should.equal("test 2");

should check for getKey methods if a key doesn't exist.

twig({data: '{{ obj.value }}'}).render({
    obj: {
        getValue: function() {
            return "val";
        },
        isValue: function() {
            return "not val";
        }
    }
}).should.equal("val");

should check for isKey methods if a key doesn't exist.

twig({data: '{{ obj.value }}'}).render({
    obj: {
        isValue: function() {
            return "val";
        }
    }
}).should.equal("val");

should check for getKey methods on prototype objects.

			var object = {
                getValue: function() {
                    return "val";
                }
            };
			function Subobj() {};
			Subobj.prototype = object;
			var subobj = new Subobj();

            twig({data: '{{ obj.value }}'}).render({
                obj: subobj
            }).should.equal("val");

should return null if a period key doesn't exist.

twig({data: '{{ obj.value == null }}'}).render({
    obj: {}
}).should.equal("true");

should return null if a bracket key doesn't exist.

twig({data: '{{ obj["value"] == null }}'}).render({
    obj: {}
}).should.equal("true");

Twig.js Expressions ->

Basic Operators ->

should add numbers

var test_template = twig({data: '{{ a + b }}'});
numeric_test_data.forEach(function(pair) {
    var output = test_template.render(pair);
    output.should.equal( (pair.a + pair.b).toString() );
});

should subtract numbers

var test_template = twig({data: '{{ a - b }}'});
numeric_test_data.forEach(function(pair) {
    var output = test_template.render(pair);
    output.should.equal( (pair.a - pair.b).toString() );
});

should multiply numbers

var test_template = twig({data: '{{ a * b }}'});
numeric_test_data.forEach(function(pair) {
    var output = test_template.render(pair);
    output.should.equal((pair.a * pair.b).toString() );
});

should divide numbers

var test_template = twig({data: '{{ a / b }}'});
numeric_test_data.forEach(function(pair) {
    var output = test_template.render(pair);
    output.should.equal((pair.a / pair.b).toString() );
});

should divide numbers and return an int result

var test_template = twig({data: '{{ a // b }}'});
numeric_test_data.forEach(function(pair) {
    var output = test_template.render(pair);
    // Get expected truncated result
    var c = parseInt(pair.a/pair.b);

    output.should.equal(c.toString() );
});

should raise numbers to a power

var test_template = twig({data: '{{ a ** b }}'});
var pow_test_data = [
    {a: 2, b:3, c: 8}
    , {a: 4, b:.5, c: 2}
    , {a: 5, b: 1, c: 5}
];
pow_test_data.forEach(function(pair) {
    var output = test_template.render(pair);
    output.should.equal(pair.c.toString() );
});

should concatanate values

twig({data: '{{ "test" ~ a }}'}).render({a:1234}).should.equal("test1234");
twig({data: '{{ a ~ "test" ~ a }}'}).render({a:1234}).should.equal("1234test1234");
twig({data: '{{ "this" ~ "test" }}'}).render({a:1234}).should.equal("thistest");

// Test numbers
var test_template = twig({data: '{{ a ~ b }}'});
numeric_test_data.forEach(function(pair) {
    var output = test_template.render(pair);
    output.should.equal(pair.a.toString() + pair.b.toString());
});
// Test strings
test_template = twig({data: '{{ a ~ b }}'});
string_data.forEach(function(pair) {
    var output = test_template.render(pair);
    output.should.equal(pair.a.toString() + pair.b.toString());
});

should handle multiple chained operations

var data = {a: 4.5, b: 10, c: 12,  d: -0.25, e:0, f: 65,  g: 21, h: -0.0002};
var test_template = twig({data: '{{a/b+c*d-e+f/g*h}}'});
var output = test_template.render(data);
var expected = data.a / data.b + data.c * data.d - data.e + data.f / data.g * data.h;
output.should.equal(expected.toString());

should handle parenthesis in chained operations

var data = {a: 4.5, b: 10, c: 12,  d: -0.25, e:0, f: 65,  g: 21, h: -0.0002};
var test_template = twig({data: '{{a   /(b+c )*d-(e+f)/(g*h)}}'});
var output = test_template.render(data);
var expected = data.a / (data.b + data.c) * data.d - (data.e + data.f) / (data.g * data.h);
output.should.equal(expected.toString());

Comparison Operators ->

should support less then

var test_template = twig({data: '{{ a < b }}'});
numeric_test_data.forEach(function(pair) {
    var output = test_template.render(pair);
    output.should.equal((pair.a < pair.b).toString() );
});

should support less then or equal

var test_template = twig({data: '{{ a <= b }}'});
numeric_test_data.forEach(function(pair) {
    var output = test_template.render(pair);
    output.should.equal((pair.a <= pair.b).toString() );
});

should support greater then

var test_template = twig({data: '{{ a > b }}'});
numeric_test_data.forEach(function(pair) {
    var output = test_template.render(pair);
    output.should.equal((pair.a > pair.b).toString() );
});

should support greater then or equal

var test_template = twig({data: '{{ a >= b }}'});
numeric_test_data.forEach(function(pair) {
    var output = test_template.render(pair);
    output.should.equal((pair.a >= pair.b).toString() );
});

should support equals

var test_template = twig({data: '{{ a == b }}'});
boolean_data.forEach(function(pair) {
    var output = test_template.render(pair);
    output.should.equal((pair.a == pair.b).toString() );
});
equality_data.forEach(function(pair) {
    var output = test_template.render(pair);
    output.should.equal((pair.a == pair.b).toString() );
});

should support not equals

var test_template = twig({data: '{{ a != b }}'});
boolean_data.forEach(function(pair) {
    var output = test_template.render(pair);
    output.should.equal((pair.a != pair.b).toString() );
});
equality_data.forEach(function(pair) {
    var output = test_template.render(pair);
    output.should.equal((pair.a != pair.b).toString() );
});

should support boolean or

var test_template = twig({data: '{{ a or b }}'});
boolean_data.forEach(function(pair) {
    var output = test_template.render(pair);
    output.should.equal((pair.a || pair.b).toString() );
});

should support boolean and

var test_template = twig({data: '{{ a and b }}'});
boolean_data.forEach(function(pair) {
    var output = test_template.render(pair);
    output.should.equal((pair.a && pair.b).toString() );
});

should support boolean not

var test_template = twig({data: '{{ not a }}'});
test_template.render({a:false}).should.equal(true.toString());
test_template.render({a:true}).should.equal(false.toString());

Other Operators ->

should support the ternary operator

var test_template = twig({data: '{{ a ? b:c }}'})
    , output_t = test_template.render({a: true,  b: "one", c: "two"})
    , output_f = test_template.render({a: false, b: "one", c: "two"});

output_t.should.equal( "one" );
output_f.should.equal( "two" );

should support the ternary operator with objects in it

var test_template2 = twig({data: '{{ (a ? {"a":e+f}:{"a":1}).a }}'})
    , output2 = test_template2.render({a: true, b: false, e: 1, f: 2});

output2.should.equal( "3" );

should support the ternary operator inside objects

var test_template2 = twig({data: '{{ {"b" : a or b ? {"a":e+f}:{"a":1} }.b.a }}'})
    , output2 = test_template2.render({a: false, b: false, e: 1, f: 2});

output2.should.equal( "1" );

should support in/containment functionality for arrays

var test_template = twig({data: '{{ "a" in ["a", "b", "c"] }}'});
test_template.render().should.equal(true.toString());

var test_template = twig({data: '{{ "d" in ["a", "b", "c"] }}'});
test_template.render().should.equal(false.toString());

should support not in/containment functionality for arrays

var test_template = twig({data: '{{ "a" not in ["a", "b", "c"] }}'});
test_template.render().should.equal(false.toString());

var test_template = twig({data: '{{ "d" not in ["a", "b", "c"] }}'});
test_template.render().should.equal(true.toString());

should support in/containment functionality for strings

var test_template = twig({data: '{{ "at" in "hat" }}'});
test_template.render().should.equal(true.toString());

var test_template = twig({data: '{{ "d" in "not" }}'});
test_template.render().should.equal(false.toString());

should support not in/containment functionality for strings

var test_template = twig({data: '{{ "at" not in "hat" }}'});
test_template.render().should.equal(false.toString());

var test_template = twig({data: '{{ "d" not in "not" }}'});
test_template.render().should.equal(true.toString());

should support in/containment functionality for objects

var test_template = twig({data: '{{ "value" in {"key" : "value", "2": "other"} }}'});
test_template.render().should.equal(true.toString());

var test_template = twig({data: '{{ "d" in {"key_a" : "no"} }}'});
test_template.render().should.equal(false.toString());

should support not in/containment functionality for objects

var test_template = twig({data: '{{ "value" not in {"key" : "value", "2": "other"} }}'});
test_template.render().should.equal(false.toString());

var test_template = twig({data: '{{ "d" not in {"key_a" : "no"} }}'});
test_template.render().should.equal(true.toString());

Twig.js Filters ->

should chain

var test_template = twig({data: '{{ ["a", "b", "c"]|keys|reverse }}' });
test_template.render().should.equal("2,1,0" );

url_encode ->

should encode URLs

var test_template = twig({data: '{{ "http://google.com/?q=twig.js"|url_encode() }}' });
test_template.render().should.equal("http%3A%2F%2Fgoogle.com%2F%3Fq%3Dtwig.js" );

json_encode ->

should encode strings to json

var test_template = twig({data: '{{ test|json_encode }}' });
test_template.render({test:'value'}).should.equal('"value"' );

should encode numbers to json

var test_template = twig({data: '{{ test|json_encode }}' });
test_template.render({test:21}).should.equal('21' );

should encode arrays to json

var test_template = twig({data: '{{ [1,"b",3]|json_encode }}' });
test_template.render().should.equal('[1,"b",3]' );

should encode objects to json

var test_template = twig({data: '{{ {"a":[1,"b",3]}|json_encode }}' });
test_template.render().should.equal('{"a":[1,"b",3]}' );

upper ->

should convert text to uppercase

var test_template = twig({data: '{{ "hello"|upper }}' });
test_template.render().should.equal("HELLO" );

lower ->

should convert text to lowercase

var test_template = twig({data: '{{ "HELLO"|lower }}' });
test_template.render().should.equal("hello" );

capitalize ->

should capitalize the first word in a string

var test_template = twig({data: '{{ "hello world"|capitalize }}' });
test_template.render().should.equal("Hello world" );

title ->

should capitalize all the words in a string

var test_template = twig({data: '{{ "hello world"|title }}' });
test_template.render().should.equal("Hello World" );

length ->

should determine the length of a string

var test_template = twig({data: '{{ "test"|length }}' });
test_template.render().should.equal("4");

should determine the length of an array

var test_template = twig({data: '{{ [1,2,4,76,"tesrt"]|length }}' });
test_template.render().should.equal("5");

should determine the length of an object

var test_template = twig({data: '{{ {"a": "b", "c": "1", "test": "test"}|length }}' });
test_template.render().should.equal("3");

sort ->

should sort an array

var test_template = twig({data: '{{ [1,5,2,7]|sort }}' });
test_template.render().should.equal("1,2,5,7" );

test_template = twig({data: '{{ ["test","abc",2,7]|sort }}' });
test_template.render().should.equal("2,7,abc,test" );

should sort an object

var test_template = twig({data: "{% set obj =  {'c': 1,'d': 5,'t': 2,'e':7}|sort %}{% for key,value in obj|sort %}{{key}}:{{value}} {%endfor %}" });
test_template.render().should.equal("c:1 t:2 d:5 e:7 " );

test_template = twig({data: "{% set obj = {'m':'test','z':'abc','a':2,'y':7} %}{% for key,value in obj|sort %}{{key}}:{{value}} {%endfor %}" });
test_template.render().should.equal("a:2 y:7 z:abc m:test " );

reverse ->

should reverse an array

var test_template = twig({data: '{{ ["a", "b", "c"]|reverse }}' });
test_template.render().should.equal("c,b,a" );

should reverse an object

keys ->

should return the keys of an array

var test_template = twig({data: '{{ ["a", "b", "c"]|keys }}' });
test_template.render().should.equal("0,1,2" );

should return the keys of an object

var test_template = twig({data: '{{ {"a": 1, "b": 4, "c": 5}|keys }}' });
test_template.render().should.equal("a,b,c" );

test_template = twig({data: '{{ {"0":"a", "1":"b", "2":"c"}|keys }}' });
test_template.render().should.equal("0,1,2" );

merge ->

should merge two objects into an object

// Object merging
var test_template = twig({data: '{% set obj= {"a":"test", "b":"1"}|merge({"b":2,"c":3}) %}{% for key in obj|keys|sort %}{{key}}:{{obj[key]}} {%endfor %}' });
test_template.render().should.equal('a:test b:2 c:3 ' );

should merge two arrays into and array

// Array merging
var test_template = twig({data: '{% set obj= ["a", "b"]|merge(["c", "d"]) %}{% for key in obj|keys|sort %}{{key}}:{{obj[key]}} {%endfor %}' });
test_template.render().should.equal('0:a 1:b 2:c 3:d ' );

should merge an object and an array into an object

// Mixed merging
var test_template = twig({data: '{% set obj= ["a", "b"]|merge({"a": "c", "3":4}, ["c", "d"]) %}{% for key in obj|keys|sort %}{{key}}:{{obj[key]}} {%endfor %}' });
test_template.render().should.equal('0:a 1:b 3:4 4:c 5:d a:c ' );

// Mixed merging(2)
test_template = twig({data: '{% set obj= {"1":"a", "a":"b"}|merge(["c", "d"]) %}{% for key in obj|keys %}{{key}}:{{obj[key]}} {%endfor %}' });
test_template.render().should.equal('1:a a:b 2:c 3:d ' );

join ->

should join all values in an object

var test_template = twig({data: '{{ {"a":"1", "b": "b", "c":test}|join("-") }}' });
test_template.render({"test": "t"}).should.equal("1-b-t" );

should joing all values in an array

var test_template = twig({data: '{{ [1,2,4,76]|join }}' });
test_template.render().should.equal("12476" );
test_template = twig({data: '{{ [1+ 5,2,4,76]|join("-" ~ ".") }}' });
test_template.render().should.equal("6-.2-.4-.76" );

default ->

should not provide the default value if a key is defined and not empty

var test_template = twig({data: '{{ var|default("Not Defined") }}' });
test_template.render({"var":"value"}).should.equal("value" );

should provide a default value if a key is not defined

var test_template = twig({data: '{{ var|default("Not Defined") }}' });
test_template.render().should.equal("Not Defined" );

should provide a default value if a value is empty

var test_template = twig({data: '{{ ""|default("Empty String") }}' });
test_template.render().should.equal("Empty String" );

test_template = twig({data: '{{ var.key|default("Empty Key") }}' });
test_template.render({'var':{}}).should.equal("Empty Key" );

date ->

should recognize timestamps

           var template = twig({data: '{{ 27571323556134|date("d/m/Y @ H:i:s") }}'})
               , date = new Date(27571323556134); // 13/09/2843 @ 08:59:16 EST

           template.render().should.equal( stringDate(date) );

should recognize string date formats

           var template = twig({data: '{{ "Tue Aug 14 08:52:15 +0000 2007"|date("d/m/Y @ H:i:s") }}'})
               , date = new Date(1187081535000); // 14/08/2007 @ 04:52:15 EST

           template.render().should.equal( stringDate(date) );

replace ->

should replace strings provided in a map

var template = twig({data: '{{ "I like %this% and %that%."|replace({"%this%": foo, "%that%": "bar"}) }}'});
template.render({foo: "foo"}).should.equal("I like foo and bar." );

format ->

should replace formatting tags with parameters

var template = twig({data: '{{ "I like %s and %s."|format(foo, "bar") }}'});
template.render({foo: "foo"}).should.equal("I like foo and bar." );

striptags ->

should remove tags from a value

var template = twig({data: '{{ "<p>Test paragraph.</p><!-- Comment --> <a href=\\"#fragment\\">Other text</a>"|striptags }}'});
template.render().should.equal("Test paragraph. Other text" );

escape ->

should convert unsafe characters to HTML entities

var template = twig({data: '{{ "<p>Test paragraph.</p><!-- Comment --> <a href=\'#fragment\'>Other text</a>"|escape }}'});
template.render().should.equal("&lt;p&gt;Test paragraph.&lt;/p&gt;&lt;!-- Comment --&gt; &lt;a href=&#039;#fragment\&#039;&gt;Other text&lt;/a&gt;" );

e ->

should alias escape function with e

var template = twig({data: '{{ "<p>Test paragraph.</p><!-- Comment --> <a href=\'#fragment\'>Other text</a>"|e }}'});
template.render().should.equal("&lt;p&gt;Test paragraph.&lt;/p&gt;&lt;!-- Comment --&gt; &lt;a href=&#039;#fragment\&#039;&gt;Other text&lt;/a&gt;" );

nl2br ->

should convert newlines into html breaks

var template = twig({data: '{{ test|nl2br }}'});
template.render({ test: 'Line 1\r\nLine 2\nLine 3\rLine 4\n\n' }).should.equal("Line 1<br />Line 2<br />Line 3<br />Line 4<br /><br />");

trim ->

should trim whitespace from strings

var template = twig({data: '{{ test|trim }}'});
template.render({ test: '\r\n Test\n  ' }).should.equal("Test");

number_format ->

should round to nearest integer if no parameters

var template = twig({data: '{{ 1234.56|number_format }}'});
template.render().should.equal("1,235");

should have customizable decimal points

var template = twig({data: '{{ 1234.567890123|number_format(4) }}'});
template.render().should.equal("1,234.5679");

should have customizable decimal seperator

var template = twig({data: '{{ 1234.567890123|number_format(2,",") }}'});
template.render().should.equal("1,234,57");

should have customizable thousands seperator

var template = twig({data: '{{ 1234.5678|number_format(2,","," ") }}'});
template.render().should.equal("1 234,57");

Twig.js Loader ->

should load a template from the filesystem asynchronously

twig({
    id:   'fs-node-async',
    path: 'test/templates/test.twig',
    load: function(template) {
        // Render the template
        template.render({
            test: "yes",
            flag: true
        }).should.equal("Test template = yes\n\nFlag set!");

        done();
    }
});

should load a template from the filesystem synchronously

var template = twig({
    id:   'fs-node-sync',
    path: 'test/templates/test.twig',
    async: false
});
// Render the template
template.render({
    test: "yes",
    flag: true
}).should.equal("Test template = yes\n\nFlag set!");

Twig.js Blocks ->

should load a parent template and render the default values

twig({
    id:   'remote-no-extends',
    path: 'test/templates/template.twig',
    async: false
});

// Load the template
twig({ref: 'remote-no-extends'}).render({ }).should.equal( "Default Title - body" );

should load a child template and replace the parent block's content

// Test loading a template from a remote endpoint
twig({
    id:   'child-extends',
    path: 'test/templates/child.twig',

    load: function(template) {
        template.render({ base: "template.twig" }).should.equal( "Other Title - child" );
        done();
    }
});

should have access to a parent block content

// Test loading a template from a remote endpoint
twig({
    id:   'child-parent',
    path: 'test/templates/child-parent.twig',

    load: function(template) {
        template.render({
            base: "template.twig",
            inner: ':value'
        }).should.equal( "Other Title - body:value:child" );
        done();
    }
});

should include blocks from another template for horizontal reuse

// Test horizontal reuse
twig({
    id:   'use',
    path: 'test/templates/use.twig',

    load: function(template) {
        // Load the template
        template.render({ place: "diner" }).should.equal("Coming soon to a diner near you!" );
        done();
    }
});

should make the contents of blocks available after they're rendered

// Test rendering and loading one block
twig({
    id:   'blocks',
    path: 'test/templates/blocks.twig',

    load: function(template) {
        // Render the template with the blocks parameter
        template.render({ place: "block" }, {output: 'blocks'}).msg.should.equal("Coming soon to a block near you!" );
        done();
    }
});

Twig.js Functions ->

should allow you to define a function

twig({data: '{{ square(a) }}'}).render({a:4}).should.equal("16");

should chain with other expressions

twig({data: '{{ square(a) + 4 }}'}).render({a:4}).should.equal("20");

should chain with filters

twig({data: '{{ echo(a)|default("foo") }}'}).render().should.equal("foo");

should work in for loop expressions

twig({data: '{% for i in list(1, 2, 3) %}{{ i }},{% endfor %}'}).render().should.equal("1,2,3,");

should be able to differentiate between a function and a variable

twig({data: '{{ square ( square ) + square }}'}).render({square: 2}).should.equal("6");

should work with boolean operations

twig({data: '{% if echo(true) or echo(false) %}yes{% endif %}'}).render().should.equal("yes");

should execute functions passed as context values

twig({
    data: '{{ value }}'
}).render({
    value: function() {
        return "test";
    }
}).should.equal("test");

should execute functions passed as context values with this mapped to the context

twig({
    data: '{{ value }}'
}).render({
    test: "value",
    value: function() {
        return this.test;
    }
}).should.equal("value");

should execute functions passed as context values with arguments

twig({
    data: '{{ value(1, "test") }}'
}).render({
    value: function(a, b, c) {
        return a + "-" + b + "-" + (c===undefined?"true":"false");
    }
}).should.equal("1-test-true");

should execute functions passed as context value parameters with this mapped to the context

twig({
    data: '{{ value }}'
}).render({
    test: "value",
    value: function() {
        return this.test;
    }
}).should.equal("value");

should execute functions passed as context object parameters

twig({
    data: '{{ obj.value }}'
}).render({
    obj: {
         value: function() {
            return "test";
        }
    }
}).should.equal("test");

should execute functions passed as context object parameters with arguments

twig({
    data: '{{ obj.value(1, "test") }}'
}).render({
    obj: {
         value: function(a, b, c) {
            return a + "-" + b + "-" + (c===undefined?"true":"false");
        }
    }
}).should.equal("1-test-true");

should execute functions passed as context object parameters

twig({
    data: '{{ obj["value"] }}'
}).render({
    obj: {
         value: function() {
            return "test";
        }
    }
}).should.equal("test");

should execute functions passed as context object parameters with arguments

twig({
    data: '{{ obj["value"](1, "test") }}'
}).render({
    obj: {
         value: function(a, b, c) {
            return a + "-" + b + "-" + (c===undefined?"true":"false");
        }
    }
}).should.equal("1-test-true");

Built-in Functions ->

range ->

should work over a range of numbers

twig({data: '{% for i in range(0, 3) %}{{ i }},{% endfor %}'}).render().should.equal("0,1,2,3,");

should work over a range of letters

twig({data: '{% for i in range("a", "c") %}{{ i }},{% endfor %}'}).render().should.equal("a,b,c,");

should work with an interval

twig({data: '{% for i in range(1, 15, 3) %}{{ i }},{% endfor %}'}).render().should.equal("1,4,7,10,13,");

should work with .. invocation

twig({data: '{% for i in 0..3 %}{{ i }},{% endfor %}'}).render().should.equal("0,1,2,3,");
twig({data: '{% for i in "a" .. "c" %}{{ i }},{% endfor %}'}).render().should.equal("a,b,c,");

cycle ->

should cycle through an array of values

twig({data: '{% for i in range(0, 3) %}{{ cycle(["odd", "even"], i) }};{% endfor %}'}).render().should.equal("odd;even;odd;even;");

date ->

should understand timestamps

var date = new Date(946706400 * 1000);
twig({data: '{{ date(946706400)|date("d/m/Y @ H:i:s") }}'}).render().should.equal(stringDate(date));

should understand relative dates

twig({data: '{{ date("+1 day") > date() }}'}).render().should.equal("true");
twig({data: '{{ date("-1 day") > date() }}'}).render().should.equal("false");

should understand exact dates

var date = new Date("June 20, 2010 UTC");

twig({data: '{{ date("June 20, 2010 UTC")|date("d/m/Y @ H:i:s") }}'}).render().should.equal(stringDate(date));

dump ->

should output formatted number

twig({data: '{{ dump(test) }}' }).render({ test: 5 }).should.equal('number(5)' + EOL);

should output formatted string

twig({data: '{{ dump(test) }}' }).render({ test: "String" }).should.equal('string(6) "String"' + EOL);

should output formatted boolean

twig({data: '{{ dump(test) }}' }).render({ test: true }).should.equal('bool(true)' + EOL);

should output formatted null

twig({data: '{{ dump(test) }}' }).render({ test: null }).should.equal('NULL' + EOL);

should output formatted object

twig({data: '{{ dump(test) }}' }).render({ test: {} }).should.equal('object(0) {' + EOL + '}' + EOL);

should output formatted array

twig({data: '{{ dump(test) }}' }).render({ test: [] }).should.equal('object(0) {' + EOL + '}' + EOL);

should output formatted undefined

twig({data: '{{ dump(test) }}' }).render({ test: undefined }).should.equal('undefined' + EOL);

Twig.js Tests ->

empty test ->

should identify numbers as not empty

// number
twig({data: '{{ 1 is empty }}'}).render().should.equal("false" );
twig({data: '{{ 0 is empty }}'}).render().should.equal("false" );

should identify empty strings

// String
twig({data: '{{ "" is empty }}'}).render().should.equal("true" );
twig({data: '{{ "test" is empty }}'}).render().should.equal("false" );

should identify empty arrays

// Array
twig({data: '{{ [] is empty }}'}).render().should.equal("true" );
twig({data: '{{ ["1"] is empty }}'}).render().should.equal("false" );

should identify empty objects

// Object
twig({data: '{{ {} is empty }}'}).render().should.equal("true" );
twig({data: '{{ {"a":"b"} is empty }}'}).render().should.equal("false" );
twig({data: '{{ {"a":"b"} is not empty }}'}).render().should.equal("true" );

odd test ->

should identify a number as odd

twig({data: '{{ (1 + 4) is odd }}'}).render().should.equal("true" );
twig({data: '{{ 6 is odd }}'}).render().should.equal("false" );

even test ->

should identify a number as even

twig({data: '{{ (1 + 4) is even }}'}).render().should.equal("false" );
twig({data: '{{ 6 is even }}'}).render().should.equal("true" );

divisibleby test ->

should determine if a number is divisible by the given number

twig({data: '{{ 5 is divisibleby(3) }}'}).render().should.equal("false" );
twig({data: '{{ 6 is divisibleby(3) }}'}).render().should.equal("true" );

defined test ->

should identify a key as defined if it exists in the render context

twig({data: '{{ key is defined }}'}).render().should.equal("false" );
twig({data: '{{ key is defined }}'}).render({key: "test"}).should.equal( "true" );

none test ->

should identify a key as none if it exists in the render context and is null

twig({data: '{{ key is none }}'}).render().should.equal("false");
twig({data: '{{ key is none }}'}).render({key: "test"}).should.equal("false");
twig({data: '{{ key is none }}'}).render({key: null}).should.equal("true");
twig({data: '{{ key is null }}'}).render({key: null}).should.equal("true");

sameas test ->

should identify the exact same type as true

twig({data: '{{ true is sameas(true) }}'}).render().should.equal("true");
twig({data: '{{ a is sameas(1) }}'}).render({a: 1}).should.equal("true");
twig({data: '{{ a is sameas("test") }}'}).render({a: "test"}).should.equal("true");
twig({data: '{{ a is sameas(true) }}'}).render({a: true}).should.equal("true");

should identify the different types as false

twig({data: '{{ false is sameas(true) }}'}).render().should.equal("false");
twig({data: '{{ true is sameas(1) }}'}).render().should.equal("false");
twig({data: '{{ false is sameas("") }}'}).render().should.equal("false");
twig({data: '{{ a is sameas(1) }}'}).render({a: "1"}).should.equal("false");

make[1]: Leaving directory `/home/john/Dropbox/workspace/twig.js'


text:
import path from 'path';
import express from 'express';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import compression from 'compression';
import morgan from 'morgan';

import httpProxy from 'express-http-proxy';

import log from './../helpers/log';

import accountApi from '../routes/api/account';
import tournamentApi from '../routes/api/tournament';
import matchApi from '../routes/api/match';
import teamApi from '../routes/api/team';
import statsApi from '../routes/api/stats';
import playerApi from '../routes/api/player';

import configuration from './configuration';
import passport from './passport/passport';

const indexRoute = require('../routes/index');

const STATS_BASE_URL_PREFIX = 'STATS_BASE_URL_';

const getStatsBaseUrl = () => {
  const env = configuration.OWN_NODE_ENV;
  return configuration[STATS_BASE_URL_PREFIX + env];
}

const NEG5_API_HOST_PROP = 'NEG5_API_HOST';

const ONE_DAY_MS = 1000 * 60 * 60 * 24;

export default () => {
  const app = express();

  if (configuration.OWN_NODE_ENV === 'PROD') {
      app.locals.pretty = false;
  }

  app.set('STATS_BASE_URL', getStatsBaseUrl());
  app.set(NEG5_API_HOST_PROP, process.env.NEG5_API_BASE_URL);

  log.INFO('STATS_BASE_URL : ' + app.get('STATS_BASE_URL'));
  log.INFO('NEG5_API_HOST: ' + app.get(NEG5_API_HOST_PROP));

  morgan.token('currentUser', (req, res) => {
    return req.currentUser || 'no-user-attached';
  });
  app.use(bodyParser.urlencoded({
    extended: true,
  }));
  app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
  });
  app.use(bodyParser.json());
  app.use('/neg5-api', httpProxy(app.get(NEG5_API_HOST_PROP), {
    proxyReqPathResolver: req => `/neg5-api${req.url}`,
  }));
  app.use(cookieParser());
  app.use(compression());
  app.use(passport.initialize());

  app.set('views', path.join(__dirname, '../../views'));
  app.set('view engine', 'jade');

  const cacheTime = process.env.NODE_ENV === 'production' ? parseInt(configuration.STATIC_ASSETS_CACHE_TIME_MS) || ONE_DAY_MS : 0;
  app.use(express.static(path.join(__dirname, '../../public'), { maxAge: cacheTime }));
  log.INFO('Set static cache time of: ' + cacheTime + 'ms');

  app.use((request, response, next) => {
    if (process.env.NODE_ENV === 'production') {
      if (request.headers['x-forwarded-proto'] !== 'https') {
        return response.redirect(`https://${request.headers.host}${request.url}`);
      }
      return next();
    }
    return next();
  });

  indexRoute(app);
  accountApi(app);
  tournamentApi(app);
  matchApi(app);
  teamApi(app);
  statsApi(app);
  playerApi(app);

  return app;
};

redpajama_set_name: RedPajamaGithub


text:
layout: single
author_profile: true
permalink: /cv/
---

# This is page 1


text:
from ciscoconfparse import CiscoConfParse

cisco_cfg = CiscoConfParse("cisco_ipsec.txt")

print cisco_cfg

cryptomaps = cisco_cfg.find_objects(r"^crypto map CRYPTO")

for i in cryptomaps:
   print "Crypto match: ",i.text
   for child in i.children:
      print child.text

print "\n### Matching PFS group2 only\n";

cryptomaps = cisco_cfg.find_objects_w_child(parentspec=r"^crypto map CRYPTO", childspec=r"pfs group2")

for i in cryptomaps:
   print "Crypto match: ",i.text
   for child in i.children:
      print child.text

print "\n### Maps not use AES:\n";

trans_sets = cisco_cfg.find_objects(r"crypto ipsec transform-set(?!.*esp-aes)")

import re

for i in trans_sets:
   #print "Crypto match: ",i.text
   tmp_transform_set = re.search(r'transform-set (.*?) esp-', i.text);
   #print "Match: ",tmp_transform_set.group(1);
   cryptomaps = cisco_cfg.find_objects_w_child(parentspec=r"^crypto map CRYPTO", childspec=tmp_transform_set.group(1));
   for i in cryptomaps:
      print "Crypto match: ",i.text
      for child in i.children:
         print child.text


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>UCR Libraries                                                    /All Locations</title>
<base target="_self"/>
<link href="/scripts/ProStyles.css" rel="stylesheet" type="text/css"/>
<link href="/screens/styles.css" rel="stylesheet" type="text/css"/>
<link href="/screens/favicon.ico" rel="shortcut icon" type="ximage/icon"/>

<meta content="1800;URL=/" http-equiv="Refresh"/>

<meta content="IE=8;FF=3;OtherUA=4" http-equiv="X-UA-Compatible"><meta content="text/html;charset=utf-8" http-equiv="Content-type"><link href="/screens/styles_print.css" media="print" rel="stylesheet" type="text/css">
</link></meta></meta>

<link href="/screens/sIFR-screen.css" media="screen" rel="stylesheet" type="text/css"/>
<link href="/screens/sIFR-print.css" media="print, projection" rel="stylesheet" type="text/css"/>
<link href="/screens/design6wide.css" media="screen" rel="stylesheet" type="text/css"/>
<link href="/screens/print6.css" media="print" rel="stylesheet" type="text/css"/>
<link href="/screens/sms.css" media="screen" rel="stylesheet" type="text/css"/>

<link href="/screens/helper.css" media="all" rel="stylesheet" type="text/css"/>
<link href="/screens/default.css" media="all" rel="stylesheet" type="text/css"/>
<link href="/screens/default.ultimate.css" media="all" rel="stylesheet" type="text/css"/>
<link href="/screens/ucrlibraries.css" rel="stylesheet" type="text/css"/>
<link href="/screens/font-awesome/css/font-awesome.css" media="screen" rel="stylesheet" type="text/css"/>

 Ask a Librarian

 My Accounts

 Connect From Off-Campus

 New Search

My Library Account

<form action="/patroninfo%7ES5" method="POST" name="patform" target="_self">
<fieldset>
<legend>
Please enter the following information:</legend>

If you haven't previously created a PIN, leave the PIN field blank and submit your information. You will then be asked to create your own PIN.
</fieldset></form>

Patron Barcode Number:

Enter your Barcode Number beginning with '21210' from your UCR/Library Card.

<input id="code" maxlength="128" name="code" size="40" type="PASSWORD" value="">
</input>

PIN

For example, enter "1234"

<input id="pin" maxlength="40" name="pin" size="40" type="PASSWORD" value="">
</input>

<input name="pat_submit" type="hidden" value="xxx"/>

Submit

When you finish, you should completely close all your browser windows to ensure your MyScotty session is ended.

Forgot Your PIN?
<input style="display:none" type="submit">
</input>

<link crossorigin="anonymous" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" integrity="sha384-T8Gy5hrqNKT+hzMclPo118YTQO6cYprQmhrYwIiQ/3axmI1hQomh7Ud2hPOy8SP1" rel="stylesheet">

<link href="https://www.stackmap.com/integration/ucr/StackMap.css" media="all" rel="stylesheet" type="text/css"/>

</link>


text:
<!DOCTYPE html>

    <?php echo $meta ?>

    <title><?php __(site()->title() . ' | Panel | ' . l('login')) ?></title>

    <?php echo assets::css() ?>

    <?php if($stylesheet = kirby()->option('panel.stylesheet')): ?>
    <?php echo css($stylesheet) ?>
    <?php endif ?>

  <body class="login grey <?php echo panel()->direction() ?>">

      <?php if($error): ?>

        <?php __($error) ?>
        ×

      <?php elseif($welcome): ?>

        <?php __($welcome) ?>
        ×

      <?php endif ?>

      <?php echo $form ?>

    <?php echo assets::js() ?>


text:
layout: docs_ui
title: Supersonic Documentation
header_title: Supersonic UI
header_sub_title: Learn how to build beautiful mobile apps with the Supersonic UI framework.
parent_id: supersonic
section_id: ui
---

<section class="docs-section" id="overview">
# Supersonic UI

This section will teach you how to utilise Supersonic components in your app. Supersonic provides access to a huge number of UI components, with special native implementations for some core components, such as the navigation and tab bars. All Supersonic components (even the native ones) can be styled with CSS, but be aware that native styling is kept separate from your basic CSS. To learn more about available components, check out the guides:

  - [CSS components][css-components]
  - [Native components][native-components]
  - [Styling native components][styling-native-components]

Besides the CSS and native components, your app's UI is influnced by:

  - [The Splashscreen][splashscreen-guide], which is shown at app start.
  - [Dialogs][dialogs-guide], which can be used to interrupt the normal flow of the app to inform the user or prompt for an action.
  - [App Rotations][rotations-guide]. You can control whether your app rotates along with the device, or lock it to a single orientation for a consistent user experience.

</section>

[css-components]: /supersonic/guides/ui/components
[native-components]: /supersonic/guides/ui/native-components
[styling-native-components]: /supersonic/guides/ui/styling-native-components
[splashscreen-guide]: /supersonic/guides/ui/splashscreen
[dialogs-guide]: /supersonic/guides/ui/dialogs
[rotations-guide]: /supersonic/guides/ui/app-rotations


text:
@class WDDrawing;

@interface WDSettingsController : UIViewController <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate> {
    IBOutlet UITableView    *table_;
    NSArray                 *configuration_;
    UITextField             *gridSpacing_;
    UITableViewCell         *unitsCell_;
    NSNumberFormatter       *formatter_;
}

@property (nonatomic, weak) WDDrawing *drawing;

- (NSString *) dimensionsString;

@end


text:
package hudson.plugins.analysis.collector;

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import hudson.plugins.analysis.core.AbstractHealthDescriptor;
import hudson.plugins.analysis.core.HealthDescriptor;
import hudson.plugins.analysis.core.NullHealthDescriptor;
import hudson.plugins.analysis.test.AbstractHealthDescriptorTest;
import hudson.plugins.analysis.util.model.AnnotationProvider;

import org.junit.Test;
import org.jvnet.localizer.Localizable;

/**
 * Tests the class {@link AnalysisHealthDescriptor}.
 *
 * @author Ulli Hafner
 */
public class AnalysisHealthDescriptorTest extends AbstractHealthDescriptorTest {
    /**
     * Verify number of items.
     */
    @Test
    public void verifyNumberOfItems() {
        AnnotationProvider provider = mock(AnnotationProvider.class);
        AnalysisHealthDescriptor healthDescriptor = new AnalysisHealthDescriptor(NullHealthDescriptor.NULL_HEALTH_DESCRIPTOR);

        Localizable description = healthDescriptor.createDescription(provider);
        assertEquals(WRONG_DESCRIPTION, Messages.Analysis_ResultAction_HealthReportNoItem(), description.toString());

        when(provider.getNumberOfAnnotations()).thenReturn(1);
        description = healthDescriptor.createDescription(provider);
        assertEquals(WRONG_DESCRIPTION, Messages.Analysis_ResultAction_HealthReportSingleItem(), description.toString());

        when(provider.getNumberOfAnnotations()).thenReturn(2);
        description = healthDescriptor.createDescription(provider);
        assertEquals(WRONG_DESCRIPTION, Messages.Analysis_ResultAction_HealthReportMultipleItem(2), description.toString());
    }

    @Override
    protected AbstractHealthDescriptor createHealthDescriptor(final HealthDescriptor healthDescriptor) {
        return new AnalysisHealthDescriptor(healthDescriptor);
    }
}


text:
package bad.robot.temperature.server

import java.net.InetAddress
import java.time.Clock

import bad.robot.temperature.IpAddress._
import bad.robot.temperature._
import cats.data.NonEmptyList
import cats.effect.IO
import cats.implicits._
import org.http4s._
import org.http4s.dsl.io._

object ConnectionsEndpoint {

  private implicit val encoder = jsonEncoder[List[Connection]]

  def apply(connections: Connections, ipAddresses: => NonEmptyList[Option[InetAddress]] = currentIpAddress)(implicit clock: Clock) = HttpService[IO] {
    case GET -> Root / "connections" => {
      Ok(connections.all).map(_.putHeaders(xForwardedHost(ipAddresses)))
    }

    case GET -> Root / "connections" / "active" / "within" / LongVar(period) / "mins" => {
      Ok(connections.allWithin(period)).map(_.putHeaders(xForwardedHost(ipAddresses)))
    }
  }

  private def xForwardedHost(ipAddresses: NonEmptyList[Option[InetAddress]]): Header = {
    Header("X-Forwarded-Host", ipAddresses.map(_.fold("unknown")(_.getHostAddress)).mkString_("", ", ", ""))
  }

}


text:
module Alerter
  module AlertsHelper
  end
end


text:
package com.facebook.buck.step.fs;

import com.facebook.buck.step.ExecutionContext;
import com.facebook.buck.step.Step;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;

import java.io.IOException;
import java.nio.file.Path;

public class SymlinkTreeStep implements Step {

  private final Path root;
  private final ImmutableMap<Path, Path> links;

  public SymlinkTreeStep(Path root, ImmutableMap<Path, Path> links) {
    this.root = Preconditions.checkNotNull(root);
    this.links = Preconditions.checkNotNull(links);
  }

  @Override
  public String getDescription(ExecutionContext context) {
    return "link tree @ " + root.toString();
  }

  @Override
  public String getShortName() {
    return "link_tree";
  }

  @Override
  public int execute(ExecutionContext context) {
    for (ImmutableMap.Entry<Path, Path> ent : links.entrySet()) {
      Path target = context.getProjectFilesystem().resolve(ent.getValue());
      Path link = context.getProjectFilesystem().resolve(root.resolve(ent.getKey()));
      try {
        context.getProjectFilesystem().mkdirs(link.getParent());
        context.getProjectFilesystem().createSymLink(target, link, true /* force */);
      } catch (IOException e) {
        String msg = String.format("failed creating linking \"%s\" -> \"%s\"", link, target);
        context.logError(e, msg);
        e.printStackTrace(context.getStdErr());
        return 1;
      }
    }
    return 0;
  }

  @Override
  public boolean equals(Object obj) {
    if (!(obj instanceof SymlinkTreeStep)) {
      return false;
    }
    SymlinkTreeStep that = (SymlinkTreeStep) obj;
    return Objects.equal(this.root, that.root) && Objects.equal(this.links, that.links);
  }

  @Override
  public int hashCode() {
    return Objects.hashCode(root, links);
  }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Hist. Champ. France (Paris) 1: 270, tab. 457:1EFH (1791)

#### Original name
Peziza vesiculosa var. alba Bull.

### Remarks
null


text:
<?php

namespace Strider2038\ImgCache\Tests\Unit\Imaging\Parsing\Processing;

use PHPUnit\Framework\TestCase;
use Strider2038\ImgCache\Imaging\Image\ImageParameters;
use Strider2038\ImgCache\Imaging\Image\ImageParametersFactoryInterface;
use Strider2038\ImgCache\Imaging\Parsing\ImageParametersModifierInterface;
use Strider2038\ImgCache\Imaging\Parsing\Processing\ThumbnailProcessingConfigurationParser;
use Strider2038\ImgCache\Imaging\Processing\ProcessingConfiguration;
use Strider2038\ImgCache\Imaging\Processing\Transforming\TransformationCreatorInterface;
use Strider2038\ImgCache\Imaging\Processing\Transforming\TransformationInterface;

class ThumbnailProcessingConfigurationParserTest extends TestCase
{
    /** @var TransformationCreatorInterface */
    private $transformationsCreator;

    /** @var ImageParametersFactoryInterface */
    private $imageParametersFactory;

    /** @var ImageParametersModifierInterface */
    private $imageParametersModifier;

    protected function setUp(): void
    {
        $this->transformationsCreator = \Phake::mock(TransformationCreatorInterface::class);
        $this->imageParametersFactory = \Phake::mock(ImageParametersFactoryInterface::class);
        $this->imageParametersModifier = \Phake::mock(ImageParametersModifierInterface::class);
    }

    /**
     * @test
     * @param string $configuration
     * @param int $count
     * @dataProvider configurationsProvider
     */
    public function parse_givenConfigurationWithTransformations_countOfTransformationsReturned(
        string $configuration,
        int $count
    ): void {
        $parser = $this->createThumbnailProcessingConfigurationParser();
        $this->givenTransformationCreator_findAndCreateTransformation_returnsTransformation();
        $defaultParameters = $this->givenImageParametersFactory_createImageParameters_returnsImageParameters();

        $parsedConfiguration = $parser->parseConfiguration($configuration);

        $this->assertTransformationsCount($count, $parsedConfiguration);
        $this->assertTransformationCreator_findAndCreateTransformation_isCalledTimes($count);
        $this->assertImageParametersModifier_updateParametersByConfiguration_isCalledTimes(0);
        $this->verifyProcessingConfiguration($parsedConfiguration, $defaultParameters);
    }

    /**
     * @test
     * @param string $configuration
     * @param int $count
     * @dataProvider configurationsProvider
     */
    public function getRequestConfiguration_givenConfigurationWithParameters_countOfParametersConfiguratorConfigureVerified(
        string $configuration,
        int $count
    ): void {
        $parser = $this->createThumbnailProcessingConfigurationParser();
        $this->givenTransformationCreator_findAndCreateTransformation_returnsNull();
        $defaultParameters = $this->givenImageParametersFactory_createImageParameters_returnsImageParameters();

        $parsedConfiguration = $parser->parseConfiguration($configuration);

        $this->assertTransformationsCount(0, $parsedConfiguration);
        $this->assertTransformationCreator_findAndCreateTransformation_isCalledTimes($count);
        $this->assertImageParametersModifier_updateParametersByConfiguration_isCalledTimes($count);
        $this->verifyProcessingConfiguration($parsedConfiguration, $defaultParameters);
    }

    public function configurationsProvider(): array
    {
        return [
            ['', 0],
            ['q95', 1],
            ['sz85_q7', 2],
        ];
    }

    private function createThumbnailProcessingConfigurationParser(): ThumbnailProcessingConfigurationParser
    {
        $parser = new ThumbnailProcessingConfigurationParser(
            $this->transformationsCreator,
            $this->imageParametersFactory,
            $this->imageParametersModifier
        );

        return $parser;
    }

    private function givenTransformationCreator_findAndCreateTransformation_returnsTransformation(): void
    {
        $transformation = \Phake::mock(TransformationInterface::class);

        \Phake::when($this->transformationsCreator)
            ->findAndCreateTransformation(\Phake::anyParameters())
            ->thenReturn($transformation);
    }

    private function givenTransformationCreator_findAndCreateTransformation_returnsNull(): void
    {
        \Phake::when($this->transformationsCreator)
            ->findAndCreateTransformation(\Phake::anyParameters())
            ->thenReturn(null);
    }

    private function verifyProcessingConfiguration(
        ProcessingConfiguration $configuration,
        ImageParameters $imageParameters
    ): void {
        $this->assertImageParametersFactory_createImageParameters_isCalledOnce();
        $this->assertSame($imageParameters, $configuration->getImageParameters());
    }

    private function assertTransformationsCount(int $count, ProcessingConfiguration $configuration): void
    {
        $transformations = $configuration->getTransformations();
        $this->assertEquals($count, $transformations->count());
    }

    private function assertTransformationCreator_findAndCreateTransformation_isCalledTimes(int $times): void
    {
        \Phake::verify($this->transformationsCreator, \Phake::times($times))
            ->findAndCreateTransformation(\Phake::anyParameters());
    }

    private function assertImageParametersModifier_updateParametersByConfiguration_isCalledTimes(int $times): void
    {
        \Phake::verify($this->imageParametersModifier, \Phake::times($times))
            ->updateParametersByConfiguration(\Phake::anyParameters());
    }

    private function givenImageParametersFactory_createImageParameters_returnsImageParameters(): ImageParameters
    {
        $imageParameters = \Phake::mock(ImageParameters::class);
        \Phake::when($this->imageParametersFactory)->createImageParameters()->thenReturn($imageParameters);

        return $imageParameters;
    }

    private function assertImageParametersFactory_createImageParameters_isCalledOnce(): void
    {
        \Phake::verify($this->imageParametersFactory, \Phake::times(1))->createImageParameters();
    }
}


text:
package mako

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"

	"github.com/golang/protobuf/proto"
	mpb "github.com/google/mako/spec/proto/mako_go_proto"
)

const koDataPathEnvName = "KO_DATA_PATH"

// MustGetBenchmark wraps getBenchmark in log.Fatalf
func MustGetBenchmark() *string {
	b, err := getBenchmark()
	if err != nil {
		log.Fatalf("unable to determine benchmark_key: %v", err)
	}
	return b
}

// getBenchmark fetches the appropriate benchmark_key for this configured environment.
func getBenchmark() (*string, error) {
	// Figure out what environment we're running in from the Mako configmap.
	env, err := getEnvironment()
	if err != nil {
		return nil, err
	}
	// Read the Mako config file for this environment.
	data, err := readConfigFromKoData(env)
	if err != nil {
		return nil, err
	}
	// Parse the Mako config file.
	bi := &mpb.BenchmarkInfo{}
	if err := proto.UnmarshalText(string(data), bi); err != nil {
		return nil, err
	}

	// Return the benchmark_key from this environment's config file.
	return bi.BenchmarkKey, nil
}

// readConfigFromKoData reads the named config file from kodata.
func readConfigFromKoData(environment string) ([]byte, error) {
	koDataPath := os.Getenv(koDataPathEnvName)
	if koDataPath == "" {
		return nil, fmt.Errorf("%q does not exist or is empty", koDataPathEnvName)
	}
	fullFilename := filepath.Join(koDataPath, environment+".config")
	return ioutil.ReadFile(fullFilename)
}


text:
"use strict";

import Q = require('q');
import * as tl from "azure-pipelines-task-lib/task";
import ContainerConnection from "docker-common-v2/containerconnection";

export function run(connection: ContainerConnection): any {
    var defer = Q.defer<any>();
    connection.setDockerConfigEnvVariable();
    defer.resolve(null);
    return defer.promise;
}


text:
layout: post
title:  "Brainhack in Paris: Anatomy"
date:   2018-02-12 16:31:06
big: 1
project_categories: Events 2018
image: brainhack_paris_anatomy_2018.png
description: "19-21 February 2018 at Mozilla Paris"
---

### Location

Mozilla, 16 Boulevard Montmartre, 75009 Paris

### Registration

[Link for more information](http://www.bcblab.com/BCB/Events/Entries/2018/2/19_BrainHack_in_Paris__Anatomy.html)


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"
        "http://www.w3.org/TR/REC-html40/strict.dtd">

<title>Unison Tour: Web Mining</title>
<link rel="stylesheet" type="text/css" href="../styles/unison.css">

Unison Tour: Web Mining

Mining for Sequences Using Predifined Criteria

http://unison-db.org/browse_views.pl?cv_id=5

Frequently used queries are stored as "canned views". This makes it
easy to bookmark dynamic queries, and this is the primary mechanism I use
to convey search results to others. In a near-future release, we will
permit restriction by species and sequence "age".

Mining for Sequences Using User Criteria

http://unison-db.org/search_sets.pl

This page integrates precomputed results from HMMs, PSSMs, and
Prospect threading for family-specific mining. The left side allows the
user to define sequence selection criteria. At the top is menu of curated
sequence sets. In the default example, sequences are selected using models
(i.e., HMMs, PSSMs, or PDBs) for TNF superfamily members, and "hits" are
categorized according to the specified curated set of
sequences.


text:
namespace llvm {
  class Type;
  class TargetInstrInfo;
  class X86Subtarget;

class X86RegisterInfo final : public X86GenRegisterInfo {
public:
  const X86Subtarget &Subtarget;

private:
  /// Is64Bit - Is the target 64-bits.
  ///
  bool Is64Bit;

  /// IsWin64 - Is the target on of win64 flavours
  ///
  bool IsWin64;

  /// SlotSize - Stack slot size in bytes.
  ///
  unsigned SlotSize;

  /// StackPtr - X86 physical register used as stack ptr.
  ///
  unsigned StackPtr;

  /// FramePtr - X86 physical register used as frame ptr.
  ///
  unsigned FramePtr;

  /// BasePtr - X86 physical register used as a base ptr in complex stack
  /// frames. I.e., when we need a 3rd base, not just SP and FP, due to
  /// variable size stack objects.
  unsigned BasePtr;

public:
  X86RegisterInfo(const X86Subtarget &STI);

  // FIXME: This should be tablegen'd like getDwarfRegNum is
  int getSEHRegNum(unsigned i) const;

  /// Code Generation virtual methods...
  ///
  bool trackLivenessAfterRegAlloc(const MachineFunction &MF) const override;

  /// getMatchingSuperRegClass - Return a subclass of the specified register
  /// class A so that each register in it has a sub-register of the
  /// specified sub-register index which is in the specified register class B.
  const TargetRegisterClass *
  getMatchingSuperRegClass(const TargetRegisterClass *A,
                           const TargetRegisterClass *B,
                           unsigned Idx) const override;

  const TargetRegisterClass *
  getSubClassWithSubReg(const TargetRegisterClass *RC,
                        unsigned Idx) const override;

  const TargetRegisterClass*
  getLargestLegalSuperClass(const TargetRegisterClass *RC) const override;

  /// getPointerRegClass - Returns a TargetRegisterClass used for pointer
  /// values.
  const TargetRegisterClass *
  getPointerRegClass(const MachineFunction &MF,
                     unsigned Kind = 0) const override;

  /// getCrossCopyRegClass - Returns a legal register class to copy a register
  /// in the specified class to or from. Returns NULL if it is possible to copy
  /// between a two registers of the specified class.
  const TargetRegisterClass *
  getCrossCopyRegClass(const TargetRegisterClass *RC) const override;

  unsigned getRegPressureLimit(const TargetRegisterClass *RC,
                               MachineFunction &MF) const override;

  /// getCalleeSavedRegs - Return a null-terminated list of all of the
  /// callee-save registers on this target.
  const MCPhysReg *
  getCalleeSavedRegs(const MachineFunction* MF) const override;
  const uint32_t *getCallPreservedMask(CallingConv::ID) const override;
  const uint32_t *getNoPreservedMask() const;

  /// getReservedRegs - Returns a bitset indexed by physical register number
  /// indicating if a register is a special register that has particular uses and
  /// should be considered unavailable at all times, e.g. SP, RA. This is used by
  /// register scavenger to determine what registers are free.
  BitVector getReservedRegs(const MachineFunction &MF) const override;

  bool hasBasePointer(const MachineFunction &MF) const;

  bool canRealignStack(const MachineFunction &MF) const;

  bool needsStackRealignment(const MachineFunction &MF) const override;

  bool hasReservedSpillSlot(const MachineFunction &MF, unsigned Reg,
                            int &FrameIdx) const override;

  void eliminateFrameIndex(MachineBasicBlock::iterator MI,
                           int SPAdj, unsigned FIOperandNum,
                           RegScavenger *RS = nullptr) const override;

  // Debug information queries.
  unsigned getFrameRegister(const MachineFunction &MF) const override;
  unsigned getStackRegister() const { return StackPtr; }
  unsigned getBaseRegister() const { return BasePtr; }
  // FIXME: Move to FrameInfok
  unsigned getSlotSize() const { return SlotSize; }
};

// getX86SubSuperRegister - X86 utility function. It returns the sub or super
// register of a specific X86 register.
// e.g. getX86SubSuperRegister(X86::EAX, MVT::i16) return X86:AX
unsigned getX86SubSuperRegister(unsigned, MVT::SimpleValueType, bool High=false);

//get512BitRegister - X86 utility - returns 512-bit super register
unsigned get512BitSuperRegister(unsigned Reg);

} // End llvm namespace

#endif


text:
"""Script to parse Windows Jump List files:
* .automaticDestinations-ms
* .customDestinations-ms
"""

import argparse
import logging
import sys

import pyolecf

from dtformats import jump_list
from dtformats import output_writers

def Main():
  """The main program function.

  Returns:
    bool: True if successful or False if not.
  """
  argument_parser = argparse.ArgumentParser(description=(
      'Extracts information from Windows Jump List files.'))

  argument_parser.add_argument(
      '-d', '--debug', dest='debug', action='store_true', default=False,
      help='enable debug output.')

  argument_parser.add_argument(
      'source', nargs='?', action='store', metavar='PATH',
      default=None, help='path of the Windows Jump List file.')

  options = argument_parser.parse_args()

  if not options.source:
    print('Source file missing.')
    print('')
    argument_parser.print_help()
    print('')
    return False

  logging.basicConfig(
      level=logging.INFO, format='[%(levelname)s] %(message)s')

  output_writer = output_writers.StdoutWriter()

  try:
    output_writer.Open()
  except IOError as exception:
    print(f'Unable to open output writer with error: {exception!s}')
    print('')
    return False

  if pyolecf.check_file_signature(options.source):
    jump_list_file = jump_list.AutomaticDestinationsFile(
        debug=options.debug, output_writer=output_writer)
  else:
    jump_list_file = jump_list.CustomDestinationsFile(
        debug=options.debug, output_writer=output_writer)

  jump_list_file.Open(options.source)

  print('Windows Jump List information:')

  number_of_entries = len(jump_list_file.entries)
  print(f'Number of entries:\t\t{number_of_entries:d}')

  number_of_entries = len(jump_list_file.recovered_entries)
  print(f'Number of recovered entries:\t{number_of_entries:d}')

  print('')

  for lnk_file_entry in jump_list_file.entries:
    print(f'LNK file entry: {lnk_file_entry.identifier:s}')

    for shell_item in lnk_file_entry.GetShellItems():
      print(f'Shell item: 0x{shell_item.class_type:02x}')

    print('')

  jump_list_file.Close()

  output_writer.Close()

  return True

if __name__ == '__main__':
  if not Main():
    sys.exit(1)
  else:
    sys.exit(0)


text:
package org.reactor.event;

public interface ReactorEvent {

}


text: > A set of UI elements following the siimple design guidelines


text: Option map for Z39.50 result sets


text:
module SuckerPunch
  class Railtie < ::Rails::Railtie
    initializer "sucker_punch.logger" do
      SuckerPunch.logger = Rails.logger
    end

    config.to_prepare do
      SuckerPunch.clear_queues
    end
  end
end


text:
Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

At this file we also include the `file1.md`
<%>samples/files/file1.md</%>


text:
#region Usings

using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;

using org.GraphDefined.Vanaheimr.Illias;
using org.GraphDefined.Vanaheimr.BouncyCastle;
using Org.BouncyCastle.Bcpg;
using Org.BouncyCastle.Bcpg.OpenPgp;

#endregion

namespace org.GraphDefined.Vanaheimr.Hermod.Mail
{

    /// <summary>
    /// An e-mail builder.
    /// </summary>
    public abstract class AbstractEMailBuilder : AbstractEMail
    {

        #region Data

        protected static readonly String[] TextLineSplitter = new String[] { "\r\n", "\r", "\n" };

        protected readonly List<EMailBodypart> _Attachments;

        #endregion

        #region Properties

        //ToDo: "resentSender", "resentDate", "resentMessageId", "Resent-From",
        //      "Resent-Reply-To", "Resent-To", "Resent-Cc", "Resent-Bcc",

        private readonly Message_Id        _Reference;

        private readonly List<Message_Id>  _References;

        #region From

        private EMailAddress _From;

        /// <summary>
        /// The sender of this e-mail.
        /// </summary>
        public EMailAddress From
        {

            get
            {

                if (_From != null)
                    return _From;

                var _FromString = MailHeaders.
                                      Where(kvp => kvp.Key.ToLower() == "from").
                                      FirstOrDefault();

                if (_FromString.Key != null)
                {
                    _From = EMailAddress.Parse(_FromString.Value);
                    return _From;
                }

                return null;

            }

            set
            {

                if (value != null)
                {

                    _From = value;

                    this.SetEMailHeader("From", value.ToString());

                }

            }

        }

        #endregion

        #region To

        private EMailAddressListBuilder _To;

        /// <summary>
        /// The receivers of this e-mail.
        /// </summary>
        public EMailAddressListBuilder To
        {

            get
            {

                if (_To != null)
                    return _To;

                var _ToString = MailHeaders.
                                      Where(kvp => kvp.Key.ToLower() == "to").
                                      FirstOrDefault();

                if (_ToString.Key != null)
                {
                    _To = EMailAddressListBuilder.Parse(_ToString.Value);
                    return _To;
                }

                return null;

            }

            set
            {

                if (value != null)
                {

                    _To = value;

                    this.SetEMailHeader("To", value.ToString());

                }

            }

        }

        #endregion

        #region ReplyTo

        private readonly EMailAddressListBuilder _ReplyTo;

        /// <summary>
        /// The receivers of any reply on this e-mail.
        /// </summary>
        public EMailAddressListBuilder ReplyTo
        {

            get
            {
                return _ReplyTo;
            }

            set
            {
                if (value != null)
                    _ReplyTo.Add(value);
            }

        }

        #endregion

        #region Cc

        private readonly EMailAddressListBuilder _Cc;

        /// <summary>
        /// Additional receivers of this e-mail.
        /// </summary>
        public EMailAddressListBuilder Cc
        {

            get
            {
                return _Cc;
            }

            set
            {
                if (value != null)
                    _Cc.Add(value);
            }

        }

        #endregion

        #region Bcc

        private readonly EMailAddressListBuilder _Bcc;

        /// <summary>
        /// Additional but hidden receivers of this e-mail.
        /// </summary>
        public EMailAddressListBuilder Bcc
        {

            get
            {
                return _Bcc;
            }

            set
            {
                if (value != null)
                    _Bcc.Add(value);
            }

        }

        #endregion

        #region Subject

        private String _Subject;

        /// <summary>
        /// The subject of this e-mail.
        /// </summary>
        public String Subject
        {

            get
            {

                if (_Subject != null)
                    return _Subject;

                var _String = MailHeaders.
                                      Where(kvp => kvp.Key.ToLower() == "subject").
                                      FirstOrDefault();

                if (_String.Key != null)
                {
                    _Subject = _String.Value;
                    return _Subject;
                }

                return "";

            }

            set
            {

                if (value != null && value != String.Empty && value.Trim() != "")
                {
                    _Subject = value.Trim();
                    this.SetEMailHeader("Subject", value.ToString());
                }

            }

        }

        #endregion

        #region Date

        private DateTime? _Date;

        /// <summary>
        /// The sending timestamp of this e-mail.
        /// </summary>
        public DateTime Date
        {

            get
            {

                if (_Date.HasValue)
                    return _Date.Value;

                var _String = MailHeaders.
                                      Where(kvp => kvp.Key.ToLower() == "date").
                                      FirstOrDefault();

                if (_String.Key != null)
                {
                    _Date = DateTime.Parse(_String.Value);
                    return _Date.Value;
                }

                return DateTime.MinValue;

            }

            set
            {
                this.SetEMailHeader("Date", value.ToLocalTime().ToString("ddd, d MMM yyyy HH:mm:ss zzz"));
            }

        }

        #endregion

        /// <summary>
        /// The unique message identification of the e-mail.
        /// </summary>
        public Message_Id?               MessageId                { get; }

        /// <summary>
        /// The security level of the e-mail.
        /// </summary>
        public EMailSecurity             SecurityLevel            { get; set; }

        /// <summary>
        /// The symmetric key algorithm to use.
        /// </summary>
        public SymmetricKeyAlgorithmTag  SymmetricKeyAlgorithm    { get; set; }

        /// <summary>
        /// The hash algorithm to use.
        /// </summary>
        public HashAlgorithmTag          HashAlgorithm            { get; set; }

        /// <summary>
        /// The compression algorithm to use.
        /// </summary>
        public CompressionAlgorithmTag   CompressionAlgorithm     { get; set; }

        /// <summary>
        /// The passphrase.
        /// </summary>
        public String                    Passphrase               { get; set; }

        #region Body

        private EMailBodypart _Body;

        /// <summary>
        /// The e-mail body.
        /// </summary>
        public EMailBodypart Body
        {

            get
            {
                return _Body;
            }

            set
            {
                if (value != null)
                    _Body = value;
            }

        }

        #endregion

        #region AsImmutable

        /// <summary>
        /// Convert this e-mail builder to an immutable e-mail.
        /// </summary>
        public EMail AsImmutable
        {
            get
            {

                if (From.Address.Value.IsNullOrEmpty() ||
                    !To.Any()                          ||
                    Subject.IsNullOrEmpty())
                {
                    throw new Exception("Invalid email!");
                }

                return new EMail(this);

            }
        }

        #endregion

        #endregion

        #region Constructor(s)

        #region AbstractEMailBuilder()

        /// <summary>
        /// Create a new e-mail builder.
        /// </summary>
        public AbstractEMailBuilder()
            : base()
        {

            this._To                    = EMailAddressListBuilder.Empty;
            this._ReplyTo               = EMailAddressListBuilder.Empty;
            this._Cc                    = EMailAddressListBuilder.Empty;
            this._Bcc                   = EMailAddressListBuilder.Empty;
            this._Subject               = "";
            this. Date                  = DateTime.UtcNow;
            this._References            = new List<Message_Id>();
            this._Attachments           = new List<EMailBodypart>();

            this.SecurityLevel          = EMailSecurity.auto;
            this.SymmetricKeyAlgorithm  = SymmetricKeyAlgorithmTag.Aes256;
            this.HashAlgorithm          = HashAlgorithmTag.Sha512;
            this.CompressionAlgorithm   = CompressionAlgorithmTag.Zip;

            _MailHeaders.Add(new KeyValuePair<String, String>("MIME-Version", "1.0"));

        }

        #endregion

        #region AbstractEMailBuilder(EMail)

        /// <summary>
        /// Parse the e-mail from the given e-mail.
        /// </summary>
        /// <param name="EMail">An e-mail.</param>
        public AbstractEMailBuilder(EMail EMail)
            : base(EMail)
        {

            this._Body = new EMailBodypart(EMail.ToText);

        }

        #endregion

        #region AbstractEMailBuilder(MailText)

        /// <summary>
        /// Parse the e-mail from the given text lines.
        /// </summary>
        /// <param name="MailText">The E-Mail as an enumeration of strings.</param>
        public AbstractEMailBuilder(IEnumerable<String> MailText)
            : base(MailText)
        {

            this._Body = new EMailBodypart(MailText);

        }

        #endregion

        #endregion

        #region AddAttachment(EMailBodypart)

        /// <summary>
        /// Add an attachment to this e-mail.
        /// </summary>
        /// <param name="EMailBodypart">An attachment.</param>
        public T AddAttachment<T>(EMailBodypart EMailBodypart)
            where T : AbstractEMailBuilder
        {

            _Attachments.Add(EMailBodypart);

            return (T) this;

        }

        #endregion

        #region (protected, abstract) EncodeBodyparts()

        /// <summary>
        /// Encode all nested e-mail body parts.
        /// </summary>
        protected abstract EMailBodypart _EncodeBodyparts();

        #endregion

        #region (internal) EncodeBodyparts()

        /// <summary>
        /// Encode this and all nested e-mail body parts.
        /// </summary>
        internal AbstractEMailBuilder EncodeBodyparts()
        {

            var SignTheMail     = false;
            var EncryptTheMail  = false;

            EMailBodypart BodypartToBeSecured = null;

            #region Add attachments, if available...

            if (_Attachments       == null ||
                _Attachments.Count == 0)
                BodypartToBeSecured  = _EncodeBodyparts();

            else
                BodypartToBeSecured  = new EMailBodypart(ContentTypeBuilder:       AEMail => new MailContentType(AEMail, MailContentTypes.multipart_mixed) { CharSet = "utf-8" }.GenerateMIMEBoundary(),
                                                         ContentTransferEncoding:  "8bit",
                                                         Content:                  new String[] { "This is a multi-part message in MIME format." },
                                                         NestedBodyparts:          new EMailBodypart[] { _EncodeBodyparts() }.
                                                                                Concat(_Attachments));

            #endregion

            #region Check security settings

            switch (SecurityLevel)
            {

                case EMailSecurity.autosign:

                    if (From.SecretKeyRing != null &&
                        From.SecretKeyRing.GetSecretKeys().Cast<PgpSecretKey>().ToList().Any()   &&
                        Passphrase.IsNotNullOrEmpty())
                        SignTheMail = true;

                    break;

                case EMailSecurity.sign:

                    if (From.SecretKeyRing == null ||
                       !From.SecretKeyRing.GetSecretKeys().Cast<PgpSecretKey>().ToList().Any()   ||
                        Passphrase.IsNullOrEmpty())
                        throw new ApplicationException("Can not sign the e-mail!");

                    SignTheMail = true;

                    break;

                case EMailSecurity.auto:

                    if (From.SecretKeyRing != null &&
                        From.SecretKeyRing.GetSecretKeys().Cast<PgpSecretKey>().ToList().Any()   &&
                        Passphrase.IsNotNullOrEmpty())
                        SignTheMail = true;

                    if (SignTheMail &&
                        (!To.Any() | To.Any(v => v.PublicKeyRing != null && v.PublicKeyRing.GetPublicKeys().Cast<PgpPublicKey>().ToList().Any() )) &&
                        (!Cc.Any() | Cc.Any(v => v.PublicKeyRing != null && v.PublicKeyRing.GetPublicKeys().Cast<PgpPublicKey>().ToList().Any() )))
                        EncryptTheMail = true;

                    break;

                case EMailSecurity.encrypt:

                    if (From.SecretKeyRing == null  ||
                       !From.SecretKeyRing.GetSecretKeys().Cast<PgpSecretKey>().ToList().Any()    ||
                        Passphrase.IsNullOrEmpty()  ||
                        To.Any(v => v.PublicKeyRing == null || !v.PublicKeyRing.GetPublicKeys().Cast<PgpPublicKey>().ToList().Any() ) ||
                        Cc.Any(v => v.PublicKeyRing == null || !v.PublicKeyRing.GetPublicKeys().Cast<PgpPublicKey>().ToList().Any() ))
                        throw new ApplicationException("Can not sign and encrypt the e-mail!");

                    EncryptTheMail = true;

                    break;

            }

            #endregion

            #region Sign the e-mail

            if (SignTheMail & !EncryptTheMail)
            {

                var dataToBeSigned      = BodypartToBeSecured.

                                              // Include headers of this MIME body
                                              // https://tools.ietf.org/html/rfc1847 Security Multiparts for MIME:
                                              ToText().

                                              // Any trailing whitespace MUST then be removed from the signed material
                                              Select(line => line.TrimEnd()).

                                              // Canonical text format with <CR><LF> line endings
                                              // https://tools.ietf.org/html/rfc3156 5. OpenPGP signed data
                                              Aggregate((a, b) => a + "\r\n" + b)

                                              //ToDo: Apply Content-Transfer-Encoding
                                              ;

                // MIME Security with OpenPGP (rfc3156, https://tools.ietf.org/html/rfc3156)
                // OpenPGP Message Format     (rfc4880, https://tools.ietf.org/html/rfc4880)
                _Body = new EMailBodypart(ContentTypeBuilder:          AMail => new MailContentType(AMail, MailContentTypes.multipart_signed) {
                                                                           MicAlg    = "pgp-sha512",
                                                                           Protocol  = "application/pgp-signature",
                                                                           CharSet   = "utf-8",
                                                                       },
                                          ContentTransferEncoding:     "8bit",
                                          NestedBodyparts:             new EMailBodypart[] {

                                                                           BodypartToBeSecured,

                                                                           new EMailBodypart(ContentTypeBuilder:       AMail => new MailContentType(AMail, MailContentTypes.application_pgp__signature) { CharSet = "utf-8" },
                                                                                //    ContentTransferEncoding:  "8bit",
                                                                                ContentDescription:       "OpenPGP digital signature",
                                                                                ContentDisposition:       ContentDispositions.attachment.ToString() + "; filename=\"signature.asc\"",
                                                                                Content:                  new String[] {

                                                                                OpenPGP.CreateSignature(new MemoryStream(dataToBeSigned.ToUTF8Bytes()),
                                                                                From.SecretKeyRing?.GetSecretKeys().Cast<PgpSecretKey>().ToList().First(),
                                                                                Passphrase,
                                                                                HashAlgorithm: HashAlgorithm).

                                                                                WriteTo(new MemoryStream(), CloseOutputStream: false).
                                                                                ToUTF8String()

                                                                                })

                                                                       }
                                         );

            }

            #endregion

            #region Encrypt the e-mail

            else if (SignTheMail & EncryptTheMail)
            {

                var Plaintext   = BodypartToBeSecured.ToText().Aggregate((a, b) => a + "\r\n" + b).ToUTF8Bytes();
                var Ciphertext  = new MemoryStream();

                OpenPGP.EncryptSignAndZip(InputStream:            new MemoryStream(Plaintext),
                                          Length:                 (UInt64) Plaintext.Length,
                                          SecretKey:              From.SecretKeyRing?.GetSecretKeys().Cast<PgpSecretKey>().ToList().First(),
                                          Passphrase:             Passphrase,
                                          PublicKey:              To.First().PublicKeyRing.GetPublicKeys().Cast<PgpPublicKey>().ToList().First(),
                                          OutputStream:           Ciphertext,
                                          SymmetricKeyAlgorithm:  SymmetricKeyAlgorithm,
                                          HashAlgorithm:          HashAlgorithm,
                                          CompressionAlgorithm:   CompressionAlgorithm,
                                          ArmoredOutput:          true,
                                          Filename:               "encrypted.asc",
                                          LastModificationTime:   DateTime.UtcNow);

                // MIME Security with OpenPGP (rfc3156, https://tools.ietf.org/html/rfc3156)
                // OpenPGP Message Format     (rfc4880, https://tools.ietf.org/html/rfc4880)
                _Body = new EMailBodypart(ContentTypeBuilder:          AMail => new MailContentType(AMail, MailContentTypes.multipart_encrypted) {
                                                                           Protocol = "application/pgp-encrypted",
                                                                           CharSet  = "utf-8",
                                                                       },
                                          ContentTransferEncoding:     "8bit",
                                          NestedBodyparts:             new EMailBodypart[] {

                                                                           new EMailBodypart(ContentTypeBuilder:   AMail => new MailContentType(AMail, MailContentTypes.application_pgp__encrypted) { CharSet = "utf-8" },
                                                                                ContentDescription:   "PGP/MIME version identification",
                                                                                ContentDisposition:   ContentDispositions.attachment.ToString() + "; filename=\"signature.asc\"",
                                                                                Content:              new String[] { "Version: 1" }),

                                                                           new EMailBodypart(ContentTypeBuilder:   AMail => new MailContentType(AMail, MailContentTypes.application_octet__stream) { CharSet = "utf-8" },
                                                                                ContentDescription:   "OpenPGP encrypted message",
                                                                                ContentDisposition:   ContentDispositions.inline.ToString() + "; filename=\"encrypted.asc\"",
                                                                                Content:              new String[] { Ciphertext.ToArray().ToUTF8String() }),

                                                                       }
                                         );

            }

            #endregion

            else
                this._Body = BodypartToBeSecured;

            return this;

        }

        #endregion

    }

}


text:
package PracticeLeetCode;

public class _121BestTimeToBuyAndSellStock {
	psvm

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/C:/Users/Alessio/StudioProjects/Release/maps/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/22.0.0/res/values-port/values.xml -->
    <eat-comment/>
    <bool name="abc_action_bar_embed_tabs">false</bool>
</resources>


text:
typedef struct storage {
	struct storage *(*copy)(struct storage *this);
	void (*free)(struct storage **this);

	item_type type;

	cmp_result (*compare)(struct storage *this, struct storage *other);

	bool (*has_item)(struct storage *this, item *data);
	item *(*get_item)(struct storage *this, item *data);
	bool (*set_item)(struct storage *this, item **data);
	bool (*del_item)(struct storage *this, item *data);
} storage;

typedef storage *(*storage_ctor)(item_type data_type);

typedef struct map {
	struct map *(*copy)(struct map *this);
	void (*free)(struct map **this);

	item_type type;

	cmp_result (*compare)(struct map *this, struct map *other);

	item_type key_type;
	storage *underlying;

	item *(*get)(struct map *this, item *key);

	bool (*set)(struct map *this, item *key, item *value);
	bool (*set_link)(struct map *this, item *key, item **value);
} map;

typedef struct {
	item_type key_type;
	storage_ctor storage_new;
} map_params;

map *map_construct(map_params params);

#define map_new(...) map_construct((map_params){ \
	.key_type = i_integer, \
	.storage_new = (storage_ctor)bin_tree_new, \
	__VA_ARGS__ \
})

#define I(key) (item *)&(integer){ \
	.copy = integer_copy, .type = i_integer, .value = key \
}

#define S(key) (item *)&(string){ \
	.copy = string_copy, .type = i_string, .value = key \
}

#endif


text:
layout: post
bgimage: 8142015.png
title: How did we get here?
---

Before we talk go into publishing to the blog itself I wanted to talk about how this blog came to be.

Sort of like the origin tale of a great super-hero saga (except its really just how stylesheets and ruby). I am going to breakdown the how in two sections.
As for the source of this blog - this is public on my [Github] (https://github.com/munadm)

##Story so far

So the idea behind making a blog isn't of course a grand one. Everyone and their uncle has one and with so many frameworks available it is perhaps one of the easier projects to shoot through a weekend
However what I saw in most of the frameworks is that they were very...fake-pretty. I mean sure there are some amazing themes out there but in all honesty most are not designed to be future-proof against the growing inch of mobile screens.

Thus the idea behind my project was to figure out a way to use an existing renderer but build a theme that looks the part of a decent web application.
I went theme first because at the end of the day I wanted a small enough asset library to not hamper load time. By pure chance I read about an article on [Material Design Lite] (http://www.getmdl.io/).
It had a lot of things going for it. It was a tiny CDN hosted library with enough assets to get started. It was flexible with custom rendering that wont step over some hierarchical style inheritance and best of all it had the reliance and familiarity of a android app that would look amazing on a web application.
So it was settled, I grabbed a template blog they were demoing out and got started in ripping out the guts to make it conform to how I want it to look.

The second great run of luck was with jekyll. Deemed for "Blogging like a hacker" its a small yet elegant framework that is built around YAML mastheads and liquid templating.
It was initially clunky to get started with but the excellent [jekyll-now] (https://github.com/barryclark/jekyll-now) offers a great quickstart on how to get started with the baseplate version in minutes. From there came the hard part of merging the existing framework to my mdl theme. But with great tinkering yields great results and thus I was able to get it going relatively quickly

##To be continued...

My ideas is to incorporate as many mdl features as I can muster. I am hoping to get the disqus module running for version 2 and in the future incorporate some of those sweet animation components in the mdl library.
The end goal is realistically hand it over to a more avid blogger who can really put this through the paces and see what kinda improvements I can incorporate to future releases