text:
var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
var async = require('async');
var underscore = require('underscore');
var util = require('../util');
var sqlBuilder = require('../sqlBuilder');

var config, connection, _dataSource;

function setDataSource(dataSource) {
    _dataSource = dataSource;
    config = {
        userName: dataSource.user,
        password: dataSource.password,
        server: dataSource.host,
        // If you're on Windows Azure, you will need this:
        options: {
            encrypt: true,
            port: dataSource.port,
            database: dataSource.database,
            connectTimeout: 25000,
            requestTimeout: 25000,
            tdsVersion: '7_3_A'
        }
    };
    /*connection = new Connection(config);
    connection.on('connect', function(err) {
            console.log(err);
            console.log('connected.......')
        }
    );*/
}

function query(sql, callback) {
    console.log(sql);
    if('T' === _dataSource.isVpn) {
        vpnQuery(sql, callback);
        return;
    }
    connection = new Connection(config);
    connection.on('connect', function(err) {
            if(err) {
                console.log(err);
                return;
            }
            var result = [];

            var request = new Request(sql, function(err, rowCount) {
                if (err) {
                    console.log(err);
                }
                callback(result);
            });

            request.on('row', function(columns) {
                var obj = {};
                columns.forEach(function(column) {
                    var key = column.metadata.colName;
                    obj[key]  = column.value ? column.value : '';
                });
                result.push(obj);
            });

            connection.execSql(request);
        }
    ).on('error', function(err) {
            console.log('Error: \n');
            console.log(err);
        }
    );

    //connection.close();
}

function queryByBuilder(builder, start, length, callback, tableName, pkColName) {
    queryByPage(builder.build(), start, length, callback, tableName, pkColName);
}

function queryByPage(sql, start, length, callback, tableName, pkColName, orderBy) {
    sql = sql.toLowerCase();
    if(_dataSource.isVpn) {
        vpnQueryByPage(sql, start, length, callback, tableName, pkColName, orderBy);
        return;
    }

    var countSql = getCountSql(sql);

    async.parallel({
        totalCount: function(callback) {
            if(!tableName || !pkColName) {
                callback(null, length);
                return;
            }
            console.log(countSql);
            connection.on('connect', function(err) {
                    if(err) {
                        console.log(err);
                        return;
                    }
                    var result = [];

                    var request = new Request(sql, function(err, rowCount) {
                        if (err) {
                            console.log(err);
                        }
                        callback(null, result[0].count);
                    });

                    request.on('row', function(columns) {
                        var obj = {};
                        columns.forEach(function(column) {
                            var key = column.metadata.colName;
                            obj[key]  = column.value ? column.value : '';
                        });
                        result.push(obj);
                    });

                    connection.execSql(request);
                }
            );
        },
        rows: function(callback) {
            sql = getPageSql(sql, tableName, pkColName, start, length, orderBy);
            console.log(sql);
            connection = new Connection(config);
            connection.on('connect', function(err) {
                    if(err) {
                        console.log(err);
                        return;
                    }
                    var result = [];

                    var request = new Request(sql, function(err, rowCount) {
                        if (err) {
                            console.log(err);
                        }
                        callback(null, result);
                    });

                    request.on('row', function(columns) {
                        var obj = {};
                        columns.forEach(function(column) {
                            var key = column.metadata.colName.toLowerCase();
                            var value = column.value;

                            if(value && underscore._.isDate(value)) {
                                obj[key] = util.utilDate.format(value, 'yyyy-MM-dd hh:mm:ss');
                            } else {
                                obj[key]  = value ? value : '';
                            }
                        });
                        result.push(obj);
                    });

                    connection.execSql(request);
                }
            );
        }
    }, function(err, results) {
        var result = {draw: 1, recordsTotal: results.totalCount, recordsFiltered: results.totalCount, data: results.rows};
        callback(result);
    })
}

function getCountSql(sql) {
    var idx = sql.lastIndexOf('from');
    return 'select count(1) count ' + sql.substr(idx);
}

function getPageSql(sql_, tableName, pkColName, start, length, orderBy) {
    var sql;
    if(tableName && pkColName) {
        sql = "select top %length * from (select row_number() over(order by %pkColName) as n, * from (%sql) tt) t where t.n > %start";
        sql = util.utilString.replaceAll(sql, '%length', length);
        sql = util.utilString.replaceAll(sql, '%pkColName', pkColName);
        sql = util.utilString.replaceAll(sql, '%sql', sql_);
        sql = util.utilString.replaceAll(sql, '%start', start);
        if(orderBy) {
            sql += " order by " + orderBy;
        }
    } else {
        sql = "SELECT top " + length + " * FROM (" + sql_ + ") t";
    }

    return sql;
}

function vpnQuery(sql, callback) {
    console.log(sql);
    var request = require('request');
    request.post({url: 'http://localhost:8080/db', form: {host: _dataSource.host, port: _dataSource.port, user: _dataSource.user, password: _dataSource.password, sql: sql, database: _dataSource.database}}, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            callback(JSON.parse(body));
        } else {
            console.log(error);
            callback();
        }
    });
}

function vpnQueryByPage(sql, start, length, callback, tableName, pkColName, orderBy) {
    var countSql = getCountSql(sql, tableName);
    console.log(countSql);
    var pageSql = getPageSql(sql, tableName, pkColName, start, length, orderBy);
    console.log(pageSql);
    var request = require('request');
    request.post({url: 'http://localhost:8080/db', form: {host: _dataSource.host, port: _dataSource.port, user: _dataSource.user, password: _dataSource.password, sql: pageSql, countSql: countSql, database: _dataSource.database}}, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            callback(JSON.parse(body));
        } else {
            console.log(error);
            callback({});
        }
    });
}

function getUsers(callback) {
    query(getUserSql(), callback);
}

function getPrivileges(callback) {
    query(getPrivilegesSql(), callback);
}

function getCharsets(callback) {
    query(getCharsetsSql(), callback);
}

function getSchemas(callback) {
    query(getSchemaSql(), callback);
}

function getTables(schema, callback) {
    query(getTableSql(schema), callback);
}

function getViews(schema, callback) {
    query(getViewSql(schema), callback);
}

function getFunctions(schema, callback) {
    query(getFunctionsSql(schema), callback);
}

function getProcedures(schema, callback) {
    query(getProceduresSql(schema), callback);
}

function getColumns(schema, table, callback) {
    query(getColumnSql(schema, table), callback);
}

function getConstraints(schema, table, callback) {
    query(getConstraintsSql(schema, table), callback);
}

function getIndexes(schema, table, callback) {
    query(getIndexesSql(schema, table), callback);
}

function getTriggers(schema, table, callback) {
    query(getTriggersSql(schema, table), callback);
}

function getParameters(schema, methodName, callback) {
    query(getParametersSql(schema, methodName), callback);
}

function getFKConstraintsColumns(schema,callback, conditions) {
    query(getFKConstraintsColumnsSql(schema, conditions), callback);
}

module.exports = {
    setDataSource: setDataSource,
    query: query,
    queryByPage: queryByPage,
    queryByBuilder: queryByBuilder,
    getUsers: getUsers,
    getPrivileges: getPrivileges,
    getCharsets: getCharsets,
    getSchemas: getSchemas,
    getTables: getTables,
    getViews: getViews,
    getFunctions: getFunctions,
    getProcedures: getProcedures,
    getColumns: getColumns,
    getConstraints: getConstraints,
    getIndexes: getIndexes,
    getTriggers: getTriggers,
    getParameters: getParameters,
    getFKConstraintsColumns: getFKConstraintsColumns,
    getSearchSql: getSearchSql
};

function getUserSql() {
    return "select\n" +
        "                name as name,\n" +
        "                name as displayName,\n" +
        "                'N' as isExpired,\n" +
        "                'N' as isLocked\n" +
        "            from sys.schemas\n" +
        "            order by schema_id asc";
}

function getPrivilegesSql() {
    return "select distinct\n" +
        "                permission_name as name,\n" +
        "                permission_name as displayName\n" +
        "            from fn_builtin_permissions(default)\n" +
        "            order by permission_name asc";
}

function getCharsetsSql() {
    return "select\n" +
        "                name as name,\n" +
        "                name as displayName,\n" +
        "                0 as maxLength\n" +
        "            from sys.syscharsets\n" +
        "            order by name asc";
}

function getSchemaSql() {
    return "select\n" +
        "                name as name,\n" +
        "                'N' as isPublic,\n" +
        "                (case when database_id > 3 then 'N' else 'Y' end) as isSystem\n" +
        "            from sys.databases\n" +
        "            order by name asc";
}

function getTableSql(schema) {
    return "select\n" +
        "                name name,\n" +
        "                (select top 1 convert(varchar, value) from [" + schema + "].sys.extended_properties where major_id = object_id) displayName,\n" +
        "                'N' as isTemporary\n" +
        "            from  [" + schema + "].sys.TABLES\n" +
        "            order by name asc";
}

function getViewSql(schema) {
    return "select\n" +
        "                table_name as name,\n" +
        "                table_name as displayName,\n" +
        "                null as viewTypeOwner,\n" +
        "                null as viewType,\n" +
        "                'N' as isSystemView\n" +
        "            from [" + schema + "].INFORMATION_SCHEMA.views\n" +
        "            order by table_name asc";
}

function getProceduresSql(schema) {
    return "select\n" +
        "                ROUTINE_NAME as name,\n" +
        "                ROUTINE_NAME as displayName,\n" +
        "                'Y' as isValid,\n" +
        "                'N' as isDebug,\n" +
        "                'N' as isDeterministic\n" +
        "            from [" + schema + "].INFORMATION_SCHEMA.ROUTINES\n" +
        "            where\n" +
        "                ROUTINE_CATALOG = '" + schema + "' and\n" +
        "                ROUTINE_TYPE = 'PROCEDURE'\n" +
        "            order by ROUTINE_NAME asc";
}

function getColumnSql(schema, table) {
    return "select\n" +
        "                col.name as name,\n" +
        "                (select top 1 convert(varchar, value) from [" + schema + "].sys.extended_properties where major_id = col.object_id and minor_id = col.column_id) displayName,\n" +
        "                col.column_id as position,\n" +
        "                (select top 1 name from [" + schema + "].sys.types where system_type_id = col.system_type_id) as dataType,\n" +
        "                null as dataTypeOwner,\n" +
        "                null as dataTypePackage,\n" +
        "                col.max_length as maxLength,\n" +
        "                col.PRECISION as numPrecision,\n" +
        "                col.SCALE as numScale,\n" +
        "                (case when col.IS_NULLABLE = 0 then 'N' else 'Y' end) as isNullable,\n" +
        "                'N' as isHidden,\n" +
        "                ISNULL((SELECT top 1 'Y' FROM sysobjects where xtype='PK' and  parent_obj=col.object_id and name in (SELECT name  FROM sysindexes WHERE indid in(SELECT indid FROM sysindexkeys WHERE id = col.object_id AND colid=col.column_id))), 'N') as isPrimaryKey,\n" +
        "                isnull((select top 1 'Y' from SYSFOREIGNKEYS where fkeyid=col.object_id and fkey=col.column_id), 'N') as isForeignKey\n" +
        "            from [" + schema + "].sys.columns col\n" +
        "            where\n" +
        "                col.object_id = (select object_id from [" + schema + "].sys.tables where name='" + table + "') or \n" +
        "                col.object_id = (select object_id from [" + schema + "].sys.views where name='" + table + "')\n" +
        "            order by col.column_id asc";
}

function getFunctionsSql(schema) {
    return "select\n" +
        "                ROUTINE_NAME as name,\n" +
        "                ROUTINE_NAME as displayName,\n" +
        "                'Y' as isValid,\n" +
        "                'N' as isDebug,\n" +
        "                'N' as isDeterministic\n" +
        "            from [" + schema + "].INFORMATION_SCHEMA.ROUTINES\n" +
        "            where\n" +
        "                ROUTINE_CATALOG = '" + schema + "' and\n" +
        "                ROUTINE_TYPE = 'FUNCTION'\n" +
        "            order by ROUTINE_NAME asc";
}

function getParametersSql(schema, methodName) {
    return "select\n" +
        "                a.PARAMETER_NAME as name,\n" +
        "                a.PARAMETER_NAME as displayName,\n" +
        "                null as PROGRAM_NAME,\n" +
        "                a.SPECIFIC_NAME as METHOD_NAME,\n" +
        "                b.ROUTINE_TYPE as METHOD_TYPE,\n" +
        "                0 as OVERLOAD,\n" +
        "                a.ORDINAL_POSITION as POSITION,\n" +
        "                a.ORDINAL_POSITION as SEQUENCE,\n" +
        "                (case when a.PARAMETER_MODE is null then 'OUT' else a.PARAMETER_MODE end) as IN_OUT,\n" +
        "                null as DATA_TYPE_OWNER,\n" +
        "                null as DATA_TYPE_PACKAGE,\n" +
        "                a.DATA_TYPE as DATA_TYPE_NAME,\n" +
        "                a.CHARACTER_MAXIMUM_LENGTH  as DATA_LENGTH,\n" +
        "                a.NUMERIC_PRECISION as DATA_PRECISION,\n" +
        "                a.NUMERIC_SCALE as DATA_SCALE\n" +
        "            from [" + schema + "].INFORMATION_SCHEMA.PARAMETERS a, [" + schema + "].INFORMATION_SCHEMA.ROUTINES b\n" +
        "            where\n" +
        "                a.SPECIFIC_CATALOG = b.ROUTINE_CATALOG and\n" +
        "                a.SPECIFIC_NAME = b.SPECIFIC_NAME and\n" +
        "                a.SPECIFIC_CATALOG = '" + schema + "' and\n" +
        "                a.SPECIFIC_NAME = '" + methodName + "'\n" +
        "            order by\n" +
        "                a.SPECIFIC_NAME,\n" +
        "                a.ORDINAL_POSITION asc";
}

function getConstraintsSql(schema, table) {
    return "select\n" +
        "                a.constraint_name as name,\n" +
        "                a.CONSTRAINT_TYPE constraintType,\n" +
        "                '' as fkConstraintOwner,\n" +
        "                '' as fkConstraintName,\n" +
        "                'Y' as isEnabled,\n" +
        "                null as checkCondition\n" +
        "                from\n" +
        "                INFORMATION_SCHEMA.TABLE_CONSTRAINTS a,\n" +
        "                INFORMATION_SCHEMA.KEY_COLUMN_USAGE b\n" +
        "            where\n" +
        "                a.table_name = b.table_name and\n" +
        "                a.table_catalog = b.table_catalog and\n" +
        "                a.constraint_name = b.constraint_name and\n" +
        "                a.TABLE_catalog = '" + schema + "' and\n" +
        "                a.table_name = '" + table + "'\n" +
        "            order by\n" +
        "                a.TABLE_NAME,\n" +
        "                a.CONSTRAINT_NAME asc";
}

function getIndexesSql(schema, table) {
    return "select\n" +
        "                name as name,\n" +
        "                (select name from dbo.sysobjects where id=object_id) as tableName,\n" +
        "                '' as columnName,\n" +
        "                (case when is_unique = 0 then 'N' else 'Y' end) as isUnique,\n" +
        "                'Y' as isAsc,\n" +
        "                (case when is_disabled = 0 then 'N' else 'Y' end) as isValid\n" +
        "            from [" + schema + "].sys.indexes\n" +
        "            where\n" +
        "                name is not null and\n" +
        "                object_id = (select id from [" + schema + "].dbo.sysobjects where name='" + table + "' and xtype='U')\n" +
        "            order by name asc";
}

function getTriggersSql(schema, table) {
    return "select\n" +
        "                t.name name,\n" +
        "                '' as triggerType,\n" +
        "                '' as triggeringEvent,\n" +
        "                'Y' as isEnabled,\n" +
        "                'Y' as isValid,\n" +
        "                'N' as isDebug,\n" +
        "                'Y' as isForEachRow\n" +
        "            from [" + schema + "].sys.TRIGGERS t\n" +
        "            where\n" +
        "               object_id = (select id from [" + schema + "].dbo.sysobjects where name='" + table + "' and xtype='U')\n " +
        "            order by parent_id, name asc";
}

function getFKConstraintsColumnsSql(schema, conditions) {
    var sql = "SELECT\n" +
        "  (select name from dbo.sysobjects where id=constid) constraint_name,\n" +
        "  (select name from dbo.sysobjects where id=fkeyid) table_name,\n" +
        "  (select name from sys.columns where OBJECT_ID= fkeyid and column_id=fkey) column_name,\n" +
        "  (select name from dbo.sysobjects where id=rkeyid) referenced_table_name,\n" +
        "  (select name from sys.columns where OBJECT_ID= rkeyid and column_id=rkey) referenced_column_name\n" +
        "FROM [" + schema + "].sys.SYSFOREIGNKEYS b";

    if(conditions) {
        var tableName = conditions.tableName;
        var columnName = conditions.columnName;
        var isAnd;
        var where = ' WHERE ';
        if(tableName) {
            where += "fkeyid = (select id from dbo.sysobjects where name='" + tableName + "')";
            isAnd = true;
        }
        if(columnName) {
            if(isAnd) {
                where += ' AND ';
            }
            where += "fkey = (select column_id from sys.columns where OBJECT_ID= fkeyid and name='" + columnName + "')";
            isAnd = true;
        }

        sql += where;
    }

    return sql;
}

function getSearchSql(value, schemas, filter) {
    var sql = '';
    for(var i = 0; i < schemas.length; i++) {
        var schema = schemas[i];
        var objSql = sqlBuilder.create()
            .query("'" + schema.name + "' id, name, '' comment, (case when (type in ('AF','FN', 'FS', 'FT', 'IF', 'TF')) then 'FUNCTION' when (type in ('F', 'PK', 'UQ')) then 'CONSTRAINT' when (type in ('IT', 'S', 'U', 'TT')) then 'TABLE' when (type in ('P', 'PC', 'X')) then 'PROCEDURE' when (type in ('TA', 'TR')) then 'TRIGGER' when type='V' then 'VIEW' else '' end) dbType")
            .from("[" + schema.name + "].sys.objects");
        if(filter) {
            objSql.where();
            var array = filter.split(',');
            if(underscore._.indexOf(array, 'TABLE') > -1) {
                objSql.ands("type in ('IT', 'S', 'U', 'TT')");
            }
            if(underscore._.indexOf(array, 'VIEW') > -1) {
                objSql.ands("type in ('V')");
            }
            if(underscore._.indexOf(array, 'CONSTRAINT') > -1 || underscore._.indexOf(array, 'INDEX') > -1) {
                objSql.ands("type in ('F', 'PK', 'UQ')");
            }
            if(underscore._.indexOf(array, 'TRIGGER') > -1) {
                objSql.ands("type in ('TA', 'TR')");
            }
            if(underscore._.indexOf(array, 'PROCEDURE') > -1) {
                objSql.ands("type in ('P', 'PC', 'X')");
            }
            if(underscore._.indexOf(array, 'FUNCTION') > -1) {
                objSql.ands("type in ('AF','FN', 'FS', 'FT', 'IF', 'TF')");
            }
        } else {
            objSql.where("type in ('AF', 'F', 'FN', 'FS', 'FT', 'IF', 'IT', 'P', 'PC', 'PK', 'S', 'U', 'TA', 'TR', 'TF', 'TT', 'UQ', 'V', 'X')");
        }
        objSql.like("name", value);
        sql += objSql.build();

        if(!filter || (filter && underscore._.indexOf(filter.split(','), 'COLUMN') > -1)) {
            var columnSql = sqlBuilder.create()
                .query("'" + schema.name + "'+'.'+(select name from dbo.sysobjects where id=col.object_id) id,col.name as name,(select top 1 convert(varchar, value) from [" + schema.name + "].sys.extended_properties where major_id = col.object_id and minor_id = col.column_id) comment, 'COLUMN' dbType")
                .from("[" + schema.name + "].sys.columns col")
                .where()
                .build();

            sql += '\n UNION ALL \n' + columnSql;
        }

        if(i < schemas.length - 1) {
            sql += '\n UNION ALL \n';
        }
    }
    return "SELECT * FROM (" + sql + ") t ORDER BY t.dbType";
}


text:
<?php

namespace Qafeen\Aadhaar;

use Illuminate\Support\ServiceProvider;
use Validator;

class AadhaarServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Validator::extend('valid_aadhaar', function () {
            return app('aadhaar')->isValid();
        });
    }

    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('aadhaar', function ($app) {
            return $app->make(Aadhaar::class);
        });
    }
}

redpajama_set_name: RedPajamaGithub


text:
package eu.modernmt.processing.tokenizer.jflex;

import eu.modernmt.lang.Languages;
import eu.modernmt.lang.UnsupportedLanguageException;
import eu.modernmt.processing.ProcessingException;
import eu.modernmt.processing.TextProcessor;
import eu.modernmt.processing.string.SentenceBuilder;
import eu.modernmt.processing.tokenizer.jflex.annotators.*;

import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * Created by davide on 29/01/16.
 * Updated by andrearossi on 01/03/2017
 *

 * A JFlexTokenizer is an object that performs word tokenization of a string
 * based on the JFlexTokenizer tokenization and analysis library.
 *

 * It has knowledge of all the JFlex tokenization classes
 * (that JFlex implements as Annotators),
 * one for each source language that JFlex supports:
 * Catalan, Czech, German, Greek, ENglish, Spanish, Finnish, French, Hungarian,
 * Icelandic, Italian, Latvian, Dutch, Polish, Portuguese, Romanian, Russian,
 * Slovak, Slovene, Swedish, Tamil.
 */
public class JFlexTokenizer extends TextProcessor<SentenceBuilder, SentenceBuilder> {

    /*For each language that the JFlex library supports, this map stores a couple
        <language -> Class of the JFlex annotator for that language>

	The language is a Locale object, obtained as Languages.LANGUAGE_NAME
	The Annotator class is taken from JFlex library as AnnotatorLanguageName.class.
	In JFlex, all specific annotators extend a common interface Annotator.*/
    private static final Map<Locale, Class<? extends JFlexTokenAnnotator>> ANNOTATORS = new HashMap<>();

    static {
        ANNOTATORS.put(Languages.CATALAN, CatalanTokenAnnotator.class);
        ANNOTATORS.put(Languages.CZECH, CzechTokenAnnotator.class);
        ANNOTATORS.put(Languages.GERMAN, GermanTokenAnnotator.class);
        ANNOTATORS.put(Languages.GREEK, GreekTokenAnnotator.class);
        ANNOTATORS.put(Languages.ENGLISH, EnglishTokenAnnotator.class);
        ANNOTATORS.put(Languages.SPANISH, SpanishTokenAnnotator.class);
        ANNOTATORS.put(Languages.FINNISH, FinnishTokenAnnotator.class);
        ANNOTATORS.put(Languages.FRENCH, FrenchTokenAnnotator.class);
        ANNOTATORS.put(Languages.HUNGARIAN, HungarianTokenAnnotator.class);
        ANNOTATORS.put(Languages.ICELANDIC, IcelandicTokenAnnotator.class);
        ANNOTATORS.put(Languages.ITALIAN, ItalianTokenAnnotator.class);
        ANNOTATORS.put(Languages.LATVIAN, LatvianTokenAnnotator.class);
        ANNOTATORS.put(Languages.DUTCH, DutchTokenAnnotator.class);
        ANNOTATORS.put(Languages.POLISH, PolishTokenAnnotator.class);
        ANNOTATORS.put(Languages.PORTUGUESE, PortugueseTokenAnnotator.class);
        ANNOTATORS.put(Languages.ROMANIAN, RomanianTokenAnnotator.class);
        ANNOTATORS.put(Languages.RUSSIAN, RussianTokenAnnotator.class);
        ANNOTATORS.put(Languages.SLOVAK, SlovakTokenAnnotator.class);
        ANNOTATORS.put(Languages.SLOVENE, SloveneTokenAnnotator.class);
        ANNOTATORS.put(Languages.SWEDISH, SwedishTokenAnnotator.class);
        ANNOTATORS.put(Languages.TAMIL, TamilTokenAnnotator.class);
    }

    /*among all annotators for all languages supported by JFlex,
     * this is the specific annotator for the source language
     * (the language of the SentenceBuilder string to edit)*/
    private final JFlexTokenAnnotator annotator;

    /**
     * This constructor initializes che JFlexTokenizer
     * by setting the source and target language to handle,
     * and by choosing and trying to instantiate the specific JFLex annotator
     * that suits the source language of the string to translate.
     *
     * @param sourceLanguage the language of the input String
     * @param targetLanguage the language the input String must be translated to
     * @throws UnsupportedLanguageException the requested language is not supported by this software
     */
    public JFlexTokenizer(Locale sourceLanguage, Locale targetLanguage) throws UnsupportedLanguageException {
        super(sourceLanguage, targetLanguage);

        Class<? extends JFlexTokenAnnotator> annotatorClass = ANNOTATORS.get(sourceLanguage);

        if (annotatorClass == null) {
            this.annotator = new StandardTokenAnnotator((Reader) null);
        } else {
            try {
                this.annotator = annotatorClass.getConstructor(Reader.class).newInstance((Reader) null);
            } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) {
                throw new Error("Error during class instantiation: " + annotatorClass.getName(), e);
            }
        }
    }

    /**
     * This method uses the Annotator object for the current source language
     * to perform word tokenization of the current string in the SentenceBuilder.
     *

     * It extracts the string from tne StringBuilder, and uses it to
     * build a TokensAnnotatedString.
     * By the interaction between annotator and annotatedString,
     * the indexes of start and end of each token are found
     * and stored in the annotatedString.
     *

     * In the end, such indexes are used to build an array of token strings,
     * that is passed to the TokenizerUtils static object
     * so that it can transform each token String into an actual WORD Token.*
     *
     * @param builder  the SentenceBuilder that holds the current string to tokenize
     * @param metadata additional information on the current pipe
     *                 (not used in this specific operation)
     * @return the SentenceBuilder received as a parameter;
     * its internal state has been updated by the execution of the call() method
     * @throws ProcessingException
     */
    @Override
    public SentenceBuilder call(SentenceBuilder builder, Map<String, Object> metadata) throws ProcessingException {
        TokensAnnotatedString astring = wrap(builder);

        annotator.yyreset(astring.getReader());

        int type;
        while ((type = next(annotator)) != JFlexTokenAnnotator.YYEOF) {
            annotator.annotate(astring, type);
        }

        return astring.compile(builder);
    }

    protected TokensAnnotatedString wrap(SentenceBuilder builder) {
        return new TokensAnnotatedString(builder.toString(), false);
    }

    /**
     * Method that, given an annotator, returns the next token index
     * in the string the annotator is working on.
     *
     * @param annotator the JFlexAnnotator for the string under analysis
     * @return the index of the next token
     * @throws ProcessingException
     */
    private static int next(JFlexTokenAnnotator annotator) throws ProcessingException {
        try {
            return annotator.next();
        } catch (IOException e) {
            throw new ProcessingException(e);
        }
    }

}


text:
"use strict";
define('admin/plugins/portalmark/marksinput', [], function () {
	var socketId = 'nodebb-plugin-portal-mark';
	var marksinput = {},
		modal,markTag,callback,
		timeoutId = 0;

	function findForm(target, tagName) {
		if (!target) return null;
		if ($(target).length == 0) return null;
		if ($(target).prop('tagName') == tagName) return $(target);
		return findForm($(target).parent(), tagName);
	}

	marksinput.init = function () {
		var inputEL = $('.marks-input');
		if (!inputEL.length) {
			return;
		}
		inputEL.on('click', function () {
      var $this = $(this);
      var targetName = $this.attr('input-target');
			var form = findForm($this, 'FORM') || $this.parent().parent();
			var target = form.find('[name="' + targetName + '"]');
      $this.html('')
			if (target.length > 0) {
				marksinput.mark(function (markTag) {
          if(markTag){
            target.val(markTag);
          }
          $this.html('')
				});
			}
		});
	};

	marksinput.mark = function (onComplete) {
		if ($('#mark_choose_modal').length == 0) {
			ajaxify.loadTemplate('portalmark/mark_choose_modal', function (template) {
				translator.translate(templates.parse(template), function (translatedTemplate) {
					$('body').append(translatedTemplate);
					doChoose('#mark_choose_modal', onComplete);
				});
			});
		} else {
			doChoose('#mark_choose_modal', onComplete);
		}
	};

	function doChoose(templateTag, onComplete) {
    callback = onComplete
		modal = $(templateTag);
		modal.on('shown.bs.modal', onPortalmarkModalShown);
    modal.on('hidden.bs.modal', function(){
      onComplete(null)
    })
		$('#mark-confirm').hide();
		modal.find('.modal-header h3').translateText('Choose Portals');
		modal.modal('show');
	}

	function onPortalmarkModalShown() {
		var loadingEl = $('#marks-loading');
		if (!loadingEl.length) {
			return;
		}
		socket.emit('plugins.' + socketId + '.marks.get', [], function (err, data) {
			if (err) {
				return app.alertError(err.message);
			}

			templates.parse('portalmark/mark_list', {
				marks: data
			}, function (html) {
				modal.find('.modal-body .data-list').html(html);
				$('#marks-loading').remove();
				$('.modal-body [data-toggle="tooltip"]').tooltip();
			});

			modal.on('click', '.mark-list .mark-row', function (e) {
				selectMark($(this));
			});
			$('#mark_thread_commit').on('click', function(){
        modal.modal('hide');
        var commitEl = $('#mark_thread_commit');
        if (!commitEl.prop('disabled') && markTag) {
          commitEl.prop('disabled', true);
          if (typeof callback === 'function') {
            callback(markTag);
          }
        }
      });
		});
	}
  function selectMark(marktag) {
    var parentTag = marktag.find('[data-name="mark-parent"]').val();
    var tagEL = marktag.html();
    if (parentTag != "" && parentTag != "{marks.parent}") {
      tagEL = modal.find('.mark-row[data-tag="' + parentTag + '"]').html() + tagEL;
    }
    modal.find('#confirm-marks-name').html(tagEL);
    $('#mark-confirm').show();
    markTag = marktag.attr('data-tag');
    $('#mark_thread_commit').prop('disabled', !markTag);
  }

	return marksinput
});


text:
from __future__ import unicode_literals
import frappe

def get_context(context):
	return { "doc": frappe.get_doc("About Us Settings", "About Us Settings") }


text:
use std::collections::HashMap;
use std::fs::File;
use std::path::Path;
use std::marker::PhantomData;

use csv::Writer;
use serde::{Serialize, Deserialize};

use trading::tick::GenTick;
use transport::tickstream::GenTickSink;
use transport::textlog::debug;

// TODO: Non `CommandServer`-Based Logging

pub struct CsvSink<T> {
    writer: Writer<File>,
    ghost: PhantomData<T>,
}

/// A tick sink that writes data to a CSV file.  As long as the data is able to be split up into columns and serialized, this sink should be able to handle it.
/// Requires that the setting `output_path` be supplied in the settings `HashMap`.
impl<T> GenTickSink<T> for CsvSink<T> where T : Serialize, T : for<'de> Deserialize<'de> {
    fn new(settings: HashMap<String, String>) -> Result<Self, String> {
        let output_path = match settings.get("output_path") {
            Some(p) => p,
            None => { return Err(String::from("You must supply an `output_path` argument in the input `HashMap`~")) },
        };

        Ok(CsvSink {
            writer: Writer::from_path(Path::new(output_path)).map_err(debug)?,
            ghost: PhantomData{},
        })
    }

    fn tick(&mut self, t: GenTick<T>) {
        if let Err(e) = self.writer.serialize((t.timestamp, t.data)) {
            println!("Error while writing line to file: {:?}", e);
        }
        let _ = self.writer.flush(); // TODO: find a better way to handle this
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<CrawlItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Text>kasne 40min!</Text>
  <Rating>0.5</Rating>
  <Source>http://pauza.hr/menu/sombrero-catering-remiza</Source>
</CrawlItem>


text:
/*** Page Route ***/

app.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider

  // Main Container
  .state('app', {
    url: '',
    abstract: true,
    views: {
      'appContainer': {
        templateUrl: 'views/common/layout.html',
      }
    }
  })

  // Home
  .state('app.home', {
    url: '/home',
    views: {
      'mainContainer': {
        templateUrl: 'views/home/home-index.html',
        controller: 'HomeCtrl'
      }
    }
  })

  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/home');

});


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../../core/str/enum.SearchStep.html">

Redirecting to ../../../core/str/enum.SearchStep.html...


text:
require File.expand_path('../../test_helper', __FILE__)
require 'rails/generators'
require File.expand_path('../../../lib/generators/janus/install_generator', __FILE__)

class Janus::Generators::InstallGeneratorTest < Rails::Generators::TestCase
  tests Janus::Generators::InstallGenerator

  destination Rails.root.join('tmp').to_s
  setup :prepare_destination

  test "create" do
    run_generator
    assert_file 'config/initializers/janus.rb'
    assert_file 'config/locales/janus.en.yml'
  end
end


text:
#pragma region Includes
#include <stdio.h>
#include <tchar.h>
#include <windows.h>
#include <assert.h>
#pragma endregion

/*!
* VolumeSupportsSparseFiles determines if the volume supports sparse streams.
*
* \param lpRootPathName
* Volume root path e.g. C:\
*/
BOOL VolumeSupportsSparseFiles(LPCTSTR lpRootPathName);

/*!
* IsSparseFile determines if a file is sparse.
*
* \param lpFileName
* File name
*/
BOOL IsSparseFile(LPCTSTR lpFileName);

/*!
* Get sparse file sizes.
*
* \param lpFileName
* File name
*
* \see
* http://msdn.microsoft.com/en-us/library/aa365276.aspx
*/
BOOL GetSparseFileSize(LPCTSTR lpFileName);

/*!
* Create a sparse file.
*
* \param lpFileName
* The name of the sparse file
*/
HANDLE CreateSparseFile(LPCTSTR lpFileName);

/*!
* Converting a file region to A sparse zero area.
*
* \param hSparseFile
* Handle of the sparse file
*
* \param start
* Start address of the sparse zero area
*
* \param size
* Size of the sparse zero block. The minimum sparse size is 64KB.
*
* \remarks
* Note that SetSparseRange does not perform actual file I/O, and unlike the
* WriteFile function, it does not move the current file I/O pointer or sets
* the end-of-file pointer. That is, if you want to place a sparse zero block
* in the end of the file, you must move the file pointer accordingly using
* the FileStream.Seek function, otherwise DeviceIoControl will have no effect
*/
void SetSparseRange(HANDLE hSparseFile, LONGLONG start, LONGLONG size);

/*!
* Query the sparse file layout.
*
* \param lpFileName
* File name
*/
BOOL GetSparseRanges(LPCTSTR lpFileName);


text:
Redirector
=================
[![Language](https://img.shields.io/badge/language-PHP-blue.svg)](https://github.com/rockbarato/Redirector)

## Installation

Just download the zip and change the constants at `index.php` file.

```php
define('ANDROID_URL', 'https://play.google.com/store/apps/details?id=com.android.chrome&hl=es_419');
define('iOS_URL', 'https://itunes.apple.com/us/app/chrome-web-browser-by-google/id535886823?mt=8');
define('OPTIONAL_URL', 'https://www.google.com/chrome/');
```

## Requirements

* PHP 5.6 and above
* Apache 2

Feel free to collaborate with ideas, issues and/or pull requests.

## License
Redirector is available under the [MIT](http://opensource.org/licenses/MIT) license. See the LICENSE file for more info.


text:
package org.castafiore.web;

import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.castafiore.resource.FileData;
import org.castafiore.resource.ResourceLocator;
import org.castafiore.resource.ResourceLocatorFactory;
import org.castafiore.ui.UIException;
import org.castafiore.utils.ChannelUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping(value="/castafiore")
public class CastafioreController {

	public void doMethod(HttpServletRequest request, HttpServletResponse response){

	}

	@RequestMapping(value="/resource/{type}/{path}")
	public void doResource(@PathVariable(value="type")String type,@PathVariable(value="path") String path, HttpServletRequest request, HttpServletResponse response){
		String spec = null;
		try
		{
			//spec = request.getParameter("spec");
			spec = type + ":" + path;
			//logger.debug(spec);
			ResourceLocator locator = ResourceLocatorFactory.getResourceLocator(spec);
			String width = request.getParameter("width");
			FileData f = locator.getResource(spec, width);
			if(f != null)
			{
				try
				{
					OutputStream os = response.getOutputStream();
					response.setContentType(f.getMimeType());
					((HttpServletResponse)response).setHeader("Content-Disposition", "filename=" + f.getName());
					ChannelUtil.TransferData(f.getInputStream(), os);
					os.flush();
				}
				catch(ClassCastException cce)
				{
					throw new Exception("the file specified by the path " + spec + " is not a binary file");
				}
			}
			else
			{
				 throw new Exception("the file specified by the path " + spec + " cannot be found. Possibly deleted");
			}
		}
		catch(Exception e)
		{
			if(spec == null)
				throw new UIException("unable to load resource since the specification passed is null" ,e);
			else
				throw new UIException("unable to load resource with the specification " + spec ,e);
		}
	}

	public void doExecute(HttpServletRequest request, HttpServletResponse response){

	}

}


text:
layout: post
title:  "DSpace 7 - PO transition"
date:   2019-04-07 23:34:00
categories: DSpace7
---

# Rebasing pull request to master again

Rebased again to the last state of HEAD.

# Starting point: pull request still not merged

The automated travis CI build job is currently choking on the double curly braces in some of the messages.
https://travis-ci.org/DSpace/dspace-angular/jobs/504940152

# Language specific tests passing?

To check if the tests that I wrote myself, are effectively passing.
My own tests were all passing, but the original protractor e2e test from wwelling failed because the homepage now had
DSpace between double quotes, instead of without them.

# Updated .pot catalog and .po english translation with latest en.json content

Now all the keys defined by the developers are in the new catalogs.
What remains is to replace the occurrences of keys in the code, with the English version of those keys, which act as the
keys in the new system.

# Duplicate keys

Some strings appear several times in the catalog, "Field", "Cancel", "Confirm", just to name a few.
The message key extractor prefixed those with a msgctxt entry, which is standard for the gettext format, but what Angular
NGX translate doesn't support.

TODO: test the case out where one would deliberatly want to give such a double occurence, a different translation. My guess
right now, is that we can only give a single translation to a single (literal) original.

## DSpace 7 Angular

* Explore if there's any opportunity to extend documentation or tests in other parts of the DSpace Angular code.
* UI for enabling/disabling particular languages
    * Continue with implementing the actions and the reducer for the language switch.
* Build a feature where users can customize their own language tags, straight from the UI, by switching on some kind of "translator" mode, to do these changes at runtime
* UI for exporting their customized messages
* [Angular Universal](https://angular.io/guide/universal) tutorial based on Tour of Heroes
* Continue where I left off in ng-book

## Analyzer.atmire.com work

* Change String based implementation of error message handling with types and objects, according to Antoine Snyers recent Atmire DevTalk.
* Change string based implementation of the different browse styles to an object, according to Antoine Snyers recent Atmire DevTalk
* Optimize my hideous methods for getItemcount and getRepoCount.
* Re-test the check if we return the right repository to a user who tries to add a new one
* Updating a repository: touch/change the base URL or not?
* Batch ingest: switch to newer add repository methods.
* WCAG testing against the start page to ensure it's accessible for people who rely on assistive tools.
* Transition from plain CSS to SASS to make it prettier and learn about SASS at the same time
* Instead of the 5 minute cron job, look into a gitlab webhook that executes the update script on prod whenever something is committed to master.
* Add documentation to the methods of the item controller
* Change the back button on the item page with a real link back to the repository analysis, instead of the current history -1 hack.
* Create a new item test to check if the publication date is correct, or has a high chance of being wrong

## Productivity

* Get my IntelliJ IDEA Shortcuts for comments in order

## Jekyll http://bram-atmire.github.io/ site

* Make it prettier

## Atmire.com work

Investigate and work on search engine optimization (SEO) for the main atmire.com website.
Look into web.dev from google for this (thank you Philip)

## Learning just for learning

* CSS: Go through the fabulous [CSS Diner](https://flukeout.github.io/)


text:
/**
 * This package contains the annotations and support classes you need as a user of lombok, for
 * all features which aren't (yet) supported as a first class feature. Features that involve the
 * annotations and support classes in this package may change or may be removed entirely in future versions,
 * and bugs may not be solved as expediently. For the status and likely future of any feature, refer
 * to the official feature documentation.
 *
 * @see lombok
 * @see Lombok features (experimental)
 */
package lombok.experimental;


text:
#include <aws/marketplace-entitlement/model/Entitlement.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace MarketplaceEntitlementService
{
namespace Model
{

Entitlement::Entitlement() :
    m_productCodeHasBeenSet(false),
    m_dimensionHasBeenSet(false),
    m_customerIdentifierHasBeenSet(false),
    m_valueHasBeenSet(false),
    m_expirationDateHasBeenSet(false)
{
}

Entitlement::Entitlement(JsonView jsonValue) :
    m_productCodeHasBeenSet(false),
    m_dimensionHasBeenSet(false),
    m_customerIdentifierHasBeenSet(false),
    m_valueHasBeenSet(false),
    m_expirationDateHasBeenSet(false)
{
  *this = jsonValue;
}

Entitlement& Entitlement::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("ProductCode"))
  {
    m_productCode = jsonValue.GetString("ProductCode");

    m_productCodeHasBeenSet = true;
  }

  if(jsonValue.ValueExists("Dimension"))
  {
    m_dimension = jsonValue.GetString("Dimension");

    m_dimensionHasBeenSet = true;
  }

  if(jsonValue.ValueExists("CustomerIdentifier"))
  {
    m_customerIdentifier = jsonValue.GetString("CustomerIdentifier");

    m_customerIdentifierHasBeenSet = true;
  }

  if(jsonValue.ValueExists("Value"))
  {
    m_value = jsonValue.GetObject("Value");

    m_valueHasBeenSet = true;
  }

  if(jsonValue.ValueExists("ExpirationDate"))
  {
    m_expirationDate = jsonValue.GetDouble("ExpirationDate");

    m_expirationDateHasBeenSet = true;
  }

  return *this;
}

JsonValue Entitlement::Jsonize() const
{
  JsonValue payload;

  if(m_productCodeHasBeenSet)
  {
   payload.WithString("ProductCode", m_productCode);

  }

  if(m_dimensionHasBeenSet)
  {
   payload.WithString("Dimension", m_dimension);

  }

  if(m_customerIdentifierHasBeenSet)
  {
   payload.WithString("CustomerIdentifier", m_customerIdentifier);

  }

  if(m_valueHasBeenSet)
  {
   payload.WithObject("Value", m_value.Jsonize());

  }

  if(m_expirationDateHasBeenSet)
  {
   payload.WithDouble("ExpirationDate", m_expirationDate.SecondsWithMSPrecision());
  }

  return payload;
}

} // namespace Model
} // namespace MarketplaceEntitlementService
} // namespace Aws


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Sydowia 5(3-6): 241 (1951)

#### Original name
Xylosphaeria deviata Petr.

### Remarks
null


text:
package org.apache.camel.management;

import javax.management.MBeanServer;
import javax.management.ObjectName;

import org.apache.camel.builder.RouteBuilder;
import org.junit.jupiter.api.Test;

import static org.apache.camel.management.DefaultManagementObjectNameStrategy.TYPE_PROCESSOR;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class ManagedLogEndpointTest extends ManagementTestSupport {

    @Test
    public void testLogEndpoint() throws Exception {
        getMockEndpoint("mock:a").expectedMessageCount(10);

        for (int i = 0; i < 10; i++) {
            template.sendBody("direct:start", "" + i);
            Thread.sleep(100);
        }

        assertMockEndpointsSatisfied();

        MBeanServer mbeanServer = getMBeanServer();

        ObjectName name = getCamelObjectName(TYPE_PROCESSOR, "log-foo");
        mbeanServer.isRegistered(name);

        Long total = (Long) mbeanServer.getAttribute(name, "ExchangesTotal");
        assertEquals(10, total.intValue());

        Integer received = (Integer) mbeanServer.getAttribute(name, "ReceivedCounter");
        assertEquals(10, received.intValue());

        String last = (String) mbeanServer.getAttribute(name, "LastLogMessage");
        assertNotNull(last);
        assertTrue(last.startsWith("Received: 10 messages so far."));

        Double rate = (Double) mbeanServer.getAttribute(name, "Rate");
        assertNotNull(rate);
        assertTrue(rate > 0);

        Double average = (Double) mbeanServer.getAttribute(name, "Average");
        assertNotNull(average);
        assertTrue(average > 0);

        // reset
        mbeanServer.invoke(name, "resetThroughputLogger", null, null);

        // total not reset
        total = (Long) mbeanServer.getAttribute(name, "ExchangesTotal");
        assertEquals(10, total.intValue());

        // but the last log message is
        last = (String) mbeanServer.getAttribute(name, "LastLogMessage");
        assertNull(last);

        received = (Integer) mbeanServer.getAttribute(name, "ReceivedCounter");
        assertEquals(0, received.intValue());

        rate = (Double) mbeanServer.getAttribute(name, "Rate");
        assertEquals((Double) 0.0d, rate);

        average = (Double) mbeanServer.getAttribute(name, "Average");
        assertEquals((Double) 0.0d, average);
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start").routeId("foo")
                        .to("log:foo?groupSize=10").id("log-foo")
                        .to("mock:a");
            }
        };
    }

}


text:
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;

namespace osu.Framework.Development
{
    public static class DebugUtils
    {
        public static bool IsDebugBuild => is_debug_build.Value;

        private static readonly Lazy<bool> is_debug_build = new Lazy<bool>(() =>
            // https://stackoverflow.com/a/2186634
            (Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly()).GetCustomAttributes(false).OfType<DebuggableAttribute>().Any(da => da.IsJITTrackingEnabled)
        );
    }
}


text:
import copy

import networkx as nx

import Alg1_Helper as helper
import UnifyExceptionTypes as uet
from ServiceChains import ChainSubchainDependencyAdministrator

class MappingManager(object):
  """
  Administrates the mapping of links and VNFs. Provides supplementary
  information for mapping based on the current state.
  """

  def __init__ (self, net, req, chains, overall_highest_delay, dry_init,
                lat_aspect_local_dist, lat_aspect_dst_orientation):
    """
    Initializes a MappingManager object.

    :param net:
    :param req:
    :param chains:
    :param overall_highest_delay:
    :param dry_init:
    :param lat_aspect_local_dist:
    :param lat_aspect_dst_orientation:
    """
    self.log = helper.log.getChild(self.__class__.__name__)
    self.log.setLevel(helper.log.getEffectiveLevel())

    self.log.info("Initializing MappingManager object...")

    # list of tuples of mapping (vnf_OBJECT, node_id) which are already mapped
    # by another, eariler orchestration. These NFs are later removed from the
    # resource, but never modified.
    self.initial_vnf_mapping = []
    for i in net.infras:
      for n in net.running_nfs(i.id):
        self.initial_vnf_mapping.append((n, i.id))

    # list of tuples of mapping (vnf_id, node_id)
    self.vnf_mapping = []
    if not dry_init:
      # SAP mapping can be done here based on their ID-s
      try:
        for vnf, dv in req.network.nodes_iter(data=True):
          if dv.type == 'SAP':
            sapid = dv.id
            sapfound = False
            for n, dn in net.network.nodes_iter(data=True):
              if dn.type == 'SAP':
                if dn.id == sapid:
                  self.vnf_mapping.append((vnf, n))
                  sapfound = True
                  break
            if not sapfound:
              self.log.error("No SAP found in network with ID: %s" % sapid)
              raise uet.MappingException(
                "No SAP found in network with ID: %s. SAPs are mapped "
                "exclusively by their ID-s." % sapid)
      except AttributeError as e:
        raise uet.BadInputException("Node data with name %s" % str(e),
                                    "Node data not found")

    # same graph structure as the request, edge data stores the mapped path
    self.link_mapping = nx.MultiDiGraph()

    # bandwidth is not yet summed up on the links
    # AND possible Infra nodes and DYNAMIC links are not removed
    self.req = req
    # NOTE: a BadInputException is thrown if the chains are not E2E between SAPs
    self.chains = chains

    # the delay value which is considered to be infinite (although it should be
    # a constant not to zero out the latency component of objective function
    # calculation)
    self.overall_highest_delay = overall_highest_delay

    # a networkX graph containing a colored request graph, where colors are
    # defined by the set of e2e chains using a node or link
    self.colored_req = None

    # chain - subchain pairing, stored in a bipartie graph
    self.chain_subchain_admin = ChainSubchainDependencyAdministrator(
                                self.chains, overall_highest_delay, self.log)

    # stores an initial list for every VNF where we may start to search for
    # hosts.
    self.potential_hosts_cache = {}

    # saved loop SGHops to be added back to output. key: (i,j,k), data: SGhop
    self.saved_loop_sghops = {}

    # latency preference calculation aspects
    # weight of length of a single SGHop's path delay
    self.lat_aspect_local_dist = lat_aspect_local_dist
    # how much the deviation from the shortest path between current position
    # and (sub)chain destination should be punished
    self.lat_aspect_dst_orientation = lat_aspect_dst_orientation

  def getCurrentHostOfVNF (self, vnf_id):
    """
    If the chain is between VNFs, those must be already mapped.
    Input is an ID from the request graph. Return -1 if the node is not
    mapped.

    :param vnf_id: ID of VNF to look for host
    """
    ret = -1
    for v, n in self.vnf_mapping:
      if v == vnf_id:
        ret = n
        break
    return ret

  def addChain_SubChainDependency (self, subchain_object, e2e_chain_ids):
    """
    Adds a link between a subchain id and all the chain ids that are
    contained subcid.

    :param subchain_object: Subchain object to be added
    :param e2e_chain_ids: List of E2E chain IDs
    :return:
    """
    self.chain_subchain_admin.addDependency(subchain_object, e2e_chain_ids)

  def getLocalAllowedLatency (self, subchain_id=None, vnf1=None, vnf2=None,
                              linkid=None):
    """
    Checks all sources/types of latency requirement, and identifies
    which is the strictest. The smallest 'maximal allowed latency' will be
    the strictest one. We cannot use paths with higher latency value than
    this one. The request link is ordered vnf1, vnf2. This reqlink is part of
    subchain_id subchain.
    This function should only be called on SG links.
    Can be called with omitting subchain ID OR vnf1,vnf2,linkid, but not both
    at the same time!
    """
    # if there is latency requirement on a request link
    link_maxlat = self.overall_highest_delay
    chain_maxlat = self.overall_highest_delay
    if vnf1 is not None and vnf2 is not None and linkid is not None:
      if self.req.network[vnf1][vnf2][linkid].type != 'SG':
        raise uet.InternalAlgorithmException(
          "getLocalAllowedLatency function should only be called on SG links!")
      if hasattr(self.req.network[vnf1][vnf2][linkid], 'delay'):
        if self.req.network[vnf1][vnf2][linkid].delay is not None:
          link_maxlat = self.req.network[vnf1][vnf2][linkid].delay
    elif subchain_id is not None:
      # find the strictest chain latency which applies to this link
      for e2e_chain in self.chain_subchain_admin.getInvolvedE2EChains(
                                                                    subchain_id):
        if e2e_chain['avail_latency'] < chain_maxlat:
          chain_maxlat = e2e_chain['avail_latency']

      if min(chain_maxlat, link_maxlat) > self.overall_highest_delay:
        raise uet.InternalAlgorithmException("Local allowed latency should"
                                             " never exceed the "
                                             "overall_highest_delay")
    else:
      raise uet.InternalAlgorithmException("Invalid invocation of "
                "getLocalAllowedLatency function, no parameters are given!")
    latreq_to_return = min(chain_maxlat, link_maxlat)
    if latreq_to_return < helper.zero_float_value:
      latreq_to_return = 1e-3
      # this should be the ideal operation, but most of the cases the latency
      # parameters from the resources are missing, so we substitute them with
      # zero in order they do not ruin anything with the missing resources...
      # raise uet.BadInputException("End-to-end delay requirement shouldn't
      #  be "
      # "zero!","Local allowed latency for chain %s is %f"
      #                             %(chain_link_ids, lal))
    return latreq_to_return

  def areChainEndsReachableInLatency (self, used_lat, potential_host, subcid):
    """
    Does a forward checking to determine whether the ending SAPs of the involved
    E2E chains of this subchain are still reachable in terms of latency if we
    map the current VNF to 'potential_host' during the mapping of 'subcid'.
    """
    for e2e_chain in self.chain_subchain_admin.getInvolvedE2EChains(subcid):
      # Chain end should always be available because they are E2E chains.
      chainend = self.getCurrentHostOfVNF(e2e_chain['chain'][-1])
      if self.shortest_paths_lengths[potential_host][chainend] > \
            self.getLocalAllowedLatency(subcid) - used_lat:
        self.log.debug(
          "Potential mapping of a VNF to host %s was too far from"
          " chain end %s because of E2E latency requirement on chain %s" %
          (potential_host, chainend, e2e_chain))
        return False
    return True

  def isVNFMappingDistanceGood (self, vnf1, vnf2, n1, n2):
    """
    Mapping vnf2 to n2 shouldn`t be further from n1 (vnf1`s host) than
    the strictest latency requirement of all the links between vnf1 and vnf2
    """
    # this equals to the min of all latency requirements (req link local OR
    # remaining E2E) that is given for any SGHop between vnf1 and vnf2.
    max_permitted_vnf_dist = float("inf")
    for i, j, linkid, d in self.req.network.edges_iter([vnf1], data=True,
                                                       keys=True):
      if self.req.network[i][j][linkid].type != 'SG':
        self.log.warn(
          "There is a not SG link left in the Service Graph, but now it "
          "didn`t cause a problem.")
        continue
      if j == vnf2:
        # i,j are always vnf1,vnf2
        subchain_id_involved = None
        for subchain in self.chain_subchain_admin.getSubchains():
          # the 'subchain' variable of Subchain class contains a zipped list
          if (vnf1, vnf2, linkid) in subchain['subchain']:
            subchain_id_involved = subchain.id
            # each of the request links may be involved in one subchain, which
            # can be involved in multiple E2E chains
            break
        # We still have to check link-wise latency requirement if there are no
        # subchains involved.
        lal = self.getLocalAllowedLatency(subchain_id_involved, vnf1, vnf2,
                                          linkid)
        if lal < max_permitted_vnf_dist:
          max_permitted_vnf_dist = lal
    # check if the maximal permitted delay is smaller than the distance
    if self.shortest_paths_lengths[n1][n2] > max_permitted_vnf_dist:
      self.log.debug("Potential node mapping was too far from last host because"
                     " of link or remaining E2E latency requirement!")
      return False
    else:
      return True

  def updateChainLatencyInfo (self, subchain_id, used_lat, last_used_host):
    """
    Updates how much latency does the mapping process has left which
    applies for this subchain.
    """
    self.chain_subchain_admin.updateRemainingLatencyInfo(subchain_id, used_lat)

  def addShortestRoutesInLatency (self, lenghts, routes):
    """
    Shortest paths are between physical nodes. These are needed to
    estimate the importance of laltency in the objective function.
    """
    self.shortest_paths_lengths = lenghts
    self.shortest_paths_routes = routes

  def addReqLink_ChainMapping (self, colored_req):
    """
    SGHop -> E2E chain mapping is required to calculate the splitted EdgeReqs
    for the lower layer orchestration algorithm. The graph should be deepcopied
    because the preprocessor changes it!
    """
    self.colored_req = copy.deepcopy(colored_req)

  def getSGHopOfChainMappedHere (self, cid, infra, last_sghop_id):
    """
    Returns an SGHop ID which is part of 'cid' chain and its path traverses
    'infra'. Should be used when this infra is only used as forwarding infra,
    but not as for hosting VNF for 'cid'. last_sghop_id indicates where is the
    requirement division process in the chain.
    WTF? always returns last_sghop_id??
    """
    for c in self.chains:
      if cid == c['id']:
        for vnf1, vnf2, lid in zip(c['chain'][:-1], c['chain'][1:],
                                   c['link_ids']):
          if infra in self.link_mapping[vnf1][vnf2][lid]['mapped_to']:
            if last_sghop_id in c['link_ids']:
              if lid == last_sghop_id:
                return lid
            else:
              return lid
    else:
      raise uet.InternalAlgorithmException("SGHop for chain %s couldn't be "
                                           "found in infra %s" % (cid, infra))

  def genPathOfChains (self, nffg):
    """
    Returns a generator of the mapped stucture starting from the beginning of
    chains and finding which Infra nodes are used during the mapping. Generates
    (chain_id, entering_sghop_id, infra_id) tuples, and iterates on all chains.
    The 2nd item is the ID of the first VNF of the chain path part which is
    mapped to this infra OR None if no VNF is mapped here (just transit infra).
    Returns also SAPs on the path!
    """
    for c in self.chains:
      prev_infra_of_path = None
      for vnf1, vnf2, lid in zip(c['chain'][:-1], c['chain'][1:],
                                 c['link_ids']):
        # iterate on 'mapped_to' attribute of vnf1,vnf2,lid link of
        # link_mapping structure
        path_of_lid = self.link_mapping[vnf1][vnf2][lid]['mapped_to']
        for forwarding_infra in path_of_lid:
          if prev_infra_of_path is None or \
                forwarding_infra != prev_infra_of_path:
            prev_infra_of_path = forwarding_infra
            yield c['id'], vnf2 if \
              self.getCurrentHostOfVNF(vnf2) == forwarding_infra or \
              self.getCurrentHostOfVNF(
                vnf1) == forwarding_infra else None, \
                  forwarding_infra
            # VNF2 is handled by the iteration on link mapping structure (
            # because
            # 'mapped_to' contains the hosting infra of vnf1 and vnf2 as well)

  def getNextOutputChainId (self):
    """
    Gets an available ID for the output Service chains to ensure uniqueness

    :return: unique ID for chains
    """
    return self.chain_subchain_admin.getNextChainID()

  def isItTransitInfraNow (self, infra, sg_hop_obj):
    """
    Checks whether this infra routes the traffic of the chain only at this part
    (indicated by sg_hop) of the chain. The infra may host other parts of the
    chain where it also hosts VNFs.
    """
    sghop_hosting_path = self.link_mapping[sg_hop_obj.src.node.id] \
                           [sg_hop_obj.dst.node.id][sg_hop_obj.id]['mapped_to'][
                         1:-1]
    return infra in sghop_hosting_path

  def getNextChainPieceOfReqSubgraph (self, cid, subgraph, sg_hop):
    """
    Iterates on all the "inbound" SGHops of this subgraph (these are not part
    of the subgraph, they were the bordering edges in the request graph) and
    finds the part of the given chain (cid) which starts from sg_hop and is
    mapped here.
    We don't need the BiSBiS directly but all the VNF-s of subgraph should be
    mapped to the same BiSBiS.
    """
    # A structure for storing SGHop
    # store list, there can be multiple disjoint chain parts mapped
    # here (if an internal VNF is mapped elsewhere)
    if self.colored_req is None:
      raise uet.InternalAlgorithmException("A mapping from requirement links to"
            " E2E chains is required by the E2E requirement splitting algorithm,"
            " but the colored req graph is not given!")
    for i, j, k, d in self.colored_req.edges_iter(data=True, keys=True):
      if i not in subgraph.nodes_iter() and j in subgraph.nodes_iter() \
         and k == sg_hop:
        # i,j,k is an inbound SGHop from the (implicitly) given BiSBiS
        if cid in d['color']:
          for c in self.chains:
            if cid == c['id'] and j in c['chain']:
              found_beginnig = False
              # i is not mapped to this Infra, but to the previous Infra.
              chain_piece = [i, j]
              link_ids_piece = [k]
              vnf2, lid = None, None
              # find which part of the chain is mapped here
              for vnf1, vnf2, lid in zip(c['chain'][:-1], c['chain'][1:],
                                         c['link_ids']):
                if (vnf1 != j or lid != c['link_ids'][c['link_ids'].
                   index(sg_hop) + 1]) \
                   and not found_beginnig:
                  continue
                elif not found_beginnig:
                  found_beginnig = True
                if found_beginnig:
                  if subgraph.has_edge(vnf1, vnf2, key=lid):
                    chain_piece.append(vnf2)
                    link_ids_piece.append(lid)
                    continue
                  else:
                    break
              # vnf2 is mapped to the next Infra
              # the subgraph CAN'T have SAP-s, so vnf2 can be a SAP if
              # this infra is the last to host a VNF for this chain
              if vnf2 is None or lid is None:
                raise uet.InternalAlgorithmException("Chain and link ID "
                          "shouldn't be empty in getting next piece of chain")
              chain_piece.append(vnf2)
              link_ids_piece.append(lid)
              return chain_piece, link_ids_piece
    else:
      raise uet.InternalAlgorithmException("Mapped chain part couldn't be found"
                                           " on a given infra for chain %s!"
                                           % cid)

  def getRemainingE2ELatency (self, chain_id):
    """
    Returns the remaining latency of a given E2E chain.

    :param chain_id: ID of a request chain
    """
    return self.chain_subchain_admin.getRemainingE2ELatency(chain_id)

  def cmpBasedOnDelayDist (self, h1, h2, origin):
    """
    Determines whether h1 or h2 is closer to origin based on distance measured
    in latency.

    :param h1: infrastructure node
    :param h2: infrastructure node
    :param origin: node to compare the distance to.
    """
    if self.shortest_paths_lengths[origin][h1] < \
       self.shortest_paths_lengths[origin][h2]:
      return -1
    elif self.shortest_paths_lengths[origin][h1] > \
       self.shortest_paths_lengths[origin][h2]:
      return 1
    elif len(self.shortest_paths_routes[origin][h1]) < \
       len(self.shortest_paths_routes[origin][h2]):
      return -1
    elif len(self.shortest_paths_routes[origin][h1]) > \
      len(self.shortest_paths_routes[origin][h2]):
      return 1
    else:
      return 0

  def _calcDelayComponent (self, layer_level, layer_idx, layer_length,
                           lat_value_step_cnt, sumlat, lal):
    """
    Calculates a the composite metric of delay preference value. Destination
    orientation punishes hosts which are far from the shortest path which leads
    towards the (sub)chain end. Distance layers are identified by the ratio of
    the number of the remaining VNFs in the subchain and the strictest local
    latency requirement.
    Local distance punishes the hosts which are far from the last used host.
    The components are weighted by their respective aspect values.

    :param layer_level: which distance layer is the host
    :param layer_idx:
    :param layer_length:
    :param lat_value_step_cnt:
    :param sumlat:
    :param lal:
    :return:
    """
    dst_orientation_comp = (float(layer_level) + layer_idx/float(layer_length)) \
                                      / lat_value_step_cnt
    local_dist_comp = float(sumlat) / lal
    return (self.lat_aspect_dst_orientation*dst_orientation_comp +
            self.lat_aspect_local_dist*local_dist_comp) / \
           (self.lat_aspect_dst_orientation + self.lat_aspect_local_dist)

  def calcDelayPrefValues (self, hosts_with_lat_paths_lids, vnf_id, reqlid,
                           chain_id, infra_id):
    """
    Sorts potential hosts in the network based on a composite key:
    Firstly, based on how far is the host from the shortest path between the
    (sub)chain ends, creates sets, called distance layers.
    Secondly, based on distance from the current host, measured in delay.
    Also calculates their latency component value, and returns a list of tuples:
    (host, lat_pref_value).

    :param hosts_with_lat_paths_lids: potential hosts of the VNF
    :param vnf_id: VNF ID to be hosted
    :param reqlid: request link, which leads towards the VNF
    :param chain_id: (sub)chain ID
    :param infra_id: host wich was used by the previous VNF
    :return:
    """
    # should always be mapped already
    self.log.debug("Calculating latency preference values for placing VNF %s "
                   % vnf_id)
    target_request_node, chain_link_ids = self.chain_subchain_admin.\
                          getTerminatorAndRequestPathOfStrictestChain(chain_id)
    host_of_chainend = self.getCurrentHostOfVNF(target_request_node)
    if host_of_chainend == -1:
      raise uet.InternalAlgorithmException("Last VNF of best-effort subchain "
                                           "should already be mapped "
                                           "temporarily!")

    # get the data of the best possible path towards the current target in
    # the substrate graph
    sh_path = self.shortest_paths_routes[infra_id][host_of_chainend]
    sh_path_lat = self.shortest_paths_lengths[infra_id][host_of_chainend]

    # get the number of remaining SGHop mappings
    remaining_chain_len = len(chain_link_ids[chain_link_ids.index(reqlid):])
    if remaining_chain_len == 1:
      raise uet.InternalAlgorithmException("Sorting based on latency preference"
                                           " value shouldn't be called when "
                                           "only one request link is left!")
    # If the current cid is a best-effort subchain, lal will be around the
    # self.overall_highest_delay (maybe decremented a bit already) -> which
    # means almost surely only one distance layer in the structure.
    lal = self.getLocalAllowedLatency(chain_id)
    dist_layer_step = float(lal) / \
                      remaining_chain_len
    dist_layers = {}
    for h, path, linkids, sumlat in hosts_with_lat_paths_lids:
      if h in sh_path:
        if 0 in dist_layers:
          dist_layers[0].append((h, path, linkids, sumlat))
        else:
          dist_layers[0] = [(h, path, linkids, sumlat)]
      else:
        k = 2
        placed_h_in_dist_layer = False
        while sh_path_lat + (k - 1) * dist_layer_step <= lal:
          if self.shortest_paths_lengths[infra_id][h] + \
             self.shortest_paths_lengths[h][host_of_chainend] < \
                sh_path_lat + k * dist_layer_step:
            if k - 1 in dist_layers:
              dist_layers[k - 1].append((h, path, linkids, sumlat))
            else:
              dist_layers[k - 1] = [(h, path, linkids, sumlat)]
            placed_h_in_dist_layer = True
            break
          k += 1
        if not placed_h_in_dist_layer:
          self.log.debug(
            "Host %s was filtered from subgraph of chain %s because it"
            " was too far from current and destination hosts!" %
            (h, chain_link_ids))
    # sort host inside distance layers and calculate the pref values.
    hosts_with_lat_values_paths_lids = []
    lat_value_step_cnt = (lal - sh_path_lat) / \
                         dist_layer_step
    self.log.debug("Dist layers: %s" % dist_layers)
    for k in dist_layers:
      current_layer = sorted(dist_layers[k], cmp=lambda h1, h2,
                                                        origin=infra_id: \
        self.cmpBasedOnDelayDist(h1[0], h2[0], origin))
      i = 0.0
      for h, path, linkids, sumlat in current_layer:
        hosts_with_lat_values_paths_lids.append(
          (h, path, linkids, sumlat, self._calcDelayComponent(
                    k, i, len(current_layer), lat_value_step_cnt, sumlat, lal)))
        i += 1.0
      self.log.debug(
        "Processed distance layer %s for mapping VNF %s" % (k, vnf_id))
    return hosts_with_lat_values_paths_lids

  def getAllCurrentlyMappedVNFs(self, infra_id):
    """
    Returns all vnfs which are currently placed (possibly mapped) onto this
    infra. Or mapped by an earlier orchestration.

    :param infra_id: host to look for hosted VNFs
    :return:
    """
    currently_mapped_nfs = []
    for v, iid in self.initial_vnf_mapping:
      if iid == infra_id:
        currently_mapped_nfs.append(v)
    return currently_mapped_nfs

  def getMappedPathOfSGHop(self, vnf1, vnf2, sg_hopid):
    """
    Returns the currently (temporarily) mapped path of a SGHop link with node
    ids and path link ids in two lists. Returns None, None if the link is not
    yet mapped.

    :param vnf1: Starting NF
    :param vnf2: Terminating NF
    :param sg_hopid: EdgeSGLink ID which connects the VNFs
    :return:
    """
    if self.link_mapping.has_edge(vnf1, vnf2, sg_hopid):
      return self.link_mapping[vnf1][vnf2][sg_hopid]['mapped_to'], \
             self.link_mapping[vnf1][vnf2][sg_hopid]['path_link_ids']
    else:
      return None, None

  def getPotentialHosts(self, vnf_id, net, req):
    """
    Returns and caches the potentional hosts of a VNF.
    net and req should be the prepocessed MultiDiGraph objects.

    :param req:
    :param vnf_id:
    :param net:
    :return:
    """
    if vnf_id in self.potential_hosts_cache:
      self.log.debug("Returning cached potential hosts for VNF%s: %s"%
                     (vnf_id, self.potential_hosts_cache[vnf_id]))
      return self.potential_hosts_cache[vnf_id]
    # allow only infras which has some 'supported'
    self.log.debug("Potential hosts #1 (unfiltered) for  VNF %s: %s"
                   % (vnf_id, net.nodes()))
    potential_hosts = filter(lambda h, nodes=net.node:
                             nodes[h].type == 'INFRA' and nodes[h].supported is
                                                          not None,
                             net.nodes())
    # allow only hosts which supports this NF
    self.log.debug("Potential hosts #2 (non-Infras and nodes without "
                   "supported NFs are filtered) for  VNF %s: %s"
                   % (vnf_id, potential_hosts))
    potential_hosts = filter(lambda h, v=vnf_id, nodes=net.node,
                                    vnfs=req.node: vnfs[v].functional_type in
                                                        nodes[h].supported,
                             potential_hosts)
    self.log.debug("Potential hosts #3 (not supporting this NF type are "
                   "filtered) for  VNF %s: %s" % (vnf_id, potential_hosts))
    # allow only hosts which complies to placement_criteria if any
    potential_hosts = filter(lambda h, v=vnf_id, vnfs=req.node:
                             len(vnfs[v].placement_criteria) == 0 or h in vnfs[
                               v].placement_criteria,
                             potential_hosts)
    self.log.debug("Potential hosts #4 (filtering due to placement criteria)"
                   " for  VNF %s: %s" % (vnf_id, potential_hosts))

    # save this for later use.
    self.potential_hosts_cache[vnf_id] = potential_hosts
    return potential_hosts

  def saveLoopSGHops(self, req):
    """
    Saves the loop SGHops to be added back later to the output NFFG object

    :param req: request NFFG with restored SGHop objects
    :return:
    """
    for i,j,k,sg in req.network.edges(data=True, keys=True):
      if i == j:
        self.saved_loop_sghops[(i,j,k)] = sg
        req.del_edge(sg.src, sg.dst, sg.id)
        self.log.debug("Saving loop SGHop %s on node %s"%(sg, i))
    return req

  def restoreSavedLoopSGHopsToOutputNFFG(self, nffg):
    """
    Restores the initailly saved loop SGHops, which need to go  through the
    mapping process transparently.

    :param nffg: output NFFG object
    :return:
    """
    for i,j,k in self.saved_loop_sghops:
      sg = self.saved_loop_sghops[(i,j,k)]
      # i == j and dst.node == src.node
      # i can be a SAP and an NF
      for n,m,key,link in nffg.network.out_edges_iter([i],
                                                      data=True, keys=True):
        if n == i and link.src.id == sg.src.id and link.dst.node.type == 'INFRA':
          hosting_infra = link.dst.node.id
          hosting_port = link.dst.id
          match_str = "in_port="
          action_str = "output="
          match_str += str(hosting_port)
          if sg.flowclass is not None:
            match_str += ";flowclass=%s" % sg.flowclass
          action_str += str(hosting_port)
          self.log.debug("Adding loop flowrule based on saved loop SGhops: "
                         "%s => %s added to Port %s of %s"%
                         (match_str, action_str, hosting_port, hosting_infra))
          nffg.network.node[hosting_infra].ports[hosting_port].add_flowrule(
            match_str, action_str, bandwidth=sg.bandwidth, delay=sg.delay,
            id=sg.id, constraints=sg.constraints)
          break
    return nffg


text:
<!--
  ~ Copyright 2014-2016 Groupon, Inc
  ~ Copyright 2014-2016 The Billing Project, LLC
  ~
  ~ The Billing Project licenses this file to you under the Apache License, version 2.0
  ~ (the "License"); you may not use this file except in compliance with the
  ~ License.  You may obtain a copy of the License at:
  ~
  ~    http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  ~ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
  ~ License for the specific language governing permissions and limitations
  ~ under the License.
  -->

<overdueConfig>
    <accountOverdueStates>
        <state name="OD4">
            <condition>
                <numberOfUnpaidInvoicesEqualsOrExceeds>5</numberOfUnpaidInvoicesEqualsOrExceeds>
                <controlTagInclusion>AUTO_PAY_OFF</controlTagInclusion>
            </condition>
            <externalMessage>Reached OD3</externalMessage>
            <blockChanges>true</blockChanges>
            <disableEntitlementAndChangesBlocked>true</disableEntitlementAndChangesBlocked>
            <autoReevaluationInterval>
                <unit>DAYS</unit><number>5</number>
            </autoReevaluationInterval>
        </state>
        <state name="OD3">
            <condition>
                <responseForLastFailedPaymentIn>
                    <response>INVALID_CARD</response>
                    <response>LOST_OR_STOLEN_CARD</response>
                </responseForLastFailedPaymentIn>
            </condition>
            <externalMessage>Reached OD3</externalMessage>
            <blockChanges>true</blockChanges>
            <disableEntitlementAndChangesBlocked>true</disableEntitlementAndChangesBlocked>
            <autoReevaluationInterval>
                <unit>DAYS</unit><number>5</number>
            </autoReevaluationInterval>
        </state>
        <state name="OD2">
            <condition>
                <totalUnpaidInvoiceBalanceEqualsOrExceeds>5.00</totalUnpaidInvoiceBalanceEqualsOrExceeds>
            </condition>
            <externalMessage>Reached OD2</externalMessage>
            <blockChanges>true</blockChanges>
            <disableEntitlementAndChangesBlocked>true</disableEntitlementAndChangesBlocked>
            <autoReevaluationInterval>
                <unit>DAYS</unit><number>5</number>
            </autoReevaluationInterval>
        </state>
        <state name="OD1">
            <condition>
                <timeSinceEarliestUnpaidInvoiceEqualsOrExceeds>
                    <unit>DAYS</unit><number>30</number>
                </timeSinceEarliestUnpaidInvoiceEqualsOrExceeds>
            </condition>
            <externalMessage>Reached OD1</externalMessage>
            <blockChanges>true</blockChanges>
            <disableEntitlementAndChangesBlocked>false</disableEntitlementAndChangesBlocked>
            <autoReevaluationInterval>
                <unit>DAYS</unit><number>5</number>
            </autoReevaluationInterval>
        </state>
    </accountOverdueStates>
</overdueConfig>


text:
// Copyright 2012 Google Inc. All Rights Reserved.
package octopus;

/**
 * @author kodologist@gmail.com
 */
public interface ServiceListener {
  void serviceAdded(Service service);
  void serviceRemoved(Service service);
  void serviceResolved(ServiceDescriptor serviceDescriptor);
}


text:
#include "pch.h"
#include "PlayingTable.xaml.h"
#include "cpprest/asyncrt_utils.h"

using namespace BlackjackClient;

using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;

using namespace Windows::Networking;

#include "CardShape.xaml.h"
#include <string>
#include "cpprest/json.h"

using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Data;
using namespace BlackjackClient;

PlayingTable::PlayingTable() : m_dealerResource(L"dealer"), m_alreadyInsured(false), m_client(L"http://localhost:34568/blackjack/")
{
    InitializeComponent();

    this->serverAddress->Text = ref new Platform::String(L"http://localhost:34568/blackjack/");

    this->playerName->Text = Windows::System::UserProfile::UserInformation::GetDisplayNameAsync()->GetResults();

    size_t players = 5;

    for (size_t i = 0; i < players; i++)
    {
        auto player = ref new PlayerSpace();
        playerPanel->Children->Append(player);
        _playerSpaces.push_back(player);
    }

    EnableExit();
    EnableConnecting();

    DisableDisconnecting();
    DisableHit();
    DisableBetting();
    DisableInsurance();
}

PlayingTable::~PlayingTable()
{
}

void BlackjackClient::PlayingTable::AddDealerCard(Card card)
{
    Thickness margin;
    margin.Left = 5 + _dealerCards.size() * (CardWidthRect * SCALE_FACTOR * .25 + 0);
    margin.Top = 12;
    margin.Bottom = 0;
    margin.Right = 0;

    auto crd = ref new CardShape();
    crd->VerticalAlignment = Windows::UI::Xaml::VerticalAlignment::Top;
    crd->HorizontalAlignment = Windows::UI::Xaml::HorizontalAlignment::Left;
    crd->Margin = margin;
    crd->_suit = (int)card.suit;
    crd->_value = (int)card.value;
    crd->_visible = (Platform::Boolean)card.visible;

    crd->adjust();

    _dealerCards.push_back(card);
    dealerGrid->Children->Append(crd);
}

bool BlackjackClient::PlayingTable::InterpretError(HRESULT hr)
{
    if ( hr == S_OK ) return false;

    switch(hr)
    {
    case 0x800C0005:
        this->resultLabel->Text = L"Error communicating with server";
        break;
    default:
        this->resultLabel->Text = L"Internal error";
        break;
    }

    return true;
}

void BlackjackClient::PlayingTable::Refresh()
{
    this->resultLabel->Text = L"Waiting for other players";

    std::wostringstream buf;
    buf << _tableId << L"?request=refresh&name=" << uri::encode_uri(m_name,uri::components::path);

    auto request = m_client.request(methods::PUT, buf.str());

    auto ctx = pplx::task_continuation_context::use_current();

    request.then([this](pplx::task<http_response> tsk) {

        this->resultLabel->Text = L"";

        try
        {
            auto response = tsk.get();
            InterpretResponse(response);
        }
        catch (const http_exception &exc)
        {
            InterpretError(exc.error_code().value());
            this->resultLabel->Text = L"Waiting for other players";
            Refresh();
        }
    }, ctx);
}

void BlackjackClient::PlayingTable::InterpretResponse(http_response &response)
{
    if ( response.headers().content_type() != L"application/json" ) return;

    this->resultLabel->Text = L"";

    response.extract_json().then(
        [this,response](json::value jsonResponse)
        {
            BlackjackClient::PlayingTable ^_this = this;
            http_response r = response;
            _this->InterpretResponse(jsonResponse);
        }, pplx::task_continuation_context::use_current());
}

void BlackjackClient::PlayingTable::InterpretResponse(json::value jsonResponse)
{
    BJPutResponse answer = BJPutResponse::FromJSON(jsonResponse);
    json::value players = answer.Data[PLAYERS];

    bool allow_double = false;
    bool allow_insurance = false;

    size_t i = 0;

    for (auto iter = players.as_array().begin(); iter != players.as_array().end() && i < _playerSpaces.size(); ++iter,i++)
    {
        Player player = Player::FromJSON(*iter);

        if ( player.Name == DEALER )
        {
            if ( player.Hand.cards.size() == 1  && _dealerCards.size() == 2)
            {
                // The cards are already shown.
                continue;
            }

            ClearDealerCards();

            for (size_t j = 0; j < player.Hand.cards.size(); j++)
            {
                AddDealerCard(player.Hand.cards[j]);
            }

            if ( player.Hand.cards.size() == 1 )
            {
                // Add a dummy card that isn't shown.
                AddDealerCard(Card(CardSuit::CS_Club, CardValue::CV_Ace, false));
                if ( player.Hand.cards[0].value == CardValue::CV_Ace && !m_alreadyInsured )
                    allow_insurance = true;
            }
            continue;
        }

        if ( uri::decode(player.Name) == m_name )
        {
            allow_double = (player.Hand.cards.size() == 2);
        }

        _playerSpaces[i-1]->Update(player);

        for (size_t j = _playerSpaces[i-1]->CardsHeld(); j < player.Hand.cards.size(); j++)
        {
            _playerSpaces[i-1]->AddCard(player.Hand.cards[j]);
        }

        if (player.Hand.result != BJHandResult::HR_None)
        {
            _playerSpaces[i-1]->ShowResult(player.Hand.result);
        }
    }

    switch (answer.Status)
    {
    case ST_PlaceBet:
        this->resultLabel->Text = L"Place your bet!";
        EnableBetting();
        DisableHit();
        DisableInsurance();
        EnableExit();
        EnableDisconnecting();
        break;
    case ST_YourTurn:
        this->resultLabel->Text = L"Your turn!";
        DisableExit();
        DisableDisconnecting();
        DisableBetting();
        EnableHit();
        doubleButton->Visibility = allow_double ? Windows::UI::Xaml::Visibility::Visible : Windows::UI::Xaml::Visibility::Collapsed;
        if (allow_insurance) EnableInsurance(); else DisableInsurance();
        break;
    case ST_Refresh:
        this->resultLabel->Text = L"Waiting for other players";
        DisableExit();
        DisableDisconnecting();
        DisableHit();
        DisableBetting();
        Refresh();
        break;
    }
}

void BlackjackClient::PlayingTable::BetButton_Click(Platform::Object^ sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^ e)
{
    if ( _tableId.empty() || m_name.empty() )
        return;

    ClearPlayerCards();
    ClearDealerCards();

    DisableExit();
    DisableDisconnecting();
    DisableBetting();

    std::wstring betText(betBox->Text->Data());

    this->resultLabel->Text = L"Waiting for a response";

    std::wostringstream buf;
    buf << _tableId << L"?request=bet&amount=" << betText << "&name=" << uri::encode_uri(m_name,uri::components::query);

    auto request = m_client.request(methods::PUT, buf.str());

    auto ctx = pplx::task_continuation_context::use_current();

    request.then([this](pplx::task<http_response> tsk) {

        this->resultLabel->Text = L"";

        try
        {
            auto response = tsk.get();
            InterpretResponse(response);
        }
        catch (const http_exception &exc)
        {
            InterpretError(exc.error_code().value());
            EnableExit();
            EnableDisconnecting();
            EnableBetting();
        }
    }, ctx);
}

void BlackjackClient::PlayingTable::InsuranceButton_Click(Platform::Object^ sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^ e)
{
    if ( _tableId.empty() || m_name.empty() )
        return;

    ClearTable();
    DisableHit();
    DisableInsurance();
    m_alreadyInsured = true;

    std::wstring betText(buyInsuranceTextBox->Text->Data());

    this->resultLabel->Text = L"Waiting for a response";

    std::wostringstream buf;
    buf << _tableId << L"?request=insure&amount=" << betText << "&name=" << uri::encode_uri(m_name,uri::components::query);

    auto request = m_client.request(methods::PUT, buf.str());

    auto ctx = pplx::task_continuation_context::use_current();

    request.then([this](pplx::task<http_response> tsk) {

        this->resultLabel->Text = L"";

        try
        {
            auto response = tsk.get();
            InterpretResponse(response);
        }
        catch (const http_exception &exc)
        {
            InterpretError(exc.error_code().value());
            EnableHit();
            EnableInsurance();
        }
    }, ctx);
}

void BlackjackClient::PlayingTable::DoubleButton_Click(Platform::Object^ sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^ e)
{
    if ( _tableId.empty() || m_name.empty() )
        return;

    DisableHit();
    DisableInsurance();

    this->resultLabel->Text = L"Waiting for a response";

    std::wostringstream buf;
    buf << _tableId << L"?request=double&name=" << uri::encode_uri(m_name,uri::components::query);

    auto request = m_client.request(methods::PUT, buf.str());

    auto ctx = pplx::task_continuation_context::use_current();

    request.then([this](pplx::task<http_response> tsk) {

        this->resultLabel->Text = L"";

        try
        {
            auto response = tsk.get();
            InterpretResponse(response);
        }
        catch (const http_exception &exc)
        {
            InterpretError(exc.error_code().value());
            EnableHit();
        }
    }, ctx);
}

void BlackjackClient::PlayingTable::StayButton_Click(Platform::Object^ sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^ e)
{
    if ( _tableId.empty() || m_name.empty() )
        return;

    DisableHit();
    DisableInsurance();

    this->resultLabel->Text = L"Waiting for a response";

    std::wostringstream buf;
    buf << _tableId << L"?request=stay&name=" << uri::encode_uri(m_name,uri::components::query);

    auto request = m_client.request(methods::PUT, buf.str());

    auto ctx = pplx::task_continuation_context::use_current();

    request.then([this](pplx::task<http_response> tsk) {

        this->resultLabel->Text = L"";

        try
        {
            auto response = tsk.get();
            InterpretResponse(response);
        }
        catch (const http_exception &exc)
        {
            InterpretError(exc.error_code().value());
            EnableHit();
        }
    }, ctx);
}

void BlackjackClient::PlayingTable::HitButton_Click(Platform::Object^ sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^ e)
{
    if ( _tableId.empty() || m_name.empty() )
        return;

    DisableInsurance();

    this->resultLabel->Text = L"Waiting for a response";

    std::wostringstream buf;
    buf << _tableId << L"?request=hit&name=" << uri::encode_uri(m_name,uri::components::query);

    auto request = m_client.request(methods::PUT, buf.str());

    auto ctx = pplx::task_continuation_context::use_current();

    request.then([this](pplx::task<http_response> tsk) {

        this->resultLabel->Text = L"";

        try
        {
            auto response = tsk.get();
            InterpretResponse(response);
        }
        catch (const http_exception &exc)
        {
            InterpretError(exc.error_code().value());
        }
    }, ctx);
}

void BlackjackClient::PlayingTable::ExitButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
    if ( _tableId.empty() || m_name.empty() )
    {
        Windows::ApplicationModel::Core::CoreApplication::Exit();
    }
    else
    {
        DisableExit();
        DisableConnecting();

        auto ctx = pplx::task_continuation_context::use_current();

        std::wostringstream buf;
        buf << _tableId << L"?name=" << uri::encode_uri(m_name,uri::components::query);

        auto request = m_client.request(methods::DEL, buf.str());

        request.then([this](pplx::task<http_response> tsk) {

            EnableExit();

            this->resultLabel->Text = L"";

            try
            {
                auto response = tsk.get();
            }
            catch (const http_exception &exc)
            {
                InterpretError(exc.error_code().value());
                EnableExit();
            }

            Windows::ApplicationModel::Core::CoreApplication::Exit();
        }, ctx);
    }
}

void BlackjackClient::PlayingTable::JoinButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
    m_name = this->playerName->Text->Data();

    if ( m_name.size() == 0 )
    {
        this->resultLabel->Text = L"Please state your name!";
        return;
    }

    _tableId = L"1";

    DisableExit();
    DisableConnecting();

    this->resultLabel->Text = L"Joining table";

    uri_builder bldr(this->serverAddress->Text->Data());
    bldr.append_path(m_dealerResource);
    m_client = http_client(bldr.to_string());

    std::wostringstream buf;
    buf << _tableId << L"?name=" << uri::encode_uri(m_name,uri::components::query);

    auto request = m_client.request(methods::POST, buf.str());

    auto ctx = pplx::task_continuation_context::use_current();

    request.then([this](pplx::task<http_response> tsk) {

        EnableExit();

        this->resultLabel->Text = L"";

        try
        {
            auto response = tsk.get();

            this->resultLabel->Text = L"Place your bet!";

            EnableDisconnecting();
            EnableBetting();

            InterpretResponse(response);
        }
        catch (const http_exception &exc)
        {
            InterpretError(exc.error_code().value());
            EnableConnecting();
            _tableId = L"";
        }
    }, ctx);
}

void BlackjackClient::PlayingTable::LeaveButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
    this->resultLabel->Text = L"Leaving table";

    DisableExit();
    DisableBetting();
    DisableDisconnecting();

    auto ctx = pplx::task_continuation_context::use_current();

    std::wostringstream buf;
    buf << _tableId << L"?name=" << uri::encode_uri(m_name,uri::components::query);

    auto request = m_client.request(methods::DEL, buf.str());

    request.then([this](pplx::task<http_response> tsk) {

        EnableExit();

        try
        {
            auto response = tsk.get();

            EnableConnecting();
            ClearDealerCards();
            ClearTable();

            this->resultLabel->Text = L"Thanks for playing!";

            _tableId = L"";
        }
        catch (const http_exception &exc)
        {
            InterpretError(exc.error_code().value());
            EnableBetting();
            EnableDisconnecting();
        }
    }, ctx);
}

void PlayingTable::OnNavigatedTo(NavigationEventArgs^ e)
{
}


text:
package com.digitalpetri.opcua.stack.core.types.structured;

import com.digitalpetri.opcua.stack.core.serialization.UaEncoder;
import com.digitalpetri.opcua.stack.core.types.UaDataType;
import com.digitalpetri.opcua.stack.core.Identifiers;
import com.digitalpetri.opcua.stack.core.serialization.DelegateRegistry;
import com.digitalpetri.opcua.stack.core.serialization.UaDecoder;
import com.digitalpetri.opcua.stack.core.types.builtin.NodeId;

@UaDataType("EventNotificationList")
public class EventNotificationList extends NotificationData {

    public static final NodeId TypeId = Identifiers.EventNotificationList;
    public static final NodeId BinaryEncodingId = Identifiers.EventNotificationList_Encoding_DefaultBinary;
    public static final NodeId XmlEncodingId = Identifiers.EventNotificationList_Encoding_DefaultXml;

    protected final EventFieldList[] _events;

    public EventNotificationList() {
        super();
        this._events = null;
    }

    public EventNotificationList(EventFieldList[] _events) {
        super();
        this._events = _events;
    }

    public EventFieldList[] getEvents() {
        return _events;
    }

    @Override
    public NodeId getTypeId() {
        return TypeId;
    }

    @Override
    public NodeId getBinaryEncodingId() {
        return BinaryEncodingId;
    }

    @Override
    public NodeId getXmlEncodingId() {
        return XmlEncodingId;
    }

    public static void encode(EventNotificationList eventNotificationList, UaEncoder encoder) {
        encoder.encodeArray("Events", eventNotificationList._events, encoder::encodeSerializable);
    }

    public static EventNotificationList decode(UaDecoder decoder) {
        EventFieldList[] _events = decoder.decodeArray("Events", decoder::decodeSerializable, EventFieldList.class);

        return new EventNotificationList(_events);
    }

    static {
        DelegateRegistry.registerEncoder(EventNotificationList::encode, EventNotificationList.class, BinaryEncodingId, XmlEncodingId);
        DelegateRegistry.registerDecoder(EventNotificationList::decode, EventNotificationList.class, BinaryEncodingId, XmlEncodingId);
    }

}