text:
#include "configuration_db.hpp"
#include <string>
#include <cstdio>
#include <iostream>
#include <boost/bind.hpp>
#include <openssl/sha.h>
#include "hash.hpp"
#include "sqlite3.h"
#include <vector>
#include "configuration_primitives.hpp"
#include <boost/function.hpp>
#include "slot.hpp"
#include "sockets.hpp"

using namespace dfterm;
using namespace std;
using namespace boost;
using namespace trankesbel;

ConfigurationDatabase::ConfigurationDatabase()
{
    db = (sqlite3*) 0;
}

ConfigurationDatabase::~ConfigurationDatabase()
{
    if (db)
        sqlite3_close(db);
    db = (sqlite3*) 0;
}

OpenStatus ConfigurationDatabase::open(const UnicodeString &filename)
{
    if (db) sqlite3_close(db);
    db = (sqlite3*) 0;

    string filename_utf8 = TO_UTF8(filename);

    /* Test if the database exists on the disk. */
    bool database_exists = true;
    int result = sqlite3_open_v2(filename_utf8.c_str(), &db, SQLITE_OPEN_READONLY, (const char*) 0);
    if (result)
        database_exists = false;
    else
        sqlite3_close(db);
    db = (sqlite3*) 0;

    result = sqlite3_open(filename_utf8.c_str(), &db);
    if (result)
        return Failure;

    /* Create tables. These calls fail if they already exist (which is not bad). */
    result = sqlite3_exec(db, "CREATE TABLE Users(Name TEXT, ID TEXT, PasswordSHA512 TEXT, PasswordSalt TEXT, Admin TEXT);", 0, 0, 0);
    result = sqlite3_exec(db, "CREATE TABLE Slotprofiles(Name TEXT, ID TEXT, Width TEXT, Height TEXT, Path TEXT, WorkingPath TEXT, SlotType TEXT, AllowedWatchers TEXT, AllowedLaunchers TEXT, AllowedPlayers TEXT, AllowedClosers TEXT, ForbiddenWatchers TEXT, ForbiddenLaunchers TEXT, ForbiddenPlayers TEXT, ForbiddenClosers TEXT, MaxSlots TEXT);", 0, 0, 0);
    result = sqlite3_exec(db, "CREATE TABLE MOTD(Content TEXT);", 0, 0, 0);
    result = sqlite3_exec(db, "CREATE TABLE GlobalSettings(Key TEXT, Value TEXT);", 0, 0, 0);
    result = sqlite3_exec(db, "CREATE TABLE AllowedAndForbiddenSocketAddressRanges(Allowed TEXT, Forbidden TEXT, DefaultAllowance TEXT);", 0, 0, 0);

    /* Create an admin user, if database was created. */
    if (!database_exists)
        return OkCreatedNewDatabase;

    return Ok;
}

int ConfigurationDatabase::maximumSlotsCallback(ui32* maximum, void* v_self, int argc, char** argv, char** colname)
{
    assert(maximum && v_self);

    ui32 value = 0xffffffff;
    bool correct_key = false;

    int i;
    for (i = 0; i < argc; ++i)
    {
        if (!argv[i]) continue;

        if (!strcmp(colname[i], "Value"))
        {
            value = strtol(argv[i], 0, 10);
            break;
        }
        if (!strcmp(colname[i], "Key") && !strcmp(argv[i], "MaximumSlots"))
            correct_key = true;
    }

    if (correct_key)
        (*maximum) = value;

    return 0;
}

int ConfigurationDatabase::slotprofileNameListDataCallback(vector<UnicodeString>* name_list, void* v_self, int argc, char** argv, char** colname)
{
    assert(name_list && v_self);

    int i;
    for (i = 0; i < argc; ++i)
    {
        if (!argv[i]) continue;

        if (!strcmp(colname[i], "Name"))
        {
            string name_utf8 = argv[i];
            (*name_list).push_back(UnicodeString::fromUTF8(name_utf8));
        }
    }

    return 0;
}

int ConfigurationDatabase::slotprofileDataCallback(SlotProfile* sp, void* v_self, int argc, char** argv, char** colname)
{
    assert(sp && v_self);

    int i;
    for (i = 0; i < argc; ++i)
    {
        if (!argv[i]) continue;

        if (!strcmp(colname[i], "Name"))
            sp->setNameUTF8(argv[i]);
        else if (!strcmp(colname[i], "ID"))
            sp->setID(ID::getUnSerialized(string(argv[i])));
        else if (!strcmp(colname[i], "Width"))
            sp->setWidth(strtol(argv[i], NULL, 10));
        else if (!strcmp(colname[i], "Height"))
            sp->setHeight(strtol(argv[i], NULL, 10));
        else if (!strcmp(colname[i], "Path"))
            sp->setExecutable(argv[i]);
        else if (!strcmp(colname[i], "WorkingPath"))
            sp->setWorkingPath(argv[i]);
        else if (!strcmp(colname[i], "SlotType"))
        {
            SlotType st = InvalidSlotType;
            for (st = (SlotType) 0; st != InvalidSlotType; st = (SlotType) ((size_t) st + 1))
                if (!strcmp(argv[i], SlotNames[(size_t) st].c_str()))
                    break;
            sp->setSlotType(st);
        }
        else if (!strcmp(colname[i], "AllowedWatchers"))
            sp->setAllowedWatchers(UserGroup::unSerialize(argv[i]));
        else if (!strcmp(colname[i], "AllowedLaunchers"))
            sp->setAllowedLaunchers(UserGroup::unSerialize(argv[i]));
        else if (!strcmp(colname[i], "AllowedPlayers"))
            sp->setAllowedPlayers(UserGroup::unSerialize(argv[i]));
        else if (!strcmp(colname[i], "AllowedClosers"))
            sp->setAllowedClosers(UserGroup::unSerialize(argv[i]));
        else if (!strcmp(colname[i], "ForbiddenWatchers"))
            sp->setForbiddenWatchers(UserGroup::unSerialize(argv[i]));
        else if (!strcmp(colname[i], "ForbiddenLaunchers"))
            sp->setForbiddenLaunchers(UserGroup::unSerialize(argv[i]));
        else if (!strcmp(colname[i], "ForbiddenPlayers"))
            sp->setForbiddenPlayers(UserGroup::unSerialize(argv[i]));
        else if (!strcmp(colname[i], "ForbiddenClosers"))
            sp->setForbiddenClosers(UserGroup::unSerialize(argv[i]));
        else if (!strcmp(colname[i], "MaxSlots"))
            sp->setMaxSlots(strtol(argv[i], NULL, 10));
    }

    return 0;
};

int ConfigurationDatabase::userDataCallback(SP<User>* user, void* v_self, int argc, char** argv, char** colname)
{
    assert(user && (*user));

    string password_salt, password_hash;
    int i;
    for (i = 0; i < argc; ++i)
    {
        if (!argv[i]) continue;

        if (!strcmp(colname[i], "Name"))
            (*user)->setNameUTF8(string(argv[i]));
        else if (!strcmp(colname[i], "PasswordSHA512"))
            password_hash = argv[i];
        else if (!strcmp(colname[i], "PasswordSalt"))
            password_salt = argv[i];
        else if (!strcmp(colname[i], "ID"))
        {
            ID id;
            id.unSerialize(string(argv[i]));
            (*user)->setID(id);
        }
        else if (!strcmp(colname[i], "Admin"))
            if (!strcmp(argv[i], "Yes"))
                (*user)->setAdmin(true);
    }
    (*user)->setPasswordSalt(password_salt);
    (*user)->setPasswordHash(password_hash);

    return 0;
};

int ConfigurationDatabase::userListDataCallback(vector<SP<User> >* user_list, void* v_self, int argc, char** argv, char** colname)
{
    assert(user_list && v_self);

    string name, password_hash, password_salt;
    ID id;
    bool admin = false;

    int i;
    for (i = 0; i < argc; ++i)
    {
        if (!argv[i]) continue;

        if (!strcmp(colname[i], "Name"))
            name = argv[i];
        else if (!strcmp(colname[i], "PasswordSHA512"))
            password_hash = argv[i];
        else if (!strcmp(colname[i], "PasswordSalt"))
            password_salt = argv[i];
        else if (!strcmp(colname[i], "ID"))
            id.unSerialize(string(argv[i]));
        else if (!strcmp(colname[i], "Admin"))
            if (!strcmp(argv[i], "Yes"))
                admin = true;
    }

    if (name.size() <= 0) return 0;

    SP<User> user(new User);
    user->setPasswordSalt(password_salt);
    user->setPasswordHash(password_hash);
    user->setID(id);
    user->setName(UnicodeString::fromUTF8(name));
    user->setAdmin(admin);

    (*user_list).push_back(user);
    return 0;
};

int ConfigurationDatabase::motdCallback(UnicodeString* us, void* v_self, int argc, char** argv, char** colname)
{
    assert(us && v_self);

    int i;
    for (i = 0; i < argc; ++i)
    {
        if (!argv[i]) continue;

        if (!strcmp(colname[i], "Content"))
            (*us) = TO_UNICODESTRING(string(argv[i]));
    }

    return 0;
}

int ConfigurationDatabase::allowedAndForbiddenSocketAddressRangesCallback(bool* default_allowance, SocketAddressRange* allowed, SocketAddressRange* forbidden, void* v_self, int argc, char** argv, char** colname)
{
    assert(allowed);
    assert(forbidden);
    assert(default_allowance);

    int i;
    for (i = 0; i < argc; ++i)
    {
        if (!argv[i]) continue;

        if (!strcmp(colname[i], "Allowed"))
        {
            bool result = allowed->unSerialize(hex_to_bytes(argv[i]));
            if (!result)
            {
                LOG(Error, "The socket address range for allowed connections in database is malformed.");
                return 1;
            }
        }
        else if (!strcmp(colname[i], "Forbidden"))
        {
            bool result = forbidden->unSerialize(hex_to_bytes(argv[i]));
            if (!result)
            {
                LOG(Error, "The socket address range for allowed connections in database is malformed.");
                return 1;
            }
        }
        else if (!strcmp(colname[i], "DefaultAllowance"))
        {
            if (!strcmp(argv[i], "Yes"))
                (*default_allowance) = true;
            else if (!strcmp(argv[i], "No"))
                (*default_allowance) = false;
            else
            {
                LOG(Error, "The default allowance field in database for address restrictions is malformed. Defaulting it to allow everyone.");
                (*default_allowance) = true;
            }
        }
    }

    return 0;
}

static int c_callback(void* a, int b, char** c, char** d)
{
    function4<int, void*, int, char**, char**>* sql_callback_function =
    (function4<int, void*, int, char**, char**>*) a;

    return (*sql_callback_function)((void*) 0x1, b, c, d);
}

void ConfigurationDatabase::saveMOTD(UnicodeString motd)
{
    saveMOTDUTF8(TO_UTF8(motd));
}

void ConfigurationDatabase::saveMOTDUTF8(string motd_utf8)
{
    assert(db);

    string motd_escaped = escape_sql_string(motd_utf8);

    char* errormsg = (char*) 0;

    string statement;
    statement = string("DELETE FROM MOTD;");
    int result = sqlite3_exec(db, statement.c_str(), 0, 0, &errormsg);
    if (result != SQLITE_OK) /* Yes, next one is a warning and not an error */
    { LOG(Error, "Error while executing SQL statement \"" << statement << "\": " << errormsg); };

    if (errormsg) sqlite3_free(errormsg);
    errormsg = (char*) 0;

    statement = string("INSERT INTO MOTD(Content) VALUES(\'") + motd_escaped + string("\');");
    result = sqlite3_exec(db, statement.c_str(), 0, 0, &errormsg);
    if (result != SQLITE_OK)
    { LOG(Error, "Error while executing SQL statement \"" << statement << "\": " << errormsg); };

    if (errormsg) sqlite3_free(errormsg);
}

string ConfigurationDatabase::loadMOTDUTF8()
{
    return TO_UTF8(loadMOTD());
}

UnicodeString ConfigurationDatabase::loadMOTD()
{
    assert(db);

    UnicodeString motd;

    function4<int, void*, int, char**, char**> sql_callback_function;
    sql_callback_function = boost::bind(&ConfigurationDatabase::motdCallback, this, &motd, _1, _2, _3, _4);

    string statement = string("SELECT Content FROM MOTD;");
    char* errormsg = (char*) 0;
    int result = sqlite3_exec(db, statement.c_str(), c_callback, (void*) &sql_callback_function, &errormsg);
    if (result != SQLITE_OK)
    { LOG(Error, "Error while executing SQL statement \"" << statement << "\": " << errormsg); };

    if (errormsg) sqlite3_free(errormsg);

    return motd;
}

vector<SP<User> > ConfigurationDatabase::loadAllUserData()
{
    assert(db);

    vector<SP<User> > result_users;

    function4<int, void*, int, char**, char**> sql_callback_function;
    sql_callback_function = boost::bind(&ConfigurationDatabase::userListDataCallback, this, &result_users, _1, _2, _3, _4);

    string statement;
    statement = string("SELECT Name, ID, PasswordSHA512, PasswordSalt, Admin FROM Users;");
    int result = sqlite3_exec(db, statement.c_str(), c_callback, (void*) &sql_callback_function, 0);
    if (result != SQLITE_OK) return vector<SP<User> >();

    return result_users;
}

void ConfigurationDatabase::deleteSlotProfileData(const UnicodeString &name)
{
    assert(db);

    string name_utf8 = TO_UTF8(name);
    if (escape_sql_string(name_utf8).size() < 1) return;

    string statement = string("DELETE FROM Slotprofiles WHERE Name = \'") + escape_sql_string(name_utf8) + string("\';");
    sqlite3_exec(db, statement.c_str(), 0, 0, 0);
}

void ConfigurationDatabase::deleteUserData(const UnicodeString &name)
{
    assert(db);

    string name_utf8 = TO_UTF8(name);
    if (escape_sql_string(name_utf8).size() < 1) return;

    string statement = string("DELETE FROM Users WHERE Name = \'") + escape_sql_string(name_utf8) + string("\';");
    sqlite3_exec(db, statement.c_str(), 0, 0, 0);
}

SP<User> ConfigurationDatabase::loadUserData(const ID& id)
{
    assert(db);

    string id_str = escape_sql_string(id.serialize());

    SP<User> r_result(new User);
    function4<int, void*, int, char**, char**> sql_callback_function;
    sql_callback_function = boost::bind(&ConfigurationDatabase::userDataCallback, this, &r_result, _1, _2, _3, _4);

    string statement;
    statement = string("SELECT Name, ID, PasswordSHA512, PasswordSalt, Admin FROM Users WHERE ID = \'") + id_str + string("\';");
    int result = sqlite3_exec(db, statement.c_str(), c_callback, (void*) &sql_callback_function, 0);
    if (result != SQLITE_OK) return SP<User>();
    if (r_result->getNameUTF8().size() == 0) return SP<User>();

    return r_result;
}

SP<User> ConfigurationDatabase::loadUserData(const UnicodeString &name)
{
    assert(db);

    string name_utf8 = TO_UTF8(name);
    if (escape_sql_string(name_utf8).size() < 1) return SP<User>();

    SP<User> r_result(new User);
    function4<int, void*, int, char**, char**> sql_callback_function;
    sql_callback_function = boost::bind(&ConfigurationDatabase::userDataCallback, this, &r_result, _1, _2, _3, _4);

    string statement;
    statement = string("SELECT Name, ID, PasswordSHA512, PasswordSalt, Admin FROM Users WHERE Name = \'") + escape_sql_string(name_utf8) + string("\';");
    int result = sqlite3_exec(db, statement.c_str(), c_callback, (void*) &sql_callback_function, 0);
    if (result != SQLITE_OK) return SP<User>();
    if (r_result->getNameUTF8().size() == 0) return SP<User>();

    return r_result;
}

void ConfigurationDatabase::saveUserData(User* user)
{
    assert(db && user);

    string name_utf8 = TO_UTF8(user->getName());
    if (escape_sql_string(name_utf8).size() < 1) return;

    string statement;
    statement = string("DELETE FROM Users WHERE Name = \'") + escape_sql_string(name_utf8) + string("\';");
    int result = sqlite3_exec(db, statement.c_str(), 0, 0, 0);

    string admin_str("No");
    if (user->isAdmin()) admin_str = "Yes";

    statement = string("INSERT INTO Users(Name, ID, PasswordSHA512, PasswordSalt, Admin) VALUES(\'") + escape_sql_string(name_utf8) + string("\', \'") + escape_sql_string(user->getID().serialize()) + string("\', \'") + escape_sql_string(user->getPasswordHash()) + string("\', \'") + escape_sql_string(user->getPasswordSalt()) + string("\', \'") + admin_str + string("\');");
    result = sqlite3_exec(db, statement.c_str(), 0, 0, 0);
};

void ConfigurationDatabase::saveSlotProfileData(SlotProfile* slotprofile)
{
    assert(db && slotprofile);

    string name = slotprofile->getNameUTF8();

    string statement;
    statement = string("DELETE FROM Slotprofiles WHERE NAME = \'") + escape_sql_string(name) + string("\';");
    int result = sqlite3_exec(db, statement.c_str(), 0, 0, 0);

    stringstream ss;
    ss << "INSERT INTO Slotprofiles(Name, ID, Width, Height, Path, WorkingPath, SlotType, AllowedWatchers, AllowedLaunchers, AllowedPlayers, AllowedClosers, ForbiddenWatchers, ForbiddenLaunchers, ForbiddenPlayers, ForbiddenClosers, MaxSlots) VALUES(\'" <<
    escape_sql_string(slotprofile->getNameUTF8()) << "\',\'" <<
    escape_sql_string(slotprofile->getID().serialize()) << "\',\'" <<
    slotprofile->getWidth() << "\',\'" <<
    slotprofile->getHeight() << "\',\'" <<
    escape_sql_string(slotprofile->getExecutableUTF8()) << "\',\'" <<
    escape_sql_string(slotprofile->getWorkingPathUTF8()) << "\',\'" <<
    escape_sql_string(SlotNames[(size_t) slotprofile->getSlotType()]) << "\',\'" <<
    escape_sql_string(slotprofile->getAllowedWatchers().serialize()) << "\',\'" <<
    escape_sql_string(slotprofile->getAllowedLaunchers().serialize()) << "\',\'" <<
    escape_sql_string(slotprofile->getAllowedPlayers().serialize()) << "\',\'" <<
    escape_sql_string(slotprofile->getAllowedClosers().serialize()) << "\',\'" <<
    escape_sql_string(slotprofile->getForbiddenWatchers().serialize()) << "\',\'" <<
    escape_sql_string(slotprofile->getForbiddenLaunchers().serialize()) << "\',\'" <<
    escape_sql_string(slotprofile->getForbiddenPlayers().serialize()) << "\',\'" <<
    escape_sql_string(slotprofile->getForbiddenClosers().serialize()) << "\',\'" <<
    slotprofile->getMaxSlots() << "\');";

    char* errormsg = (char*) 0;
    result = sqlite3_exec(db, ss.str().c_str(), 0, 0, &errormsg);
    if (result != SQLITE_OK)
        LOG(Error, "Error while executing SQL statement \"" << ss.str() << "\": " << errormsg);
    if (errormsg) sqlite3_free(errormsg);
};

vector<UnicodeString> ConfigurationDatabase::loadSlotProfileNames()
{
    assert(db);

    vector<UnicodeString> name_list;

    function4<int, void*, int, char**, char**> sql_callback_function;
    sql_callback_function = boost::bind(&ConfigurationDatabase::slotprofileNameListDataCallback, this, &name_list, _1, _2, _3, _4);

    char* errormsg = (char*) 0;

    string statement;
    statement = string("SELECT Name FROM Slotprofiles;");
    int result = sqlite3_exec(db, statement.c_str(), c_callback, (void*) &sql_callback_function, &errormsg);
    if (result != SQLITE_OK)
    {
        LOG(Error, "Error while executing SQL statement \"" << statement << "\": " << errormsg);
        if (errormsg) sqlite3_free(errormsg);
        return name_list;
    }
    if (errormsg) sqlite3_free(errormsg);

    return name_list;
}

SP<SlotProfile> ConfigurationDatabase::loadSlotProfileData(const UnicodeString &name)
{
    assert(db);

    string name_utf8 = TO_UTF8(name);

    SlotProfile sp;

    function4<int, void*, int, char**, char**> sql_callback_function;
    sql_callback_function = boost::bind(&ConfigurationDatabase::slotprofileDataCallback, this, &sp, _1, _2, _3, _4);

    char* errormsg = (char*) 0;

    string statement;
    statement = string("SELECT Name, ID, Width, Height, Path, WorkingPath, SlotType, AllowedWatchers, AllowedLaunchers, AllowedPlayers, AllowedClosers, ForbiddenWatchers, ForbiddenLaunchers, ForbiddenPlayers, ForbiddenClosers, MaxSlots FROM Slotprofiles WHERE Name = \'") + escape_sql_string(name_utf8) + string("\';");
    int result = sqlite3_exec(db, statement.c_str(), c_callback, (void*) &sql_callback_function, &errormsg);
    if (result != SQLITE_OK)
    {
        LOG(Error, "Error while executing SQL statement \"" << statement << "\": " << errormsg);
        if (errormsg) sqlite3_free(errormsg);
        return SP<SlotProfile>();
    }
    if (errormsg) sqlite3_free(errormsg);

    return SP<SlotProfile>(new SlotProfile(sp));
};

void ConfigurationDatabase::saveMaximumNumberOfSlots(ui32 maximum)
{
    assert(db);

    string statement = string("DELETE FROM GlobalSettings WHERE Key = \'MaximumSlots\';");
    int result = sqlite3_exec(db, statement.c_str(), 0, 0, 0);

    char* errormsg = (char*) 0;

    stringstream ss;
    ss << maximum;
    statement = string("INSERT INTO GlobalSettings(Key, Value) VALUES(\'MaximumSlots\', \'") + escape_sql_string(ss.str()) + string("\');");
    result = sqlite3_exec(db, statement.c_str(), 0, 0, &errormsg);
    if (result != SQLITE_OK)
    { LOG(Error, "Error while executing SQL statement \"" << statement << "\": " << errormsg); };

    if (errormsg) sqlite3_free(errormsg);
}

ui32 ConfigurationDatabase::loadMaximumNumberOfSlots()
{
    assert(db);

    ui32 maximum = 0xffffffff;
    function4<int, void*, int, char**, char**> sql_callback_function;
    sql_callback_function = boost::bind(&ConfigurationDatabase::maximumSlotsCallback, this, &maximum, _1, _2, _3, _4);

    string statement = string("SELECT Key, Value FROM GlobalSettings WHERE Key = \'MaximumSlots\';");
    char* errormsg = (char*) 0;
    int result = sqlite3_exec(db, statement.c_str(), c_callback, (void*) &sql_callback_function, &errormsg);
    if (result != SQLITE_OK)
    {
        LOG(Error, "Error while executing SQL statement \"" << statement << "\": " << errormsg);
        if (errormsg) sqlite3_free(errormsg);
        return 0xffffffff;
    }
    if (errormsg) sqlite3_free(errormsg);

    return maximum;
}

void ConfigurationDatabase::saveAllowedAndForbiddenSocketAddressRanges(bool default_allowance, const SocketAddressRange &allowed, const SocketAddressRange &forbidden)
{
    assert(db);

    char* errormsg = (char*) 0;

    string allowed_str = allowed.serialize();
    string forbidden_str = forbidden.serialize();

    string statement = string("DELETE FROM AllowedAndForbiddenSocketAddressRanges;");
    int result = sqlite3_exec(db, statement.c_str(), 0, 0, &errormsg);
    if (result != SQLITE_OK)
    { LOG(Error, "Error while executing SQL statement \"" << statement << "\": " << errormsg); };
    if (errormsg) sqlite3_free(errormsg);

    string default_allowance_str("Yes");
    if (!default_allowance)
        default_allowance_str = "No";

    stringstream ss;
    ss << "INSERT INTO AllowedAndForbiddenSocketAddressRanges(Allowed, Forbidden, DefaultAllowance) VALUES(\'" << bytes_to_hex(allowed_str) << "\', \'" << bytes_to_hex(forbidden_str) << "\', \'" << default_allowance_str << "\');";
    result = sqlite3_exec(db, ss.str().c_str(), 0, 0, &errormsg);
    if (result != SQLITE_OK)
    { LOG(Error, "Error while executing SQL statement \"" << ss.str() << "\": " << errormsg); };

    if (errormsg) sqlite3_free(errormsg);
}

void ConfigurationDatabase::loadAllowedAndForbiddenSocketAddressRanges(bool* default_allowance, SocketAddressRange* allowed, SocketAddressRange* forbidden)
{
    assert(allowed);
    assert(forbidden);
    assert(db);
    assert(default_allowance);

    SocketAddressRange allowed_f, forbidden_f;
    bool default_allowance_f = true;

    function4<int, void*, int, char**, char**> sql_callback_function;
    sql_callback_function = boost::bind(&ConfigurationDatabase::allowedAndForbiddenSocketAddressRangesCallback, this, &default_allowance_f, &allowed_f, &forbidden_f, _1, _2, _3, _4);

    string statement = string("SELECT Allowed, Forbidden, DefaultAllowance FROM AllowedAndForbiddenSocketAddressRanges;");
    char* errormsg = (char*) 0;
    int result = sqlite3_exec(db, statement.c_str(), c_callback, (void*) &sql_callback_function, &errormsg);
    if (result != SQLITE_OK)
    {
        LOG(Error, "Error while executing SQL statement \"" << statement << "\": " << errormsg);
        if (errormsg) sqlite3_free(errormsg);
        return;
    }
    if (errormsg) sqlite3_free(errormsg);

    (*allowed) = allowed_f;
    (*forbidden) = forbidden_f;
    (*default_allowance) = default_allowance_f;
}

data1D dfterm::escape_sql_string(const data1D &str)
{
    data1D result;
    result.reserve(str.size());
    size_t str_size = str.size();

    size_t i1;
    for (i1 = 0; i1 < str_size; ++i1)
    {
        if (str[i1] == '\'')
            result.append("\'\'");
        else if (str[i1] == 0)
            continue;
        else
            result.push_back(str[i1]);
    }

    return result;
}


text:
layout: default
---

{{ page.title }}

	<time datetime="{{ page.date | date_to_xmlschema }}" class="ff-date-color by-line">{{ page.date | date_to_string }}</time>

		{{ content }}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

    </data>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/linearLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center">

            <TextView
                android:id="@+id/right_cnt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="20sp"
                app:layout_constraintBottom_toTopOf="@+id/wrong_cnt"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.5"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                tools:text="@string/test_result_correct" />

            <TextView
                android:id="@+id/wrong_cnt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="20sp"
                app:layout_constraintBottom_toTopOf="@+id/progressBar"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.5"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/right_cnt"
                tools:text="@string/test_result_wrong" />

            <doit.study.droid.quiz_summary.ui.DeathStarLoader
                android:id="@+id/progressBar"
                android:layout_width="200dp"
                android:layout_height="200dp"
                app:ds_progress="0"
                app:ds_wave_color="@android:color/black"
                app:layout_constraintBottom_toTopOf="@+id/textSummary"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.5"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/wrong_cnt" />

            <TextView
                android:id="@+id/textSummary"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:padding="16dp"
                android:textSize="23sp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/progressBar"
                tools:text="test" />

        </androidx.constraintlayout.widget.ConstraintLayout>
    </ScrollView>
</layout>


text:
<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <string name="appname">Paniers Carte</string>
</resources>


text:
package com.querydsl.core.types.dsl;

import java.util.Map;

import org.jetbrains.annotations.Nullable;

import com.querydsl.core.types.ConstantImpl;
import com.querydsl.core.types.Expression;
import com.querydsl.core.types.MapExpression;
import com.querydsl.core.types.Ops;

/**
 * {@code MapExpressionBase} is an abstract base class for {@link MapExpression} implementations
 *
 * @author tiwe
 *
 * @param <K> key type
 * @param <V> value type
 * @param <Q> result type for {@code get(K)} invocations
 */
public abstract class MapExpressionBase<K, V, Q extends SimpleExpression<? super V>> extends DslExpression<Map<K,V>> implements MapExpression<K,V> {

    private static final long serialVersionUID = 2856001983312366841L;

    @Nullable
    private transient volatile NumberExpression<Integer> size;

    @Nullable
    private transient volatile BooleanExpression empty;

    public MapExpressionBase(Expression<Map<K, V>> mixin) {
        super(mixin);
    }

    /**
     * Create a {@code (key, value) in this} expression
     *
     * @param key key of entry
     * @param value value of entry
     * @return expression
     */
    public final BooleanExpression contains(K key, V value) {
        return get(key).eq(value);
    }

    /**
     * Create a {@code (key, value) in this} expression
     *
     * @param key key of entry
     * @param value value of entry
     * @return expression
     */
    @SuppressWarnings("unchecked")
    public final BooleanExpression contains(Expression<K> key, Expression<V> value) {
        return get(key).eq((Expression) value);
    }

    /**
     * Create a {@code key in keys(this)} expression
     *
     * @param key key
     * @return expression
     */
    public final BooleanExpression containsKey(Expression<K> key) {
        return Expressions.booleanOperation(Ops.CONTAINS_KEY, mixin, key);
    }

    /**
     * Create a {@code key in keys(this)} expression
     *
     * @param key key
     * @return expression
     */
    public final BooleanExpression containsKey(K key) {
        return Expressions.booleanOperation(Ops.CONTAINS_KEY, mixin, ConstantImpl.create(key));
    }

    /**
     * Create a {@code value in values(this)} expression
     *
     * @param value value
     * @return expression
     */
    public final BooleanExpression containsValue(Expression<V> value) {
        return Expressions.booleanOperation(Ops.CONTAINS_VALUE, mixin, value);
    }

    /**
     * Create a {@code value in values(this)} expression
     *
     * @param value value
     * @return expression
     */
    public final BooleanExpression containsValue(V value) {
        return Expressions.booleanOperation(Ops.CONTAINS_VALUE, mixin, ConstantImpl.create(value));
    }

    /**
     * Create a {@code this.get(key)} expression
     *
     * @param key key
     * @return this.get(key)
     */
    public abstract Q get(Expression<K> key);

    /**
     * Create a {@code this.get(key)} expression
     *
     * @param key key
     * @return this.get(key)
     */
    public abstract Q get(K key);

    /**
     * Create a {@code this.isEmpty()} expression
     *
     * @return this.isEmpty()
     */
    public final BooleanExpression isEmpty() {
        if (empty == null) {
            empty = Expressions.booleanOperation(Ops.MAP_IS_EMPTY, mixin);
        }
        return empty;
    }

    /**
     * Create a {@code !this,isEmpty()} expression
     *
     * @return !this.isEmpty()
     */
    public final BooleanExpression isNotEmpty() {
        return isEmpty().not();
    }

    /**
     * Create a {@code this.size()} expression
     *
     * @return this.size()
     */
    public final NumberExpression<Integer> size() {
        if (size == null) {
            size = Expressions.numberOperation(Integer.class, Ops.MAP_SIZE, mixin);
        }
        return size;
    }

}


text:
package com.mongodb.operation;

import com.mongodb.async.SingleResultCallback;
import com.mongodb.binding.AsyncWriteBinding;
import com.mongodb.binding.WriteBinding;
import org.bson.BsonDocument;
import org.bson.BsonInt32;

import static com.mongodb.assertions.Assertions.notNull;
import static com.mongodb.operation.CommandOperationHelper.executeWrappedCommandProtocol;
import static com.mongodb.operation.CommandOperationHelper.executeWrappedCommandProtocolAsync;
import static com.mongodb.operation.OperationHelper.VoidTransformer;

/**
 * Operation to drop a database in MongoDB.  The {@code execute} method throws MongoCommandFailureException if something goes wrong, but
 * it will not throw an Exception if the collection does not exist before trying to drop it.
 *
 * @since 3.0
 */
public class DropDatabaseOperation implements AsyncWriteOperation<Void>, WriteOperation<Void> {
    private static final BsonDocument DROP_DATABASE = new BsonDocument("dropDatabase", new BsonInt32(1));
    private final String databaseName;

    /**
     * Construct a new instance.
     *
     * @param databaseName the name of the database for the operation.
     */
    public DropDatabaseOperation(final String databaseName) {
        this.databaseName = notNull("databaseName", databaseName);
    }

    @Override
    public Void execute(final WriteBinding binding) {
        return executeWrappedCommandProtocol(databaseName, DROP_DATABASE, binding, new VoidTransformer<BsonDocument>());
    }

    @Override
    public void executeAsync(final AsyncWriteBinding binding, final SingleResultCallback<Void> callback) {
        executeWrappedCommandProtocolAsync(databaseName, DROP_DATABASE, binding, new VoidTransformer<BsonDocument>(), callback);
    }
}


text:
var fs = require("fs");
var chalk = require('chalk');
var path = require('path');
var existsSync = fs.existsSync;
var readdirSync = fs.readdirSync;
var rmdirSync = fs.rmdirSync;
var unlinkSync = fs.unlinkSync;
var statSync = fs.statSync;
var validateProjectName = require('validate-npm-package-name');

function isCnFuc(language) {
	return language === "cn" ? true : false;
}

function emptyFs(path) {
	var files = [];
	var dir = [];
	if (existsSync(path)) {
		files = readdirSync(path);
		files.forEach(function(file, index) {
			var curPath = path + "/" + file;
			if (statSync(curPath).isDirectory()) {
				emptyFs(curPath);
			} else {
				unlinkSync(curPath);
			}
		});
		dir = readdirSync(path);
		dir.forEach(function(dirName, index) {
			rmdirSync(path + "/" + dirName);
		});
	}
}

/**
 * isSafeToCreateProjectIn function is created from `create-react-app`
 * which is on create-react-app/packages/create-react-app/createReactApp.js line 740 of version 2.0.4
 */
function isSafeToCreateProjectIn(root, name) {
	// These files should be allowed to remain on a failed install,
	// but then silently removed during the next create.
	const errorLogFilePatterns = [
		'npm-debug.log',
		'yarn-error.log',
		'yarn-debug.log',
	];

  const validFiles = [
    '.DS_Store',
    'Thumbs.db',
    '.git',
    '.gitignore',
    '.idea',
    'README.md',
    'LICENSE',
    'web.iml',
    '.hg',
    '.hgignore',
    '.hgcheck',
    '.npmignore',
    'mkdocs.yml',
    'docs',
    '.travis.yml',
    '.gitlab-ci.yml',
    '.gitattributes',
  ];
  console.log();

  const conflicts = fs
    .readdirSync(root)
    .filter(file => !validFiles.includes(file))
    // Don't treat log files from previous installation as conflicts
    .filter(
      file => !errorLogFilePatterns.some(pattern => file.indexOf(pattern) === 0)
    );

  if (conflicts.length > 0) {
    console.log(
      `The directory ${chalk.green(name)} contains files that could conflict:`
    );
    console.log();
    for (const file of conflicts) {
      console.log(`  ${file}`);
    }
    console.log();
    console.log(
      'Either try using a new directory name, or remove the files listed above.'
    );

    return false;
  }

  // Remove any remnant files from a previous installation
  const currentFiles = fs.readdirSync(path.join(root));
  currentFiles.forEach(file => {
    errorLogFilePatterns.forEach(errorLogFilePattern => {
      // This will catch `(npm-debug|yarn-error|yarn-debug).log*` files
      if (file.indexOf(errorLogFilePattern) === 0) {
        unlinkSync(path.join(root, file));
      }
    });
  });
  return true;
}

// validate an app(project) name
// - Nameing Rules: https://www.npmjs.com/package/validate-npm-package-name#naming-rules
// - Referenced: https://github.com/facebook/create-react-app/blob/master/packages/create-react-app/createReactApp.js#L664
function checkAppName(appName) {
  const validationResult = validateProjectName(appName);
  if (!validationResult.validForNewPackages) {
    console.error(
      `Could not create a project called ${chalk.red(
        `"${appName}"`
      )} because of npm naming restrictions: `
    );
    printValidationResults(validationResult.errors);
    printValidationResults(validationResult.warnings);
    process.exit(1);
  }

  function printValidationResults(results) {
    if (typeof results !== 'undefined') {
      results.forEach(error => {
        console.error(chalk.red(`  *  ${error}`));
      });
    }
  }
}

module.exports = {
	isCnFuc: isCnFuc,
	emptyFs: emptyFs,
  isSafeToCreateProjectIn: isSafeToCreateProjectIn,
  checkAppName: checkAppName
};


text:
<!-- WB Insert -->
{% if not env.pywb_proxy_magic %}

{% assets "pywb-js" %}
<script type="text/javascript" src="{{ ASSET_URL }}"></script>
{% endassets %}

{% else %}

{% assets "proxy-js" %}
<script type="text/javascript" src="{{ host_prefix }}{{ ASSET_URL }}"></script>
{% endassets %}

{% endif %}

<script>
{% set urlsplit = cdx.url | urlsplit %}
  wbinfo = {}
  wbinfo.top_url = "{{ top_url }}";
{% if is_framed %}
  // Fast Top-Frame Redirect
  if (window == window.top && wbinfo.top_url) {
    var loc = window.location.href.replace(window.location.hash, "");
    loc = decodeURI(loc);

    if (loc != decodeURI(wbinfo.top_url)) {
        window.location.href = wbinfo.top_url + window.location.hash;
    }
  }
{% endif %}
  wbinfo.url = "{{ cdx.url }}";
  wbinfo.timestamp = "{{ cdx.timestamp }}";
  wbinfo.request_ts = "{{ wb_url.timestamp }}";
  wbinfo.prefix = decodeURI("{{ wb_prefix }}");
  wbinfo.mod = "{{ replay_mod }}";
  wbinfo.is_framed = {{ is_framed | tobool }};
  wbinfo.is_live = {{ is_live | tobool }};
  wbinfo.coll = "{{ coll }}";
  wbinfo.proxy_magic = "{{ env.pywb_proxy_magic }}";
  wbinfo.static_prefix = "{{ host_prefix }}/{{ static_path }}/bundle/";

{% if not wb_url.is_banner_only or env.pywb_proxy_magic %}
  wbinfo.enable_auto_fetch = true;
  wbinfo.auto_fetch_worker_prefix = "{{ host_prefix }}/static_cors/bundle/";

  wbinfo.wombat_ts = "{{ wombat_ts }}";
  wbinfo.wombat_sec = "{{ wombat_sec }}";
  wbinfo.wombat_scheme = "{{ urlsplit.scheme }}";
  wbinfo.wombat_host = "{{ urlsplit.netloc }}";

  wbinfo.wombat_opts = {};

  if (window && window._WBWombatInit) {
    window._WBWombatInit(wbinfo);
  }
{% else %}
window.devicePixelRatio = 1;
{% endif %}

</script>

<script>
wbinfo.state = "{{ curr_mode }}";
wbinfo.metadata = {{ cdx.metadata | default('{}') }};
</script>

<!-- Set canonical url -->
<link rel="canonical" href="{{ cdx.url }}"/>

{% if env.pywb_proxy_magic %}

<script>
wbinfo.proxy_user = "{{ user }}";
wbinfo.proxy_coll = "{{ coll }}";
wbinfo.proxy_rec = "{{ rec }}";
wbinfo.proxy_mode = "{{ type }}";
wbinfo.curr_browser = "{{ browser }}";

// for vi_ queries from vidrw
wbinfo.coll = "$video";
</script>

{% endif %}

<!-- End WB Insert -->


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Generic;
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;

using Microsoft.NET.StringTools;

#nullable disable

namespace Microsoft.Build.Tasks
{
    /// <summary>
    /// Given a list of items, determine which are in the cone of the folder passed in and which aren't.
    /// </summary>
    public class FindUnderPath : TaskExtension
    {
        /// <summary>
        /// Filter based on whether items fall under this path or not.
        /// </summary>
        [Required]
        public ITaskItem Path { get; set; }

        /// <summary>
        /// Files to consider.
        /// </summary>
        public ITaskItem[] Files { get; set; } = Array.Empty<ITaskItem>();

        /// <summary>
        /// Set to true if the paths of the output items should be updated to be absolute
        /// </summary>
        public bool UpdateToAbsolutePaths { get; set; }

        /// <summary>
        /// Files that were inside of Path.
        /// </summary>
        [Output]
        public ITaskItem[] InPath { get; set; }

        /// <summary>
        /// Files that were outside of Path.
        /// </summary>
        [Output]
        public ITaskItem[] OutOfPath { get; set; }

        /// <summary>
        /// Execute the task.
        /// </summary>
        public override bool Execute()
        {
            var inPathList = new List<ITaskItem>();
            var outOfPathList = new List<ITaskItem>();

            string conePath;

            try
            {
                conePath =
                    Strings.WeakIntern(
                        System.IO.Path.GetFullPath(FileUtilities.FixFilePath(Path.ItemSpec)));
                conePath = FileUtilities.EnsureTrailingSlash(conePath);
            }
            catch (Exception e) when (ExceptionHandling.IsIoRelatedException(e))
            {
                Log.LogErrorWithCodeFromResources(null, "", 0, 0, 0, 0,
                    "FindUnderPath.InvalidParameter", "Path", Path.ItemSpec, e.Message);
                return false;
            }

            int conePathLength = conePath.Length;

            Log.LogMessageFromResources(MessageImportance.Low, "FindUnderPath.ComparisonPath", Path.ItemSpec);

            foreach (ITaskItem item in Files)
            {
                string fullPath;
                try
                {
                    fullPath =
                        Strings.WeakIntern(
                            System.IO.Path.GetFullPath(FileUtilities.FixFilePath(item.ItemSpec)));
                }
                catch (Exception e) when (ExceptionHandling.IsIoRelatedException(e))
                {
                    Log.LogErrorWithCodeFromResources(null, "", 0, 0, 0, 0,
                        "FindUnderPath.InvalidParameter", "Files", item.ItemSpec, e.Message);
                    return false;
                }

                // Compare the left side of both strings to see if they're equal.
                if (String.Compare(conePath, 0, fullPath, 0, conePathLength, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    // If we should use the absolute path, update the item contents
                    // Since ItemSpec, which fullPath comes from, is unescaped, re-escape when setting
                    // item.ItemSpec, since the setter for ItemSpec expects an escaped value.
                    if (UpdateToAbsolutePaths)
                    {
                        item.ItemSpec = EscapingUtilities.Escape(fullPath);
                    }

                    inPathList.Add(item);
                }
                else
                {
                    outOfPathList.Add(item);
                }
            }

            InPath = inPathList.ToArray();
            OutOfPath = outOfPathList.ToArray();
            return true;
        }
    }
}


text:
<?php

namespace Snap\Control;

use
	\Snap\Lib\Control\Redirect,
	\Snap\Lib\Control\Reroute;

abstract class Router extends \Snap\Lib\Core\StdObject {

	protected
		$routingTable = array(),
		$redirect = null,
		$asJson,
		$isRaw;

	public function __construct(){
		parent::__construct();

		$this->asJson = isset($_GET['__asJson']);
		$this->isRaw = isset($_GET['__contentOnly']);
	}

	protected function duplicate( Router $in ){
		$this->routingTable = &$in->routingTable;
	}

	protected function addRoute( &$mount, $dex, $action ){
		if ( $dex{0} == '/' ){
			if ( $dex == '/' ){
				$mount[$dex] = $action;
			}else{
				if ( !isset($mount['/settings']) ){
					$mount['/settings'] = array();
				}
				$mount['/settings'][substr($dex,1)] = $action;
			}
		}else{
			$mount = &$mount[ $dex ];

			if ( is_array($action) ){
				foreach( $action as $route => $act ){
					if ( $route{0} != '/' && !isset($mount[$route]) ){
						$mount[$route] = array();
					}

					$this->addRoute( $mount, $route, $act );
				}
			}else{
				$mount['/'] = $action;
			}
		}
	}

	public function setHome( $action ){
		$this->addRoute($this->routingTable, '/', $action);
	}

	public function addRoutes( array $routing ){
		foreach( $routing as $route => $action ){
			$mount = &$this->routingTable;

			if ( $route{0} == '/' ){
				$this->addRoute( $mount, $route, $action );
			}elseif ( is_array($action) ){
				$this->addRoute( $mount, $route, $action );
			}else{
				$indexs = explode( '/', $route );
				$lastMount = &$mount;
				$lastDex = '/'; // this should never happen

				while( !empty($indexs) ){
					$dex = array_shift( $indexs );
					if ( !isset($mount[$dex]) ){
						$mount[$dex] = array();
					}

					$lastMount = &$mount;
					$lastDex = $dex;

					$mount = &$mount[$dex];
				}

				$this->addRoute( $lastMount, $lastDex, $action );
			}
		}
	}

	protected function findRoute( $path ){
		$mount = $this->routingTable;
		$settings = array();
		$back = array();

		$lastAction = $this->routingTable['/'];
		$lastPath = $path;
		$lastBack = $back;
		$lastSettings = array();

		while( !empty($path) ){
			$p = array_shift($path);

			if ( isset($mount[$p]) ){
				$mount = $mount[$p];

				if ( isset($mount['/settings']) ){
					$settings = $mount['/settings'] + $settings; // build the settings
				}

				if ( isset($mount['/']) ){
					$lastSettings = $settings;
					$lastPath = $path;
					$lastBack = $back;
					$lastAction = $mount['/'];
				}

				$back[] = $p;
			}else{
				$path = null;
			}
		}

		return array(
			'settings' => $lastSettings,
			'action'   => $lastAction,
			'back'     => $lastBack,
			'info'     => $lastPath
		);
	}

	protected function translateRoute( $routeInfo ){
		$action   = $routeInfo['action'];
		$back     = $routeInfo['back'];
		$info     = $routeInfo['info'];
		$settings = $routeInfo['settings'];
		$content  = null;

		if ( is_callable($action) ){
			$content = $action( $info );
		}elseif( $action instanceof \Snap\Node\Core\Snapable ){
			$content = $action;
		}else{
			$content = $action;
		}

		if ( $content instanceof \Snap\Node\Core\Page ){
			$page = $content;
		}else{
			$page = null;

			if ( isset($settings['page']) ){
				$page = $settings['page'];
			}

			if( $page instanceof \Snap\Node\Core\Page ){
				// nothing to do
			}elseif ( $page == null ){
				$page = new \Snap\Node\Page\Basic();
			}elseif ( is_callable($page) ){
				$page = $page();
			}else{
				// it should be a string
				$page = new $page();
			}

			if( $content instanceof \Snap\Node\Core\Snapable ){
				$page->setTemplateData(array(
					'content' => $content
				));
			}elseif( is_string($content) ){
				if ( class_exists($content) ){
					$page->setTemplateData(array(
						'content' => new $content()
					));
				}else{
					$page->setTemplateData(array(
						'content' => new \Snap\Node\Core\Text( $content )
					));
				}
			}elseif( is_array($content) ){
				$page->setViewData( $content );
			}elseif( !empty($back) ){
				return $this->translateRoute( $this->findRoute( $back ) );
			}else return null;
		}

		return array(
			'settings' => $settings,
			'action'   => $page,
			'back'     => $back,
			'info'     => $info
		);
	}

	protected function loadHeaders( $ctype ){
		switch ( $ctype ){
			case 'htm' :
			case 'html' :
				header('Content-type: text/html');
				break;

			case 'json' :
				if (isset($_SERVER['HTTP_ACCEPT']) && (strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false)) {
    				header('Content-type: application/json');
				} else {
					header('Content-type: text/plain');
				}
				break;

			case 'js' :
				header('Content-type: application/javascript');
				break;

			case 'css' :
				header('Content-type: text/css');
				break;

			case "jpeg":
				$ctype = 'jpg';
			case "jpg" :
			case "gif" :
			case "png" :
				header('Content-type: image/'.$ctype);
				break;

			default :
				break;
		}
	}

	protected function respond( $data ){
		\Snap\Lib\Core\Session::save();

		echo $this->asJson ? $this->makeJson( $data ) : $this->makeHtml($data);

		$em = \Snap\Model\Doctrine::getEntityManager();
		if ( $em ){
			try {
				$em->flush();
			}catch( \Exception $ex ){
				// TODO : make a global way to handle exceptions and logging
				// TODO : there has to be a better way to do this than... this
				$this->logError( $ex );
			}
		}
	}

	abstract protected function loadRoutes();

	protected function makeJson( $response ){
		$this->loadHeaders( 'json' );

		$response['request'] = static::$pageRoot;
		$response['redirect'] = $this->redirect;
		// TODO : protect from some darkness that can come with the data, would rather not need to do this?
		$response['content'] = utf8_encode( $response['content'] );

		return json_encode( $response );
	}

	protected function makeHtml( $response ){
		if ( !is_null($this->redirect) ){
			header( 'Location: '.static::$pageRoot.'/'.$this->redirect ) ;
		}elseif ( $this->isRaw ){
			return $response['content'];
		}else{
			$this->loadHeaders( 'htm' );

			$js = '';
			if ( isset($response['js']) ){
				foreach( $response['js'] as $link ){
					if ( $link != '' ){ /* TODO : where is this coming from ? */
						$js .= "\n<script type='text/javascript' src='$link'></script>";
					}
				}
			}

			$css = '';
			if ( isset($response['css']) ){
				foreach( $response['css'] as $link ){
					if ( $link != '' ){
						$css .= "\n<link type='text/css' rel='stylesheet' href='$link'/>";
					}
				}
			}

			$title = isset($response['title']) ? $response['title'] : '';
			$meta = isset($response['meta']) ? $response['meta'] : '';
			$bodyClass = isset($response['bodyClass']) ? $response['bodyClass'] : '';
			$debug = isset($response['debug']) ? $response['debug'] : '';
			$junk = isset($response['junk']) ? $response['junk'] : '';
			$content = isset($response['content']) ? $response['content'] : '';
			$onload = isset($response['onload']) ? $response['onload'] : '';

			// TODO : favicon would be nice...
			return <<<HTML
<!DOCTYPE HTML>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en'>
	<head>
		<title>{$title}</title>
		<link rel="icon" type="image/ico" href="/resources/favicon.ico"/>
		<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>
		{$meta}
		<!-- js links -->
		{$js}
		<!-- css links -->
		{$css}
	</head>
	<body class="{$bodyClass}">
		<pre>{$debug}</pre>
		{$junk}
		{$content}
		{$onload}
	</body>
</html>
HTML;
		}
	}

	public function serve(){
		$this->serveRoute( static::$pageData );
	}

	protected function serveRoute( $route ){
		try{
			$response = null;

			if ( count($route) > 0 ){
				$data = $route;
				$mode = $data[0];
				$info = implode( '/', array_slice($data, 1) );

				$fileManager = new \Snap\Lib\File\Manager( static::$pageRequest, $mode, $info ); // populate from $_GET

				if ( $fileManager->getMode() ){
					$accessor = $fileManager->getAccessor();
					$this->loadHeaders( $accessor->getContentType() );
					$this->isRaw = $accessor->isRawContent();
					$response = array( 'content' => $fileManager->getContent(new \Snap\Node\Page\Basic()) );
				}
			}

			if ( is_null($response) ){
				// delay this to improve performance of reflective resource delivery
				$this->loadRoutes();
				$settings = $this->translateRoute( $this->findRoute($route) );

				if ( $settings['action'] ){
					$response = $settings['action']->serve( $this );
				}else{
					$response = array( 'content' => '<!-- Page Not Found -->' );
				}
			}

			$this->respond( $response );
		}catch( Reroute $reroute ){
			// TODO : this is a stop gap measure right now
			$this->serveRoute( explode('/',$reroute->getReroute()) );
		}catch( Redirect $redirect ){
			// TODO : this is a stop gap measure right now
			$this->redirect = $redirect->getRedirect();
			$this->respond( array('content' => '') );
		}catch( \Exception $ex ){
			echo '-=System Error=-';
			$this->logError( $ex );
		}
	}
}


text:
namespace AgileObjects.ReadableExpressions.Translations
{
    using System;
#if NET35
    using Microsoft.Scripting.Ast;
#else
    using System.Linq.Expressions;
#endif

    /// <summary>
    /// Implementing classes will translate an Expression to a source-code string.
    /// </summary>
    public interface ITranslation : ITranslatable
    {
        /// <summary>
        /// Gets the ExpressionType of the translated Expression.
        /// </summary>
        ExpressionType NodeType { get; }

        /// <summary>
        /// Gets the type of the translated Expression.
        /// </summary>
        Type Type { get; }
    }
}


text:
var
  where = 'client' // Adds files only to the client
;

Package.describe({
  name    : 'pegaMultiselect:ui',
  summary : 'pegaMultiselect UI - LESS Release of pegaMultiselect UI',
  version : '{version}',
  git     : 'git://github.com/pegaMultiselect/Multiselect-Pega-LESS.git',
});

Package.onUse(function(api) {

  api.versionsFrom('1.0');
  api.use('less', 'client');

  api.addFiles([
    {files}
  ], 'client');

});


text:
import nussl
import matplotlib.pyplot as plt
import time
import warnings
import numpy as np

warnings.filterwarnings("ignore")
start_time = time.time()

def visualize_and_embed(sources):
    plt.figure(figsize=(10, 6))
    plt.subplot(211)
    nussl.utils.visualize_sources_as_masks(sources,
        y_axis='mel', db_cutoff=-40, alpha_amount=2.0)
    plt.subplot(212)
    nussl.utils.visualize_sources_as_waveform(
        sources, show_legend=False)
    plt.show()
    nussl.play_utils.multitrack(sources)

audio_path = nussl.efz_utils.download_audio_file(
    'schoolboy_fascination_excerpt.wav')
audio_signal = nussl.AudioSignal(audio_path)

separators = [
    nussl.separation.primitive.FT2D(audio_signal),
    nussl.separation.primitive.HPSS(audio_signal),
    nussl.separation.primitive.Melodia(audio_signal),
]

weights = [2, 1, 2]
returns = [[1], [0], [1]]

fixed_centers = np.array([
    [0 for i in range(sum(weights))],
    [1 for i in range(sum(weights))],
])

ensemble = nussl.separation.composite.EnsembleClustering(
    audio_signal, 2, separators=separators, init=fixed_centers,
    fit_clusterer=False, weights=weights, returns=returns)
ensemble.clusterer.cluster_centers_ = fixed_centers
estimates = ensemble()

estimates = {
    f'Cluster {i}': e for i, e in enumerate(estimates)
}

visualize_and_embed(estimates)
# -

end_time = time.time()
time_taken = end_time - start_time
print(f'Time taken: {time_taken:.4f} seconds')


text:
<?php
/*
 * Website http://www.codehelper.io
 * Author: khoaofgod@yahoo.com
 * Any bugs, question, please visit our forum at http://www.codehelper.io
 */
class ip_codehelper {
    public function getRealIP() {
        $ipaddress = '';
        if(isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
            $ipaddress =  $_SERVER['HTTP_CF_CONNECTING_IP'];
        } else if (isset($_SERVER['HTTP_X_REAL_IP'])) {
            $ipaddress = $_SERVER['HTTP_X_REAL_IP'];
        }
        else if (isset($_SERVER['HTTP_CLIENT_IP']))
            $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
        else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
            $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
        else if(isset($_SERVER['HTTP_X_FORWARDED']))
            $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
        else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
            $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
        else if(isset($_SERVER['HTTP_FORWARDED']))
            $ipaddress = $_SERVER['HTTP_FORWARDED'];
        else if(isset($_SERVER['REMOTE_ADDR']))
            $ipaddress = $_SERVER['REMOTE_ADDR'];
        else
            $ipaddress = 'UNKNOWN';

        return $ipaddress;
    }

    public function getLocation($ip="") {
        if($ip == "") {
            $ip = $this->getRealIP();
        }
        if(!class_exists("phpFastCache")) {
            die("Please required phpFastCache Class");
        }
        // you should change this to cURL()
        $data = phpFastCache::get("codehelper_ip_".md5($ip));
        // caching 1 week
        if($data == null) {
            $url = "http://api.codehelper.io/ips/?php&ip=".$ip;
            $json = file_get_contents($url);
            $data = json_decode($json,true);
            phpFastCache::set("codehelper_ip_".md5($ip),$data,3600*24*7);
        }

        return $data;
    }

    public function SSLForwardJS() {
        $ip = $this->getRealIP();
        if(!class_exists("phpFastCache")) {
            die("Please required phpFastCache Class");
        }

        // you should change this to cURL()
        $data = phpFastCache::get("codehelper_ip_ssl".md5($ip));
        // caching 1 week
        if($data == null) {
            $url = "http://api.codehelper.io/ips/?callback=codehelper_ip_callback&ip=".$ip;
            $data = file_get_contents($url);
            phpFastCache::set("codehelper_ip_ssl".md5($ip),$data,3600*24*7);
        }
        return $data;
    }
}


text: class Foo { static prop: number; }


text:
(function () {
  'use strict';

  angular
    .module('cvs')
    .controller('ImageUploaderCtrl', ImageUploaderCtrl);

  ImageUploaderCtrl.$inject = ['$scope', '$state', '$window', '$filter'];

  function ImageUploaderCtrl($scope, $state, $window, $filter) {

    var vm = this;

    vm.init = function() {

    };
  }
}());


text:
/*********************************************************************************
* (Random number chooser) Write a method that returns a random number between    *
* 1 and 54, excluding the numbers passed in the argument. The method header is   *
* specified as follows:                                                          *
* public static int getRandom(int... numbers)                                    *
*********************************************************************************/
public class Exercise_07_13 {

	/** Method getRandom returns a random number between 1 and 54,
	*   excluding the numbers passed in the argument.*/
	public static int getRandom(int... numbers) {
		int num;	// Random number
		boolean isExcluded; // Is the number excluded
		do {
			isExcluded = false;
			num = 1 + (int)(Math.random() * 5);
			for (int e: numbers) {
				if (num == e)
					isExcluded = true;
			}
		} while (isExcluded); // Test if number is Excluded
		return num;
	}
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

require(APPPATH.'/libraries/REST_Controller.php');
class Auto extends REST_Controller {

	private $indexType;
	private $searchData;

    public function __construct() {
        parent::__construct();
		$this->indexType			= $this->uri->segment(2, 0);
		$this->searchData			=  $this->input->get();
   		$this->load->library('autocomplate');
	}

	public function index_get()
	{

	}
	public function stay_get()
	{
		header('Content-Type: application/json');
		$_GET['response'] = $this->autocomplate->prefix($this->indexType, $this->searchData);
		echo json_encode($_GET, JSON_UNESCAPED_UNICODE);
	}
	public function cast_get()
	{
		header('Content-Type: application/json');
		$_GET['response'] = $this->autocomplate->prefix($this->indexType, $this->searchData);
		echo json_encode($_GET, JSON_UNESCAPED_UNICODE);
	}
	public function photo_get()
	{
		header('Content-Type: application/json');
		$_GET['response'] = $this->autocomplate->prefix($this->indexType, $this->searchData);
		echo json_encode($_GET, JSON_UNESCAPED_UNICODE);
	}
	public function travel_get()
	{
		header('Content-Type: application/json');
		$_GET['response'] = $this->autocomplate->prefix($this->indexType, $this->searchData);
		echo json_encode($_GET, JSON_UNESCAPED_UNICODE);
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ISAAR.MSolve.PreProcessor.Interfaces;
using ISAAR.MSolve.Matrices.Interfaces;
using ISAAR.MSolve.Matrices;
using System.IO;
using ISAAR.MSolve.PreProcessor.Elements;

namespace ISAAR.MSolve.PreProcessor.Embedding
{

    public class CohesiveElementEmbedder : IFiniteElementDOFEnumerator
    {
        private readonly Model model;
        private readonly Element embeddedElement;
        private readonly IEmbeddedDOFInHostTransformationVector transformation;
        private readonly Dictionary<SuperElementDOF, int> superElementMap = new Dictionary<SuperElementDOF, int>();
        private readonly Dictionary<EmbeddedNode, Dictionary<DOFType, int>> dofToHostMapping = new Dictionary<EmbeddedNode, Dictionary<DOFType, int>>();
        //PROSTHIKI EMBEDDED: comment out to private apo to transformation matrix
        private Matrix2D<double> transformationMatrix;
        ////EMBEDDED:
        //public Matrix2D<double> transformationMatrix;

        //private bool isElementEmbedded = false;

        public CohesiveElementEmbedder(Model model, Element embeddedElement, IEmbeddedDOFInHostTransformationVector transformation)
        {
            this.model = model;
            this.embeddedElement = embeddedElement;
            this.transformation = transformation;
            Initialize();
            // PROSTHIKI EMBEDDED:
            ModifyTransformationMatrix();
        }

        // PROSTHIKI EMBEDDED:
        public void ModifyTransformationMatrix()
        {
            double[,] updatedtransformationMatrixData = new double[64, 232];
            for (int j = 0; j < 40; j++)
            {
                for (int k = 0; k < 232; k++)
                {
                    updatedtransformationMatrixData[j, k] = transformationMatrix[24 + j, k];
                }
            }
            for (int j = 0; j < 24; j++)
            {
                for (int k = 0; k < 232; k++)
                {
                    updatedtransformationMatrixData[40+j, k] = transformationMatrix[j, k];
                }
            }
            transformationMatrix = new Matrix2D<double>(updatedtransformationMatrixData);
        }

        private void InitializeMappings()
        {
            var e = embeddedElement.ElementType as IEmbeddedElement;
            superElementMap.Clear();
            int index = 0;
            foreach (var embeddedNode in e.EmbeddedNodes)
            {
                int nodeOrderInEmbeddedElement = embeddedElement.Nodes.IndexOf(embeddedNode.Node);
                var currentEmbeddedNodeDOFs = embeddedElement.ElementType.DOFEnumerator.GetDOFTypes(embeddedElement)[nodeOrderInEmbeddedElement];
                //var currentNodeDOFs = currentEmbeddedNodeDOFs.Intersect(embeddedNode.DependentDOFs);
                var independentEmbeddedDOFs = currentEmbeddedNodeDOFs.Except(embeddedNode.DependentDOFs);

                // TODO: Optimization to exclude host DOFs that embedded node does not depend on.
                for (int i = 0; i < embeddedNode.EmbeddedInElement.Nodes.Count; i++)
                {
                    var currentNodeDOFs = embeddedNode.EmbeddedInElement.ElementType.DOFEnumerator.GetDOFTypes(embeddedNode.EmbeddedInElement)[i];
                    foreach (var dof in currentNodeDOFs)
                    {
                        var superElementDOF = new SuperElementDOF() { DOF = dof, EmbeddedNode = embeddedNode.Node, HostNode = embeddedNode.EmbeddedInElement.Nodes[i], Element = embeddedNode.EmbeddedInElement };
                        if (!superElementMap.ContainsKey(superElementDOF))
                        {
                            superElementMap.Add(superElementDOF, index);
                            index++;
                        }
                    }
                }

                //var independentEmbeddedDOFs = model.NodalDOFsDictionary[embeddedNode.Node.ID].Select(x => x.Key).Except(embeddedNode.DependentDOFs);
                //int nodeOrderInEmbeddedElement = embeddedElement.Nodes.IndexOf(embeddedNode.Node);

                //var independentEmbeddedDOFs = embeddedElement.ElementType.DOFEnumerator.GetDOFTypes(embeddedElement)[nodeOrderInEmbeddedElement].Except(embeddedNode.DependentDOFs);

                foreach (var dof in independentEmbeddedDOFs)
                {
                    var superElementDOF = new SuperElementDOF() { DOF = dof, EmbeddedNode = embeddedNode.Node, HostNode = null, Element = null };
                    if (!superElementMap.ContainsKey(superElementDOF))
                    {
                        superElementMap.Add(superElementDOF, index);
                        index++;
                    }
                }
            }

            foreach (var node in embeddedElement.Nodes.Except(e.EmbeddedNodes.Select(x => x.Node)))
            {
                int nodeOrderInEmbeddedElement = embeddedElement.Nodes.IndexOf(node);
                var currentNodeDOFs = embeddedElement.ElementType.DOFEnumerator.GetDOFTypes(embeddedElement)[nodeOrderInEmbeddedElement];
                foreach (var dof in currentNodeDOFs)
                {
                    var superElementDOF = new SuperElementDOF() { DOF = dof, EmbeddedNode = node, HostNode = null, Element = null };
                    if (!superElementMap.ContainsKey(superElementDOF))
                    {
                        superElementMap.Add(superElementDOF, index);
                        index++;
                    }
                }
            }
        }

        private void CalculateTransformationMatrix()
        {
            var e = embeddedElement.ElementType as IEmbeddedElement;
            int row = 0;
            int col = 0;
            int totalRows = embeddedElement.ElementType.DOFEnumerator.GetDOFTypes(embeddedElement).SelectMany(x => x).Count();
            var matrix = new double[totalRows, superElementMap.Count];

            foreach (var embeddedNode in e.EmbeddedNodes)
            {
                var localTransformationMatrix = transformation.GetTransformationVector(embeddedNode);
                var localHostDOFs = transformation.GetDOFTypesOfHost(embeddedNode);
                int nodeOrderInEmbeddedElement = embeddedElement.Nodes.IndexOf(embeddedNode.Node);
                var embeddedNodeDOFQuantity = embeddedElement.ElementType.DOFEnumerator.GetDOFTypes(embeddedElement)[nodeOrderInEmbeddedElement].Count;
                int dependentDOFs = transformation.GetDependentDOFTypes.Count;

                for (int i = 0; i < dependentDOFs; i++)
                {
                    col = 0;
                    for (int j = 0; j < localHostDOFs.Count; j++)
                    {
                        for (int k = 0; k < localHostDOFs[j].Count; k++)
                        {
                            var superelement = new SuperElementDOF() { DOF = localHostDOFs[j][k], Element = embeddedNode.EmbeddedInElement, EmbeddedNode = embeddedNode.Node, HostNode = embeddedNode.EmbeddedInElement.Nodes[j] };
                            matrix[row + i, superElementMap[superelement]] = localTransformationMatrix[i][col];
                            col++;
                        }
                    }
                }
                row += dependentDOFs;

                var independentEmbeddedDOFs = embeddedElement.ElementType.DOFEnumerator.GetDOFTypes(embeddedElement)[nodeOrderInEmbeddedElement].Except(embeddedNode.DependentDOFs).ToArray();
                for (int j = 0; j < independentEmbeddedDOFs.Length; j++)
                {
                    var superelement = new SuperElementDOF() { DOF = independentEmbeddedDOFs[j], Element = null, HostNode = null, EmbeddedNode = embeddedNode.Node };
                    matrix[row, superElementMap[superelement]] = 1;
                    row++;
                }
            }

            foreach (var node in embeddedElement.Nodes.Except(e.EmbeddedNodes.Select(x => x.Node)))
            {
                int nodeOrderInEmbeddedElement = embeddedElement.Nodes.IndexOf(node);
                var currentNodeDOFs = embeddedElement.ElementType.DOFEnumerator.GetDOFTypes(embeddedElement)[nodeOrderInEmbeddedElement];
                for (int j = 0; j < currentNodeDOFs.Count; j++)
                {
                    var superelement = new SuperElementDOF() { DOF = currentNodeDOFs[j], Element = null, HostNode = null, EmbeddedNode = node };
                    matrix[row, superElementMap[superelement]] = 1;
                    row++;
                }
            }

            //StreamWriter sw = File.CreateText(String.Format("TransformationMatrix{0}.txt", embeddedElement.ID));
            //for (int i = 0; i < totalRows; i++)
            //{
            //    var line = String.Empty;
            //    for (int j = 0; j < superElementMap.Count; j++)
            //        line += matrix[i,j].ToString() + ";";
            //    sw.WriteLine(line);
            //}
            //sw.Close();
            transformationMatrix = new Matrix2D<double>(matrix);
        }

        private void Initialize()
        {
            var e = embeddedElement.ElementType as IEmbeddedElement;
            if (e == null) return;
            if (e.EmbeddedNodes.Count == 0) return;

            InitializeMappings();
            CalculateTransformationMatrix();
        }

        //public IMatrix2D<double> GetTransformedMatrix(IMatrix2D<double> matrix)
        //{
        //    var e = embeddedElement.ElementType as IEmbeddedElement;
        //    //if (e == null || !isElementEmbedded) return matrix;
        //    if (e == null) return matrix;
        //    if (e.EmbeddedNodes.Count == 0) return matrix;

        //    return transformationMatrix.Transpose() * ((SymmetricMatrix2D<double>)matrix).ToMatrix2D() * transformationMatrix;
        //}

        public IMatrix2D<double> GetTransformedMatrix(IMatrix2D<double> matrix)
        {
            var e = embeddedElement.ElementType as IEmbeddedElement;
            //if (e == null || !isElementEmbedded) return matrix;
            if (e == null) return matrix;
            if (e.EmbeddedNodes.Count == 0) return matrix;
            //PrintUtilities.WriteToFile(transformationMatrix.Data, @"C:\Users\turbo-x\Desktop\cohesive_check_MSOLVE_2\paradeigma_apo_arxika_swsta_embeded_shell_gia_check_tou_rve_embedding_sto_MSolve\elegxos_alalgwn_fe2_tax_me1_arxiko_chol_dixws_me1_OneElementRVECheckExample\transformationMatrix.txt");//transformationMatrix.Data();
            return transformationMatrix.Transpose() * ((Matrix2D<double>)matrix) * transformationMatrix;
        }

        public double[] GetTransformedVector(double[] vector)
        {
            var e = embeddedElement.ElementType as IEmbeddedElement;
            //if (e == null || !isElementEmbedded) return matrix;
            if (e == null) return vector;
            if (e.EmbeddedNodes.Count == 0) return vector;

            return (transformationMatrix * new Vector<double>(vector)).Data;
        }

        public double[] GetTransformedForcesVector(double[] vector)
        {
            var e = embeddedElement.ElementType as IEmbeddedElement;
            //if (e == null || !isElementEmbedded) return matrix;
            if (e == null) return vector;
            if (e.EmbeddedNodes.Count == 0) return vector;

            return (transformationMatrix.Transpose() * new Vector<double>(vector)).Data;
        }

        public IList<IList<DOFType>> GetDOFTypes(Element element)
        {
            //return element.ElementType.GetElementDOFTypes(element);

            var dofs = new List<IList<DOFType>>();
            Node currentNode = null;
            List<DOFType> nodeDOFs = null;

            foreach (var superElement in superElementMap)
            {
                Node node = superElement.Key.HostNode == null ? superElement.Key.EmbeddedNode : superElement.Key.HostNode;

                if (currentNode != node)
                {
                    if (nodeDOFs != null)
                        dofs.Add(nodeDOFs);
                    currentNode = node;
                    nodeDOFs = new List<DOFType>();
                }
                nodeDOFs.Add(superElement.Key.DOF);
            }
            if (nodeDOFs != null)
                dofs.Add(nodeDOFs);

            return dofs;
        }

        public IList<IList<DOFType>> GetDOFTypesForDOFEnumeration(Element element)
        {
            //if (embeddedElement != element) throw new ArgumentException();

            var nodesDictionary = new Dictionary<Node, int>();
            int index = 0;
            foreach (var node in element.Nodes)
            {
                nodesDictionary.Add(node, index);
                index++;
            }

            var dofs = new List<IList<DOFType>>();
            for (int i = 0; i < element.Nodes.Count; i++)
                dofs.Add(new List<DOFType>());

            Node currentNode = null;
            List<DOFType> nodeDOFs = null;

            foreach (var superElement in superElementMap)
            {
                if (superElement.Key.HostNode != null) continue;
                Node node = superElement.Key.EmbeddedNode;
                //Node node = superElement.Key.HostNode == null ? superElement.Key.EmbeddedNode : superElement.Key.HostNode;

                if (currentNode != node)
                {
                    if (nodeDOFs != null)
                        dofs[nodesDictionary[currentNode]] = nodeDOFs;
                    currentNode = node;
                    nodeDOFs = new List<DOFType>();
                }
                nodeDOFs.Add(superElement.Key.DOF);
            }
            if (nodeDOFs != null)
                dofs[nodesDictionary[currentNode]] = nodeDOFs;
            //dofs.Add(nodeDOFs);

            return dofs;
        }

        public IList<Node> GetNodesForMatrixAssembly(Element element)
        {
            var nodes = new List<Node>();
            Node currentNode = null;
            foreach (var superElement in superElementMap)
            {
                Node node = superElement.Key.HostNode == null ? superElement.Key.EmbeddedNode : superElement.Key.HostNode;
                if (currentNode != node)
                {
                    if (currentNode != null)
                        nodes.Add(currentNode);
                    currentNode = node;
                }
                //if (nodes.IndexOf(node) < 0)
                //    nodes.Add(node);
            }
            if (currentNode != null)
                nodes.Add(currentNode);

            return nodes;
        }
    }
}


text:
var ndarray = require('ndarray');
var show = require('../');
var fs =  require('fs');
var fill = require('ndarray-fill')
var pool = require('ndarray-scratch')
var expected = fs.readFileSync(__dirname + '/1d/expected.txt', 'utf8');

var test = require('tape');
test('1d', function (t) {
  var m = pool.zeros([3])
  fill(m,function(i) { return i })

  t.equal(show(m) + '\n', expected);
  t.end();
});


text:
{% extends "wagtailadmin/base.html" %}
{% load i18n wagtailadmin_tags %}
{% block titletag %}{% blocktrans with snippet_type_name_plural=model_opts.verbose_name_plural|capfirst %}Snippets {{ snippet_type_name_plural }}{% endblocktrans %}{% endblock %}

{% block extra_js %}
    {{ block.super }}

    {% if can_delete_snippets %}

    {% endif %}
{% endblock %}

{% block content %}

                {% blocktrans with snippet_type_name_plural=model_opts.verbose_name_plural|capfirst %}Snippets {{ snippet_type_name_plural }}{% endblocktrans %}

                {% if is_searchable %}
                    <form class="col search-form" action="{% url 'wagtailsnippets:list' model_opts.app_label model_opts.model_name %}" method="get" novalidate>

                            {% for field in search_form %}
                                {% include "wagtailadmin/shared/field_as_li.html" with field=field field_classes="field-small iconfield" input_classes="icon-search" %}
                            {% endfor %}

<input type="submit" value="Search" class="button" />

                    </form>
                {% endif %}

                {% if can_delete_snippets %}
                    {% blocktrans with snippet_type_name=model_opts.verbose_name_plural %}Delete {{ snippet_type_name }}{% endblocktrans %}
                {% endif %}
                {% if can_add_snippet %}
                    {% blocktrans with snippet_type_name=model_opts.verbose_name %}Add {{ snippet_type_name }}{% endblocktrans %}
                    {# TODO: figure out a way of saying "Add a/an [foo]" #}
                {% endif %}

            {% include "wagtailsnippets/snippets/results.html" %}

{% endblock %}


text:
import logging
import json
import re
import time
import os
import traceback
import sys
import Utils
import cv2
import hashlib
from BeautifulSoup import BeautifulSoup
from selenium.webdriver.common.by import By

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
#Reduce logging for selenium
from selenium.webdriver.remote.remote_connection import LOGGER
LOGGER.setLevel(logging.WARNING)

class Address:
    def __init__(self, url, observer, options):
        self.url = url
        self.observer = observer
        self.options = options

        self.vars = {} #Map of js variables and their values
        self.links = {} #Map of the links and the amount of times they appear
        self.image_filename = "" #Filename
        self.image_hash = "" #Hash of the image
        self.driver  = self.get_driver()

    def get_url(self,url):
        proxies = {'http' : "http://%s" % self.observer.ip, 'https': "https://%s" % self.observer.ip}
        if self.options.no_proxy:
            proxies = {}
        try:
            r = self.observer.session.get(url, proxies=proxies, verify=False, timeout=5)
            self.content = r.content
        except Exception as e:
            return 0
        #Save source
        self.save_source()
        return 1

    def save_source(self):
        filename = "tmp/source/%s" % Utils.as_filename("%s-%s.txt" % (self.url, self.observer.ip))
        f = open(filename, 'w')
        f.write(self.content)

    def set_data(self):
        vars = self.parse_scripts()
        self.get_child("",vars,0)
        self.parse_links()

    def parse_scripts(self):
        soup = BeautifulSoup(self.content)
        all_data = []
        res_dict = {}
        logging.debug("Parsing script for %s" % self.url)
        for script_part in soup.findAll('script'):
            try:
                json_data = re.findall('({.*})', script_part.string)
                for j_data in json_data:
                    try:
                        data = json.loads(j_data)
                        if len(data):
                            all_data.append(data)
                    except:
                        pass
            except:
                pass

        for data in all_data:
            res_dict.update(data)
        return res_dict

    ## Recursively populate self.vars map for js variables
    def get_child(self,name,child,place):
        if place == 5:
            return
        if type(child) is dict:
            for leaf in child:
                if name != "":
                    use_name = name + "-" + str(leaf)
                else:
                    use_name = str(leaf)
                self.get_child(use_name,child[leaf],place + 1)
        else:
            self.vars[name] = child

    def parse_links(self):
        soup = BeautifulSoup(self.content)
        for link in soup.findAll('a'):
            if 'href' in link:
                link_name = link['href'].strip().replace(" ","")
                if not link_name in self.links:
                    self.links[link_name] = 0
                self.links[link_name] += 1

    def get_driver(self):
        dcap = dict(DesiredCapabilities.PHANTOMJS)
        dcap["phantomjs.page.settings.userAgent"] = ( self.observer.ua )

        service_args = ['--ignore-ssl-errors=true', '--ssl-protocol=any']
        if not self.options.no_proxy:
            service_args.append("--proxy=%s" % self.observer.ip)

        driver = webdriver.PhantomJS(service_log_path=os.path.devnull, desired_capabilities=dcap, service_args=service_args)
        driver.set_window_size(1280,800)
        driver.set_page_load_timeout(20)
        driver.set_script_timeout(30)

        return driver

    def take_screenshot(self):
        driver = self.driver
        driver.get(self.url)
        time.sleep(10)
        try:
            filename = "tmp/screen/%s" % Utils.as_filename("%s-%s.png" % (self.url,self.observer.ip))
            driver.save_screenshot(filename)
            self.image_filename = filename
            image = self.read_image()
            self.image_hash = hashlib.md5(image).hexdigest()
            logging.debug("Saved %s" % filename)
        except Exception as e:
            print "Error taking screenshot: %s" % (traceback.format_exception(*sys.exc_info()))
            driver.close()
            driver.quit()
            return 0

    def perform_action(self,action):
        try:
            driver = self.driver
            driver.get(self.url)
            time.sleep(10)
            try:
                element = driver.find_element_by_id('new_button')
                logging.debug("Element chosen is: %s" % element)
                element.click()
                logging.debug("Clicked on element %s" % element)
            except Exception as e:
                print "Error taking action %s: %s" % (action,traceback.format_exception(*sys.exc_info()))
                driver.close()
                driver.quit()
                return 0
        except:
            print "Error with observer %s" % self.observer.ip

    def read_image(self):
        image = cv2.imread(self.image_filename)
        if image is None:
            print "Error getting image of url %s for file %s of observer %s" % (url,filename, self.ip)
        return image


text:
LinuxProgramRep
===============

Language:C/C++, IDE:Eclipse, Desktop:Ubuntu 14.04 X64 and Windows 7 X64 for cygwin, include POSIX threads, msgQ , shareMem, semaphore and gTest. This repository(project)  is use to programming practice!


text:
<?php

namespace phpDocumentor\Reflection\DocBlock\Tag;

/**
 * Test class for \phpDocumentor\Reflection\DocBlock\ThrowsTag
 *
 * @author    Mike van Riel <mike.vanriel@naenius.com>
 * @copyright 2010-2011 Mike van Riel / Naenius. (http://www.naenius.com)
 * @license   http://www.opensource.org/licenses/mit-license.php MIT
 * @link      http://phpdoc.org
 */
class ThrowsTagTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Test that the \phpDocumentor\Reflection\DocBlock\Tag\ThrowsTag can
     * understand the @throws DocBlock.
     *
     * @param string $type
     * @param string $content
     * @param string $extractedType
     * @param string $extractedTypes
     * @param string $extractedDescription
     *
     * @covers \phpDocumentor\Reflection\DocBlock\Tag\ThrowsTag
     * @dataProvider provideDataForConstructor
     *
     * @return void
     */
    public function testConstructorParsesInputsIntoCorrectFields(
        $type,
        $content,
        $extractedType,
        $extractedTypes,
        $extractedDescription
    ) {
        $tag = new ThrowsTag($type, $content);

        $this->assertEquals($type, $tag->getName());
        $this->assertEquals($extractedType, $tag->getType());
        $this->assertEquals($extractedTypes, $tag->getTypes());
        $this->assertEquals($extractedDescription, $tag->getDescription());
    }

    /**
     * Data provider for testConstructorParsesInputsIntoCorrectFields()
     *
     * @return array
     */
    public function provideDataForConstructor()
    {
        return array(
            array('throws', '', '', array(), ''),
            array('throws', 'int', 'int', array('int'), ''),
            array(
                'throws',
                'int Number of Bobs',
                'int',
                array('int'),
                'Number of Bobs'
            ),
            array(
                'throws',
                'int|double Number of Bobs',
                'int|double',
                array('int', 'double'),
                'Number of Bobs'
            ),
            array(
                'throws',
                "int Number of \n Bobs",
                'int',
                array('int'),
                "Number of \n Bobs"
            ),
            array(
                'throws',
                " int Number of Bobs",
                'int',
                array('int'),
                "Number of Bobs"
            ),
            array(
                'throws',
                "int\nNumber of Bobs",
                'int',
                array('int'),
                "Number of Bobs"
            )
        );
    }
}


text:
#if TARGET_OS_IPHONE
#import <UIKit/UIKit.h>
#define COLOR_CLASS UIColor
#else
#import <Cocoa/Cocoa.h>
#define COLOR_CLASS NSColor
#endif

@class MXFMixfaderInterface;

typedef NS_ENUM(NSUInteger, MXFConnectEvent) {
	CONNECT_START,
	CONNECT_SUCCESS,
	CONNECT_FAIL,
	DISCONNECT_START,
	DISCONNECT_END,
};

typedef NS_ENUM(NSUInteger, MXFRSSILevelType) {
    VERY_LOW,
    LOW,
    NORMAL,
    HIGH,
    VERY_HIGH,
};

typedef NS_ENUM(NSUInteger, MXFModeType) {
    NORMAL_M = 1,
    SHARED_M = 2,
};

typedef NS_ENUM(NSUInteger, MXFNotifType) {
    NOTIFICATION_OFF,
    NOTIFICATION_ON,
};

typedef NS_ENUM(NSUInteger, MXFButtonType) {
    RELEASE,
    PUSH,
};

typedef NS_ENUM(NSUInteger, MXFBatterieType) {
    NO_CHARGE,
    CHARGE,
};

typedef NS_ENUM(NSUInteger, MXFCalibrationStateType){
    CALIBRATION_IDLE,
    CALIBRATION_START,
    CALIBRATION_FAIL,
    CALIBRATION_CANCEL,
    CALIBRATION_END,
    CALIBRATION_LEFT_DONE,
    CALIBRATION_RIGHT_DONE,
};

typedef NS_ENUM(NSUInteger, MXFFaderNotificationModeType) {
    FADER_NOTIFY_ALWAYS,
    FADER_NOTIFY_ON_VALUE_CHANGE,
};

typedef struct
{
    uint16_t cutMin;
    uint16_t cutMax;
} MXFCutProfile;

typedef void(^MXFStatsCompletion)(BOOL success, NSError * _Nullable error,NSInteger crossfaderCycles, NSInteger batterieCycles, NSInteger buttonClicks, NSInteger connectionCount);

typedef void(^MXFRenameCompletion)(BOOL success, NSError * _Nullable error, NSString * _Nullable name);

typedef void(^MXFFaderCompletion)(BOOL succes, NSError * _Nullable error, BOOL state);

typedef void(^MXFModeCompletion)(BOOL succes, NSError * _Nullable error, MXFModeType mode);

typedef void(^MXFCalibrationCompletion)(BOOL succes, uint16_t cutMin, uint16_t cutMax, uint16_t calMin, uint16_t calMax, NSError * _Nullable error);

typedef void(^MXFBlinkLedCompletion)(NSError * _Nullable error);

typedef void(^MXFColorCompletion)(NSError * _Nullable error);

typedef void (^MXFConnectCompletion) (MXFConnectEvent event, NSError * _Nullable error);

typedef void (^MXFScanBlock) (MXFMixfaderInterface * _Nullable mixfader, NSError * _Nullable error);

typedef void (^MXFBatteryBlock) (NSInteger battery, BOOL charging, NSError * _Nullable error);


text: #include "Source\ScriptingElement.h"


text:
import urllib2
import sys
import json
import requests
from scipy.spatial import distance

url = "http://" + sys.argv[1]
jumlah = "1000"
worker = sys.argv[2]
i = 1
while True:
	list_centroid = requests.get(url + "/centroid").json()
	list_dataset = requests.get(url + "/dataset?rowNumbers="+jumlah+"&workerName="+worker).json()
	list_kirim_data = []
	for dataset in list_dataset:
		if "data" in dataset:
			dist = []
			sys.stdout.write('\rPROCESSING ' + dataset['_id'])
			for centroid in list_centroid:
				dist.append(distance.euclidean(dataset['data'], centroid))
			minimal = min(float(s) for s in dist)
			temp = {}
			temp['id'] = dataset['_id']
			temp['result'] = dist.index(minimal)
			list_kirim_data.append(temp)

	list_kirim_data = json.dumps(list_kirim_data)
	headers = {'Content-type': 'application/json'}
	sys.stdout.write('\nIteration #' + str(i) +' -- POSTING DATA TO SERVER...\n')
	requests.post(url + "/dataset", data='{"dataSet": '+list_kirim_data+'}', headers=headers).text
	i = i+1


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.esri.arcgis.samples.rasteranalysis.MainActivity" >

    <item
        android:id="@+id/menu_analysis"
        android:icon="@android:drawable/ic_menu_gallery"
        android:showAsAction="always"
        android:title="@string/menu_analysis">
        <group android:checkableBehavior="single" >
            <item
                android:id="@+id/menu_analysis_los"
                android:title="@string/menu_analysis_los"/>
            <item
                android:id="@+id/menu_analysis_viewshed"
                android:title="@string/menu_analysis_viewshed"/>
        </group>
    </item>

</menu>


text:
                Name:

                    <input type="text" id="inputName" class="form-control" placeholder="Name" ng-model="campaign.basic.name" ng-required="true"/>

                Description:

<textarea id="inputDescription" class="form-control" placeholder="Description" rows="4" ng-model="campaign.basic.description"></textarea>

                Frequency:

                        <button type="button" class="btn btn-danger">{{campaign.basic.frequency}}</button>
                        <button type="button" class="btn btn-danger dropdown-toggle">

                        </button>

{{dispatch}}

This campaign will be sent {{campaign.basic.frequency}}


text:
const mongoose = require('mongoose');
const path = require('path');
const config = require(path.resolve('./config/config'));
const crypto = require('crypto');
const errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));
const logger = require(path.resolve('./config/lib/logger'));
const nodemailer = require('nodemailer');
const Farm = mongoose.model('Farm');
const User = mongoose.model('User');
const smtpTransport = nodemailer.createTransport(config.mailer.options);
const jwt = require('jsonwebtoken');
const qs = require('querystring');

/**
 * post:发送邀请链接
 */
exports.inviteToJoin = function (req, res) {

  req.checkBody('user', '用户不能为空').notEmpty();
  req.checkBody('user.name', '用户名不能为空').notEmpty();
  req.checkBody('user.name', '用户名长度为4-20字符').len(4, 20);
  req.checkBody('inviteeEmail', 'Email不能为空').notEmpty();
  req.sanitizeBody('inviteeEmail').toArray();
  req.checkBody('inviteeEmail', 'Email格式有误').isEmailList();
  req.checkBody('role', 'role格式有误').notEmpty().isIn(['admin', 'user']);
  req.checkBody('accessData', 'accessData格式有误').notEmpty().isBoolean();
  req.checkBody('accessDevice', 'accessDevice格式有误').notEmpty().isBoolean();

  req.getValidationResult()
    .then(checkResult)
    .then(genToken)
    .then(saveInvitor)
    .then(genUrlToken)
    .then(genEmailContent)
    .then(sendEmail)
    .catch(({ code, message }) => {
      return res.status(code).json({ message });
    });

  /**
   * 检查req.body: checkResult
   * @param { result } name description
   * @return { farmer } Description
   */
  function checkResult(result) {
    return new Promise((resolve, reject) => {
      if (!result.isEmpty()) {
        result.useFirstErrorOnly();
        return res.status(400).json({
          message: result.array()[0].msg
        });
      } else {
        const { user } = req.body;
        return resolve({ farmer: user });
      }
    });
  }

  /**
   * 根据Email生成Token: genToken
   * @param { farmer } name description
   * @return { farmer } Description
   */
  function genToken({ farmer }) {
    const bodyEmails = [...new Set(req.body.inviteeEmail)];
    // Array(length).fill()可以生成length范围的新数组
    const tokenTasks = Array(bodyEmails.length).fill().map(() => randomToken(20));
    return new Promise((resolve, reject) => {
      Promise.all(tokenTasks)
        .then(tokens => {
          farmer.inviteList = bodyEmails.map((e, idx) => {
            return { email: e, inviteToken: tokens[idx], inviteAt: new Date() };
          });
          return resolve({ farmer });
        })
        .catch(({ code, message }) => {
          return reject({ code, message });
        });
    });

    function randomToken(size) {
      return new Promise((resolve, reject) => {
        crypto.randomBytes(size, (err, buffer) => {
          if (err) return reject({ code: 400, message: err });
          const token = buffer.toString('hex');
          return resolve(token);
        });
      });
    }
  }

  /**
   * 保存邀请信息: saveInvitor
   * @param { farmer }
   * @return { farmer }
   */
  function saveInvitor({ farmer }) {
    return new Promise((resolve, reject) => {
      User
        .findOne({ username: farmer.name })
        .then(doc => {
          if (!doc) {
            return reject({ code: 404, message: '邀请者不存在' });
          } else return Farm.update({ name: farmer.name }, {
            $push: { inviteList: { $each: [] } }  // 相当于新建文档
          }, { upsert: true });
        })
        .then(() => {
          return Farm.findOne({ name: farmer.name });
        })
        .then(doc => {
          const inviteList = doc.inviteList;
          const emails = inviteList.map(l => l.email);
          const pushList = farmer.inviteList.filter(p => !emails.includes(p.email));
          const otherList = farmer.inviteList.filter(p => emails.includes(p.email));
          const otherListEmails = otherList.map(o => o.email);
          const sendList = [...pushList, ...inviteList.filter(l => otherListEmails.includes(l.email) && !l.verified)];
          farmer.inviteList = sendList;
          return Farm.update({ name: farmer.name }, {
            $push: { inviteList: { $each: pushList } }
          });
        })
        .then(() => {
          return resolve({ farmer });
        })
        .catch(err => {
          return reject({ code: 400, message: errorHandler.getErrorMessage(err) });
        });
    });
  }

  /**
   * 生成邀请: genUrlToken
   * @param { farmer } name description
   * @return { farmer, token } Description
   */
  function genUrlToken({ farmer }) {
    const { role, accessData, accessDevice } = req.body;
    return new Promise((resolve, reject) => {
      const urlTokens = farmer.inviteList.map(l => jwt.sign({ role, accessData, accessDevice }, l.inviteToken));
      farmer.inviteList.forEach((l, idx) => {
        l.urlToken = urlTokens[idx];
      });
      resolve({ farmer });
    });
  }

  /**
   * 生成邮件: genEmailContent
   * @param { famer } name description
   * @return { farmer } Description
   */
  function genEmailContent({ farmer }) {
    return new Promise((resolve, reject) => {
      const httpTransport = 'http://';
      if (config.secure && config.secure.ssl === true) {
        httpTransport = 'https://';
      }
      const baseUrl = req.app.get('domain') || httpTransport + req.headers.host;
      const renderTasks = farmer.inviteList.map(l => renderHtml(l.urlToken, l.email));
      Promise.all(renderTasks)
        .then(emailHTMLs => {
          farmer.inviteList.forEach((l, idx) => {
            l.html = emailHTMLs[idx];
          });
          return resolve({ farmer });
        })
        .catch(({ code, message }) => {
          return reject({ code, message });
        });

      function renderHtml(token, email) {
        return new Promise((resolve, reject) => {
          res.render(path.resolve('./modules/farm/server/templates/invite-email'), {
            name: farmer.name,
            appName: config.app.title,
            url: `${baseUrl}/api/farm/join?token=${token}&inviter=${farmer.name}&invitee=${email}`
          }, function (err, emailHTML) {
            if (err) return reject({ code: 400, message: err });
            else return resolve(emailHTML);
          });
        });
      }
    });
  }

  /**
   * 发送邮件: sendEmail
   * @param { farmer } name description
   * @return { } Description
   */
  function sendEmail({ farmer }) {
    return new Promise((resolve, reject) => {
      const sendTasks = farmer.inviteList.map(l => sendEmail(l.email, l.html));
      Promise.all(sendTasks)
        .then(() => {
          return res.status(202).json({
            message: '邮件以发送'
          });
        })
        .catch(({ code, message }) => {
          return reject({ code, message });
        });
    });

    function sendEmail(inviteeEmail, htmlContent) {
      return new Promise((resolve, reject) => {
        const mailOptions = {
          to: inviteeEmail,
          from: config.mailer.from,
          subject: '邀请您加入农场',
          html: htmlContent
        };
        smtpTransport.sendMail(mailOptions, function (err) {
          if (!err) {
            return resolve('An email has been sent to the provided email with further instructions.');
          } else {
            return reject({ code: 400, message: `Failure sending email to ${inviteeEmail}` });
          }
        });
      });
    }
  }

};

/**
 * get:确认邀请链接
 */
exports.joinFarm = function (req, res) {

  /**
   * 有些邮箱服务器会把&转换为& req解析时可能是invitee或amp;invitee
   */
  const url = qs.parse(req.url.replace('&', '&'));
  req.query.invitee = url.invitee;
  req.query.inviter = url.inviter;

  req.checkQuery('token', 'token不能为空').notEmpty();

  req.getValidationResult()
    .then(checkResult)
    .then(verifyInviter)
    .then(verifyEmail)
    .then(verifyToken)
    .then(savePayload)
    .catch(({ code, message }) => {
      return res.status(code).json({ message });
    });

  /**
   * checkResult
   * 检查req.body
   * @param {obj} {result} validator检测的结果
   * @return {obj} {query}
   */
  function checkResult(result) {
    return new Promise((resolve, reject) => {
      if (!result.isEmpty()) {
        result.useFirstErrorOnly();
        return reject({ code: 400, message: result.array()[0].msg });
      } else {
        const { token } = req.query;
        const email = req.query.invitee;
        const inviter = req.query.inviter;
        const query = { token, inviter, email };
        return resolve({ query });
      }
    });
  }

  /**
   * 验证inviter: verifyInviter
   * @param { query } name description
   * @return { query, farmer } Description
   */
  function verifyInviter({ query }) {
    return new Promise((resolve, reject) => {
      Farm.findOne({ name: query.inviter })
        .then(doc => {
          if (!doc) return reject({ code: 404, message: '邀请人不存在' });
          else return resolve({ query, farmer: doc });
        })
        .catch(err => {
          return reject({ code: 400, message: errorHandler.getErrorMessage(err) });
        });
    });
  }

  /**
   * 验证email: verifyEmail
   * @param { query, farmer } name description
   * @return { query, farmer } Description
   */
  function verifyEmail({ query, farmer }) {
    return new Promise((resolve, reject) => {
      const invitee = farmer.inviteList.find(l => l.email === query.email);
      if (!invitee) return reject({ code: 404, message: '邮箱信息有误' });
      else if (invitee.verified) return reject({ code: 400, message: '以加入' });
      else return resolve({ query, invitee });
    });
  }

  /**
   * 验证token: verifyToken
   * @param { query, invitee } name description
   * @return { query, invitee, decoded } Description
   */
  function verifyToken({ query, invitee }) {
    return new Promise((resolve, reject) => {
      jwt.verify(query.token, invitee.inviteToken, (err, decoded) => {
        if (err) return reject({ code: 400, message: 'Token信息有误' });
        else return resolve({ query, invitee, decoded });
      });
    });
  }

  /**
   * 保存受邀者信息: savePayload
   * @param { query, invitee, decoded } name description
   * @return {} Description
   */
  function savePayload({ query, invitee, decoded }) {
    return new Promise((resolve, reject) => {
      Farm.update({ 'name': query.inviter, 'inviteList.email': invitee.email }, {
        $set: {
          'inviteList.$.verified': true,
          'inviteList.$.verifyAt': new Date(),
          'inviteList.$.role': decoded.role,
          'inviteList.$.accessData': decoded.accessData,
          'inviteList.$.accessDevice': decoded.accessDevice
        }
      })
      .then(() => {
        return res.status(200).json({ message: '加入成功' });
      })
      .catch(err => {
        return reject({ code: 400, message: errorHandler.getErrorMessage(err) });
      });
    });
  }

};