text:
from pytest import raises
from pyplus.parse import *

def fun(arg):
    return arg

def test_create_lazy_parser():
    parser = create_lazy_parser(False)
    assert "string" == parser("string")
    assert b"string" == parser(b"string")
    assert u"string" == parser(u"string")
    assert lazy_parse is create_lazy_parser(True)
    assert fun is create_lazy_parser(fun)

def test_create_parser():
    parser = create_parser(False)
    assert "string" == parser("string")
    assert b"string" == parser(b"string")
    assert u"string" == parser(u"string")
    assert parse is create_parser(True)
    assert fun is create_parser(fun)

def test_lazy_parse():
    assert 1 == lazy_parse("1")
    assert -1.5 == lazy_parse("-3 / 2")
    assert False is lazy_parse("False")
    assert None is lazy_parse("None")
    assert True is lazy_parse("True")
    assert {u"key": b"value"} == lazy_parse("{u'key': b'value'}")
    assert [1, 1.5] == lazy_parse("[1, 1.5]")
    assert {True, False, None} == lazy_parse("{True, False,  None}")
    assert ("1", "2") == lazy_parse("('1', '2')")

def test_lazy_parse_bytes():
    assert 1 == lazy_parse(b"1")
    assert -1.5 == lazy_parse(b"-3 / 2")
    assert False is lazy_parse(b"False")
    assert None is lazy_parse(b"None")
    assert True is lazy_parse(b"True")
    assert {u"key": b"value"} == lazy_parse(b"{u'key': b'value'}")
    assert [1, 1.5] == lazy_parse(b"[1, 1.5]")
    assert {True, False, None} == lazy_parse(b"{True, False, None}")
    assert ("1", "2") == lazy_parse(b"('1', '2')")

def test_lazy_parse_unicode():
    assert 1 == lazy_parse(u"1")
    assert -1.5 == lazy_parse(u"-3 / 2")
    assert False is lazy_parse(u"False")
    assert None is lazy_parse(u"None")
    assert True is lazy_parse(u"True")
    assert {u"key": b"value"} == lazy_parse(u"{u'key': b'value'}")
    assert [1, 1.5] == lazy_parse(u"[1, 1.5]")
    assert {True, False, None} == lazy_parse(u"{True, False, None}")
    assert ("1", "2") == lazy_parse(u"('1', '2')")

def test_lazy_parse_exception():
    with raises(ValueError, message="could not parse string: 'string'"):
        lazy_parse("string", errors=True)
    assert lazy_parse("string") == "string"

    with raises(ValueError, message="could not parse string: 'string + 5'"):
        lazy_parse("string + 5", errors=True)
    assert lazy_parse("string + 5") == "string + 5"

    with raises(ValueError, message="could not parse string: '[1, 2)'"):
        lazy_parse("[1, 2)", errors=True)
    assert lazy_parse("[1, 2)") == "[1, 2)"

    with raises(ValueError, message="could not parse string: 'a = 5'"):
        lazy_parse("a = 5", errors=True)
    assert lazy_parse("a = 5") == "a = 5"

def test_lazy_parse_exception_bytes():
    with raises(ValueError, message="could not parse string: 'string'"):
        lazy_parse(b"string", errors=True)
    assert lazy_parse(b"string") == b"string"

    with raises(ValueError, message="could not parse string: 'string + 5'"):
        lazy_parse(b"string + 5", errors=True)
    assert lazy_parse(b"string + 5") == b"string + 5"

    with raises(ValueError, message="could not parse string: '[1, 2)'"):
        lazy_parse(b"[1, 2)", errors=True)
    assert lazy_parse(b"[1, 2)") == b"[1, 2)"

    with raises(ValueError, message="could not parse string: 'a = 5'"):
        lazy_parse(b"a = 5", errors=True)
    assert lazy_parse(b"a = 5") == b"a = 5"

def test_lazy_parse_exception_unicode():
    with raises(ValueError, message="could not parse string: 'string'"):
        lazy_parse(u"string", errors=True)
    assert lazy_parse(u"string") == "string"

    with raises(ValueError, message="could not parse string: 'string + 5'"):
        lazy_parse(u"string + 5", errors=True)
    assert lazy_parse(u"string + 5") == u"string + 5"

    with raises(ValueError, message="could not parse string: '[1, 2)'"):
        lazy_parse(u"[1, 2)", errors=True)
    assert lazy_parse(u"[1, 2)") == u"[1, 2)"

    with raises(ValueError, message="could not parse string: 'a = 5'"):
        lazy_parse(u"a = 5", errors=True)
    assert lazy_parse(u"a = 5") == u"a = 5"

def test_parse():
    assert 1 == parse("1")
    assert -1.5 == parse("-3 / 2")
    assert False is parse("false")
    assert None is parse("null")
    assert True is parse("true")
    assert {u"key": b"value"} == parse("{u'key': b'value'}")
    assert [1, 1.5] == parse("[1, 1.5]")
    assert {True, False, None} == parse("{True, False, None}")
    assert ("1", "2") == parse("('1', '2')")
    assert "string" == parse("string")

def test_parse_bytes():
    assert 1 == parse(b"1")
    assert -1.5 == parse(b"-3 / 2")
    assert False is parse(b"false")
    assert None is parse(b"null")
    assert True is parse(b"true")
    assert {u"key": b"value"} == parse(b"{u'key': b'value'}")
    assert [1, 1.5] == parse(b"[1, 1.5]")
    assert {True, False, None} == parse(b"{True, False, None}")
    assert ("1", "2") == parse(b"('1', '2')")
    assert b"string" == parse(b"string")

def test_parse_unicode():
    assert 1 == parse(u"1")
    assert -1.5 == parse(u"-3 / 2")
    assert False is parse(u"false")
    assert None is parse(u"null")
    assert True is parse(u"true")
    assert {u"key": b"value"} == parse(u"{u'key': b'value'}")
    assert [1, 1.5] == parse(u"[1, 1.5]")
    assert {True, False, None} == parse(u"{True, False, None}")
    assert ("1", "2") == parse(u"('1', '2')")
    assert u"string" == parse(u"string")

def test_parse_exception():
    with raises(ValueError, message="could not parse string: 'string'"):
        parse("string", errors=True)
    assert parse("string") == "string"

    with raises(ValueError, message="could not parse string: 'x'"):
        parse("x", errors=True)
    assert parse("x") == "x"

def test_parse_exception_bytes():
    with raises(ValueError, message="could not parse string: 'string'"):
        parse(b"string", errors=True)
    assert parse(b"string") == b"string"

    with raises(ValueError, message="could not parse string: 'x'"):
        parse(b"x", errors=True)
    assert parse(b"x") == b"x"

def test_parse_exception_unicode():
    with raises(ValueError, message="could not parse string: 'string'"):
        parse(u"string", errors=True)
    assert parse(u"string") == u"string"

    with raises(ValueError, message="could not parse string: 'x'"):
        parse(u"x", errors=True)
    assert parse(u"x") == u"x"

def test_parser_bool():
    assert False is parse_bool("False")
    assert False is parse_bool("false")
    assert False is parse_bool("FALSE")
    assert True is parse_bool("True")
    assert True is parse_bool("true")
    assert True is parse_bool("TRUE")

def test_parser_bool_bytes():
    assert True is parse_bool(b"True")
    assert True is parse_bool(b"true")
    assert True is parse_bool(b"TRUE")
    assert False is parse_bool(b"False")
    assert False is parse_bool(b"false")
    assert False is parse_bool(b"FALSE")

def test_parser_bool_unicode():
    assert True is parse_bool(u"True")
    assert True is parse_bool(u"true")
    assert True is parse_bool(u"TRUE")
    assert False is parse_bool(u"False")
    assert False is parse_bool(u"false")
    assert False is parse_bool(u"FALSE")

def test_parse_bool_exception():
    with raises(ValueError, message="could not convert string to bool: '0'"):
        parse_bool("0", errors=True)
    assert parse_bool("0") == "0"

    with raises(ValueError, message="could not convert string to bool: 'T'"):
        parse_bool("T", errors=True)
    assert parse_bool("T") == "T"

    with raises(ValueError, message="could not convert string to bool: 'None'"):
        parse_bool("None", errors=True)
    assert parse_bool("None") == "None"

def test_parse_bool_exception_bytes():
    with raises(ValueError, message="could not convert string to bool: '0'"):
        parse_bool(b"0", errors=True)
    assert parse_bool(b"0") == b"0"

    with raises(ValueError, message="could not convert string to bool: 'T'"):
        parse_bool(b"T", errors=True)
    assert parse_bool(b"T") == b"T"

    with raises(ValueError, message="could not convert string to bool: 'None'"):
        parse_bool(b"None", errors=True)
    assert parse_bool(b"None") == b"None"

def test_parse_bool_exception_unicode():
    with raises(ValueError, message="could not convert string to bool: '0'"):
        parse_bool(u"0", errors=True)
    assert parse_bool(u"0") == u"0"

    with raises(ValueError, message="could not convert string to bool: 'T'"):
        parse_bool(u"T", errors=True)
    assert parse_bool(u"T") == u"T"

    with raises(ValueError, message="could not convert string to bool: 'None'"):
        parse_bool(u"None", errors=True)
    assert parse_bool(u"None") == u"None"

def test_parse_none():
    assert None is parse_none("")
    assert None is parse_none("#N/A")
    assert None is parse_none("None")
    assert None is parse_none("null")
    assert None is parse_none("undefined")

def test_parse_none_bytes():
    assert None is parse_none(b"")
    assert None is parse_none(b"#N/A")
    assert None is parse_none(b"None")
    assert None is parse_none(b"null")
    assert None is parse_none(b"undefined")

def test_parse_none_unicode():
    assert None is parse_none(u"")
    assert None is parse_none(u"#N/A")
    assert None is parse_none(u"None")
    assert None is parse_none(u"null")
    assert None is parse_none(u"undefined")

def test_parse_none_exception():
    with raises(ValueError, message="could not convert string to None: '0'"):
        parse_none("0", errors=True)
    assert parse_none("0") == "0"

    with raises(ValueError, message="could not convert string to None: 'False'"):
        parse_none("False", errors=True)
    assert parse_none("False") == "False"

    with raises(ValueError, message="could not convert string to None: 'n'"):
        parse_none("n", errors=True)
    assert parse_none("n") == "n"

def test_parse_none_exception_bytes():
    with raises(ValueError, message="could not convert string to None: '0'"):
        parse_none(b"0", errors=True)
    assert parse_none(b"0") == b"0"

    with raises(ValueError, message="could not convert string to None: 'False'"):
        parse_none(b"False", errors=True)
    assert parse_none(b"False") == b"False"

    with raises(ValueError, message="could not convert string to None: 'n'"):
        parse_none(b"n", errors=True)
    assert parse_none(b"n") == b"n"

def test_parse_none_exception_unicode():
    with raises(ValueError, message="could not convert string to None: '0'"):
        parse_none(u"0", errors=True)
    assert parse_none(u"0") == u"0"

    with raises(ValueError, message="could not convert string to None: 'False'"):
        parse_none(u"False", errors=True)
    assert parse_none(u"False") == u"False"

    with raises(ValueError, message="could not convert string to None: 'n'"):
        parse_none(u"n", errors=True)
    assert parse_none(u"n") == u"n"


text:
@charset "UTF-8";

/*
Sahana - Default Theme - Stylesheet
-----------------------------------------------------------------------------------
designer : Prabhath Sirisena - prabhath@vesess.com - http://nidahas.com
updated : Priyanga Fonseka  - jo@opensource.lk
updated for SahanaPy : Fran Boon  - francisboon@gmail.com
updated for print form : Michael Howden - michael.howden@gmail.com
Some content used from: http://matthewjamestaylor.com/blog/perfect-full-page.htm

Selectors are listed in their order of appearance in the html, where applicable.
----------------------------------------------------------------------------------

  |---- Neutralizing Styles
  |---- Basic Page Formatting Styles
  |---- Header
    +---- menu_auth
  |---- menu_modules
  |---- Content ( Home, Result, Module specific styles )
  |---- Footer
  |---- Form Layout Styles
  |---- Popup Form Styles
  |---- Popup Menu Styles
  |---- Message Display Styles

*/

/* Neutralizing Styles
   ------------------------------------------------------------------------------- */
/* Neutralize styling: Elements we want to clean out entirely */
html, body, form, fieldset, textarea { margin: 0; padding: 0; font: 100%/125% Arial, Helvetica, sans-serif; }

/* Neutralize styling: Elements with a vertical margin */
h1, h2, h3, h4, h5, h6, p, pre,
blockquote, ul, ol, dl, address { margin: 0 0 1em 0; padding: 0;  }

/* Apply left margin: Only to the few elements that need it */
dd, blockquote { margin-left: 1em; }
/* Breaks CSS dropdown menus
li { margin-left: 1em; }
*/

/* Clear floats without structural markup */
.clearfix:after { content: ".";  display: block; height: 0; clear: both; visibility: hidden; }

/* Hides from IE-mac */
* html .clearfix { height: 1%; }

/* Basic Page Formatting Styles
   ------------------------------------------------------------------------------- */
body { font-size: 0.8em; color: #000; direction: ltr; }
/* Miscellaneous conveniences: */
form label { cursor: pointer; }
fieldset { border: none; }

table { border-collapse: collapse }

#form-container {
    width: 800;
    padding-top:0;
    padding-bottom:20;
    padding-right:20;
    padding-left:20;
    border-style: solid;
    border-width: 1;
    border-color: black;
    margin: 10
}

#form-container-landscape {
    width: 900;
    padding-top:0;
    padding-bottom:20;
    padding-right:20;
    padding-left:20;
    border-style: solid;
    border-width: 1;
    border-color: black;
    margin: 10
}

#form-header {
    /*background: url(../../img/fdm_logo_black.png) no-repeat right top;*/
    height: 70;
}

#form-header table {
    width: 100%;
}

#form-header  h2, h3, h4 {
    vertical-align:text-top;
    text-align: left;
    margin: 0 0 0 0;
}

#form-header h2 {
    font-size: 2em;
}

#form-header h2, h4 {
    padding: 0 0 0 150;
}

#form-header h4 {
    font-size: 0.7em;
}

h1 {
    font-size: 3em;
    text-align: center;
    margin-top: 30;
}

#details-container {
    padding: 10;
    border-style: solid;
    border-width: 1;
    border-color: black;
}

#details-container  label{
    font-size: 120%;
}

/* Tabular data view */
div#table-container { font_size: 0.4em; width: 100%; overflow: auto; }
div#table-container table thead tr th { border: 1px solid black; padding: 10;}
div#table-container table tbody th { border: 1px solid black; }
div#table-container table tr.even td { border: 1px solid black; text-align: center;}
div#table-container table tr.odd td { border: 1px solid black; text-align: center; }

redpajama_set_name: RedPajamaGithub


text:
package model

import (
	"fmt"
)

type Mail struct {
	Tos     string `json:"tos"`
	Subject string `json:"subject"`
	Content string `json:"content"`
}

func (this *Mail) String() string {
	return fmt.Sprintf(
		"<Tos:%s, Subject:%s, Content:%s>",
		this.Tos,
		this.Subject,
		this.Content,
	)
}


text:
import argparse
import time
import math
import mxnet as mx
from mxnet import gluon, autograd
import model
import data

parser = argparse.ArgumentParser(description='MXNet Autograd PennTreeBank RNN/LSTM Language Model')
parser.add_argument('--data', type=str, default='./data/wikitext-2/wiki.',
                    help='location of the data corpus')
parser.add_argument('--model', type=str, default='lstm',
                    help='type of recurrent net (rnn_tanh, rnn_relu, lstm, gru)')
parser.add_argument('--emsize', type=int, default=200,
                    help='size of word embeddings')
parser.add_argument('--nhid', type=int, default=200,
                    help='number of hidden units per layer')
parser.add_argument('--nlayers', type=int, default=2,
                    help='number of layers')
parser.add_argument('--lr', type=float, default=1.0,
                    help='initial learning rate')
parser.add_argument('--clip', type=float, default=0.2,
                    help='gradient clipping')
parser.add_argument('--epochs', type=int, default=40,
                    help='upper epoch limit')
parser.add_argument('--batch_size', type=int, default=32, metavar='N',
                    help='batch size')
parser.add_argument('--bptt', type=int, default=35,
                    help='sequence length')
parser.add_argument('--dropout', type=float, default=0.2,
                    help='dropout applied to layers (0 = no dropout)')
parser.add_argument('--tied', action='store_true',
                    help='tie the word embedding and softmax weights')
parser.add_argument('--cuda', action='store_true',
                    help='Whether to use gpu')
parser.add_argument('--log-interval', type=int, default=200, metavar='N',
                    help='report interval')
parser.add_argument('--save', type=str, default='model.params',
                    help='path to save the final model')
parser.add_argument('--gctype', type=str, default='none',
                    help='type of gradient compression to use, \
                          takes `2bit` or `none` for now.')
parser.add_argument('--gcthreshold', type=float, default=0.5,
                    help='threshold for 2bit gradient compression')
args = parser.parse_args()

###############################################################################
# Load data
###############################################################################

if args.cuda:
    context = mx.gpu(0)
else:
    context = mx.cpu(0)

corpus = data.Corpus(args.data)

def batchify(data, batch_size):
    """Reshape data into (num_example, batch_size)"""
    nbatch = data.shape[0] // batch_size
    data = data[:nbatch * batch_size]
    data = data.reshape((batch_size, nbatch)).T
    return data

train_data = batchify(corpus.train, args.batch_size).as_in_context(context)
val_data = batchify(corpus.valid, args.batch_size).as_in_context(context)
test_data = batchify(corpus.test, args.batch_size).as_in_context(context)

###############################################################################
# Build the model
###############################################################################

ntokens = len(corpus.dictionary)
model = model.RNNModel(args.model, ntokens, args.emsize, args.nhid,
                       args.nlayers, args.dropout, args.tied)
model.collect_params().initialize(mx.init.Xavier(), ctx=context)

compression_params = None if args.gctype == 'none' else {'type': args.gctype, 'threshold': args.gcthreshold}
trainer = gluon.Trainer(model.collect_params(), 'sgd',
                        {'learning_rate': args.lr,
                         'momentum': 0,
                         'wd': 0},
                        compression_params=compression_params)
loss = gluon.loss.SoftmaxCrossEntropyLoss()

###############################################################################
# Training code
###############################################################################

def get_batch(source, i):
    seq_len = min(args.bptt, source.shape[0] - 1 - i)
    data = source[i:i+seq_len]
    target = source[i+1:i+1+seq_len]
    return data, target.reshape((-1,))

def detach(hidden):
    if isinstance(hidden, (tuple, list)):
        hidden = [i.detach() for i in hidden]
    else:
        hidden = hidden.detach()
    return hidden

def eval(data_source):
    total_L = 0.0
    ntotal = 0
    hidden = model.begin_state(func=mx.nd.zeros, batch_size=args.batch_size, ctx=context)
    for i in range(0, data_source.shape[0] - 1, args.bptt):
        data, target = get_batch(data_source, i)
        output, hidden = model(data, hidden)
        L = loss(output, target)
        total_L += mx.nd.sum(L).asscalar()
        ntotal += L.size
    return total_L / ntotal

def train():
    best_val = float("Inf")
    for epoch in range(args.epochs):
        total_L = 0.0
        start_time = time.time()
        hidden = model.begin_state(func=mx.nd.zeros, batch_size=args.batch_size, ctx=context)
        for ibatch, i in enumerate(range(0, train_data.shape[0] - 1, args.bptt)):
            data, target = get_batch(train_data, i)
            hidden = detach(hidden)
            with autograd.record():
                output, hidden = model(data, hidden)
                L = loss(output, target)
                L.backward()

            grads = [i.grad(context) for i in model.collect_params().values()]
            # Here gradient is for the whole batch.
            # So we multiply max_norm by batch_size and bptt size to balance it.
            gluon.utils.clip_global_norm(grads, args.clip * args.bptt * args.batch_size)

            trainer.step(args.batch_size)
            total_L += mx.nd.sum(L).asscalar()

            if ibatch % args.log_interval == 0 and ibatch > 0:
                cur_L = total_L / args.bptt / args.batch_size / args.log_interval
                print('[Epoch %d Batch %d] loss %.2f, ppl %.2f'%(
                    epoch, ibatch, cur_L, math.exp(cur_L)))
                total_L = 0.0

        val_L = eval(val_data)

        print('[Epoch %d] time cost %.2fs, valid loss %.2f, valid ppl %.2f'%(
            epoch, time.time()-start_time, val_L, math.exp(val_L)))

        if val_L < best_val:
            best_val = val_L
            test_L = eval(test_data)
            model.collect_params().save(args.save)
            print('test loss %.2f, test ppl %.2f'%(test_L, math.exp(test_L)))
        else:
            args.lr = args.lr*0.25
            trainer._init_optimizer('sgd',
                                    {'learning_rate': args.lr,
                                     'momentum': 0,
                                     'wd': 0})
            model.collect_params().load(args.save, context)

if __name__ == '__main__':
    train()
    model.collect_params().load(args.save, context)
    test_L = eval(test_data)
    print('Best test loss %.2f, test ppl %.2f'%(test_L, math.exp(test_L)))


text:
import sys
import math
import operator
import re

from os import listdir
from os.path import isfile, join
from PIL import Image

IMAGE_WIDTH = 355
IMAGE_HEIGHT = 355

BORDER_DISCOUNT = 0.11

BLOCK_SIZE = 36
BLOCKS_SIZE = BLOCK_SIZE * BLOCK_SIZE

X_BLOCK_SIZE = IMAGE_WIDTH / BLOCK_SIZE;
Y_BLOCK_SIZE = IMAGE_HEIGHT / BLOCK_SIZE;

NORTH_POINT = IMAGE_HEIGHT * BORDER_DISCOUNT
WEST_POINT = IMAGE_WIDTH * BORDER_DISCOUNT
SOUTH_POINT = IMAGE_HEIGHT - WEST_POINT
EAST_POINT = IMAGE_WIDTH - WEST_POINT

HALF_WIDTH = IMAGE_WIDTH / 2
HALF_HEIGHT = IMAGE_HEIGHT / 2

def getImageRegion(x, y):

    if x >= WEST_POINT and x <= EAST_POINT and y >= NORTH_POINT and y <= SOUTH_POINT:
        return "E"

    if x <= HALF_WIDTH and y < HALF_HEIGHT:
        return "A"

    if x <= HALF_WIDTH and y >= HALF_HEIGHT:
        return "D"

    if x > HALF_WIDTH and y <= HALF_HEIGHT:
        return "B"

    return "C"

def convertHistogramIntoWords(histogram):

    newHistogram = {}

    #necessary?
    for key, value in enumerate(histogram):
        newHistogram[key] = value

    newHistogram = sorted(newHistogram.items(), key=operator.itemgetter(1), reverse=True)
    len95percent = int(len(newHistogram) * 0.95)

    words = ''
    count = 0
    for key,value in newHistogram:
        if count == len95percent:
            break
        words += 'x' + str(key)
        ++count

    return words

def generateSDLCDescriptorSample(image):

    lowColorImg = image.convert('P')

    yLeft = 0
    yRight = Y_BLOCK_SIZE

    imageDescription = []

    for y in range(0, BLOCK_SIZE):

        xLeft = 0
        xRight = X_BLOCK_SIZE

        for x in range(0, BLOCK_SIZE):

            imageBlock = lowColorImg.transform((BLOCK_SIZE, BLOCK_SIZE), Image.EXTENT, (xLeft, yLeft, xRight, yRight))
            imageHistogram = imageBlock.histogram()

            blockDescription = getImageRegion(xRight, yRight) + convertHistogramIntoWords(imageHistogram)

            imageDescription.append(blockDescription)

            xLeft += X_BLOCK_SIZE
            xRight += X_BLOCK_SIZE

        yLeft += Y_BLOCK_SIZE
        yRight += Y_BLOCK_SIZE

    return ' '.join(imageDescription)

def persistSample(path, sdlc):
    fo = open(path, "wb")
    fo.write(sdlc)
    fo.close()

def main(argv):

    print "Welcome to SDLC Descriptor Python implementation."

    imageCollectionPath = "data/colecaoDafitiPosthaus"
    queriesCollectionPath = "data/queries"

    print "Verifying datafiPosthaus and query collections."

    imageList = [ f for f in listdir(imageCollectionPath) if isfile(join(imageCollectionPath, f)) ]

    queryImageList = [ f for f in listdir(queriesCollectionPath) if isfile(join(queriesCollectionPath, f)) and re.match(r'[0-9]+.*\.jpg', f) ]

    print "Running SDLC Descriptor over DafitiPosthaus collection."
    print "This will take a time, make sure to have at least 20GB of free space on disk."

    for imagePath in queryImageList:
        imageFile = queriesCollectionPath + "/" + imagePath;

        try:
            im = Image.open(imageFile)

            sdlcImage = generateSDLCDescriptorSample(im)

            sdlcImagePath = queriesCollectionPath + "/" + imagePath.split(".")[0] + ".sdlc"

            persistSample(sdlcImagePath, sdlcImage)

        except IOError:
            pass

    print "Finished the second collection."
    print "Checkout for files with extersion .sdlc on each collection folder."

    for imagePath in imageList:
        imageFile = imageCollectionPath + "/" + imagePath;
        try:
            im = Image.open(imageFile)

            sdlcImage = generateSDLCDescriptorSample(im)

            sdlcImagePath = imageCollectionPath + "/" + imagePath.split(".")[0] + ".sdlc"
            persistSample(sdlcImagePath, sdlcImage)

        except IOError:
            pass

    print "Finished the first collection."
    print "Running SDLC Descriptor over query collection."

if __name__ == '__main__':
    main(sys.argv)


text:
package org.apache.cassandra.streaming;

import java.io.IOException;

import org.apache.cassandra.streaming.messages.StreamMessage;

public interface StreamingMessageSender
{
    void initialize() throws IOException;

    void sendMessage(StreamMessage message) throws IOException;

    boolean connected();

    void close();
}


text:
<html>
<head>
    <title></title>
    <script>
        function done()
        {
            var f = document.getElementById("iframe");
            f.parentNode.removeChild(f);
            parent.frameLoaded();
        }
    </script>
</head>
<body>
    <div>
        <iframe id="iframe" onload="done()" src="onload-remove-iframe.html">
        </iframe>
    </div>
</body>
</html>


text:
tags: daily-life
layout: post
title: "One of the downsides of growth..."
---

My workplace is growing like crazy. This is a good thing -- as Mark recently said, it was wonderfully strange to sit in a company meeting and hear almost nothing but good news (including our Inc 500 debut).

The only downside is space. In the last year or so we built a new building. Only the first, third and fourth floors are built-out, and the first is used for building and repairing our devices. (No veal cubes there.) So floors three and four are getting very cramped and we're nearing the need to cannibalize meeting rooms for office space.

No worries -- the second floor is being built-out! Hooray! Office space will jump by 50% (or so), everyone will have room to swing their arms without smacking a co-worker... but until then we on the third floor will have to deal with extremely loud drills going through concrete and the occasional two-ton gorilla jumping up and down on something down there. But it's worth it.


text:
package org.apache.camel.component.jsonapi.springboot;

import javax.annotation.Generated;
import org.apache.camel.spring.boot.DataFormatConfigurationPropertiesCommon;
import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * JSonApi data format is used for marshal and unmarshal Json API object.
 *
 * Generated by camel-package-maven-plugin - do not edit this file!
 */
@Generated("org.apache.camel.maven.packaging.SpringBootAutoConfigurationMojo")
@ConfigurationProperties(prefix = "camel.dataformat.jsonapi")
public class JsonApiDataFormatConfiguration
        extends
            DataFormatConfigurationPropertiesCommon {

    /**
     * Whether to enable auto configuration of the jsonApi data format. This is
     * enabled by default.
     */
    private Boolean enabled;
    /**
     * The classes to take into account for the marshalling
     */
    private Class<?>[] dataFormatTypes;
    /**
     * The classes to take into account while unmarshalling
     */
    private Class<?> mainFormatType;
    /**
     * Whether the data format should set the Content-Type header with the type
     * from the data format if the data format is capable of doing so. For
     * example application/xml for data formats marshalling to XML, or
     * application/json for data formats marshalling to JSon etc.
     */
    private Boolean contentTypeHeader = false;

    public Class<?>[] getDataFormatTypes() {
        return dataFormatTypes;
    }

    public void setDataFormatTypes(Class<?>[] dataFormatTypes) {
        this.dataFormatTypes = dataFormatTypes;
    }

    public Class<?> getMainFormatType() {
        return mainFormatType;
    }

    public void setMainFormatType(Class<?> mainFormatType) {
        this.mainFormatType = mainFormatType;
    }

    public Boolean getContentTypeHeader() {
        return contentTypeHeader;
    }

    public void setContentTypeHeader(Boolean contentTypeHeader) {
        this.contentTypeHeader = contentTypeHeader;
    }
}


text:
package org.fjorum.model.service;

import org.fjorum.controller.form.UserCreateForm;
import org.fjorum.controller.form.UserRightsForm;
import org.fjorum.model.entity.User;

import java.util.Optional;

public interface UserService extends EntityService<User> {

    Optional<User> getUserByNameOrEmail(String nameOrEmail);

    User create(UserCreateForm form);

    void changeRights(UserRightsForm form);

}


text:
import Exception from '@gdbots/pbj/Exception.js';
import Code from '@gdbots/schemas/gdbots/pbjx/enums/Code.js';
import RequestFailedResponseV1 from '@gdbots/schemas/gdbots/pbjx/request/RequestFailedResponseV1.js';

/**
 * @param {Message}         request   - A message using mixin 'gdbots:pbjx:mixin:request'
 * @param {Error|Exception} exception - The Exception that caused the failure.
 *
 * @returns {Message} Returns a message using mixin 'gdbots:pbjx:mixin:response'
 */
export default (request, exception) => {
  let code = Code.UNKNOWN.getValue();
  if (exception instanceof Exception) {
    code = exception.getCode() || code;
  }

  const response = RequestFailedResponseV1.create()
    .set('ctx_request_ref', request.generateMessageRef())
    .set('ctx_request', request)
    .set('error_code', code)
    .set('error_name', exception.name)
    .set('error_message', exception.message.substr(0, 2048))
    .set('stack_trace', exception.stack || null);

  if (request.has('ctx_correlator_ref')) {
    response.set('ctx_correlator_ref', request.get('ctx_correlator_ref'));
  }

  if (request.has('ctx_tenant_id')) {
    response.set('ctx_tenant_id', request.get('ctx_tenant_id'));
  }

  return response;
};


text:
'use strict';

var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; };

exports.__esModule = true;

var _keyMirror = require('keymirror');

var _keyMirror2 = _interopRequireWildcard(_keyMirror);

exports['default'] = _keyMirror2['default']({
  FOO: null,
  BAR: null,
  BAZ: null
});
module.exports = exports['default'];


text:
package ch.sama.sql.query.helper.condition;

import java.util.ArrayList;
import java.util.List;

public class OrCondition implements ICondition {
    private List<ICondition> conditions;

    public OrCondition(ICondition[] conditions) {
        this.conditions = new ArrayList<ICondition>();

        for (ICondition c : conditions) {
            this.conditions.add(c);
        }
    }

    public List<ICondition> getConditions() {
        return conditions;
    }

    @Override
    public String render(IConditionRenderer renderer) {
        return renderer.render(this);
    }
}


text:
namespace syncer {

const char* ShutdownReasonToString(ShutdownReason reason) {
  switch (reason) {
    case STOP_SYNC:
      return "STOP_SYNC";
    case DISABLE_SYNC:
      return "DISABLE_SYNC";
    case BROWSER_SHUTDOWN:
      return "BROWSER_SHUTDOWN";
  }

  NOTREACHED();
  return "";
}

}  // namespace syncer


text:
if(typeof exports === 'object') {
	var assert = require("assert");
	var alasql = require('../alasql.js');
};

describe('Test 61 - Increment', function() {

	it('AUTO_INCREMENT', function(done){
		alasql("DROP TABLE IF EXISTS test");
		alasql("CREATE TABLE test (a INT AUTO_INCREMENT, b INT)");
		alasql('insert into test (b) values (10),(20),(30)');
		var res = alasql('select * from test');
		done();
	});

	it('IDENTITY', function(done){
		alasql("DROP TABLE IF EXISTS test");
		alasql("CREATE TABLE test (a INT IDENTITY(1,1), b INT)");
		alasql('insert into test (b) values (10),(20),(30)');
		var res = alasql('select * from test');
		done();
	});

});


text:
require 'test_helper'

class ListingsControllerTest < ActionController::TestCase
  setup do
    @listing = listings(:one)
  end

  test "should get index" do
    get :index
    assert_response :success
    assert_not_nil assigns(:listings)
  end

  test "should get new" do
    get :new
    assert_response :success
  end

  test "should create listing" do
    assert_difference('Listing.count') do
      post :create, listing: { active: @listing.active, address: @listing.address, contact_email: @listing.contact_email, descrption: @listing.descrption, featured: @listing.featured, geocode: @listing.geocode, name: @listing.name, neighborhood_id: @listing.neighborhood_id, phone_number: @listing.phone_number, slug: @listing.slug, website_url: @listing.website_url, zip: @listing.zip }
    end

    assert_redirected_to listing_path(assigns(:listing))
  end

  test "should show listing" do
    get :show, id: @listing
    assert_response :success
  end

  test "should get edit" do
    get :edit, id: @listing
    assert_response :success
  end

  test "should update listing" do
    patch :update, id: @listing, listing: { active: @listing.active, address: @listing.address, contact_email: @listing.contact_email, descrption: @listing.descrption, featured: @listing.featured, geocode: @listing.geocode, name: @listing.name, neighborhood_id: @listing.neighborhood_id, phone_number: @listing.phone_number, slug: @listing.slug, website_url: @listing.website_url, zip: @listing.zip }
    assert_redirected_to listing_path(assigns(:listing))
  end

  test "should destroy listing" do
    assert_difference('Listing.count', -1) do
      delete :destroy, id: @listing
    end

    assert_redirected_to listings_path
  end
end


text:
package config

import (
	"reflect"

	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/resource"
	"sigs.k8s.io/yaml"
)

const (
	// DefaultsConfigName is the name of the defaults configmap.
	DefaultsConfigName               = "config-defaults"
	spaceContainerRegistryKey        = "spaceContainerRegistry"
	spaceClusterDomainsKey           = "spaceClusterDomains"
	spaceBuildpacksV2Key             = "spaceBuildpacksV2"
	spaceStacksV2Key                 = "spaceStacksV2"
	spaceStacksV3Key                 = "spaceStacksV3"
	spaceDefaultToV3StackKey         = "spaceDefaultToV3Stack"
	routeServiceProxyImageKey        = "routeServiceProxyImage"
	featureFlagsKey                  = "featureFlags"
	buildDisableIstioSidecarKey      = "buildDisableIstioSidecar"
	buildPodResourcesKey             = "buildPodResources"
	buildRetentionCountKey           = "buildRetentionCount"
	taskRetentionCountKey            = "taskRetentionCount"
	buildTimeoutKey                  = "buildTimeout"
	buildNodeSelectorsKey            = "buildNodeSelectors"
	appCPUPerGBOfRAMKey              = "appCPUPerGBOfRAM"
	appCPUMinKey                     = "appCPUMin"
	appDisableStartCommandLookupKey  = "appDisableStartCommandLookup"
	progressDeadlineSecondsKey       = "progressDeadlineSeconds"
	terminationGracePeriodSecondsKey = "terminationGracePeriodSeconds"
	routeTrackVirtualServiceKey      = "routeTrackVirtualService"
	routeDisableRetriesKey           = "routeDisableRetries"
	taskDefaultTimeoutMinutesKey     = "taskDefaultTimeoutMinutes"
	taskDisableVolumeMountsKey       = "taskDisableVolumeMounts"

	// Images used for build purposes

	buildKanikoExecutorImageKey   = "buildKanikoExecutorImage"
	buildInfoImageKey             = "buildInfoImage"
	buildTokenDownloadImageKey    = "buildTokenDownloadImage"
	buildHelpersImageKey          = "buildHelpersImage"
	buildpacksV2LifecycleImageKey = "buildpacksV2LifecycleImage"
	nopImageKey                   = "nopImage"
)

// DefaultsConfig contains the configuration for defaults.
type DefaultsConfig struct {
	// NOTE: The JSON tags are included here for correctly formatting the config
	// for .golden files.

	// SpaceContainerRegistry is the default container registry to assign
	// to spaces.
	SpaceContainerRegistry string `json:"spaceContainerRegistry,omitempty"`

	// SpaceClusterDomains is the default domain for spaces. Apps in the
	// space will get the name <app>.<space>.<defaultClusterDomain> by default.
	SpaceClusterDomains []DomainTemplate `json:"spaceClusterDomains,omitempty"`

	// SpaceBuildpacksV2 contains a sorted list of buildpacks to be used for CF
	// compatible builds.
	SpaceBuildpacksV2 BuildpackV2List `json:"spaceBuildpacksV2,omitempty"`

	// SpaceStacksV2 contains a list of stacks that can be used for CF compatible
	// builds.
	SpaceStacksV2 StackV2List `json:"spaceStacksV2,omitempty"`

	// SpaceStacksV3 contains a list of stacks that can be used for CF compatible
	// builds.
	SpaceStacksV3 StackV3List `json:"spaceStacksV3,omitempty"`

	// SpaceDefaultToV3Stack determines whether v3 stacks should be used by
	// default over v2 stacks.
	SpaceDefaultToV3Stack bool `json:"spaceDefaultToV3Stack,omitempty"`

	// RouteServiceProxyImage is the image URL for the Kf route service proxy deployment.
	RouteServiceProxyImage string `json:"routeServiceProxyImage,omitempty"`

	BuildKanikoExecutorImage string `json:"buildKanikoExecutorImage,omitempty"`
	BuildInfoImage           string `json:"buildInfoImage,omitempty"`
	BuildTokenDownloadImage  string `json:"buildTokenDownloadImage,omitempty"`
	BuildHelpersImage        string `json:"buildHelpersImage,omitempty"`
	NopImage                 string `json:"nopImage,omitempty"`

	// BuildpacksV2LifecycleImage is the image URL for the V2 buildpack
	// lifecycle binaries. It is expected to contain the `launcher` and
	// `builder` binaries AND to self extract those binaries into /workspace.
	BuildpacksV2LifecycleImage string `json:"buildpacksV2LifecycleImage,omitempty"`

	// BuildDisableIstioSidecar when set to true, will prevent the Istio
	// sidecar from being attached to the Build pods.
	BuildDisableIstioSidecar bool `json:"buildDisableIstioSidecar,omitempty"`

	// BuildPodResources sets the Build pod resources field.
	// NOTE: This is only applicable for built-in Tasks. For V2 builds, this
	// will be set on two steps and one for V3 and Dockerfiles. This implies
	// for a V2 build, the required Pod size will be the limit doubled.  For
	// example, if the memory limit is 1Gi, then the pod will require 2Gi.
	BuildPodResources *corev1.ResourceRequirements `json:"buildPodResources,omitempty"`

	// BuildRetentionCount is the number of completed Builds each App will
	// keep before garbage collecting.
	BuildRetentionCount *uint `json:"buildRetentionCount,omitempty"`

	// TaskRetentionCount is the number of completed Tasks each App will
	// keep before garbage collecting.
	TaskRetentionCount *uint `json:"taskRetentionCount,omitempty"`

	// BuildTimeout is the timeout value to set at the underlying TaskRun of Build, it is the time duration
	// to fail a build that takes too long to complete, valid values are specified in time unit, e.g. "1h", "30m", "60s"
	BuildTimeout string `json:"buildTimeout,omitempty"`

	// BuildNodeSelectors is the node selectors for the build node pool.
	// When it's specified, the Kf build pods are only assigned to the nodes that have labels matching the selectors.
	BuildNodeSelectors BuildNodeSelectors `json:"buildNodeSelectors,omitempty"`

	// FeatureFlags is a map of feature names to their status (enabled/disabled) represented as a bool.
	FeatureFlags FeatureFlagToggles `json:"featureFlags,omitempty"`

	// Default amount of CPU to assign an app per GB of RAM.
	AppCPUPerGBOfRAM *resource.Quantity `json:"appCPUPerGBOfRAM,omitempty"`

	// Minimum amount of CPU to assign an app.
	AppCPUMin *resource.Quantity `json:"appCPUMin,omitempty"`

	// AppDisableStartCommandLookup disables the App reconciler from looking
	// up the start command for Apps which requires fetching the container
	// configuration for every App.
	AppDisableStartCommandLookup bool `json:"appDisableStartCommandLookup,omitempty"`

	// ProgressDeadlineSeconds contains the maximum time in seconds for a deployment to make progress before it
	// is considered to be failed.
	ProgressDeadlineSeconds *int32 `json:"progressDeadlineSeconds,omitempty"`

	// The grace period is the duration in seconds after the processes running in the pod are sent
	// a termination signal and the time when the processes are forcibly halted with a kill signal.
	TerminationGracePeriodSeconds *int64 `json:"terminationGracePeriodSeconds,omitempty"`

	// RouteTrackVirtualService when set to true, will update Route status with VirtualService conditions.
	RouteTrackVirtualService bool `json:"routeTrackVirtualService,omitempty"`

	// RouteDisbaleRetries disables retries in the VirtualServices that route traffic to apps.
	// By default, Kf leaves the value unset and it's inherited from Istio.
	RouteDisableRetries bool `json:"routeDisableRetries,omitempty"`

	// TaskDefaultTimeoutMinutes sets the cluster-wide timeout for tasks.
	// If the value is null, the timeout is inherited from Tekton.
	// If the value is <= 0, then an infinite timeout is set.
	TaskDefaultTimeoutMinutes *int32 `json:"taskDefaultTimeoutMinutes,omitempty"`

	// TaskDisableVolumeMounts disables mounting NFS volumes in Tasks.
	// Mounting NFS volumes requires FUSE which grants Task Pods additional
	// system privileges.
	TaskDisableVolumeMounts bool `json:"taskDisableVolumeMounts,omitempty"`
}

// BuiltinDefaultsConfig creates a defaults configuration with default values.
func BuiltinDefaultsConfig() *DefaultsConfig {
	// CPU isn't defaulted in Cloud Foundry so we assume apps are I/O bound
	// and roughly 10 should run on a single core machine.
	defaultCPUPerGBOfRAM := resource.MustParse("100m")
	defaultAppCPUMin := resource.MustParse("100m")

	return &DefaultsConfig{
		// Default to v2 stacks like CF users expect.
		SpaceDefaultToV3Stack: false,

		// Default to what Kf did prior to scaling CPU by GB/RAM.
		AppCPUPerGBOfRAM: &defaultCPUPerGBOfRAM,

		// Prevent an app from being starved even if it doesn't need much RAM.
		AppCPUMin: &defaultAppCPUMin,
	}
}

// NewDefaultsConfigFromConfigMap creates a DefaultsConfig from the supplied
// ConfigMap with defaults provided by DefaultSpaceConfig for any blank fields.
func NewDefaultsConfigFromConfigMap(configMap *corev1.ConfigMap) (*DefaultsConfig, error) {
	defaultsConfig := BuiltinDefaultsConfig()
	// Populate string values
	for k, dest := range defaultsConfig.getStringValues() {
		if setValue, ok := configMap.Data[k]; ok {
			*dest = setValue
		}
	}

	// Populate JSON/YAML values
	for k, dest := range defaultsConfig.getInterfaceValues(false) {
		if setValue, ok := configMap.Data[k]; ok {
			if err := yaml.Unmarshal([]byte(setValue), dest); err != nil {
				return nil, err
			}
		}
	}

	return defaultsConfig, nil
}

// PatchConfigMap merges values from a DefaultsConfig onto a v1.ConfigMap. This updates the keys that are part of DefaultsConfig
// while leaving the rest of the original v1.ConfigMap (such as _example) untouched.
func (defaultsConfig *DefaultsConfig) PatchConfigMap(cm *corev1.ConfigMap) error {
	// Patch string values
	for k, setValue := range defaultsConfig.getStringValues() {
		if len(*setValue) == 0 {
			continue
		}
		cm.Data[k] = *setValue
	}

	// Patch JSON/YAML values
	for k, setValue := range defaultsConfig.getInterfaceValues(true) {
		if setValue == nil {
			continue
		}

		marshaled, err := yaml.Marshal(setValue)
		if err != nil {
			return err
		}
		// Don't rewrite values that are already equivalent. This also avoids adding
		// formatting diffs caused by the YAML marshaller.
		equalYAML, err := IsYAMLEqual(cm.Data[k], string(marshaled))
		if err != nil {
			return err
		}
		if !equalYAML {
			cm.Data[k] = string(marshaled)
		}
	}

	return nil
}

// getStringValues returns a map of the key/value pairs on a DefaultsConfig that are string values.
func (defaultsConfig *DefaultsConfig) getStringValues() map[string]*string {
	return map[string]*string{
		spaceContainerRegistryKey:     &defaultsConfig.SpaceContainerRegistry,
		routeServiceProxyImageKey:     &defaultsConfig.RouteServiceProxyImage,
		buildKanikoExecutorImageKey:   &defaultsConfig.BuildKanikoExecutorImage,
		buildInfoImageKey:             &defaultsConfig.BuildInfoImage,
		buildTokenDownloadImageKey:    &defaultsConfig.BuildTokenDownloadImage,
		buildHelpersImageKey:          &defaultsConfig.BuildHelpersImage,
		buildpacksV2LifecycleImageKey: &defaultsConfig.BuildpacksV2LifecycleImage,
		buildTimeoutKey:               &defaultsConfig.BuildTimeout,
		nopImageKey:                   &defaultsConfig.NopImage,
	}
}

// getInterfaceValues returns a map of the key/value pairs on a DefaultsConfig that are JSON/YAML encoded values.
func (defaultsConfig *DefaultsConfig) getInterfaceValues(leaveEmpty bool) map[string]interface{} {
	m := map[string]interface{}{
		spaceDefaultToV3StackKey:         &defaultsConfig.SpaceDefaultToV3Stack,
		buildDisableIstioSidecarKey:      &defaultsConfig.BuildDisableIstioSidecar,
		buildPodResourcesKey:             &defaultsConfig.BuildPodResources,
		buildRetentionCountKey:           &defaultsConfig.BuildRetentionCount,
		taskRetentionCountKey:            &defaultsConfig.TaskRetentionCount,
		buildNodeSelectorsKey:            &defaultsConfig.BuildNodeSelectors,
		appCPUPerGBOfRAMKey:              &defaultsConfig.AppCPUPerGBOfRAM,
		appCPUMinKey:                     &defaultsConfig.AppCPUMin,
		appDisableStartCommandLookupKey:  &defaultsConfig.AppDisableStartCommandLookup,
		progressDeadlineSecondsKey:       &defaultsConfig.ProgressDeadlineSeconds,
		terminationGracePeriodSecondsKey: &defaultsConfig.TerminationGracePeriodSeconds,
		routeTrackVirtualServiceKey:      &defaultsConfig.RouteTrackVirtualService,
		routeDisableRetriesKey:           &defaultsConfig.RouteDisableRetries,
		taskDefaultTimeoutMinutesKey:     &defaultsConfig.TaskDefaultTimeoutMinutes,
		taskDisableVolumeMountsKey:       &defaultsConfig.TaskDisableVolumeMounts,
	}

	if !leaveEmpty {
		m[spaceBuildpacksV2Key] = &defaultsConfig.SpaceBuildpacksV2
		m[spaceClusterDomainsKey] = &defaultsConfig.SpaceClusterDomains
		m[spaceStacksV2Key] = &defaultsConfig.SpaceStacksV2
		m[spaceStacksV3Key] = &defaultsConfig.SpaceStacksV3
		m[featureFlagsKey] = &defaultsConfig.FeatureFlags
	}

	if len(defaultsConfig.SpaceBuildpacksV2) > 0 {
		m[spaceBuildpacksV2Key] = &defaultsConfig.SpaceBuildpacksV2
	}
	if len(defaultsConfig.SpaceClusterDomains) > 0 {
		m[spaceClusterDomainsKey] = &defaultsConfig.SpaceClusterDomains
	}
	if len(defaultsConfig.SpaceStacksV2) > 0 {
		m[spaceStacksV2Key] = &defaultsConfig.SpaceStacksV2
	}
	if len(defaultsConfig.SpaceStacksV3) > 0 {
		m[spaceStacksV3Key] = &defaultsConfig.SpaceStacksV3
	}
	if len(defaultsConfig.FeatureFlags) > 0 {
		m[featureFlagsKey] = &defaultsConfig.FeatureFlags
	}

	return m
}

// IsYAMLEqual returns whether the expexted YAML matches the actual YAML.
func IsYAMLEqual(expected, actual string) (bool, error) {
	var em, am interface{}
	err := yaml.Unmarshal([]byte(expected), &em)
	if err != nil {
		return false, err
	}
	err = yaml.Unmarshal([]byte(actual), &am)
	if err != nil {
		return false, err
	}
	return reflect.DeepEqual(em, am), nil
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Aiphanes fosteriorum H.E.Moore

### Remarks
null


text:
"use strict";

var assert         = require("assert"),
    Promise        = require("bluebird"),
    thicket        = require("../../../../../lib-node/thicket"),
    LogicalClock   = thicket.c("logical-clock"),
    ClockSequencer = thicket.c("clock-sequencer");

describe("ClockSequencer", function() {
  it("should advance on demand", function(done) {
    var clock = new LogicalClock();
    var sequencer = new ClockSequencer({
      clock: clock
    });

    Promise
      .attempt(function() {
        assert.equal(sequencer.value(), 0);
        return clock.advanceTime({by: 10}).then(function() {
          return sequencer.advance();
        });
      })
      .then(function() {
        assert.equal(sequencer.value(), 10);
        return clock.advanceTime({to: 20}).then(function() {
          return sequencer.advance(10);
        });
      })
      .then(function() {
        assert.equal(sequencer.value(), 20);
      })
      .caught(function(err) {
        assert.equal(err && err.message, false);
      })
      .lastly(function() {
        done();
      });
  });
});


text:
package org.apache.kylin.jdbc;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.xml.bind.DatatypeConverter;

import org.apache.calcite.avatica.ColumnMetaData;
import org.apache.calcite.avatica.ColumnMetaData.Rep;
import org.apache.calcite.avatica.ColumnMetaData.ScalarType;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.kylin.jdbc.KylinMeta.KMetaCatalog;
import org.apache.kylin.jdbc.KylinMeta.KMetaColumn;
import org.apache.kylin.jdbc.KylinMeta.KMetaProject;
import org.apache.kylin.jdbc.KylinMeta.KMetaSchema;
import org.apache.kylin.jdbc.KylinMeta.KMetaTable;
import org.apache.kylin.jdbc.json.PreparedQueryRequest;
import org.apache.kylin.jdbc.json.SQLResponseStub;
import org.apache.kylin.jdbc.json.StatementParameter;
import org.apache.kylin.jdbc.json.TableMetaStub;
import org.apache.kylin.jdbc.json.TableMetaStub.ColumnMetaStub;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.kylin.shaded.com.google.common.annotations.VisibleForTesting;

public class KylinClient implements IRemoteClient {

    private static final Logger logger = LoggerFactory.getLogger(KylinClient.class);

    private final KylinConnectionInfo connInfo;
    private final Properties connProps;
    private HttpClient httpClient;
    private final ObjectMapper jsonMapper;

    public KylinClient(KylinConnectionInfo connInfo) {
        this.connInfo = connInfo;
        this.connProps = connInfo.getConnectionProperties();
        this.jsonMapper = new ObjectMapper();

        this.httpClient = new DefaultHttpClient();
        if (isSSL()) {
            SSLSocketFactory sslsf;
            try {
                if (isSetKeyTrustStore()) {
                    // get key store
                    KeyStore ks = KeyStore.getInstance(getSSLProperty("javax.net.ssl.keyStoreType"));
                    File ksFile = new File(getSSLProperty("javax.net.ssl.keyStore"));
                    try (FileInputStream is = new FileInputStream(ksFile)) {
                        ks.load(is, getSSLProperty("javax.net.ssl.keyStorePassword").toCharArray());
                    }

                    // get trust store
                    KeyStore ts = KeyStore.getInstance(getSSLProperty("javax.net.ssl.trustStoreType"));
                    File tsFile = new File(getSSLProperty("javax.net.ssl.trustStore"));
                    try (FileInputStream is = new FileInputStream(tsFile)) {
                        ts.load(is, getSSLProperty("javax.net.ssl.trustStorePassword").toCharArray());
                    }

                    sslsf = new SSLSocketFactory(ks, getSSLProperty("javax.net.ssl.keyStorePassword"), ts);
                } else {
                    // trust all certificates
                    sslsf = new SSLSocketFactory(new TrustStrategy() {
                        public boolean isTrusted(final X509Certificate[] chain, String authType)
                                throws CertificateException {
                            // Oh, I am easy...
                            return true;
                        }
                    });
                }
                httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, sslsf));
            } catch (Exception e) {
                throw new RuntimeException("Initialize HTTPS client failed", e);
            }
        }
    }

    @VisibleForTesting
    void setHttpClient(HttpClient httpClient) {
        this.httpClient = httpClient;
    }

    @SuppressWarnings("rawtypes")
    public static Class convertType(int sqlType) {
        Class result = Object.class;

        switch (sqlType) {
        case Types.CHAR:
        case Types.VARCHAR:
        case Types.LONGVARCHAR:
            result = String.class;
            break;
        case Types.NUMERIC:
        case Types.DECIMAL:
            result = BigDecimal.class;
            break;
        case Types.BIT:
        case Types.BOOLEAN:
            result = Boolean.class;
            break;
        case Types.TINYINT:
            result = Byte.class;
            break;
        case Types.SMALLINT:
            result = Short.class;
            break;
        case Types.INTEGER:
            result = Integer.class;
            break;
        case Types.BIGINT:
            result = Long.class;
            break;
        case Types.REAL:
        case Types.FLOAT:
        case Types.DOUBLE:
            result = Double.class;
            break;
        case Types.BINARY:
        case Types.VARBINARY:
        case Types.LONGVARBINARY:
            result = Byte[].class;
            break;
        case Types.DATE:
            result = Date.class;
            break;
        case Types.TIME:
            result = Time.class;
            break;
        case Types.TIMESTAMP:
            result = Timestamp.class;
            break;
        default:
            //do nothing
            break;
        }

        return result;
    }

    public static Object wrapObject(String value, int sqlType) {
        if (null == value) {
            return null;
        }

        switch (sqlType) {
        case Types.CHAR:
        case Types.VARCHAR:
        case Types.LONGVARCHAR:
            return value;
        case Types.NUMERIC:
        case Types.DECIMAL:
            return new BigDecimal(value);
        case Types.BIT:
        case Types.BOOLEAN:
            return Boolean.valueOf(value);
        case Types.TINYINT:
            return Byte.valueOf(value);
        case Types.SMALLINT:
            return Short.valueOf(value);
        case Types.INTEGER:
            return Integer.valueOf(value);
        case Types.BIGINT:
            return Long.valueOf(value);
        case Types.FLOAT:
            return Float.valueOf(value);
        case Types.REAL:
        case Types.DOUBLE:
            return Double.valueOf(value);
        case Types.BINARY:
        case Types.VARBINARY:
        case Types.LONGVARBINARY:
            return value.getBytes(StandardCharsets.UTF_8);
        case Types.DATE:
            return dateConvert(value);
        case Types.TIME:
            return Time.valueOf(value);
        case Types.TIMESTAMP:
            return timestampConvert(value);
        default:
            //do nothing
            break;

        }

        return value;
    }

    private boolean isSSL() {
        return Boolean.parseBoolean(connProps.getProperty("ssl", "false"));
    }

    private boolean isSetKeyTrustStore() {
        return isSetKeyStore() && isSetTrustStore();
    }

    private boolean isSetKeyStore() {
        return getSSLProperty("javax.net.ssl.keyStoreType") != null //
                && getSSLProperty("javax.net.ssl.keyStore") != null //
                && getSSLProperty("javax.net.ssl.keyStorePassword") != null;
    }

    private boolean isSetTrustStore() {
        return getSSLProperty("javax.net.ssl.trustStoreType") != null //
                && getSSLProperty("javax.net.ssl.trustStore") != null //
                && getSSLProperty("javax.net.ssl.trustStorePassword") != null;
    }

    private String getSSLProperty(String key) {
        return connProps.getProperty(key) != null ? connProps.getProperty(key) : System.getProperty(key);
    }

    private String baseUrl() {
        return (isSSL() ? "https://" : "http://") + connInfo.getBaseUrl();
    }

    private void addHttpHeaders(HttpRequestBase method) {
        method.addHeader("Accept", "application/json, text/plain, */*");
        method.addHeader("Content-Type", "application/json");
        method.addHeader("User-Agent", "KylinJDBCDriver");

        String username = connProps.getProperty("user");
        String password = connProps.getProperty("password");
        String basicAuth = DatatypeConverter
                .printBase64Binary((username + ":" + password).getBytes(StandardCharsets.UTF_8));
        method.addHeader("Authorization", "Basic " + basicAuth);
    }

    @Override
    public void connect() throws IOException {
        HttpPost post = new HttpPost(baseUrl() + "/kylin/api/user/authentication");
        addHttpHeaders(post);
        StringEntity requestEntity = new StringEntity("{}", ContentType.create("application/json", "UTF-8"));
        post.setEntity(requestEntity);

        try {
            HttpResponse response = httpClient.execute(post);

            if (response.getStatusLine().getStatusCode() != 200 && response.getStatusLine().getStatusCode() != 201) {
                throw asIOException(post, response);
            }
        } finally {
            post.releaseConnection();
        }
    }

    @Override
    public KMetaProject retrieveMetaData(String project) throws IOException {
        assert connInfo.getProject().equals(project);

        String url = baseUrl() + "/kylin/api/tables_and_columns?project=" + project;
        HttpGet get = new HttpGet(url);
        addHttpHeaders(get);

        HttpResponse response = httpClient.execute(get);
        try {
            if (response.getStatusLine().getStatusCode() != 200 && response.getStatusLine().getStatusCode() != 201) {
                throw asIOException(get, response);
            }

            List<TableMetaStub> tableMetaStubs = jsonMapper.readValue(response.getEntity().getContent(),
                    new TypeReference<List<TableMetaStub>>() {
                    });
            List<KMetaTable> tables = convertMetaTables(tableMetaStubs);
            List<KMetaSchema> schemas = convertMetaSchemas(tables);
            List<KMetaCatalog> catalogs = convertMetaCatalogs(schemas);
            return new KMetaProject(project, catalogs);
        } finally {
           get.releaseConnection();
        }
    }

    private List<KMetaCatalog> convertMetaCatalogs(List<KMetaSchema> schemas) {
        Map<String, List<KMetaSchema>> catalogMap = new LinkedHashMap<String, List<KMetaSchema>>();
        for (KMetaSchema schema : schemas) {
            List<KMetaSchema> list = catalogMap.get(schema.tableCatalog);
            if (list == null) {
                list = new ArrayList<KMetaSchema>();
                catalogMap.put(schema.tableCatalog, list);
            }
            list.add(schema);
        }

        List<KMetaCatalog> result = new ArrayList<KMetaCatalog>();
        for (List<KMetaSchema> catSchemas : catalogMap.values()) {
            String catalog = catSchemas.get(0).tableCatalog;
            result.add(new KMetaCatalog(catalog, catSchemas));
        }
        return result;
    }

    private List<KMetaSchema> convertMetaSchemas(List<KMetaTable> tables) {
        Map<String, List<KMetaTable>> schemaMap = new LinkedHashMap<String, List<KMetaTable>>();
        for (KMetaTable table : tables) {
            String key = table.tableCat + "!!" + table.tableSchem;
            List<KMetaTable> list = schemaMap.get(key);
            if (list == null) {
                list = new ArrayList<KMetaTable>();
                schemaMap.put(key, list);
            }
            list.add(table);
        }

        List<KMetaSchema> result = new ArrayList<KMetaSchema>();
        for (List<KMetaTable> schemaTables : schemaMap.values()) {
            String catalog = schemaTables.get(0).tableCat;
            String schema = schemaTables.get(0).tableSchem;
            result.add(new KMetaSchema(catalog, schema, schemaTables));
        }
        return result;
    }

    private List<KMetaTable> convertMetaTables(List<TableMetaStub> tableMetaStubs) {
        List<KMetaTable> result = new ArrayList<KMetaTable>(tableMetaStubs.size());
        for (TableMetaStub tableStub : tableMetaStubs) {
            result.add(convertMetaTable(tableStub));
        }
        return result;
    }

    private KMetaTable convertMetaTable(TableMetaStub tableStub) {
        List<KMetaColumn> columns = new ArrayList<KMetaColumn>(tableStub.getColumns().size());
        for (ColumnMetaStub columnStub : tableStub.getColumns()) {
            columns.add(convertMetaColumn(columnStub));
        }
        return new KMetaTable(tableStub.getTABLE_CAT(), tableStub.getTABLE_SCHEM(), tableStub.getTABLE_NAME(),
                tableStub.getTABLE_TYPE(), columns);
    }

    private KMetaColumn convertMetaColumn(ColumnMetaStub columnStub) {
        return new KMetaColumn(columnStub.getTABLE_CAT(), columnStub.getTABLE_SCHEM(), columnStub.getTABLE_NAME(),
                columnStub.getCOLUMN_NAME(), columnStub.getDATA_TYPE(), columnStub.getTYPE_NAME(),
                columnStub.getCOLUMN_SIZE(), columnStub.getDECIMAL_DIGITS(), columnStub.getNUM_PREC_RADIX(),
                columnStub.getNULLABLE(), columnStub.getCHAR_OCTET_LENGTH(), columnStub.getORDINAL_POSITION(),
                columnStub.getIS_NULLABLE());
    }

    private static Date dateConvert(String value) {
        ZoneId utc = ZoneId.of("UTC");
        LocalDate localDate = Date.valueOf(value).toLocalDate();
        return new Date(localDate.atStartOfDay(utc).toInstant().toEpochMilli());
    }

    private static Timestamp timestampConvert(String value) {
        ZoneId utc = ZoneId.of("UTC");
        LocalDateTime localDate = Timestamp.valueOf(value).toLocalDateTime();
        return new Timestamp(localDate.atZone(utc).toInstant().toEpochMilli());
    }

    @Override
    public QueryResult executeQuery(String sql, List<Object> paramValues,
            Map<String, String> queryToggles) throws IOException {

        SQLResponseStub queryResp = executeKylinQuery(sql, convertParameters(paramValues), queryToggles);
        if (queryResp.getIsException())
            throw new IOException(queryResp.getExceptionMessage());

        List<ColumnMetaData> metas = convertColumnMeta(queryResp);
        List<Object> data = convertResultData(queryResp, metas);

        return new QueryResult(metas, data, queryResp.getQueryId());
    }

    private List<StatementParameter> convertParameters(List<Object> paramValues) {
        if (paramValues == null) {
            return null;
        }
        List<StatementParameter> result = new ArrayList<StatementParameter>();
        for (Object v : paramValues) {
            result.add(new StatementParameter(v.getClass().getCanonicalName(), String.valueOf(v)));
        }
        return result;
    }

    private SQLResponseStub executeKylinQuery(String sql, List<StatementParameter> params,
            Map<String, String> queryToggles) throws IOException {
        String url = baseUrl() + "/kylin/api/query";
        String project = connInfo.getProject();

        PreparedQueryRequest request = new PreparedQueryRequest();
        if (null != params) {
            request.setParams(params);
        }
        request.setSql(sql);
        request.setProject(project);
        request.setBackdoorToggles(queryToggles);

        HttpPost post = new HttpPost(url);
        addHttpHeaders(post);

        String postBody = jsonMapper.writeValueAsString(request);
        logger.debug("Post body:\n {}", postBody);
        StringEntity requestEntity = new StringEntity(postBody, ContentType.create("application/json", "UTF-8"));
        post.setEntity(requestEntity);

        try {
            HttpResponse response = httpClient.execute(post);
            if (response.getStatusLine().getStatusCode() != 200 && response.getStatusLine().getStatusCode() != 201) {
                throw asIOException(post, response);
            }

            SQLResponseStub stub = jsonMapper.readValue(response.getEntity().getContent(), SQLResponseStub.class);
            return stub;
        } finally {
            post.releaseConnection();
        }
    }

    private List<ColumnMetaData> convertColumnMeta(SQLResponseStub queryResp) {
        List<ColumnMetaData> metas = new ArrayList<ColumnMetaData>();
        for (int i = 0; i < queryResp.getColumnMetas().size(); i++) {
            SQLResponseStub.ColumnMetaStub scm = queryResp.getColumnMetas().get(i);
            Class columnClass = convertType(scm.getColumnType());
            ScalarType type = ColumnMetaData.scalar(scm.getColumnType(), scm.getColumnTypeName(), Rep.of(columnClass));

            ColumnMetaData meta = new ColumnMetaData(i, scm.isAutoIncrement(), scm.isCaseSensitive(),
                    scm.isSearchable(), scm.isCurrency(), scm.getIsNullable(), scm.isSigned(), scm.getDisplaySize(),
                    scm.getLabel(), scm.getName(), scm.getSchemaName(), scm.getPrecision(), scm.getScale(),
                    scm.getTableName(), scm.getSchemaName(), type, scm.isReadOnly(), scm.isWritable(), scm.isWritable(),
                    columnClass.getCanonicalName());

            metas.add(meta);
        }

        return metas;
    }

    private List<Object> convertResultData(SQLResponseStub queryResp, List<ColumnMetaData> metas) {
        List<String[]> stringResults = queryResp.getResults();
        List<Object> data = new ArrayList<Object>(stringResults.size());
        for (String[] result : stringResults) {
            Object[] row = new Object[result.length];

            for (int i = 0; i < result.length; i++) {
                ColumnMetaData meta = metas.get(i);
                row[i] = wrapObject(result[i], meta.type.id);
            }

            data.add(row);
        }
        return (List<Object>) data;
    }

    private IOException asIOException(HttpRequestBase request, HttpResponse response) throws IOException {
        return new IOException(request.getMethod() + " failed, error code " + response.getStatusLine().getStatusCode()
                + " and response: " + EntityUtils.toString(response.getEntity()));
    }

    @Override
    public void close() throws IOException {
    }
}


text:
from tethys_sdk.testing import TethysTestCase
import tethys_services.models as service_model
from unittest import mock

from tethys_services.models import HTTPError, URLError

class WebProcessingServiceTests(TethysTestCase):
    def set_up(self):
        pass

    def tear_down(self):
        pass

    def test_unicode(self):
        wps = service_model.WebProcessingService(
            name="test_sds",
        )
        self.assertEqual("test_sds", str(wps))

    def test_activate(self):
        wps = service_model.WebProcessingService(
            name="test_sds",
            endpoint="http://localhost/geoserver/rest/",
            public_endpoint="http://publichost/geoserver/rest/",
            username="foo",
            password="password",
        )
        wps.save()
        # Check result
        mock_wps = mock.MagicMock()
        mock_wps.getcapabilities.return_value = "test"

        ret = wps.activate(mock_wps)

        mock_wps.getcapabilities.assert_called()
        self.assertEqual(mock_wps, ret)

    def test_activate_http_error_404(self):
        wps = service_model.WebProcessingService(
            name="test_sds",
            endpoint="http://localhost/geoserver/rest/",
            public_endpoint="http://publichost/geoserver/rest/",
            username="foo",
            password="password",
        )

        # Check result
        mock_wps = mock.MagicMock()
        mock_wps.getcapabilities.side_effect = HTTPError(
            url="test_url", code=404, msg="test_message", hdrs="test_header", fp=None
        )

        self.assertRaises(HTTPError, wps.activate, mock_wps)

    def test_activate_http_error_not_404(self):
        wps = service_model.WebProcessingService(
            name="test_sds",
            endpoint="http://localhost/geoserver/rest/",
            public_endpoint="http://publichost/geoserver/rest/",
            username="foo",
            password="password",
        )

        # Check result
        mock_wps = mock.MagicMock()
        mock_wps.getcapabilities.side_effect = HTTPError(
            url="test_url", code=500, msg="test_message", hdrs="test_header", fp=None
        )

        self.assertRaises(HTTPError, wps.activate, mock_wps)

    def test_activate_url_error(self):
        wps = service_model.WebProcessingService(
            name="test_sds",
            endpoint="http://localhost/geoserver/rest/",
            public_endpoint="http://publichost/geoserver/rest/",
            username="foo",
            password="password",
        )

        # Check result
        mock_wps = mock.MagicMock()
        mock_wps.getcapabilities.side_effect = URLError(reason="test_url")

        ret = wps.activate(mock_wps)

        self.assertIsNone(ret)

    def test_activate_error(self):
        wps = service_model.WebProcessingService(
            name="test_sds",
            endpoint="http://localhost/geoserver/rest/",
            public_endpoint="http://publichost/geoserver/rest/",
            username="foo",
            password="password",
        )

        # Check result
        mock_wps = mock.MagicMock()
        mock_wps.getcapabilities.side_effect = Exception

        self.assertRaises(Exception, wps.activate, mock_wps)

    @mock.patch("tethys_services.models.WebProcessingService.activate")
    @mock.patch("tethys_services.models.WPS")
    def test_get_engine(self, mock_wps, mock_activate):
        wps = service_model.WebProcessingService(
            name="test_sds",
            endpoint="http://localhost/geoserver/rest/",
            public_endpoint="http://publichost/geoserver/rest/",
            username="foo",
            password="password",
        )
        wps.save()
        # Execute
        wps.get_engine()

        # Check called
        mock_wps.assert_called_with(
            "http://localhost/geoserver/rest/",
            password="password",
            skip_caps=True,
            username="foo",
            verbose=False,
        )
        mock_activate.assert_called_with(wps=mock_wps())


text:
package org.brtracer.bug;

import java.util.TreeSet;

public class Bug {

	String bugId;
	String openDate;
	String fixDate;
	String bugSummary;
	String bugDescription;
	TreeSet<String> set = new TreeSet<String>();

	public String getBugId() {
		return bugId;
	}

	public void setBugId(String bugId) {
		this.bugId = bugId;
	}

	public String getOpenDate() {
		return openDate;
	}

	public void setOpenDate(String openDate) {
		this.openDate = openDate;
	}

	public String getFixDate() {
		return fixDate;
	}

	public void setFixDate(String fixDate) {
		this.fixDate = fixDate;
	}

	public String getBugSummary() {
		return bugSummary;
	}

	public void setBugSummary(String bugSummary) {
		this.bugSummary = bugSummary;
	}

	public String getBugDescription() {
		return bugDescription;
	}

	public void setBugDescription(String bugDescription) {
		this.bugDescription = bugDescription;
	}

	public TreeSet<String> getSet() {
		return set;
	}

	public void addFixedFile(String fileName) {
		this.set.add(fileName);
	}

}


text:
In this lab, you do image classification from scratch on a flowers dataset using the Estimator API.

## Setup

![[/fragments/start-qwiklab]]

## Create Storage Bucket

*Duration is 2 min*

![[/fragments/create-bucket]]

## Launch Cloud Datalab

![[/fragments/setup-datalab]]

## Clone course repo within your Datalab instance

![[/fragments/clone-repo-in-datalab]]

## Flowers Image Classification

__Step 1__

In Cloud Datalab, click on the __Home__ icon, and then navigate to __datalab > notebooks > training-data-analyst > courses > machine_learning > deepdive > 08_image > labs__ and open __flowers_fromscratch.ipynb__.

Note: If the cloud shell used for running the datalab command is closed or interrupted, the connection to your Cloud Datalab VM will terminate. If that happens, you may be able to reconnect using the command 'datalab connect mydatalabvm' in your new Cloud Shell. Once connected, try the above step again.

__Step 2__

In Datalab, click on __Clear | Clear all Cells__. Now read the narrative and execute each cell in turn.

![[/fragments/endqwiklab]]

Last Tested Date: 18-01-2019

Last Updated Date: 18-01-2019

![[/fragments/copyright]]


text:
<?php

	// Starts the session

		// Sets the session timeout (30 minutes)
		session_set_cookie_params(time() + (60 * 30));

		// Starts it
		session_start();

	// If session isn't active, redirects to login screen
	if(!$_SESSION["active"]) {

		// If it is a persistent cookie access
		if ($_COOKIE["QuotesMachine-PersistentLogin"]) {

			// Login redirection
			$redirection = $_SERVER["PHP_SELF"];
		}

		// Redirects to login.php
		header("Location: " . ($include_root ? $include_root : null) .  "system.login.php" . ($redirection ? "?g=" . rawurlencode($redirection) : null));
			die();
	}

	// If session is active and persistent login set, refreshes its cookies
	elseif ($_SESSION["active"] and $_COOKIE["QuotesMachine-PersistentLogin"]) {

		// Computes the cookie expiration
		$expiration = time() + (60 * 60 * 24 * 365);

		// Sets them
		setcookie("QuotesMachine-PersistentLogin", true, $expiration);
		setcookie("QuotesMachine-User", $_COOKIE["QuotesMachine-User"], $expiration);
		setcookie("QuotesMachine-Password", $_COOKIE["QuotesMachine-Password"], $expiration);
	}
?>


text:
#include "CCGeometry.h"

namespace cocos2d {

	CCPoint::CCPoint(void)
	{
		x = 0;
		y = 0;
	}

	CCPoint::CCPoint(float x, float y)
	{
		this->x = x;
		this->y = y;
	}

	bool CCPoint::CCPointEqualToPoint(const CCPoint& point1, const CCPoint& point2)
	{
		return ((point1.x == point2.x) && (point1.y == point2.y));
	}

	CCSize::CCSize(void)
	{
		width = 0;
		height = 0;
	}

	CCSize::CCSize(float width, float height)
	{
		this->width = width;
		this->height = height;
	}

	bool CCSize::CCSizeEqualToSize(const CCSize& size1, const CCSize& size2)
	{
		return ((size1.width == size2.width) && (size1.height == size2.height));
	}

	CCRect::CCRect(void)
	{
		origin.x = 0;
		origin.y = 0;

		size.width = 0;
		size.height = 0;
	}

	CCRect::CCRect(float x, float y, float width, float height)
	{
		// Only support that, the width and height > 0
		CC_ASSERT(width >= 0 && height >= 0);

		origin.x = x;
		origin.y = y;

		size.width = width;
		size.height = height;
	}

	bool CCRect::CCRectEqualToRect(const CCRect& rect1, const CCRect& rect2)
	{
		return (CCPoint::CCPointEqualToPoint(rect1.origin, rect2.origin)
			&& CCSize::CCSizeEqualToSize(rect1.size, rect2.size));
	}

	float CCRect::CCRectGetMaxX(const CCRect& rect)
	{
		return rect.origin.x + rect.size.width;
	}

	float CCRect::CCRectGetMidX(const CCRect& rect)
	{
		return (float)(rect.origin.x + rect.size.width / 2.0);
	}

	float CCRect::CCRectGetMinX(const CCRect& rect)
	{
		return rect.origin.x;
	}

	float CCRect::CCRectGetMaxY(const CCRect& rect)
	{
		return rect.origin.y + rect.size.height;
	}

	float CCRect::CCRectGetMidY(const CCRect& rect)
	{
		return (float)(rect.origin.y + rect.size.height / 2.0);
	}

	float CCRect::CCRectGetMinY(const CCRect& rect)
	{
		return rect.origin.y;
	}

	bool CCRect::CCRectContainsPoint(const CCRect& rect, const CCPoint& point)
	{
		bool bRet = false;

		if (point.x >= CCRectGetMinX(rect) && point.x <= CCRectGetMaxX(rect)
			&& point.y >= CCRectGetMinY(rect) && point.y <= CCRectGetMaxY(rect))
		{
			bRet = true;
		}

		return bRet;
	}

	bool CCRect::CCRectIntersectsRect(const CCRect& rectA, const CCRect& rectB)
	{
		return !(CCRectGetMaxX(rectA) < CCRectGetMinX(rectB)||
			CCRectGetMaxX(rectB) < CCRectGetMinX(rectA)||
			CCRectGetMaxY(rectA) < CCRectGetMinY(rectB)||
			CCRectGetMaxY(rectB) < CCRectGetMinY(rectA));
	}

}


text:
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="dev" verbose="1">
	<test name="test">
	<classes><class name="il.co.topq.difido.automation_infra_tests.ReporterTests"></class>
	</classes>
	</test>
</suite>


text:
namespace Rcpp{

    template <typename CLASS>
    class NoProtectStorage {
    public:

        NoProtectStorage() : data(R_NilValue){}

        ~NoProtectStorage(){
            data = R_NilValue;
        }

        inline void set__(SEXP x){
            data = x ;

            // calls the update method of CLASS
            // this is where to react to changes in the underlying SEXP
            static_cast<CLASS&>(*this).update(data) ;
        }

        inline SEXP get__() const {
            return data ;
        }

        inline SEXP invalidate__(){
            data = R_NilValue ;
            return data ;
        }

        inline CLASS& copy__(const CLASS& other){
            if( this != &other){
                set__(other.get__());
            }
            return static_cast<CLASS&>(*this) ;
        }

        inline bool inherits(const char* clazz) const {
            return ::Rf_inherits( data, clazz) ;
        }

        inline operator SEXP() const {
            return data;
        }

    private:
        SEXP data ;
    } ;

}

#endif


text:
package proguard.classfile.editor;

import proguard.classfile.*;
import proguard.classfile.attribute.*;
import proguard.classfile.attribute.visitor.*;
import proguard.classfile.instruction.*;
import proguard.classfile.instruction.visitor.InstructionVisitor;
import proguard.classfile.util.SimplifiedVisitor;

/**
 * This AttributeVisitor remaps variable indexes in all attributes that it
 * visits, based on a given index map.
 *
 * @author Eric Lafortune
 */
public class VariableRemapper
extends      SimplifiedVisitor
implements   AttributeVisitor,
             InstructionVisitor,
             LocalVariableInfoVisitor,
             LocalVariableTypeInfoVisitor
{
    private static final boolean DEBUG = false;

    private final CodeAttributeEditor codeAttributeEditor = new CodeAttributeEditor();

    private int[] variableMap;

    /**
     * Sets the given mapping of old variable indexes to their new indexes.
     * Variables that should disappear can be mapped to -1.
     */
    public void setVariableMap(int[] variableMap)
    {
        this.variableMap = variableMap;
    }

    // Implementations for AttributeVisitor.

    public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}

    public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
    {
        if (DEBUG)
        {
            System.out.println("VariableRemapper: "+clazz.getName()+"."+method.getName(clazz)+method.getDescriptor(clazz));
            for (int index= 0; index < codeAttribute.u2maxLocals; index++)
            {
                System.out.println("  v"+index+" -> "+variableMap[index]);
            }
        }

        // Remap the variables of the attributes, before editing the code and
        // cleaning up its local variable frame.
        codeAttribute.attributesAccept(clazz, method, this);

        // Initially, the code attribute editor doesn't contain any changes.
        codeAttributeEditor.reset(codeAttribute.u4codeLength);

        // Remap the variables of the instructions.
        codeAttribute.instructionsAccept(clazz, method, this);

        // Apply the code atribute editor.
        codeAttributeEditor.visitCodeAttribute(clazz, method, codeAttribute);
    }

    public void visitLocalVariableTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTableAttribute localVariableTableAttribute)
    {
        // Remap the variable references of the local variables.
        localVariableTableAttribute.localVariablesAccept(clazz, method, codeAttribute, this);
    }

    public void visitLocalVariableTypeTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeTableAttribute localVariableTypeTableAttribute)
    {
        // Remap the variable references of the local variables.
        localVariableTypeTableAttribute.localVariablesAccept(clazz, method, codeAttribute, this);
    }

    // Implementations for LocalVariableInfoVisitor.

    public void visitLocalVariableInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableInfo localVariableInfo)
    {
        localVariableInfo.u2index =
            remapVariable(localVariableInfo.u2index);
    }

    // Implementations for LocalVariableTypeInfoVisitor.

    public void visitLocalVariableTypeInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeInfo localVariableTypeInfo)
    {
        localVariableTypeInfo.u2index =
            remapVariable(localVariableTypeInfo.u2index);
    }

    // Implementations for InstructionVisitor.

    public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction) {}

    public void visitVariableInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, VariableInstruction variableInstruction)
    {
        // Is the new variable index different from the original one?
        int oldVariableIndex = variableInstruction.variableIndex;
        int newVariableIndex = remapVariable(oldVariableIndex);
        if (newVariableIndex != oldVariableIndex)
        {
            // Replace the instruction.
            Instruction replacementInstruction =
                new VariableInstruction(variableInstruction.opcode,
                                        newVariableIndex,
                                        variableInstruction.constant).shrink();

            codeAttributeEditor.replaceInstruction(offset, replacementInstruction);
        }
    }

    // Small utility methods.

    /**
     * Returns the new variable index of the given variable.
     */
    private int remapVariable(int variableIndex)
    {
        return variableMap[variableIndex];
    }
}


text:
package com.itmaoo.scenic.dao;

import com.itmaoo.scenic.entity.po.ImagePo;
import com.itmaoo.scenic.entity.query.ImageQuery;

public interface IImageDao extends IBaseDao<ImagePo>{

	ImagePo selectSingleByUserAndImageName(ImageQuery imageQuery);

	int updateByImageName(ImagePo image);

}