text:
void log(const char *p_fmt, ...);

bool is_logged(const char * command) {
    for (size_t i=0; ; ++i) {
        if (fun_table[i].name == nullptr) break;
        if (str_prefix(command, fun_table[i].name)) {
            return fun_table[i].logging;
        }
    }
    return false;
}

static void do_(USER *u, const char *arg) {} // Do nothing.

static void do_alarm(USER *u, const char *arg) {
    char pulse[8];
    int pulse_int = 0;
    int shift_int = 0;

    if (strlen(arg) > 0) {
        arg = first_arg(arg, pulse, sizeof(pulse));

        if (!str2int(pulse, &pulse_int, 10) || pulse_int < 0) {
            u->sendf("Alarm length '%s' is neither a positive integer nor zero.\n\r", pulse);
            return;
        }

        if (strlen(arg) > 0) {
            if (!str2int(arg, &shift_int, 10)) {
                u->sendf("Alarm shift '%s' is not an integer.\n\r", arg);
                return;
            }
        }
        else if (pulse_int > 0) {
            // Adjust the shift so that the alarm would go off immediately.
            shift_int = u->manager->get_pulse() % pulse_int + 1;
        }
    }

    u->manager->set(u->get_id(), "alarm_pulse", pulse_int);
    u->manager->set(u->get_id(), "alarm_shift", shift_int);

    if (pulse_int == 0) {
        u->send("Alarm disabled.\n\r");
        return;
    }

    if (shift_int != 0) u->sendf("Alarm set for every %d. pulse (correction %d).\n\r", pulse_int, shift_int);
    else                u->sendf("Alarm set for every %d. pulse.\n\r", pulse_int);
}

static void do_broadcas(USER *u, const char *arg) {
    u->send("Do you mean to broadcast? You must type in the full command.\n\r");
}

static void do_broadcast(USER *u, const char *arg) {
    MANAGER *m = u->manager;
    INSTANCE *ins = m->instance_find(u->get_id());
    if (!ins || !ins->user) return;

    bool broadcast_before = ins->vs.getb("broadcast");
    if (*arg == 0) {
        ins->vs.set("broadcast", !broadcast_before);
        bool broadcast_after = ins->vs.getb("broadcast");

        if (broadcast_after) u->send("Broadcasting is now enabled.\n\r");
        else                 u->send("Broadcasting is now disabled.\n\r");
        return;
    }

    if (!broadcast_before) return;

    for (size_t i=0; arg[i]; ++i) {
        if (std::iscntrl(arg[i])) {
            u->sendf("'%s' contains illegal characters.\n\r", arg);
            return;
        }
    }

    if (strlen(ins->vs.gets("team")) == 0) {
        u->send("You cannot broadcast unless you are in a team.\n\r");
        return;
    }

    std::string name;
    u->fetch_tag(&name);

    VARSET find_vs;
    find_vs.set("team", ins->vs.gets("team"));
    std::set<int> members;
    m->instance_find("user", (const VARSET *) &find_vs, &members);
    for (auto member_id : members) {
        if (member_id == u->get_id()) continue;
        INSTANCE *ins_member = m->instance_find(member_id);
        if (ins_member->vs.geti("subscribed") != u->get_id()) continue;
        ins_member->user->sendf("%s: %s\n\r", name.c_str(), arg);
    }
}

static void do_chat(USER *u, const char *arg) {
    size_t i;
    MANAGER *m = u->manager;
    INSTANCE *ins = m->instance_find(u->get_id());
    if (!ins || !ins->user) return;

    for (i=0; arg[i]; ++i) {
        if (std::iscntrl(arg[i])) {
            u->sendf("'%s' contains illegal characters.\n\r", arg);
            return;
        }
    }

    if (i == 0) {
        u->send("Chat what?\n\r");
        return;
    }

    if (strlen(ins->vs.gets("team")) == 0) {
        u->send("You cannot chat unless you are in a team.\n\r");
        return;
    }

    std::string name;
    u->fetch_tag(&name);

    VARSET find_vs;
    find_vs.set("team", ins->vs.gets("team"));
    std::set<int> members;
    m->instance_find("user", (const VARSET *) &find_vs, &members);
    for (auto member_id : members) {
        INSTANCE *ins_member = m->instance_find(member_id);
        ins_member->user->sendf("%s chats: '%s'.\n\r", name.c_str(), arg);
    }
}

static void do_claim(USER *u, const char *arg) {
    size_t i;
    MANAGER *m = u->manager;
    INSTANCE *ins = m->instance_find(u->get_id());
    if (!ins || !ins->user) return;

    for (i=0; arg[i]; ++i) {
        if (!std::isalnum(arg[i])) {
            u->sendf("'%s' contains illegal characters.\n\r", arg);
            return;
        }
    }

    if (i == 1) {
        u->send("Name length must be at least two characters.\n\r");
        return;
    }

    if (i > 16) {
        u->send("Name length must not exceed 16 characters.\n\r");
        return;
    }

    std::string old_name;
    std::string new_name = capitalize(arg);
    u->fetch_tag(&old_name);

    if (!strcasecmp(old_name.c_str(), new_name.c_str())) {
        u->sendf("You are already known as %s.\n\r", old_name.c_str());
        return;
    }

    ins->vs.set("name", new_name.c_str());
    new_name.clear();
    u->fetch_tag(&new_name);
    log("%s claims a new name and becomes %s.", old_name.c_str(), new_name.c_str());
    u->sendf("You are now known as %s.\n\r", new_name.c_str());

    if (strlen(ins->vs.gets("team")) > 0) {
        VARSET find_vs;
        find_vs.set("team", ins->vs.gets("team"));
        std::set<int> members;
        m->instance_find("user", (const VARSET *) &find_vs, &members);
        for (auto member_id : members) {
            if (member_id == u->get_id()) continue;
            INSTANCE *ins_member = m->instance_find(member_id);
            ins_member->user->sendf("%s claims a new name and becomes %s.\n\r", old_name.c_str(), new_name.c_str());
        }
    }
}

static void do_connect(USER *u, const char *arg) {
    char host[256];
    char port[8];
    char pass[32];
    char comment[256];
    arg = first_arg(arg, host, sizeof(host));
    arg = first_arg(arg, port, sizeof(port));
    arg = first_arg(arg, pass, sizeof(pass));
    std::snprintf(comment, sizeof(comment), "%s", arg);

    int port_int;
    if (!str2int(port, &port_int, 10) || port_int <= 0) {
        u->sendf("Port number '%s' is not a positive integer.\n\r", port);
        return;
    }

    if (port_int > 65535) {
        u->sendf("Port number '%s' exceeds 65535.\n\r", port);
        return;
    }

    std::snprintf(port, sizeof(port), "%d", port_int);
    MANAGER *m = u->manager;

    int d = sockets.connect(host, port);
    if (d <= 0) {
        u->sendf("Failed to connect to %s:%s.\n\r", host, port);
        return;
    }

    log("New connection %d to %s:%s.", d, host, port);

    int new_user_id = m->instance_create("user");
    if (new_user_id) {
        m->set(new_user_id, "host", host);
        m->set(new_user_id, "port", port);
        m->set(new_user_id, "descriptor", d);
        m->instance_activate(new_user_id);
        INSTANCE *ins = m->instance_find(new_user_id);
        if (ins && ins->user) {
            ins->user->disable_greet();
            if (ins->user->has_prompt()) ins->user->toggle_prompt();
            if (!ins->user->is_server()) ins->user->toggle_server();
        }
        log("Created user %d (descriptor %d).", new_user_id, d);
    }
    else {
        log("Unable to create a user (descriptor %d).", d);
        sockets.disconnect(d);
        return;
    }

    int shell = m->instance_create("shell");
    m->set(shell, "host",       host);
    m->set(shell, "port",       port);
    m->set(shell, "password",   pass);
    m->set(shell, "comment",    comment);
    m->set(shell, "user_id",    new_user_id);
    m->set(shell, "persistent", true);

    if (!m->instance_activate(shell)) {
        u->send("Failed to create a new shell.\n\r");
        sockets.disconnect(d);
        return;
    }

    m->set(new_user_id, "shell_id", shell);
    log("Created shell %d (%s:%s).", shell, host, port);
    u->sendf("Established a new %s connection to %s:%s as shell %d.\n\r", pass[0] ? "private" : "public", host, port, shell);
    if (pass[0]) u->sendf("You can only switch into this private shell by typing 'switch %s'.\n\r", pass);
}

static void do_disconnect(USER *u, const char *arg) {
    int id;
    if (!str2int(arg, &id, 10) || id <= 0) {
        u->sendf("Argument '%s' is not a positive integer.\n\r", arg);
        return;
    }

    MANAGER *m = u->manager;
    if (!m->instance_exists(id)) {
        u->send("No such instance exists.\n\r");
        return;
    }

    VARSET vs;
    m->get_vs(id, &vs);

    if (!strcmp(vs.gets("object_name"), "user")) {
        INSTANCE *ins = m->instance_find(id);
        if (ins && ins->user) {
            std::string tag;
            ins->user->fetch_tag(&tag);
            ins->user->send("You have been disconnected.\n\r");
            ins->user->paralyze();
            u->sendf("Disconnecting %s.\n\r", tag.c_str());
        }
        return;
    }

    if (strcmp(vs.gets("object_name"), "shell")) {
        u->send("Target is not a shell.\n\r");
        return;
    }

    if (!m->instance_destroy(id)) {
        u->sendf("Failed to disconnect shell %d.\n\r", id);
        return;
    }

    log("Destroyed shell %d (%s:%s).", id, vs.gets("host"), vs.gets("port"));
    u->sendf("Shell %d is now disconnected.\n\r", id);
}

static void do_exit(USER *u, const char *arg) {
    if (u->has_role(ROLE_SU)) u->rem_role(ROLE_SU);
    else {
        u->send("Alas, all good things must come to an end ...\n\r");
        u->paralyze();
    }
}

static void do_help(USER *u, const char *arg) {
    char name[12];
    char desc[61];

    u->send(" o---------------------------[ Available Commands ]---------------------------o \n\r");
    for (size_t i=0;; ++i) {
        if (fun_table[i].name == nullptr) break;
        if (!u->has_role(fun_table[i].access)) continue;
        std::snprintf(name, sizeof(name), "%-11s", fun_table[i].name);
        std::snprintf(desc, sizeof(desc), "%-60s", fun_table[i].desc);
        u->send(" | ");
        u->send(name);
        u->send(" - ");
        u->send(desc);
        u->send(" | \n\r");
    }
    u->send(" o----------------------------------------------------------------------------o \n\r");
}

static void do_list(USER *u, const char *arg) {
    char id[7];
    char host[33];
    char port[7];
    char comment[30];

    u->send("List of shells you could switch into:\n\r");

    MANAGER *m = u->manager;
    std::set<int> shells;
    m->instance_find("shell", &shells);
    size_t count = 0;
    bool first = true;
    for (auto a : shells) {
        VARSET vs;
        m->get_vs(a, &vs);
        bool pass = (vs.gets("password")[0] != '\0');
        if (pass && !u->has_role(ROLE_SU)) continue;

        if (first) {
            u->send(" o------o--------------------------------o------o-----------------------------o\n\r");
            u->send(" | ID   | HOST                           | PORT | COMMENT                     |\n\r");
            u->send(" o------o--------------------------------o------o-----------------------------o\n\r");
            first = false;
        }

        std::snprintf(id,   sizeof(id),   "%6d",   a);
        std::snprintf(host, sizeof(host), "%-32s", vs.gets("host"));
        std::snprintf(port, sizeof(port), "%6s",   vs.gets("port"));
        if (pass) {
            std::string combuf = vs.gets("comment");
            combuf.resize(19);
            std::snprintf(comment, sizeof(comment), "%-19s (PRIVATE)", combuf.c_str());
        }
        else std::snprintf(comment, sizeof(comment), "%-29s", vs.gets("comment"));

        u->sendf(" |%s|%s|%s|%s|\n\r", id, host, port, comment);
        count++;
    }
    if (count == 0) u->send("No shells available.\n\r");
    else u->send(" o------o--------------------------------o------o-----------------------------o\n\r");
}

static void do_log(USER *u, const char *arg) {
    log("%s", arg);
}

static void do_login(USER *u, const char *arg) {
    if (u->has_role(ROLE_AUTH)) {
        u->send("You have already been authenticated.\n\r");
        return;
    }

    if (strcmp(arg, "surramurra")) {
        u->send("Wrong password!\n\r");
        return;
    }

    u->add_role(ROLE_AUTH);
    u->send("You are now authenticated.\n\r");

    std::string tag;
    u->fetch_tag(&tag);
    log("%s has logged in.", tag.c_str());
}

static void do_prompt(USER *u, const char *arg) {
    u->toggle_prompt();
    if (u->has_prompt()) u->send("Prompt is now enabled.\n\r");
    else                 u->send("Prompt is now disabled.\n\r");
}

static void do_provide(USER *u, const char *arg) {
    char pass[32];
    char comment[256];
    MANAGER *m = u->manager;

    int user_id = u->get_id();
    VARSET user_vs;
    u->manager->get_vs(user_id,  &user_vs);

    if (u->manager->instance_exists(user_vs.geti("shell_id"))) {
        u->send("You cannot provide a shell while being switched into another shell.\n\r");
        return;
    }

    arg = first_arg(arg, pass, sizeof(pass));
    std::snprintf(comment, sizeof(comment), "%s", arg);

    std::string host = u->get_host();
    std::string port = u->get_port();

    int shell = m->instance_create("shell");
    m->set(shell, "host",       host.c_str());
    m->set(shell, "port",       port.c_str());
    m->set(shell, "password",   pass);
    m->set(shell, "comment",    comment);
    m->set(shell, "user_id",    user_id);
    if (!m->instance_activate(shell)) {
        u->send("Failed to create a new shell.\n\r");
        return;
    }

    INSTANCE *ins = m->instance_find(user_id);
    if (ins && ins->user) {
        if (ins->user->has_prompt()) ins->user->toggle_prompt();
        if (!ins->user->is_server()) ins->user->toggle_server();
    }

    m->set(user_id, "shell_id", shell);
    log("User %d becomes a shell %d (%s:%s).", user_id, shell, host.c_str(), port.c_str());
}

static void do_return(USER *u, const char *arg) {
    int user_id = u->get_id();
    VARSET user_vs;
    u->manager->get_vs(user_id,  &user_vs);
    int shell_id = user_vs.geti("shell_id");

    if (shell_id == 0) {
        u->send("You are not switched into any shell.\n\r");
        return;
    }

    if (!u->manager->instance_exists(shell_id)) {
        std::string tag;
        u->fetch_tag(&tag);
        u->manager->bug("%s returns from a non-existent shell %d.", tag.c_str(), shell_id);
    }

    u->manager->set(user_id, "shell_id", 0);
    u->sendf("You return from shell %d.\n\r", shell_id);
    if (!u->has_prompt()) u->toggle_prompt();
}

static void do_su(USER *u, const char *arg) {
    if (!strcmp("localhost", u->get_host())
    ||  !strcmp("127.0.0.1", u->get_host())) u->add_role(ROLE_SU|ROLE_AUTH);
    else u->send("Authentication failure.\n\r");
}

static void do_subscribe(USER *u, const char *arg) {
    MANAGER *m = u->manager;
    INSTANCE *ins = m->instance_find(u->get_id());
    if (!ins || !ins->user) return;

    std::string name;
    u->fetch_tag(&name);
    int subscribed = ins->vs.geti("subscribed");

    if (*arg == 0) {
        ins->vs.set("subscribed", 0);

        INSTANCE *subscribed_ins;
        if ( (subscribed_ins = m->instance_find(subscribed)) ) {
            std::string subscribed_tag;
            subscribed_ins->user->fetch_tag(&subscribed_tag);
            u->sendf("You are no longer subscribed to %s's broadcast.\n\r", subscribed_tag.c_str());
            subscribed_ins->user->sendf("%s is no longer subscribed to your broadcast.\n\r", name.c_str());
        }
        else u->send("Subscribe to whose broadcast?\n\r");
        return;
    }

    if (strlen(ins->vs.gets("team")) == 0) {
        u->send("You cannot subscribe unless you are in a team.\n\r");
        return;
    }

    bool found = false;
    VARSET find_vs;
    find_vs.set("team", ins->vs.gets("team"));
    std::set<int> members;
    m->instance_find("user", (const VARSET *) &find_vs, &members);
    for (auto member_id : members) {
        if (member_id == u->get_id()) continue;
        INSTANCE *ins_member = m->instance_find(member_id);
        std::string member_name;
        ins_member->user->fetch_tag(&member_name);
        if (str_prefix(arg, member_name.c_str())) {
            if (member_id == subscribed) {
                u->sendf("You have already subscribed to %s's broadcast.\n\r", member_name.c_str());
            }
            else {
                ins_member->user->sendf("%s subscribed to your broadcast.\n\r", name.c_str());
                u->sendf("You are now subscribed to %s's broadcast.\n\r", member_name.c_str());
                ins->vs.set("subscribed", member_id);
                INSTANCE *old_subscribe = m->instance_find(subscribed);
                if (old_subscribe) old_subscribe->user->sendf("%s is no longer subscribed to your broadcast.\n\r", name.c_str());
            }
            found = true;
            break;
        }
    }

    if (!found) {
        u->send("No such user is in a team with you.\n\r");
    }
}

static void do_switch(USER *u, const char *arg) {
    int shell_id = 0;
    int user_id = u->get_id();
    bool authenticated = false;

    if (strlen(arg) > 0) {
        VARSET find_vs;
        find_vs.set("password", arg);
        shell_id = u->manager->instance_find("shell", &find_vs);
        if (shell_id) authenticated = true;
    }

    if (!shell_id) {
        if (!str2int(arg, &shell_id, 10) || shell_id <= 0) {
            u->sendf("Argument '%s' is not a positive integer nor a valid shell password.\n\r", arg);
            return;
        }
    }

    if (!u->manager->instance_exists(shell_id)) {
        u->send("No such shell exists.\n\r");
        return;
    }

    VARSET shell_vs;
    VARSET user_vs;
    u->manager->get_vs(shell_id, &shell_vs);
    u->manager->get_vs(user_id,  &user_vs);

    if (strcmp(shell_vs.gets("object_name"), "shell")) {
        u->send("Target cannot be switched into.\n\r");
        return;
    }

    if (shell_vs.gets("password")[0] && !authenticated && !u->has_role(ROLE_SU)) {
        u->sendf("Shell %d is password protected.\n\r", shell_id);
        return;
    }

    if (user_vs.geti("shell_id") == shell_id) {
        u->send("You are already switched into that shell.\n\r");
        return;
    }

    u->manager->set(user_id, "shell_id", shell_id);
    u->sendf("You are now switched into shell %d.\n\r", shell_id);
    if (u->has_prompt()) u->toggle_prompt();
}

void do_team(USER *u, const char *arg) {
    size_t i;
    MANAGER *m = u->manager;
    INSTANCE *ins = m->instance_find(u->get_id());
    if (!ins || !ins->user) return;

    for (i=0; arg[i]; ++i) {
        if (std::iscntrl(arg[i])) {
            u->sendf("Team password contains illegal characters.\n\r", arg);
            return;
        }
    }

    if (i > 32) {
        u->send("Team passwords's length must not exceed 32 characters.\n\r");
        return;
    }

    std::string old_team = ins->vs.gets("team");
    std::string tag;
    VARSET find_vs;
    std::set<int> members;

    if (i == 0) {
        if (old_team.length() > 0) {
            find_vs.set("team", old_team.c_str());
            m->instance_find("user", (const VARSET *) &find_vs, &members);
            u->sendf("There %s %lu member%s in your team:\n\r", members.size() == 1 ? "is" : "are", members.size(), members.size() == 1 ? "" : "s");

            for (auto member_id : members) {
                INSTANCE *ins_member = m->instance_find(member_id);
                tag.clear();
                ins_member->user->fetch_tag(&tag);
                u->sendf(" - %-16s (%s:%s)\n\r", tag.c_str(), ins_member->user->get_host(), ins_member->user->get_port());
            }

            u->sendf("\n\rTeam password: %s\n\r", ins->vs.gets("team"));
            u->send("To leave your team, provide its password as an argument.\n\r");
        }
        else {
            u->send("You are currently not part of any team.\n\r");
            u->send("To create or join a team, execute this command with a password.\n\r");
        }
        return;
    }

    u->fetch_tag(&tag);

    if (old_team.length() > 0) {
        find_vs.set("team", old_team.c_str());
        m->instance_find("user", (const VARSET *) &find_vs, &members);
        for (auto member_id : members) {
            if (member_id == u->get_id()) continue;
            INSTANCE *ins_member = m->instance_find(member_id);
            ins_member->user->sendf("%s has left the team.\n\r", tag.c_str());
        }
    }

    if (!strcmp(arg, old_team.c_str())) {
        // Leaving a team.
        ins->vs.set("team", "");
        u->send("You leave your team.\n\r");
        return;
    }

    members.clear();
    find_vs.clear();
    find_vs.set("team", arg);
    m->instance_find("user", (const VARSET *) &find_vs, &members);

    for (auto member_id : members) {
        INSTANCE *ins_member = m->instance_find(member_id);
        ins_member->user->sendf("%s has joined the team.\n\r", tag.c_str());
    }

    ins->vs.set("team", arg);
    u->sendf("Your team password is now set to '%s'.\n\r", arg);
}

const struct fun_type fun_table[] = {
    { "",           "Bust a prompt.",                                      do_,           ROLE_NONE, false },
    { "alarm",      "Set an alarm for the defined number of pulses.",      do_alarm,      ROLE_NONE, false },
    { "broadcas",   "Broadcast without having typed the full command.",    do_broadcas,   ROLE_NONE, false },
    { "broadcast",  "Toggle broadcasting or send a message to your team.", do_broadcast,  ROLE_NONE, false },
    { "chat",       "Send a message to your team.",                        do_chat,       ROLE_NONE, false },
    { "claim",      "Claim a temporary username.",                         do_claim,      ROLE_NONE, false },
    { "connect",    "Connect a new shell to a remote host/port.",          do_connect,    ROLE_AUTH, true  },
    { "disconnect", "Disconnect a user or a shell by its ID.",             do_disconnect, ROLE_SU,   true  },
    { "exit",       "Close the connection.",                               do_exit,       ROLE_NONE, false },
    { "help",       "Display the list of available commands.",             do_help,       ROLE_NONE, false },
    { "list",       "Lists all the shells you could switch into.",         do_list,       ROLE_NONE, false },
    { "log",        "Log the text given as an argument.",                  do_log,        ROLE_SU,   false },
    { "login",      "Authenticate the current session.",                   do_login,      ROLE_NONE, false },
    { "prompt",     "Toggle the prompt that is shown after each command.", do_prompt,     ROLE_NONE, false },
    { "provide",    "Provide your connection as a shell to others.",       do_provide,    ROLE_NONE, false },
    { "return",     "Return from your current shell.",                     do_return,     ROLE_NONE, false },
    { "su",         "Elevate the current user to the superuser.",          do_su,         ROLE_AUTH, true  },
    { "subscribe",  "Subscribe to the specified user's broadcast.",        do_subscribe,  ROLE_NONE, false },
    { "switch",     "Switch into another shell.",                          do_switch,     ROLE_NONE, false },
    { "team",       "Join a specified team by its password.",              do_team,       ROLE_NONE, false },
    { nullptr,      nullptr,                                               nullptr,       0,         false }
};


text:
#ifndef LANG_HPP_BB6D2D7F_CD59_4D0F_B11D_2077A8A22947
#define LANG_HPP_BB6D2D7F_CD59_4D0F_B11D_2077A8A22947
#pragma once

/*
lang.hpp
*/
/*
Copyright © 2010 Far Group
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. The name of the authors may not be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

// Internal:
#include "bootstrap/lang.inc"

// Platform:

// Common:
#include "common/utility.hpp"

// External:

//----------------------------------------------------------------------------

template<class T>
constexpr lng operator+(lng Id, T Shift)
{
	return static_cast<lng>(std::to_underlying(Id) + Shift);
}

inline lng operator++(lng& Id, int)
{
	const auto Value = Id;
	Id = Id + 1;
	return Value;
}

const string& msg(lng Id);

#endif // LANG_HPP_BB6D2D7F_CD59_4D0F_B11D_2077A8A22947

redpajama_set_name: RedPajamaGithub


text:
var vows = require('vows'),
    assert = require('assert'),
    suite = vows.describe('CBuffer');

require('../env');

suite.addBatch({
	'sortedIndex': {
		'works with simple sorted case': {
			topic: function() {
				return CBuffer(1, 3, 5, 7, 11);
			},
			'no iterator provided': function(buffer) {
				assert.equal(buffer.sortedIndex(-1), 0);
				assert.equal(buffer.sortedIndex(1.5), 1);
			},
			'returns index of existing items': function(buffer) {
				assert.equal(buffer.sortedIndex(1), 0);
				assert.equal(buffer.sortedIndex(5), 2);
				assert.equal(buffer.sortedIndex(11), 4);
			},
			'around the corner': function(buffer) {
				assert.equal(buffer.sortedIndex(-1), 0);
				assert.equal(buffer.sortedIndex(12), 4);
			},
			'takes an iterator': function() {
				var buffer = CBuffer(7, 5, 11, 3, 1);
				function iter(a, b) {
					return Math.abs(a - 8) - Math.abs(b - 8);
				}
				assert.equal(buffer.sortedIndex(6, iter), 1);
			},

			'non-full circular buffer': {
				topic: function() {
					var buffer = CBuffer(20);
					buffer.push(1, 2, 3, 4, 5, 6, 7, 8);
					return buffer;
				},
				'works with partially complete buffers': function(buffer) {
					assert.equal(buffer.sortedIndex(3), 2);
					assert.equal(buffer.sortedIndex(8), 7);
				}
			},

			'supports classic repeative item case': {
				topic: function() {
					return CBuffer(0, 0, 0, 1, 1, 1, 1, 1, 1, 3);
				},
				'supports repative item': function(buffer) {
					assert.equal(buffer.sortedIndex(2), 9);
				}
			}
		},

		'handles circular cases': {
			'mid circular case': {
				topic: function() {
					var buffer = CBuffer(-1, 0, 1, 3, 5);
					buffer.push(7, 9);
					return buffer;
				},
				'simple circular buffer': function(buffer) {
					assert.equal(buffer.sortedIndex(0), 0);
					assert.equal(buffer.sortedIndex(2), 1);
					assert.equal(buffer.sortedIndex(4), 2);
					assert.equal(buffer.sortedIndex(7), 3);
					assert.equal(buffer.sortedIndex(8), 4);
					assert.equal(buffer.sortedIndex(10), 4);
				},
				'circular buffer on the pivot': function(buffer) {
					assert.equal(buffer.sortedIndex(4.999), 2);
					assert.equal(buffer.sortedIndex(5), 2);
					assert.equal(buffer.sortedIndex(6), 3);
				},
				'returns index of existing item': function(buffer) {
					assert.equal(buffer.sortedIndex(7), 3);
				}
			},

			'almost sorted data cases (1 item out of place)': {
				topic: function() {
					var buffer = CBuffer(-3, -1, 0, 1, 3, 5, 7);
					buffer.push(7, 9, 11, 13, 15, 17);
					return buffer;
				},
				'single item out of place': function(buffer) {
					assert.equal(buffer.sortedIndex(0), 0);
					assert.equal(buffer.sortedIndex(17), 6);
				}
			}
		}

	}
});

suite.export(module);


text:
// Build with the following commands:
// Uncomment out line 17
// C:\Windows\Microsoft.NET\Framework64\v4.0.30319\ilasm.exe /dll ThrowNonClsCompliantException.il
// C:\Users\rseacord\Documents\Visual Studio 2015\Projects\CSharpSC\NonCLSExceptions>C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc /r:ThrowNonClsCompliantException.dll CatchNonClsCompliantException.cs

// The MIT License (MIT)
//
// Copyright (c) 2017 Robert C. Seacord
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

using System;
using System.Runtime.CompilerServices;

[assembly: RuntimeCompatibility(WrapNonExceptionThrows = false)]
namespace NonCLSExceptions
{

  struct HandlesExceptions
  {
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
    static void CatchAllExceptions()
    {
      try
      {
        //        ThrowsExceptions.ThrowNonClsException();
      }
      catch (Exception e)
      {
        RuntimeWrappedException rwe = e as RuntimeWrappedException;
        if (rwe.WrappedException is object o)
        {
          Console.WriteLine(o.ToString());
        }
        else
        {
          // Handle other System.Exception types.
        }

        // Remove some permission.
        Console.Error.WriteLine("CLS compliant exception: {0}", e);
      }
      catch
      {
        // Remove the same permission as above.
        Console.WriteLine("Non-CLS compliant exception caught.");
      }
    }

    static void Main()
    {
      HandlesExceptions.CatchAllExceptions();
    }
  }
}


text:
require "hash_symbolizer/version"
require 'active_support/core_ext/hash/keys'
require 'active_support/core_ext/hash/indifferent_access'
require "hash_symbolizer/core_ext/hash"
require "hash_symbolizer/core_ext/hash_with_indifferent_access"


text:
package seedu.manager.storage;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import seedu.manager.commons.exceptions.IllegalValueException;
import seedu.manager.model.ReadOnlyTaskManager;
import seedu.manager.model.tag.UniqueTagList;
import seedu.manager.model.task.ReadOnlyTask;
import seedu.manager.model.task.Tag;
import seedu.manager.model.task.Task;
import seedu.manager.model.task.UniqueTaskList;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * An Immutable TaskManager that is serializable to XML format
 */
@XmlRootElement(name = "taskmanager")
public class XmlSerializableTaskManager implements ReadOnlyTaskManager {

    @XmlElement
    private List<XmlAdaptedTask> tasks;

    {
        tasks = new ArrayList<>();
    }

    /**
     * Empty constructor required for marshalling
     */
    public XmlSerializableTaskManager() {}

    /**
     * Conversion
     */
    public XmlSerializableTaskManager(ReadOnlyTaskManager src) {
        tasks.addAll(src.getTaskList().stream().map(XmlAdaptedTask::new).collect(Collectors.toList()));
    }

    @Override
    public UniqueTaskList getUniqueTaskList() {
        UniqueTaskList lists = new UniqueTaskList();
        for (XmlAdaptedTask p : tasks) {
            try {
                Task toAdd = p.toModelType();
                lists.add(toAdd);
            } catch (IllegalValueException e) {
                //TODO: better error handling
            	e.printStackTrace();
            }
        }
        return lists;
    }

    @Override
    public List<ReadOnlyTask> getTaskList() {
        return tasks.stream().map(p -> {
            try {
                return p.toModelType();
            } catch (IllegalValueException e) {
                e.printStackTrace();
                //TODO: better error handling
                return null;
            }
        }).collect(Collectors.toCollection(ArrayList::new));
    }

    // @@author A0148042M
    /**
     * These two methods are to get the UniqueTagList and the tag list directly.
     */
    @Override
    public UniqueTagList getUniqueTagList() {
        return null;
    }

    @Override
    public List<Tag> getTagList() {
        return null;
    }
}


text:
<?php

if(isset($_GET['contenido']))
  {
    $contenido = $_GET['contenido'];
  }
  else
  {
    $contenido = 'poa';
	$navbar_loc = 'contenido';
  }
//
//  require_once("../funciones/check_session.php");
//
//  require_once("../funciones/timeout.php");

$fechaActual= date("Y-m-d");

//echo $fechaActual;
$link=mysql_connect("localhost", "root", "");
mysql_select_db("sistema_ciencias_juridicas",$link) OR DIE ("Error: No es posible establecer la conexión");
mysql_set_charset('utf8');
 //Select * from t1 where not exists (select 1 from t2 where t2.id = t1.id)
$eventos=mysql_query("SELECT * FROM actividades where not exists (select 1 from actividades_terminadas where actividades.id_actividad = actividades_terminadas.id_Actividad)",$link);
//echo "[";

//$totalSubActi=mysql_query("SELECT count(*) as totalSubActi  FROM sub_actividad where sub_actividad.idActividad=1",$link);
//
//$numSubActRea=mysql_query("SELECT count(*) as numSubActiRea FROM  sub_actividad where sub_actividad.id_sub_Actividad in (select sub_actividades_realizadas.id_SubActividad from sub_actividades_realizadas) and sub_actividad.idActividad=1",$link);
//
//$numSubActNORea=  mysql_query("SELECT count(*) as numSubActiNOReal  FROM sub_actividad where not exists (select 1 from sub_actividades_realizadas where sub_actividades_realizadas.id_SubActividad = sub_actividad.id_sub_Actividad) and sub_actividad.idActividad=1",$link);
//$total=mysql_fetch_assoc($totalSubActi);
//$no=mysql_fetch_assoc($numSubActNORea);
//$si=mysql_fetch_assoc($numSubActRea);
//echo $si['numSubActiRea'];

while($all = mysql_fetch_assoc($eventos)){
$e = array();
$e['id'] = $all['id_actividad'];
$e['start'] = $all['fecha_inicio'];
$e['end'] = $all['fecha_fin'];
$e['title'] = $all['descripcion'];
$fechaEntrada = $all['fecha_fin'];

$totalSubActi=mysql_query("SELECT count(*) as totalSubActi  FROM sub_actividad where sub_actividad.idActividad=".$all['id_actividad'],$link);

$numSubActRea=mysql_query("SELECT count(*) as numSubActiRea FROM  sub_actividad where sub_actividad.id_sub_Actividad in (select sub_actividades_realizadas.id_SubActividad from sub_actividades_realizadas) and sub_actividad.idActividad=".$all['id_actividad'],$link);

$numSubActNORea=  mysql_query("SELECT count(*) as numSubActiNOReal  FROM sub_actividad where not exists (select 1 from sub_actividades_realizadas where sub_actividades_realizadas.id_SubActividad = sub_actividad.id_sub_Actividad) and sub_actividad.idActividad=".$all['id_actividad'],$link);
$total=mysql_fetch_assoc($totalSubActi);
$no=mysql_fetch_assoc($numSubActNORea);
$si=mysql_fetch_assoc($numSubActRea);

$si['numSubActiRea'];
$no['numSubActiNOReal'];
$total['totalSubActi'];

if($total['totalSubActi']>0){

    if($fechaEntrada<$fechaActual){
  $e['color']='red';

}else{
    $promedioRealizadas=(100/$total['totalSubActi'])*$si['numSubActiRea'];
    $prmedioNoRealizadas=(100/$total['totalSubActi'])*$no['numSubActiNOReal'];
    if($promedioRealizadas<50){
       $e['color']='red';
    }
    if($promedioRealizadas<=70 && $promedioRealizadas>=50  ){
       $e['color']='yellow';
    }
    if($promedioRealizadas>=95){
       $e['color']='blue';
    }

}

}else{

    if($fechaEntrada<$fechaActual){
  $e['color']='red';

}else{
    $e['color']='green';

}

}

//if($fechaEntrada<$fechaActual){
//  $e['color']='red';
//
//}else{
//    $e['color']='green';
//
//}

//echo json_encode($e).",";
$result[] = $e;
}
//echo "]";
//echo json_encode(array('success' => 1, 'result' => $result));
echo json_encode($result)

?>


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Viktor Holmgren</title>
    <link href='https://fonts.googleapis.com/css?family=Raleway:700|Playfair+Display' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="styles/main.css">

Hallå, Im Viktor.

I'm a software engineering student at Linköping University with a passion for cycling. When I am not studying or helping kids learn programming I sometimes work on some side projects of my own.

Recent work

                  01.
                  Rist

                  02.
                  LiTHe kod

                  03.
                  LiU Game Jam

                  04.
                  Redox

Got a project you would like me to work on, or a position that needs filling? Or how about just a friendly chat? Feel free to drop me a line or @ me on twitter

Contact

                  Email:

                    viktor.holmgren@gmail.com

                  Twitter:
                  @Viktor_Holmgren

                  LinkedIn:

                    Viktor Holmgren


text:
package com.tutorial.graphX.GraphAlgorithms

import com.tutorial.utils.SparkCommon
import org.apache.spark.graphx._

/**
  * Created by ved on 20/2/16.
  */
object PageRank {

  val sc = SparkCommon.sparkContext

  def main(args: Array[String]) {

    val file_Path="src/main/resources/twitter_followers.txt"

    /**
      * Load the edges from file
      * with 20 partitions:
      *
      */
    val edgesFile = sc.textFile(file_Path, 20)

    /**
      * Flatten and convert it into an RDD
      * of "link1,link2" format and then convert it into an RDD of Edge objects:
      */

    val edges = edgesFile.flatMap { line =>
      val links = line.split("\\W+")
      val from = links(0)
      val to = links.tail
      for (link <- to) yield (from, link)
    }.map(e => Edge(e._1.toLong, e._2.toLong, 1))

    /**
      * Load the vertices from file  with 20 partitions:
      *
      */

    val verticesFile = sc.textFile("src/main/resources/twitter_users.txt", 20)
    /**
      * Provide an index to the vertices and then swap it to make it in the (index, title) format:
      */

    val vertices = verticesFile.zipWithIndex.map(_.swap)

    /**
      * Create the graph object:
      *
      */

    val graph = Graph(vertices, edges)

    /**
      * Run PageRank and get the vertices:
      */
    val startTime = System.currentTimeMillis()
    val ranks = graph.pageRank(0.001).vertices
    println("#########ranks#####"+ranks.collect().foreach(println))
    println(s"Taking time::::::::${System.currentTimeMillis() - startTime}")

    ranks.foreach(println)

    /**
      * As ranks is in the (vertex ID, pagerank) format,
      * swap it to make it in the (pagerank,vertex ID) format:
      */

    val swappedRanks = ranks.map(_.swap)

    //swappedRanks.foreach(println)

    println("ranks is in the (vertex ID, pagerank)" + swappedRanks.collect().mkString(" \n"))

    /**
      * Sort to get the highest ranked pages first:
      */

    val sortedRanks = swappedRanks.sortByKey(false)

    //sortedRanks.foreach(print)

    println("highest ranked pages first" + sortedRanks.collect().mkString("\n"))

    /**
      * Get the highest ranked page:
      */

    val highest = sortedRanks.first

    //highest.toString().mkString(" ").foreach(print)
    println("highest ranked page" + highest.toString())

    /**
      * The preceding command gives the vertex id,
      * which you still have to look up to see the actual title with rank. Let's do a join:
      */

    val allJoin = ranks.join(vertices)
    println("##################################################")
    println("allJoin allJoin page" + allJoin.collect().foreach(println))
    println("##################################################")

    /**
      * Sort the joined RDD again after converting from the
      * (vertex ID, (page rank, title))format to the (page rank, (vertex ID, title)) format:
      */
    val finalAll = allJoin.map(v => (v._2._1, (v._1, v._2._2))).
      sortByKey(false)

    /**
      * Print the top five ranked pages
      */

    val startTime1 = System.currentTimeMillis()
   println("top five ranked pages" + finalAll.collect().take(5).mkString("\n"))
    //finalAll.collect().take(5).foreach(println)
    println(s"Taking time::::::::${System.currentTimeMillis() - startTime1}")

    //allJoin.collect().take(5).foreach(println)

  }

}


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

<TITLE>
MatchingObject (ATG Java API)
</TITLE>

<META NAME="keywords" CONTENT="atg.commerce.pricing.definition.MatchingObject class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

atg.commerce.pricing.definition

Class MatchingObject

java.lang.Object
  atg.commerce.pricing.definition.MatchingObject

public class MatchingObject
extends java.lang.Object

An element of a collection that matched

Field Summary

static java.lang.String
CLASS_VERSION

          Class version string

Constructor Summary

MatchingObject(java.lang.Object pMatchingObject,
               long pQuantity)

          constructor

Method Summary

 java.lang.Object
getMatchingObject()

          Get property MatchingObject

 long
getQuantity()

          Get property Quantity

 void
setMatchingObject(java.lang.Object pMatchingObject)

          Set property MatchingObject

 void
setQuantity(long pQuantity)

          Set property Quantity

 java.lang.String
toString()

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

CLASS_VERSION

public static java.lang.String CLASS_VERSION

Class version string

Constructor Detail

MatchingObject

public MatchingObject(java.lang.Object pMatchingObject,
                      long pQuantity)

constructor

Method Detail

setMatchingObject

public void setMatchingObject(java.lang.Object pMatchingObject)

Set property MatchingObject

Parameters:
pMatchingObject - new value to set

getMatchingObject

public java.lang.Object getMatchingObject()

Get property MatchingObject

Returns:
MatchingObject

setQuantity

public void setQuantity(long pQuantity)

Set property Quantity

Parameters:
pQuantity - new value to set

getQuantity

public long getQuantity()

Get property Quantity

Returns:
Quantity

toString

public java.lang.String toString()

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
//===--- TestContext.h - Helper for setting up ASTContexts ------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "swift/AST/ASTContext.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/Module.h"
#include "swift/AST/SourceFile.h"
#include "swift/Basic/LangOptions.h"
#include "swift/Basic/SourceManager.h"

#include "llvm/Support/Host.h"

namespace swift {
namespace unittest {

/// Helper class used to set the LangOpts target before initializing the
/// ASTContext.
///
/// \see TestContext
class TestContextBase {
public:
  LangOptions LangOpts;
  TypeCheckerOptions TypeCheckerOpts;
  SearchPathOptions SearchPathOpts;
  ClangImporterOptions ClangImporterOpts;
  SourceManager SourceMgr;
  DiagnosticEngine Diags;

  TestContextBase() : Diags(SourceMgr) {
    LangOpts.Target = llvm::Triple(llvm::sys::getProcessTriple());
  }
};

enum ShouldDeclareOptionalTypes : bool {
  DoNotDeclareOptionalTypes,
  DeclareOptionalTypes
};

/// Owns an ASTContext and the associated types.
class TestContext : public TestContextBase {
  SourceFile *FileForLookups;

public:
  ASTContext &Ctx;

  TestContext(ShouldDeclareOptionalTypes optionals = DoNotDeclareOptionalTypes);

  template <typename Nominal>
  Nominal *makeNominal(StringRef name,
                       GenericParamList *genericParams = nullptr) {
    auto result = new (Ctx) Nominal(SourceLoc(), Ctx.getIdentifier(name),
                                    SourceLoc(), /*inherited*/{},
                                    genericParams, FileForLookups);
    result->setAccess(AccessLevel::Internal);
    return result;
  }
};

} // end namespace unittest
} // end namespace swift


text:
#include "io_realm_mongodb_mongo_iterable_AggregateIterable.h"

#include "java_class_global_def.hpp"
#include "java_network_transport.hpp"
#include "util.hpp"
#include "jni_util/java_method.hpp"
#include "jni_util/jni_utils.hpp"
#include "jni_util/bson_util.hpp"

#include <realm/util/optional.hpp>
#include <realm/object-store/util/bson/bson.hpp>
#include <realm/object-store/sync/mongo_collection.hpp>
#include <jni_util/bson_util.hpp>
#include <jni.h>

using namespace realm;
using namespace realm::bson;
using namespace realm::jni_util;
using namespace realm::_impl;

static std::function<jobject(JNIEnv*, util::Optional<bson::BsonArray>)> collection_mapper_aggregate = [](JNIEnv* env, util::Optional<bson::BsonArray> array) {
    return array ? JniBsonProtocol::bson_to_jstring(env, *array) : NULL;
};

JNIEXPORT void JNICALL
Java_io_realm_mongodb_mongo_iterable_AggregateIterable_nativeAggregate(JNIEnv* env,
                                                                       jclass,
                                                                       jlong j_collection_ptr,
                                                                       jstring j_pipeline,
                                                                       jobject j_callback) {
    try {
        auto collection = reinterpret_cast<MongoCollection *>(j_collection_ptr);

        BsonArray bson_array(JniBsonProtocol::parse_checked(env, j_pipeline, Bson::Type::Array, "BSON pipeline must be a BsonArray"));

        collection->aggregate(bson_array, JavaNetworkTransport::create_result_callback(env, j_callback, collection_mapper_aggregate));
    }
    CATCH_STD()
}


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

<TITLE>
TestItem
</TITLE>

<META NAME="date" CONTENT="2011-08-16">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.nescent.VTO.lib

Class TestItem

java.lang.Object
  org.nescent.VTO.lib.TestItem

public class TestItem
extends java.lang.Object

Constructor Summary

TestItem()

Method Summary

 void
setUp()

 void
testAddSynonym()

 void
testGetFieldValue()

 void
testGetName()

 void
testGetSynonymsForSource()

 void
testGetSynonymSources()

 void
testHasColumn()

 void
testItem()

 void
testPutName()

 void
testToString()

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

TestItem

public TestItem()

Method Detail

setUp

public void setUp()
           throws java.lang.Exception

Throws:

java.lang.Exception

testItem

public void testItem()

testPutName

public void testPutName()

testHasColumn

public void testHasColumn()

testGetName

public void testGetName()

testGetFieldValue

public void testGetFieldValue()

testAddSynonym

public void testAddSynonym()

testGetSynonymSources

public void testGetSynonymSources()

testGetSynonymsForSource

public void testGetSynonymsForSource()

testToString

public void testToString()

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/EventsAssignment.iml" filepath="$PROJECT_DIR$/EventsAssignment.iml" />
      <module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
    </modules>
  </component>
</project>


text:
@interface SEPhotoView : UIView

@property (nonatomic) UIImage *image;

@end


text:
package org.apache.flume.channel.file;

import java.io.File;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Pattern;

import com.google.common.collect.Lists;

public class LogUtils {

  private static final Pattern pattern =
          Pattern.compile("^" + Log.PREFIX + "\\d+$");

  /**
   * Sort a list of files by the number after Log.PREFIX.
   */
  static void sort(List<File> logs) {
    Collections.sort(logs, new Comparator<File>() {
      @Override
      public int compare(File file1, File file2) {
        int id1 = getIDForFile(file1);
        int id2 = getIDForFile(file2);
        if (id1 > id2) {
          return 1;
        } else if (id1 == id2) {
          return 0;
        }
        return -1;
      }
    });
  }
  /**
   * Get the id after the Log.PREFIX
   */
  static int getIDForFile(File file) {
    return Integer.parseInt(file.getName().substring(Log.PREFIX.length()));
  }
  /**
   * Find all log files within a directory
   *
   * @param logDir directory to search
   * @return List of data files within logDir
   */
  static List<File> getLogs(File logDir) {
    List<File> result = Lists.newArrayList();
    File[] files = logDir.listFiles();
    if (files == null) {
      String msg = logDir + ".listFiles() returned null: ";
      msg += "File = " + logDir.isFile() + ", ";
      msg += "Exists = " + logDir.exists() + ", ";
      msg += "Writable = " + logDir.canWrite();
      throw new IllegalStateException(msg);
    }
    for (File file : files) {
      String name = file.getName();
      if (pattern.matcher(name).matches()) {
        result.add(file);
      }
    }
    return result;
  }
}


text:
<!--start-code-->

```js
const instance = (
  <Whisper trigger="focus" speaker={<Tooltip>Required</Tooltip>}>
    <Input style={{ width: 300 }} placeholder="Default Input" />
  </Whisper>
);
ReactDOM.render(instance);
```

<!--end-code-->


text:
package opennlp.fieldspring.tr.tpp

import opennlp.fieldspring.tr.text._
import opennlp.fieldspring.tr.util._
import opennlp.fieldspring.tr.resolver._
import opennlp.maxent._
import opennlp.maxent.io._
import opennlp.model._

import java.io._

import scala.collection.JavaConversions._

class MaxentPurchaseCoster(corpus:StoredCorpus, modelDirPath:String) extends PurchaseCoster {

  val windowSize = 20

  val modelDir = new File(modelDirPath)

  val toponymsToModels:Map[String, AbstractModel] =
  (for(file <- modelDir.listFiles.filter(_.getName.endsWith(".mxm"))) yield {
    val dataInputStream = new DataInputStream(new FileInputStream(file));
    val reader = new BinaryGISModelReader(dataInputStream)
    val model = reader.getModel

    (file.getName.dropRight(4).replaceAll("_", " "), model)
  }).toMap

  val potLocsToCosts = new scala.collection.mutable.HashMap[PotentialLocation, Double]

  for(doc <- corpus) {
    val docAsArray = TextUtil.getDocAsArrayNoFilter(doc)
    var tokIndex = 0
      for(token <- docAsArray) {
        if(token.isToponym && token.asInstanceOf[Toponym].getAmbiguity > 0
           && toponymsToModels.containsKey(token.getForm)) {
          val toponym = token.asInstanceOf[Toponym]
          val contextFeatures = TextUtil.getContextFeatures(docAsArray, tokIndex, windowSize, Set[String]())

          val indexToWeightMap = MaxentResolver.getIndexToWeightMap(toponymsToModels(token.getForm), contextFeatures)
          //contextFeatures.foreach(f => print(f+",")); println
          for((gazIndex, weight) <- indexToWeightMap.toList.sortBy(_._1)) {
            val loc = toponym.getCandidates.get(gazIndex)
            val potLoc = new PotentialLocation(doc.getId, tokIndex, gazIndex, loc)
            //println(" "+gazIndex+": "+(1.0-weight))
            potLocsToCosts.put(potLoc, 1.0-weight) // Here's where the cost is defined in terms of the probability mass
          }

        }
        tokIndex += 1
      }
  }

  def apply(m:Market, potLoc:PotentialLocation): Double = {
    //if(m.locations.map(_._2).toSet.contains(potLoc)) {
      1.0//potLocsToCosts.getOrElse(potLoc, 1.0) // Not sure what the default cost should be
    //}
    //else
    //  Double.PositiveInfinity
  }
}


text:
var Renderer = require("../lib/page_renderer");

var Path = require("path");

var ModuleUtils = require("../lib/utils/module_utils");

describe("setup", function() {

	var sample_config = {
		plugins: {
			template_handler: "sample_template_handler",
			content_handler: "sample_content_handler",
			template_engine: "sample_template_engine",
			compilers: {
				".js": "sample_js_compiler",
				".css": "sample_css_compiler"
			},
			helpers: {
				"numbers_helper": "sample_number_helper",
				"image_helper": "sample_image_helper"
			}
		}
	};

	it("setup the templates handler", function() {
		spyOn(ModuleUtils, "requireAndSetup").andCallFake(function(id, config) {
			return { "id": id };
		});

		Renderer.setup(sample_config);

		expect(Renderer.templates.id).toEqual("sample_template_handler");
	});

	it("setup the contents handler", function() {
		spyOn(ModuleUtils, "requireAndSetup").andCallFake(function(id, config) {
			return { "id": id };
		});

		Renderer.setup(sample_config);

		expect(Renderer.contents.id).toEqual("sample_content_handler");
	});

	it("setup the template engine", function() {
		spyOn(ModuleUtils, "requireAndSetup").andCallFake(function(id, config) {
			return { "id": id };
		});

		Renderer.setup(sample_config);

		expect(Renderer.templateEngine.id).toEqual("sample_template_engine");
	});

	it("setup each compiler", function() {
		spyOn(ModuleUtils, "requireAndSetup").andCallFake(function(id, config) {
			return { "id": id };
		});

		Renderer.setup(sample_config);

		expect(Renderer.compilers).toEqual({ ".js": { "id": "sample_js_compiler" }, ".css": { "id": "sample_css_compiler" } });
	});

	it("setup each helper", function(){
		Renderer.helpers = [];

		spyOn(ModuleUtils, "requireAndSetup").andCallFake(function(id, config){
			return {"id": id};
		});

		Renderer.setup(sample_config);
		expect(Renderer.helpers).toEqual([{"id": "sample_number_helper"}, {"id": "sample_image_helper"}]);
	});

});

describe("handle rendering request", function() {

	it("treat null request path as the root path", function() {
		spyOn(Renderer, "serveStatic");

		Renderer.templates = { "isSection": function() { return true } };
		Renderer.contents = { "isSection": function() { return true } };

		var spyCallback = jasmine.createSpy();
		Renderer.render(null, ".html", null, {}, spyCallback);

		expect(Renderer.serveStatic.mostRecentCall.args[0]).toEqual(Path.join("/index.html"));
	});

	it("point the top level request path to index files", function() {
		spyOn(Renderer, "serveStatic");

		Renderer.templates = { "isSection": function() { return true } };
		Renderer.contents = { "isSection": function() { return true } };

		var spyCallback = jasmine.createSpy();
		Renderer.render("path/test", ".html", null, {}, spyCallback);

		expect(Renderer.serveStatic.mostRecentCall.args[0]).toEqual(Path.join("path/test/index.html"));
	});

	it("serve the static file if it exists", function() {

		var spyCallback = jasmine.createSpy();

		Renderer.templates = { "isSection": function() { return false } };
		Renderer.contents = { "isSection": function() { return false } };

		spyOn(Renderer, "serveStatic").andCallFake(function(path, last_modified, callback) {
			return callback(null, { "body": "static output", "modified": true });
		});

		Renderer.render("path/test.html", ".html", null, {}, spyCallback);

		expect(spyCallback).toHaveBeenCalledWith({ "body": "static output", "modified": true });
	});

	it("compile the template in given path for the given content type", function() {

		var spyCallback = jasmine.createSpy();

		Renderer.templates = { "isSection": function() { return false } };
		Renderer.contents = { "isSection": function() { return false } };

		spyOn(Renderer, "serveStatic").andCallFake(function(path, last_modified, callback) {
			return callback({ "ignore": true, "message": "error" }, null);
		});

		spyOn(Renderer, "compileTo").andCallFake(function(path, content_type, last_modified, callback) {
			return callback(null, { "body": "compiled output", "modified": true });
		});

		Renderer.render("path/test.css", ".css", null, {}, spyCallback);

		expect(spyCallback).toHaveBeenCalledWith({ "body": "compiled output", "modified": true });
	});

	it("pass the error if compiling a template fails", function() {

		var spyCallback = jasmine.createSpy();

		Renderer.templates = { "isSection": function() { return false } };
		Renderer.contents = { "isSection": function() { return false } };

		spyOn(Renderer, "serveStatic").andCallFake(function(path, last_modified, callback) {
			return callback({ "ignore": true, "message": "error" }, null);
		});

		spyOn(Renderer, "compileTo").andCallFake(function(path, content_type, last_modified, callback) {
			return callback({ "ignore": false, "message": "Compile error" }, null);
		});

		Renderer.render("path/test.css", ".css", null, {}, spyCallback);

		expect(spyCallback).toHaveBeenCalledWith({ "body": null, "modified": true, "options": { "status": 500, "log": { "message": "[Error] Compile error" } } });
	});

	it("render the content matching the given path", function() {

		var spyCallback = jasmine.createSpy();

		Renderer.templates = { "isSection": function() { return false } };
		Renderer.contents = { "isSection": function() { return false } };

		spyOn(Renderer, "serveStatic").andCallFake(function(path, last_modified, callback) {
			return callback({ "ignore": true, "message": "error" }, null);
		});

		spyOn(Renderer, "compileTo").andCallFake(function(path, content_type, last_modified, callback) {
			return callback({ "ignore": true, "message": "error" }, null);
		});

		spyOn(Renderer, "renderContent").andCallFake(function(path, content_type, last_modified, options, callback) {
			return callback(null, { "body": "rendered output", "modified": true });
		});

		Renderer.render("path/test.css", ".css", null, {}, spyCallback);

		expect(spyCallback).toHaveBeenCalledWith({ "body": "rendered output", "modified": true });
	});

	it("pass an error if output object is invalid", function() {

		var spyCallback = jasmine.createSpy();

		Renderer.templates = { "isSection": function() { return false } };
		Renderer.contents = { "isSection": function() { return false } };

		spyOn(Renderer, "serveStatic").andCallFake(function(path, last_modified, callback) {
			return callback(null, {});
		});

		Renderer.render("path/test.css", ".css", null, {}, spyCallback);

		expect(spyCallback).toHaveBeenCalledWith({ "body": null, "modified": true, "options": { "status": 500, "log": { "message": "[Error] Response should contain body and modified properties" } } });
	});

});

describe("serving static file", function(){

	it("get the template details for the given full path", function() {
		var spyGetTemplate = jasmine.createSpy();

		Renderer.templates = {
			"getTemplate": spyGetTemplate
		};

		Renderer.serveStatic("path/test.jpg", null, function() { });

		expect(spyGetTemplate.mostRecentCall.args[0]).toEqual("path/test.jpg");
	});

	it("call the callback with the template output if template is modified", function() {
		var spyGetTemplate = jasmine.createSpy();
		spyGetTemplate.andCallFake(function(path, callback) {
			callback(null, { "last_modified": new Date(2012, 6, 13) });
		});

		var spyReadTemplate = jasmine.createSpy();
		spyReadTemplate.andCallFake(function(path, callback) {
			callback(null, "static output");
		});

		Renderer.templates = {
			"getTemplate": spyGetTemplate,
			"readTemplate": spyReadTemplate
		};

		var spyCallback = jasmine.createSpy();

		var old_date = new Date(2012, 6, 10);
		Renderer.serveStatic("path/test.jpg", old_date, spyCallback);

		expect(spyCallback).toHaveBeenCalledWith(null, { "body": "static output", "modified": true });
	});

	it("call the callback without the template output if template is not modified", function() {
		var spyGetTemplate = jasmine.createSpy();
		spyGetTemplate.andCallFake(function(path, callback) {
			callback(null, { "last_modified": new Date(2012, 6, 13) });
		});

		var spyReadTemplate = jasmine.createSpy();
		spyReadTemplate.andCallFake(function(path, callback) {
			callback(null, "static output");
		});

		Renderer.templates = {
			"getTemplate": spyGetTemplate,
			"readTemplate": spyReadTemplate
		};

		var spyCallback = jasmine.createSpy();

		var old_date = new Date(2012, 6, 15);
		Renderer.serveStatic("path/test.jpg", old_date, spyCallback);

		expect(spyCallback).toHaveBeenCalledWith(null, { "body": null, "modified": false });
	});

	it("call the callback with the error if an error occurrs in getting the template", function() {
		var spyGetTemplate = jasmine.createSpy();
		spyGetTemplate.andCallFake(function(path, callback) {
			callback("error", null);
		});

		Renderer.templates = {
			"getTemplate": spyGetTemplate
		};

		var spyCallback = jasmine.createSpy();

		var old_date = new Date(2012, 6, 15);
		Renderer.serveStatic("path/test.jpg", old_date, spyCallback);

		expect(spyCallback).toHaveBeenCalledWith({ "ignore": true, "message": "error" }, null);
	});

});

describe("compile template", function() {

	it("get the matching templates by base path", function() {
		var spyCompile = jasmine.createSpy();

		Renderer.compilers = {
			".min.js": { "compile": spyCompile }
		};

		var spyGetTemplates = jasmine.createSpy();

		Renderer.templates = {
			"getTemplates": spyGetTemplates
		};

		Renderer.compileTo("path/test.min.js", ".js", null, function() { });

		expect(spyGetTemplates.mostRecentCall.args[0]).toEqual("path/test");
	});

	it("read the template if its modified", function() {
		var spyCompile = jasmine.createSpy();

		Renderer.compilers = {
			".js": { "compile": spyCompile, "input_extensions": [".coffee"] }
		};

		var spyGetTemplates = jasmine.createSpy();
		spyGetTemplates.andCallFake(function(basePath, callback) {
			callback(null, [ { "full_path": "path/test.html", "last_modified": new Date(2012, 6, 13) },
											 { "full_path": "path/test.coffee", "last_modified": new Date(2012, 6, 13) }
										 ]);
		});

		var spyReadTemplate = jasmine.createSpy();

		Renderer.templates = {
			"getTemplates": spyGetTemplates,
			"readTemplate": spyReadTemplate
		};

		Renderer.compileTo("path/test.js", ".js", null, function() { });

		expect(spyReadTemplate.mostRecentCall.args[0]).toEqual("path/test.coffee");
	});

	it("call compile with the template output and full template path", function() {
		var spyCompile = jasmine.createSpy();

		Renderer.compilers = {
			".js": { "compile": spyCompile, "input_extensions": [".coffee"] }
		};

		var spyGetTemplates = jasmine.createSpy();
		spyGetTemplates.andCallFake(function(basePath, callback) {
			callback(null, [{ "full_path": "path/test.html", "last_modified": new Date(2012, 6, 13) },
											{ "full_path": "path/test.coffee", "last_modified": new Date(2012, 6, 13) }
										 ]);
		});

		var spyReadTemplate = jasmine.createSpy();
		spyReadTemplate.andCallFake(function(path, callback) {
			callback(null, "template output");
		});

		Renderer.templates = {
			"getTemplates": spyGetTemplates,
			"readTemplate": spyReadTemplate,
			"templateDir": "templates"
		};

		var spyCallback = jasmine.createSpy();
		Renderer.compileTo("path/test.js", ".js", null, spyCallback);

		expect(spyCompile).toHaveBeenCalledWith("template output", Path.join("templates/path/test.coffee"), jasmine.any(Function));
	});

	it("call the callback without an output if force compile option is disabled and template is not modified", function() {
		var spyCompile = jasmine.createSpy();

		Renderer.compilers = {
			".js": { "compile": spyCompile, "input_extensions": [".coffee"], "force_compile": false }
		};

		var spyGetTemplates = jasmine.createSpy();
		spyGetTemplates.andCallFake(function(basePath, callback) {
			callback(null, [{ "full_path": "path/test.html", "last_modified": new Date(2012, 6, 10) },
											{ "full_path": "path/test.coffee", "last_modified": new Date(2012, 6, 10) }
										 ]);
		});

		var spyReadTemplate = jasmine.createSpy();
		spyReadTemplate.andCallFake(function(path, callback) {
			callback(null, "template output");
		});

		Renderer.templates = {
			"getTemplates": spyGetTemplates,
			"readTemplate": spyReadTemplate
		};

		var spyCallback = jasmine.createSpy();
		Renderer.compileTo("path/test.js", ".js", new Date(2012, 6, 13), spyCallback);

		expect(spyCallback).toHaveBeenCalledWith(null, { "body": null, "modified": false });

	});

	it("call compile if force compile option is enabled and template is not modified", function() {
		var spyCompile = jasmine.createSpy();

		Renderer.compilers = {
			".css": { "compile": spyCompile, "input_extensions": [".less"], "force_compile": true }
		};

		var spyGetTemplates = jasmine.createSpy();
		spyGetTemplates.andCallFake(function(basePath, callback) {
			callback(null, [{ "full_path": "path/test.html", "last_modified": new Date(2012, 6, 13) },
											{ "full_path": "path/test.less", "last_modified": new Date(2012, 6, 13) }
										 ]);
		});

		var spyReadTemplate = jasmine.createSpy();
		spyReadTemplate.andCallFake(function(path, callback) {
			callback(null, "template output");
		});

		Renderer.templates = {
			"getTemplates": spyGetTemplates,
			"readTemplate": spyReadTemplate,
			"templateDir": "templates"
		};

		var spyCallback = jasmine.createSpy();
		Renderer.compileTo("path/test.css", ".css", new Date(2012, 11, 25), spyCallback);

		expect(spyCompile).toHaveBeenCalledWith("template output", Path.join("templates/path/test.less"), jasmine.any(Function));
	});

	it("call the callback with an error if no compiler found for the given content type", function() {
		var spyCompile = jasmine.createSpy();

		Renderer.compilers = {
			".css": { "compile": spyCompile, "input_extensions": [".less"] }
		};

		var spyCallback = jasmine.createSpy();
		Renderer.compileTo("path/test.js", ".js", new Date(2012, 6, 13), spyCallback);

		expect(spyCallback).toHaveBeenCalledWith({ "ignore": true, "message": "no compiler found" }, null);
	});

	it("call the callback with an error if no matching template is found", function() {
		var spyCompile = jasmine.createSpy();

		Renderer.compilers = {
			".js": { "compile": spyCompile, "input_extensions": [".coffee"] }
		};

		var spyGetTemplates = jasmine.createSpy();
		spyGetTemplates.andCallFake(function(basePath, callback) {
			callback("template not found", null);
		});

		Renderer.templates = {
			"getTemplates": spyGetTemplates
		};

		var spyCallback = jasmine.createSpy();
		Renderer.compileTo("path/test.js", ".js", new Date(2012, 6, 13), spyCallback);

		expect(spyCallback).toHaveBeenCalledWith({ "ignore": true, "message": "template not found" }, null);
	});

	it("call the callback with an error if non of the matched templates can be compiled", function() {
		var spyCompile = jasmine.createSpy();

		Renderer.compilers = {
			".js": { "compile": spyCompile, "input_extensions": [".coffee"] }
		};

		var spyGetTemplates = jasmine.createSpy();
		spyGetTemplates.andCallFake(function(basePath, callback) {
			return callback(null, [{ "full_path": "path/test.html", "last_modified": new Date(2012, 6, 13) },
														 { "full_path": "path/test.css", "last_modified": new Date(2012, 6, 13) }
														]);
		});

		Renderer.templates = {
			"getTemplates": spyGetTemplates
		};

		var spyCallback = jasmine.createSpy();
		Renderer.compileTo("path/test.js", ".js", new Date(2012, 6, 13), spyCallback);

		expect(spyCallback).toHaveBeenCalledWith({ "ignore": true, "message": "no compilable template found" }, null);
	});

	it("call the callback with an error if it fails to read the template", function() {
		var spyCompile = jasmine.createSpy();

		Renderer.compilers = {
			".js": { "compile": spyCompile, "input_extensions": [".coffee"] }
		};

		var spyGetTemplates = jasmine.createSpy();
		spyGetTemplates.andCallFake(function(basePath, callback) {
			callback(null, [{ "full_path": "path/test.html", "last_modified": new Date(2012, 6, 10) },
											{ "full_path": "path/test.coffee", "last_modified": new Date(2012, 6, 10) }
										 ]);
		});

		var spyReadTemplate = jasmine.createSpy();
		spyReadTemplate.andCallFake(function(path, callback) {
			callback("template read error", null);
		});

		Renderer.templates = {
			"getTemplates": spyGetTemplates,
			"readTemplate": spyReadTemplate
		};

		var spyCallback = jasmine.createSpy();
		Renderer.compileTo("path/test.js", ".js", null, spyCallback);

		expect(spyCallback).toHaveBeenCalledWith({ "ignore": false, "message": "template read error" }, null);
	});

});

describe("render content", function(){

	it("creates a new template engine instance", function() {
		var spyEvenListener = jasmine.createSpy();

		spyOn(Renderer, "createTemplateEngine").andCallFake(function() {
			return {"on": spyEvenListener};
		});

		var spyNegotiateContent = jasmine.createSpy();
		var spyNegotiateTemplate = jasmine.createSpy();
		var spyGetPartials = jasmine.createSpy();

		Renderer.contents = { "negotiateContent": spyNegotiateContent };
		Renderer.templates = { "negotiateTemplate": spyNegotiateTemplate, "getPartials": spyGetPartials };

		spyOn(Renderer, "getHelpers");

		var spyCallback = jasmine.createSpy();
		Renderer.renderContent("path/test.html", ".html", new Date(2012, 6, 18), {}, spyCallback);

		expect(Renderer.createTemplateEngine).toHaveBeenCalledWith({ "lastRender": new Date(2012, 6, 18) });
	});

	it("listen to render complete event", function() {
		var spyEvenListener = jasmine.createSpy();

		spyOn(Renderer, "createTemplateEngine").andCallFake(function() {
			return { "on": spyEvenListener };
		});

		var spyNegotiateContent = jasmine.createSpy();
		var spyNegotiateTemplate = jasmine.createSpy();
		var spyGetPartials = jasmine.createSpy();

		spyOn(Renderer, "getHelpers");

		Renderer.contents = { "negotiateContent": spyNegotiateContent };
		Renderer.templates = { "negotiateTemplate": spyNegotiateTemplate, "getPartials": spyGetPartials };

		var spyCallback = jasmine.createSpy();
		Renderer.renderContent("path/test.html", ".html", new Date(2012, 6, 18), {}, spyCallback);

		expect(spyEvenListener.argsForCall[0][0]).toEqual("renderComplete");
	});

	it("listen to render canceled event", function() {
		var spyEvenListener = jasmine.createSpy();

		spyOn(Renderer, "createTemplateEngine").andCallFake(function() {
			return { "on": spyEvenListener };
		});

		var spyNegotiateContent = jasmine.createSpy();
		var spyNegotiateTemplate = jasmine.createSpy();
		var spyGetPartials = jasmine.createSpy();

		spyOn(Renderer, "getHelpers");

		Renderer.contents = { "negotiateContent": spyNegotiateContent };
		Renderer.templates = { "negotiateTemplate": spyNegotiateTemplate, "getPartials": spyGetPartials };

		var spyCallback = jasmine.createSpy();
		Renderer.renderContent("path/test.html", ".html", new Date(2012, 6, 18), {}, spyCallback);

		expect(spyEvenListener.argsForCall[1][0]).toEqual("renderCanceled");
	});

	it("fetch and set contents for the given path", function() {
		var spyEvenListener = jasmine.createSpy();
		var spySetContent = jasmine.createSpy();

		spyOn(Renderer, "createTemplateEngine").andCallFake(function() {
			return { "on": spyEvenListener, "setContent": spySetContent };
		});

		var spyNegotiateContent = jasmine.createSpy();
		var spyNegotiateTemplate = jasmine.createSpy();
		var spyGetPartials = jasmine.createSpy();

		spyOn(Renderer, "getHelpers");

		spyNegotiateContent.andCallFake(function(path, content_type, options, callback) {
			return callback(null, { "key": "value" }, new Date(2012, 6, 17), {});
		});

		Renderer.contents = { "negotiateContent": spyNegotiateContent };
		Renderer.templates = { "negotiateTemplate": spyNegotiateTemplate, "getPartials": spyGetPartials };

		var spyCallback = jasmine.createSpy();
		Renderer.renderContent("path/test.html", ".html", new Date(2012, 6, 18), {}, spyCallback);

		expect(spySetContent).toHaveBeenCalledWith({ "key": "value" }, new Date(2012, 6, 17));
	});

	it("cancel rendering if there's an error fetching content for the given path", function(){

		var spyEvenListener = jasmine.createSpy();
		var spyCancelRender = jasmine.createSpy();

		spyOn(Renderer, "createTemplateEngine").andCallFake(function(){
			return {"on": spyEvenListener, "cancelRender": spyCancelRender};
		});

		var spyNegotiateContent = jasmine.createSpy();
		var spyNegotiateTemplate = jasmine.createSpy();
		var spyGetPartials = jasmine.createSpy();

		spyOn(Renderer, "getHelpers");

		spyNegotiateContent.andCallFake(function(path, content_type, options, callback){
			return callback("content error", null, {});
		});

		Renderer.contents = {"negotiateContent": spyNegotiateContent};
		Renderer.templates = {"negotiateTemplate": spyNegotiateTemplate, "getPartials": spyGetPartials};

		var spyCallback = jasmine.createSpy();
		Renderer.renderContent("path/test.html", ".html", new Date(2012, 6, 18), {}, spyCallback);

		expect(spyCancelRender).toHaveBeenCalledWith("content error");
	});

	it("fetch and set templates for the given path", function() {

		var spyEvenListener = jasmine.createSpy();
		var spySetTemplate = jasmine.createSpy();

		spyOn(Renderer, "createTemplateEngine").andCallFake(function() {
			return { "on": spyEvenListener, "setTemplate": spySetTemplate };
		});

		var spyNegotiateContent = jasmine.createSpy();
		var spyNegotiateTemplate = jasmine.createSpy();
		var spyGetPartials = jasmine.createSpy();

		spyOn(Renderer, "getHelpers");

		spyNegotiateTemplate.andCallFake(function(path, output_extension, template_extension, options, callback) {
			return callback(null, "template output", new Date(2012, 6, 17), {});
		});

		Renderer.contents = { "negotiateContent": spyNegotiateContent };
		Renderer.templates = { "negotiateTemplate": spyNegotiateTemplate, "getPartials": spyGetPartials };

		var spyCallback = jasmine.createSpy();
		Renderer.renderContent("path/test.html", ".html", new Date(2012, 6, 18), {}, spyCallback);

		expect(spySetTemplate).toHaveBeenCalledWith("template output", new Date(2012, 6, 17));
	});

	it("cancel rendering if there's an error fetching templates for the given path", function() {
		var spyEvenListener = jasmine.createSpy();
		var spyCancelRender = jasmine.createSpy();

		spyOn(Renderer, "createTemplateEngine").andCallFake(function() {
			return { "on": spyEvenListener, "cancelRender": spyCancelRender };
		});

		var spyNegotiateContent = jasmine.createSpy();
		var spyNegotiateTemplate = jasmine.createSpy();
		var spyGetPartials = jasmine.createSpy();

		spyOn(Renderer, "getHelpers");

		spyNegotiateTemplate.andCallFake(function(path, output_extension, template_extension, options, callback) {
			return callback("template error", null, {});
		});

		Renderer.contents = { "negotiateContent": spyNegotiateContent };
		Renderer.templates = { "negotiateTemplate": spyNegotiateTemplate, "getPartials": spyGetPartials };

		var spyCallback = jasmine.createSpy();
		Renderer.renderContent("path/test.html", ".html", new Date(2012, 6, 18), {}, spyCallback);

		expect(spyCancelRender).toHaveBeenCalledWith("template error");
	});

	it("fetch and set partials for the given path", function() {
		var spyEvenListener = jasmine.createSpy();
		var spySetPartials = jasmine.createSpy();

		spyOn(Renderer, "createTemplateEngine").andCallFake(function() {
			return { "on": spyEvenListener, "setPartials": spySetPartials };
		});

		var spyNegotiateContent = jasmine.createSpy();
		var spyNegotiateTemplate = jasmine.createSpy();
		var spyGetPartials = jasmine.createSpy();

		spyOn(Renderer, "getHelpers");

		spyGetPartials.andCallFake(function(path, extension, options, callback) {
			return callback(null, { "partial": "partial output" }, new Date(2012, 6, 17), {});
		});

		Renderer.contents = { "negotiateContent": spyNegotiateContent };
		Renderer.templates = { "negotiateTemplate": spyNegotiateTemplate, "getPartials": spyGetPartials };

		var spyCallback = jasmine.createSpy();
		Renderer.renderContent("path/test.html", ".html", new Date(2012, 6, 18), {}, spyCallback);

		expect(spySetPartials).toHaveBeenCalledWith({ "partial": "partial output" }, new Date(2012, 6, 17));
	});

	it("fetch and set helpers for the given path", function() {
		var spyEvenListener = jasmine.createSpy();
		var spySetHelpers = jasmine.createSpy();

		spyOn(Renderer, "createTemplateEngine").andCallFake(function() {
			return { "on": spyEvenListener, "setHelpers": spySetHelpers };
		});

		var spyNegotiateContent = jasmine.createSpy();
		var spyNegotiateTemplate = jasmine.createSpy();
		var spyGetPartials = jasmine.createSpy();

		Renderer.contents = { "negotiateContent": spyNegotiateContent };
		Renderer.templates = { "negotiateTemplate": spyNegotiateTemplate, "getPartials": spyGetPartials };

		var spyHelperObj = jasmine.createSpy();
		var spyHelperOptions = jasmine.createSpy();
		spyOn(Renderer, "getHelpers").andCallFake(function(basePath, extension, options, callback) {
			return callback(null, spyHelperObj, spyHelperOptions, new Date(2012, 7, 25));
		});

		var spyCallback = jasmine.createSpy();
		Renderer.renderContent("path/test.html", ".html", new Date(2012, 6, 18), {}, spyCallback);

		expect(spySetHelpers).toHaveBeenCalledWith(spyHelperObj, new Date(2012, 7, 25));
	});

});

describe("get helpers", function() {

	it("call the helper with all given arguments", function(){
		var spyHelperGet = jasmine.createSpy();

		Renderer.helpers = [{ "get": spyHelperGet }];

		var spyCallback = jasmine.createSpy();
		var spyOptions = jasmine.createSpy();
		Renderer.getHelpers("path/test", "html", spyOptions, spyCallback);

		expect(spyHelperGet).toHaveBeenCalledWith("path/test", "html", spyOptions, jasmine.any(Function));
	});

	it("call the callback with all content collected by helpers", function(){
		var spyHelperGet1 = jasmine.createSpy();
		spyHelperGet1.andCallFake(function(path, content_type, options, callback){
			return callback(null, { "tag": { "tag_helper1": "value" }, "block": { "block_helper1": "value"} }, { "opt1": "value" }, new Date(2012, 7, 25));
		});

		var spyHelperGet2 = jasmine.createSpy();
		spyHelperGet2.andCallFake(function(path, content_type, options, callback){
			return callback(null, { "tag": { "tag_helper2": "value" }, "block": { "block_helper2": "value"} }, { "opt2": "value" }, new Date(2012, 7, 27));
		});

		Renderer.helpers = [{ "get": spyHelperGet1 }, { "get": spyHelperGet2 }];

		var spyCallback = jasmine.createSpy();
		var spyOptions = jasmine.createSpy();
		Renderer.getHelpers("path/test", "html", spyOptions, spyCallback);

		expect(spyCallback).toHaveBeenCalledWith(null, { "tag": { "tag_helper1": "value", "tag_helper2": "value" }, "block": { "block_helper1": "value", "block_helper2": "value" } }, { "opt1": "value", "opt2": "value" }, new Date(2012, 7, 27));
	});

});


text:
<?php

/**
 * Enter description here ...
 *
 * @category    Mage
 * @package     Mage_GoogleCheckout
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_GoogleCheckout_Model_Resource_Api_Debug_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
    /**
     * Collection constructor
     *
     */
    protected function _construct()
    {
        $this->_init('googlecheckout/api_debug');
    }
}


text:
Metrics
=======

## Inputs

### Requested Fields

 * `ids` _Comma-separated list_ ids from `metrics` table.
 * `dimension` _Comma-sparated list_ ids from `metrics` table.  Stats will be aggregated among unique sets of dimensions.

### Campaigns

 * `company_id` _Comma-separated list_ companies
 * `group_id` _Comma-separated list_ groups
 * `campaign_id` _Comma-separated list_ campaigns

#### Campaign Selection

 * `group_end_after` _timestamp_ Groups with a campaign with stop date after unix timestamp
 * `group_start_after` _timestamp_ Groups with a campaign with start date after unix timestamp
 * `group_start_soon` _timestamp_ Groups with a campaign starting within given number of days
 * `group_status`

Value | Groups with Campaign...
------|-------------------------
_running_, _nowrunning_ | start date before current time, stop date after current time
_endingtoday_ | stop date between beginning and end of current day
_mostrecent_ | stop date within last 7 days
_missingcreative_ | No creative objects linked
_havealerts_ | start date in past, stop any time after 1 month ago (Appears to be broken)
_startingsoon_, _upcoming_ | start date after current time, and within 7 days
_deleted_ | deleted
_all_ | not deleted

* `campaign_status`

Value |  Campaigns...
------ | --------
_all_ | All
_notexpired_ | Have not reached stop date, or have stats
_running_ | Current time between start and stop date, with stats, and not paused
_upcoming_ | Start time in future
_not running_ | Current time between start and stop, with no stats
_expired_ | All (appears broken)

### Filtering

 * `filters` JSON-encoded array of filters

 #### Filter

  * `id` | Single id from `metrics` table
  * `only_include` | _Array_ Include any records matching any items in list
  * `partial_exclude` | _Array_ Exclude any records matching only items in list (Items without values not specified in list)
  * `any_exclude` | _Array_ Exclude any record matching any itmes in list

### Date Range

 * `start_date` _Timestamp_
 * `stop_date` _Timestamp_
 * `weekstart` _sun_ (default), _mon_

### Cache Control

 * `clearcache` Delete cache for this call (other callers will not get cached results, useful if broken)
 * `update` Refresh cache for this call, and request stats be updated for specified groups
 * `refreshcache` Update cache without deleting existing cache (other callers will still get cache before updated)
 * `forcecache` Enforce a cache be written for this call, even if fast

### Other/Debugging

 * `timeout` Amount of time to wait for Stats API
 * `forcespark` Force use of Spark database
 * `disablespark` Disable use of Spark database
 * `nofill` Do not fill in missing times (with time dimension) when empty
 * `human` Return header with stat name instead of `metrics` table id
 * `humantime` Return time dimension human-readable instead of timestamp

### Notes

 * Timestamps are in seconds since epoch

## Output

### CSV Format

 * Header line with each `ids` and `dimension`
 * Data lines corresponding, one for each unique set of dimensions
 * List and Object data JSON-formatted

### Headers

 * `X-CN-Timestamp` _Timestamp_ When stats fetched

### Notes
 * Timestamps are in milliseconds since epoch


text:
layout:     post
author:     Christoph Broschinski
author_lnk: https://github.com/cbroschinski
title:      University of Oldenburg reports 2022 APC expenditures
date:       2022-11-23 11:00:00
summary:
categories: [general, openAPC]
comments: true
---

The [Carl von Ossietzky University of Oldenburg](https://www.uni-oldenburg.de/en/) has updated its APC expenditures, the latest contribution provides articles for the 2022 period.

The [BIS](http://www.bis.uni-oldenburg.de/en/bishome/) (Library and Information System) is in charge of the [University's Open Access Publishing Fund](https://uol.de/en/bis/research-publishing/open-access/open-access-publication-fund), which receives support under the [DFG's Open Access Publishing Programme](https://www.dfg.de/en/research_funding/programmes/infrastructure/lis/open_access/infrastructure_funding/index.html#4).

Contact person is [Kim Braun](mailto:kim.braun@uni-oldenburg.de).

## Cost data

The new data set covers publication fees for 117 articles, total expenditure amounts to 223 629€ and the average fee is 1 911€.

The following table shows the payments the BIS has made to publishers since Oldenburg's last report.

|                                                       | Articles| Fees paid in EURO| Mean Fee paid|
|:------------------------------------------------------|--------:|-----------------:|-------------:|
|Frontiers Media SA                                     |       41|             88911|          2169|
|MDPI AG                                                |       27|             48392|          1792|
|Springer Nature                                        |       11|             19770|          1797|
|Wiley-Blackwell                                        |        8|             17284|          2160|
|Copernicus GmbH                                        |        7|             10599|          1514|
|Public Library of Science (PLoS)                       |        4|              8428|          2107|
|Informa UK Limited                                     |        3|              5412|          1804|
|EDP Sciences                                           |        2|              1178|           589|
|Oxford University Press (OUP)                          |        2|              4814|          2407|
|SAGE Publications                                      |        2|              1544|           772|
|American Institute of Mathematical Sciences (AIMS)     |        1|               915|           915|
|Elsevier BV                                            |        1|              3594|          3594|
|German Medical Science                                 |        1|               400|           400|
|Institute of Electrical & Electronics Engineers (IEEE) |        1|              1844|          1844|
|JMIR Publications Inc.                                 |        1|              1968|          1968|
|Lupine Publishers                                      |        1|               986|           986|
|Modestum Limited                                       |        1|               720|           720|
|Optica Publishing Group                                |        1|              3960|          3960|
|Scientific Research Publishing, Inc.                   |        1|               908|           908|
|Society for Neuroscience                               |        1|              2003|          2003|

## Overview

With the recent contribution included, the overall APC data for the University of Oldenburg now looks as follows:

### Fees paid per publisher (in EURO)

![plot of chunk tree_oldenburg_2022_11_24_full](/figure/tree_oldenburg_2022_11_24_full-1.png)

###  Average costs per year (in EURO)

![plot of chunk box_oldenburg_2022_11_24_year_full](/figure/box_oldenburg_2022_11_24_year_full-1.png)

###  Average costs per publisher (in EURO)

![plot of chunk box_oldenburg_2022_11_24_publisher_full](/figure/box_oldenburg_2022_11_24_publisher_full-1.png)


text:
package org.apache.poi.hwmf.record;

import org.apache.poi.hwmf.draw.HwmfGraphics;

/**
 * Marker interface for Records, which should be added to the
 * WMF object table for further selection
 */
public interface HwmfObjectTableEntry {
    public void applyObject(HwmfGraphics ctx);
}


text:
if ( $IsCoreCLR ) {
    return
}

Describe "Interface inheritance with remoting proxies" -Tags "CI" {
    $src = @"
using System;
using System.ServiceModel;

namespace MSFT_716893
{
    [ServiceContract]
    public interface IInterface1
    {
        [OperationContract]string BaseOperation(int i);
    }

    [ServiceContract]
    public interface IInterface2 : IInterface1
    {
        [OperationContract(Name="op1")]string Operation(string a);
        [OperationContract(Name="op2")]string Operation(string a, string b);
    }

    public class ServiceImplementation : IInterface2
    {
        public string Operation(string a) { return "1 - " + a; }
        public string Operation(string a, string b) { return "2 - " + a + " " + b; }
        public string BaseOperation(int i) { return "3 - " + i; }
    }

    public static class Service
    {
        static ServiceHost serviceHost;

        public static void Init()
        {
            Uri baseAddress = new Uri("http://localhost:8080/service");
            serviceHost = new ServiceHost(typeof(ServiceImplementation), baseAddress);
            serviceHost.Open();
        }

        public static IInterface1 GetProxy()
        {
            ChannelFactory<IInterface2> factory = new ChannelFactory<IInterface2>(
                serviceHost.Description.Endpoints[0].Binding,
                serviceHost.Description.Endpoints[0].Address);
            return factory.CreateChannel();
        }

        public static void Close()
        {
            serviceHost.Close();
        }
    }
}
"@

    Add-Type -TypeDefinition $src -ReferencedAssemblies System.ServiceModel.dll

    BeforeEach {
        [MSFT_716893.Service]::Init()
        $proxy = [MSFT_716893.Service]::GetProxy()
    }

    AfterEach {
        [MSFT_716893.Service]::Close()
    }

    It "Direct invocation" {
        $proxy.Operation("a") | Should -Be "1 - a"
        $proxy.Operation("a", "b") | Should -Be "2 - a b"
        $proxy.BaseOperation(42) | Should -Be "3 - 42"
    }

    It "Invocation via method constraints" {
        ([MSFT_716893.IInterface2]$proxy).Operation("c") | Should -Be "1 - c"
        ([MSFT_716893.IInterface2]$proxy).Operation("d", "e") | Should -Be "2 - d e"
        ([MSFT_716893.IInterface1]$proxy).BaseOperation(22) | Should -Be "3 - 22"
    }
}


text:
using System;
using System.Html;
using System.Runtime.CompilerServices;

[assembly: ScriptAssembly("test")]

namespace MemberTests {

    public abstract class Test {

        public void Do1() {
        }

        public int Do2() {
            return 0;
        }

        public object Do3(int i, int j) {
            return i;
        }

        public void Run() {
            Do1();
            int v = Do2();

            string s = String.FromChar('A', 3);
            int i = s.IndexOf('A');
            i = s.IndexOf('A', 1);
        }

        public abstract object getRunOptions();

        public override string ToString() {
            Bar.M1();

            X x = new X();
            Plugin.Extend(x, 10);

            return null;
        }
    }

    [ScriptExtension("$global")]
    public static class Foo {

        public static void DoStuff() {
        }
    }

    [ScriptExtension("window")]
    public static class Bar {

        public static void M1() {
        }

        public static void M2() {
        }
    }

    public class X {

        public void Update(int i) { }
    }

    [ScriptExtension("$.fn")]
    public static class Plugin {

        public static X Extend(X x, int i) {
            x.Update(i);
            return x;
        }
    }
}


text:
  <fs-dialog data-is-open="isShowing" data-working="isWorking" data-close="close('close')" data-dialog-key="$(key)">

{TITLE}

SAMPLE CONTENT

Replace with your content

{{errorStr}}

      <button type="button" class="fs-button fs-button—recommended" data-ng-click="doSomething()">{BUTTON_OK}</button>
      <button type="button" class="fs-button fs-button—minor fs-button--tertiary" data-ng-click="close('cancel')" >{BUTTON_CANCEL}</button>

  </fs-dialog>