text:
package com.erigitic.jobs;

import com.erigitic.config.AccountManager;
import com.erigitic.config.TEAccount;
import com.erigitic.main.TotalEconomy;
import com.erigitic.sql.SqlManager;
import com.erigitic.sql.SqlQuery;
import com.erigitic.util.MessageManager;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import ninja.leaping.configurate.ConfigurationNode;
import ninja.leaping.configurate.commented.CommentedConfigurationNode;
import ninja.leaping.configurate.hocon.HoconConfigurationLoader;
import ninja.leaping.configurate.loader.ConfigurationLoader;
import org.slf4j.Logger;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.block.BlockState;
import org.spongepowered.api.block.tileentity.Sign;
import org.spongepowered.api.block.tileentity.TileEntity;
import org.spongepowered.api.block.trait.BlockTrait;
import org.spongepowered.api.data.Transaction;
import org.spongepowered.api.data.manipulator.mutable.item.FishData;
import org.spongepowered.api.data.manipulator.mutable.tileentity.SignData;
import org.spongepowered.api.entity.Entity;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.entity.living.player.User;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.action.FishingEvent;
import org.spongepowered.api.event.block.ChangeBlockEvent;
import org.spongepowered.api.event.block.InteractBlockEvent;
import org.spongepowered.api.event.block.tileentity.ChangeSignEvent;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.cause.EventContext;
import org.spongepowered.api.event.cause.EventContextKeys;
import org.spongepowered.api.event.cause.entity.damage.source.EntityDamageSource;
import org.spongepowered.api.event.entity.DestructEntityEvent;
import org.spongepowered.api.item.inventory.ItemStack;
import org.spongepowered.api.item.inventory.ItemStackSnapshot;
import org.spongepowered.api.scheduler.Scheduler;
import org.spongepowered.api.scheduler.Task;
import org.spongepowered.api.service.economy.Currency;
import org.spongepowered.api.service.economy.transaction.ResultType;
import org.spongepowered.api.service.economy.transaction.TransactionResult;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.action.TextActions;
import org.spongepowered.api.text.format.TextColors;
import org.spongepowered.api.text.format.TextStyles;

public class JobManager {

    private TotalEconomy totalEconomy;
    private AccountManager accountManager;
    private MessageManager messageManager;
    private Logger logger;
    private SqlManager sqlManager;

    private File jobSetsFile;
    private ConfigurationLoader<CommentedConfigurationNode> jobSetsLoader;
    private ConfigurationNode jobSetsConfig;
    private Map<String, TEJobSet> jobSets;

    private File jobsFile;
    private ConfigurationLoader<CommentedConfigurationNode> jobsLoader;
    private ConfigurationNode jobsConfig;
    private Map<String, TEJob> jobsMap;

    private boolean databaseEnabled;

    public JobManager(TotalEconomy totalEconomy, AccountManager accountManager, MessageManager messageManager, Logger logger) {
        this.totalEconomy = totalEconomy;
        this.accountManager = accountManager;
        this.messageManager = messageManager;
        this.logger = logger;

        databaseEnabled = totalEconomy.isDatabaseEnabled();

        if (databaseEnabled) {
            sqlManager = totalEconomy.getSqlManager();
        }

        setupConfig();

        if (totalEconomy.isJobSalaryEnabled()) {
            startSalaryTask();
        }
    }

    /**
     * Start the timer that pays out the salary to each player after a specified time in seconds.
     */
    private void startSalaryTask() {
        Scheduler scheduler = totalEconomy.getGame().getScheduler();
        Task.Builder payTask = scheduler.createTaskBuilder();

        payTask.execute(() -> {
            if (totalEconomy.getGame().isServerAvailable()) {
                for (Player player : totalEconomy.getServer().getOnlinePlayers()) {
                    Optional<TEJob> optJob = getJob(getPlayerJob(player), true);

                    if (!optJob.isPresent()) {
                        player.sendMessage(Text.of(TextColors.RED, "[TE] Cannot pay your salary! Contact your administrator!"));

                        return;
                    }

                    if (optJob.get().salaryEnabled()) {
                        BigDecimal salary = optJob.get().getSalary();
                        TEAccount playerAccount = (TEAccount) accountManager.getOrCreateAccount(player.getUniqueId()).get();

                        EventContext eventContext = EventContext.builder()
                                .add(EventContextKeys.PLAYER, player)
                                .build();

                        Cause cause = Cause.builder()
                                .append(totalEconomy.getPluginContainer())
                                .build(eventContext);

                        TransactionResult result = playerAccount.deposit(totalEconomy.getDefaultCurrency(), salary, cause);

                        if (result.getResult() == ResultType.SUCCESS) {
                            Map<String, String> messageValues = new HashMap<>();
                            messageValues.put("amount", totalEconomy.getDefaultCurrency().format(salary).toPlain());

                            player.sendMessage(messageManager.getMessage("jobs.salary", messageValues));
                        } else {
                            player.sendMessage(Text.of(TextColors.RED, "[TE] Failed to pay your salary! You may want to contact your admin - TransactionResult: ", result.getResult().toString()));
                        }
                    }
                }
            }
        }).delay(jobsConfig.getNode("salarydelay").getInt(), TimeUnit.SECONDS).interval(jobsConfig.getNode("salarydelay").getInt(), TimeUnit.SECONDS).name("Pay Day").submit(totalEconomy);
    }

    /**
     * Setup the jobs config.
     */
    public void setupConfig() {
        jobSetsFile = new File(totalEconomy.getConfigDir(), "jobsets.conf");
        jobSetsLoader = HoconConfigurationLoader.builder().setFile(jobSetsFile).build();
        jobSets = new HashMap();
        reloadJobSetConfig();

        jobsFile = new File(totalEconomy.getConfigDir(), "jobs.conf");
        jobsLoader = HoconConfigurationLoader.builder().setFile(jobsFile).build();
        jobsMap = new HashMap();
        reloadJobsConfig();
    }

    /**
     * Reload the jobSet config.
     */
    public boolean reloadJobSetConfig() {
        try {
            if (!jobSetsFile.exists()) {
                totalEconomy.getPluginContainer().getAsset("jobsets.conf").get().copyToFile(jobSetsFile.toPath());
            }

            jobSetsConfig = jobSetsLoader.load();
            ConfigurationNode sets = jobSetsConfig.getNode("sets");

            sets.getChildrenMap().forEach((setName, setNode) -> {
                if (setNode != null) {
                    TEJobSet jobSet = new TEJobSet(setNode);

                    jobSets.put((String) setName, jobSet);
                }
            });

            return true;
        } catch (IOException e) {
            logger.warn("An error occurred while creating/loading the jobSets configuration file!");

            return false;
        }
    }

    /**
     * Reloads the job configuration file. Can be used for initial creation of the configuration file
     * or for simply reloading it.
     *
     * @return boolean Was the reload successful?
     */
    public boolean reloadJobsConfig() {
        try {
            if (!jobsFile.exists()) {
                totalEconomy.getPluginContainer().getAsset("jobs.conf").get().copyToFile(jobsFile.toPath());
            }

            jobsConfig = jobsLoader.load();
            ConfigurationNode jobsNode = jobsConfig.getNode("jobs");

            // Loop through each job node in the configuration file, create a TEJob object from it, and store in a HashMap
            jobsNode.getChildrenMap().forEach((k, jobNode) -> {
                if (jobNode != null) {
                    TEJob job = new TEJob(jobNode);

                    if (job.isValid()) {
                        jobsMap.put(job.getName(), job);
                    }
                }
            });

            return true;
        } catch (IOException e) {
            logger.warn("An error occurred while creating/loading the jobs configuration file!");

            return false;
        }
    }

    /**
     * Reload all job configs (jobs + sets).
     */
    public boolean reloadJobsAndSets() {
        return reloadJobsConfig() && reloadJobSetConfig();
    }

    /**
     * Add exp to player's current job.
     *
     * @param player The player to give experience to
     * @param expAmount The amount of experience to add
     */
    public void addExp(Player player, int expAmount) {
        String jobName = getPlayerJob(player);
        UUID playerUniqueId = player.getUniqueId();
        boolean jobNotifications = accountManager.getJobNotificationState(player);

        Map<String, String> messageValues = new HashMap<>();
        messageValues.put("job", titleize(jobName));
        messageValues.put("exp", String.valueOf(expAmount));

        if (databaseEnabled) {
            int newExp = getJobExp(jobName, player) + expAmount;

            SqlQuery sqlQuery = SqlQuery.builder(sqlManager.dataSource)
                    .update("experience")
                    .set(jobName)
                    .equals(String.valueOf(newExp))
                    .where("uid")
                    .equals(playerUniqueId.toString())
                    .build();

            if (sqlQuery.getRowsAffected() > 0) {
                if (jobNotifications) {
                    player.sendMessage(messageManager.getMessage("jobs.addexp", messageValues));
                }
            } else {
                logger.warn("An error occurred while updating job experience in the database!");
                player.sendMessage(Text.of(TextColors.RED, "[TE] Error adding experience! Consult an administrator!"));
            }
        } else {
            ConfigurationNode accountConfig = accountManager.getAccountConfig();

            int curExp = accountConfig.getNode(playerUniqueId.toString(), "jobstats", jobName, "exp").getInt();

            accountConfig.getNode(playerUniqueId.toString(), "jobstats", jobName, "exp").setValue(curExp + expAmount);

            if (jobNotifications) {
                player.sendMessage(messageManager.getMessage("jobs.addexp", messageValues));
            }

            try {
                accountManager.getConfigManager().save(accountConfig);
            } catch (IOException e) {
                logger.warn("An error occurred while saving the account configuration file!");
            }
        }
    }

    /**
     * Checks if the player has enough exp to level up. If they do they will gain a level and their current exp will be
     * reset.
     *
     * @param player player object
     */
    public void checkForLevel(Player player) {
        UUID playerUniqueId = player.getUniqueId();
        String jobName = getPlayerJob(player);
        int playerLevel = getJobLevel(jobName, player);
        int playerCurExp = getJobExp(jobName, player);
        int expToLevel = getExpToLevel(player);

        if (playerCurExp >= expToLevel) {
            playerLevel += 1;

            Map<String, String> messageValues = new HashMap<>();
            messageValues.put("job", titleize(jobName));
            messageValues.put("level", String.valueOf(playerLevel));

            if (databaseEnabled) {
                SqlQuery.builder(sqlManager.dataSource)
                        .update("levels")
                        .set(jobName)
                        .equals(String.valueOf(playerLevel))
                        .where("uid")
                        .equals(playerUniqueId.toString())
                        .build();

                SqlQuery.builder(sqlManager.dataSource)
                        .update("experience")
                        .set(jobName)
                        .equals(String.valueOf(playerCurExp))
                        .where("uid")
                        .equals(playerUniqueId.toString())
                        .build();
            } else {
                ConfigurationNode accountConfig = accountManager.getAccountConfig();

                accountConfig.getNode(playerUniqueId.toString(), "jobstats", jobName, "level").setValue(playerLevel);
                accountConfig.getNode(playerUniqueId.toString(), "jobstats", jobName, "exp").setValue(playerCurExp);
            }

            player.sendMessage(messageManager.getMessage("jobs.levelup", messageValues));
        }
    }

    /**
     * Checks the jobs config for the jobName.
     *
     * @param jobName name of the job
     * @return boolean if the job exists or not
     */
    public boolean jobExists(String jobName) {
        if (jobsConfig.getNode("jobs", jobName.toLowerCase()).getValue() != null) {
            return true;
        }

        return false;
    }

    /**
     * Convert strings to titles (title -> Title).
     *
     * @param input the string to be titleized
     * @return String the titileized version of the input
     */
    public String titleize(String input) {
        return input.substring(0, 1).toUpperCase() + input.substring(1).toLowerCase();
    }

    private boolean getNotificationState(UUID uuid) {
        if (databaseEnabled) {
            SqlQuery sqlQuery = SqlQuery.builder(sqlManager.dataSource)
                    .select("job_notifications")
                    .from("accounts")
                    .where("uid")
                    .equals(uuid.toString())
                    .build();

            return sqlQuery.getBoolean(totalEconomy.isJobNotificationEnabled());
        }

        return accountManager.getAccountConfig().getNode(uuid.toString(), "jobnotifications").getBoolean();
    }

    /**
     * Notifies a player when they are rewarded for completing a job action.
     *
     * @param amount The amount rewarded by the job action
     */
    private void notifyPlayerOfJobReward(Player player, BigDecimal amount, Currency currency) {
        Text amountText = currency.format(amount, currency.getDefaultFractionDigits());

        Map<String, String> messageValues = new HashMap<>();
        messageValues.put("amount", amountText.toPlain());

        player.sendMessage(messageManager.getMessage("jobs.notify", messageValues));
    }

    /**
     * Set the users's job.
     *
     * @param user User object
     * @param jobName name of the job
     */
    public boolean setJob(User user, String jobName) {
        UUID userUniqueId = user.getUniqueId();

        // Just in case the job name was not passed in as lowercase, make it lowercase
        jobName = jobName.toLowerCase();

        if (databaseEnabled) {
            SqlQuery sqlQuery = SqlQuery.builder(sqlManager.dataSource)
                    .update("accounts")
                    .set("job")
                    .equals(jobName)
                    .where("uid")
                    .equals(userUniqueId.toString())
                    .build();

            if (sqlQuery.getRowsAffected() > 0) {
                return true;
            } else {
                logger.warn("An error occurred while changing the job of " + user.getUniqueId() + "/" + user.getName() + "!");
                return false;
            }
        } else {
            ConfigurationNode accountConfig = accountManager.getAccountConfig();

            accountConfig.getNode(userUniqueId.toString(), "job").setValue(jobName);

            accountConfig.getNode(userUniqueId.toString(), "jobstats", jobName, "level").setValue(
                    accountConfig.getNode(userUniqueId.toString(), "jobstats", jobName, "level").getInt(1));

            accountConfig.getNode(userUniqueId.toString(), "jobstats", jobName, "exp").setValue(
                    accountConfig.getNode(userUniqueId.toString(), "jobstats", jobName, "exp").getInt(0));

            try {
                accountManager.getConfigManager().save(accountConfig);
            } catch (IOException e) {
                logger.warn("An error occurred while changing the job of " + user.getUniqueId() + "/" + user.getName() + "!");
            }

            return true;
        }

    }

    /**
     * Get a job set by name.
     *
     * @return Optional
     */
    public Optional<TEJobSet> getJobSet(String name) {
        return Optional.ofNullable(jobSets.getOrDefault(name, null));
    }

    /**
     * Get the user's current job as a String for output.
     *
     * @param user The user to get the job of
     * @return String the job the user currently has
     */
    public String getPlayerJob(User user) {
        UUID uuid = user.getUniqueId();

        if (databaseEnabled) {
            SqlQuery sqlQuery = SqlQuery.builder(sqlManager.dataSource)
                    .select("job")
                    .from("accounts")
                    .where("uid")
                    .equals(uuid.toString())
                    .build();

            return sqlQuery.getString("unemployed").toLowerCase();
        } else {
            ConfigurationNode accountConfig = accountManager.getAccountConfig();

            return accountConfig.getNode(user.getUniqueId().toString(), "job").getString("unemployed").toLowerCase();
        }
    }

    /**
     * Get a TEJob object by a job name.
     *
     * @param jobName Name of the job
     * @param tryUnemployed Whether or not to try returning the unemployed job when the job wasn't found
     * @return {@link TEJob} the job; {@code null} for not found
     */
    public Optional<TEJob> getJob(String jobName, boolean tryUnemployed) {
        TEJob job = jobsMap.getOrDefault(jobName, null);

        if (job != null || !tryUnemployed) {
            return Optional.ofNullable(job);
        }

        return getJob("unemployed", false);
    }

    /**
     * Get the players level for the passed in job.
     *
     * @param jobName The name of the job
     * @param user The user object
     * @return int The job level
     */
    public int getJobLevel(String jobName, User user) {
        UUID playerUniqueId = user.getUniqueId();

        // Just in case the job name was not passed in as lowercase, make it lowercase
        jobName = jobName.toLowerCase();

        if (!jobName.equals("unemployed")) {
            if (databaseEnabled) {
                SqlQuery sqlQuery = SqlQuery.builder(sqlManager.dataSource)
                        .select(jobName)
                        .from("levels")
                        .where("uid")
                        .equals(playerUniqueId.toString())
                        .build();

                return sqlQuery.getInt(1);
            } else {
                ConfigurationNode accountConfig = accountManager.getAccountConfig();

                return accountConfig.getNode(user.getUniqueId().toString(), "jobstats", jobName, "level").getInt(1);
            }
        }

        return 1;
    }

    /**
     * Get the players exp for the passed in job.
     *
     * @param jobName the name of the job
     * @param user the user object
     * @return int the job exp
     */
    public int getJobExp(String jobName, User user) {
        UUID playerUniqueId = user.getUniqueId();

        // Just in case the job name was not passed in as lowercase, make it lowercase
        jobName = jobName.toLowerCase();

        if (!jobName.equals("unemployed")) {
            if (databaseEnabled) {
                SqlQuery sqlQuery = SqlQuery.builder(sqlManager.dataSource)
                        .select(jobName)
                        .from("experience")
                        .where("uid")
                        .equals(playerUniqueId.toString())
                        .build();

                return sqlQuery.getInt(0);
            } else {
                ConfigurationNode accountConfig = accountManager.getAccountConfig();

                return accountConfig.getNode(playerUniqueId.toString(), "jobstats", jobName, "exp").getInt(0);
            }
        }

        return 0;
    }

    /**
     * Get the exp required to level.
     *
     * @param user user object
     * @return int the amount of exp needed to level
     */
    public int getExpToLevel(User user) {
        String jobName = getPlayerJob(user);
        int playerLevel = getJobLevel(jobName, user);

        int nextLevel = playerLevel + 1;
        int expToLevel = (int) ((Math.pow(nextLevel, 2) + nextLevel) / 2) * 100 - (nextLevel * 100);

        // TODO: Custom algorithm for this, set from config
        return expToLevel;
    }

    /**
     * Gets a comma separated string of all of the jobs currently in the jobs config.
     *
     * @return Text Comma separated string of jobs
     */
    public Text getJobList() {
        List<Text> texts = new ArrayList<>();

        jobsMap.forEach((jobName, jobObject) -> texts.add(Text.of(
                TextActions.runCommand("/job set " + jobName),
                TextActions.showText(Text.of("Click to change job")),
                jobName))
        );

        return Text.joinWith(Text.of(", "), texts.toArray(new Text[texts.size()]));
    }

    /**
     * Checks sign contents and converts it to a "Job Changing" sign if conditions are met.
     *
     * @param event ChangeSignEvent
     */
    @Listener
    public void onJobSignCheck(ChangeSignEvent event) {
        SignData data = event.getText();
        Text lineOne = data.lines().get(0);
        Text lineTwo = data.lines().get(1);
        String lineOnePlain = lineOne.toPlain();
        String lineTwoPlain = lineTwo.toPlain();

        if (lineOnePlain.equals("[TEJobs]")) {
            lineOne = lineOne.toBuilder().style(TextStyles.BOLD).color(TextColors.DARK_BLUE).build();

            String jobName = titleize(lineTwoPlain);
            if (jobExists(lineTwoPlain)) {
                lineTwo = Text.of(jobName).toBuilder().color(TextColors.BLACK).build();
            } else {
                lineTwo = Text.of(jobName).toBuilder().color(TextColors.RED).build();
            }

            data.set(data.lines().set(0, lineOne));
            data.set(data.lines().set(1, lineTwo));
            data.set(data.lines().set(2, Text.of()));
            data.set(data.lines().set(3, Text.of()));
        }
    }

    /**
     * Called when a player clicks a sign. If the clicked sign is a "Job Changing" sign then the player's job will
     * be changed on click.
     *
     * @param event InteractBlockEvent
     */
    @Listener
    public void onSignInteract(InteractBlockEvent.Secondary event) {
        if (event.getCause().first(Player.class).isPresent()) {
            Player player = event.getCause().first(Player.class).get();

            if (event.getTargetBlock().getLocation().isPresent()) {
                Optional<TileEntity> tileEntityOpt = event.getTargetBlock().getLocation().get().getTileEntity();

                if (tileEntityOpt.isPresent()) {
                    TileEntity tileEntity = tileEntityOpt.get();

                    if (tileEntity instanceof Sign) {
                        Sign sign = (Sign) tileEntity;
                        Optional<SignData> data = sign.getOrCreate(SignData.class);

                        if (data.isPresent()) {
                            SignData signData = data.get();
                            Text lineOneText = signData.lines().get(0);
                            Text lineTwoText = signData.lines().get(1);
                            String lineOne = lineOneText.toPlain();
                            String jobName = lineTwoText.toPlain().toLowerCase();

                            if (lineOne.equals("[TEJobs]")) {
                                Map<String, String> messageValues = new HashMap<>();
                                messageValues.put("job", titleize(jobName));

                                Optional<TEJob> optJob = getJob(jobName, false);

                                if (optJob.isPresent()) {
                                    Optional<JobBasedRequirement> optRequire = optJob.get().getRequirement();

                                    if (optRequire.isPresent()) {
                                        String reqJob = optRequire.get().getRequiredJob();
                                        Integer reqLevel = optRequire.get().getRequiredJobLevel();
                                        String reqPerm = optRequire.get().getRequiredPermission();

                                        int currentReqJobLevel = getJobLevel(reqJob, player);
                                        if (reqJob != null && reqLevel > currentReqJobLevel) {
                                            messageValues.put("job", titleize(reqJob));
                                            messageValues.put("level", reqLevel.toString());
                                            player.sendMessage(messageManager.getMessage("jobs.unmet.level", messageValues));
                                            return;
                                        }

                                        if (reqPerm != null && !player.hasPermission(reqPerm)) {
                                            player.sendMessage(messageManager.getMessage("jobs.unmet.permission", messageValues));
                                            return;
                                        }
                                    }

                                    if (setJob(player, jobName)) {
                                        player.sendMessage(messageManager.getMessage("jobs.sign", messageValues));
                                    } else {
                                        player.sendMessage(messageManager.getMessage("jobs.setfailed"));
                                    }
                                } else {
                                    player.sendMessage(messageManager.getMessage("jobs.notfound"));
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * Used for the break option in jobs. Will check if the job has the break node and if it does it will check if the
     * block that was broken is present in the config of the player's job. If it is, it will grab the job exp reward as
     * well as the pay.
     *
     * @param event ChangeBlockEvent.Break
     */
    @Listener
    public void onPlayerBlockBreak(ChangeBlockEvent.Break event) {
        if (event.getCause().first(Player.class).isPresent()) {
            Player player = event.getCause().first(Player.class).get();
            UUID playerUniqueId = player.getUniqueId();

            String playerJob = getPlayerJob(player);
            Optional<TEJob> optPlayerJob = getJob(playerJob, true);

            BlockState state = event.getTransactions().get(0).getOriginal().getState();
            String blockName = state.getType().getName();
            Optional<UUID> blockCreator = event.getTransactions().get(0).getOriginal().getCreator();

            // Enable admins to determine block information by displaying it to them - WHEN they have the flag enabled
            if (accountManager.getUserOption("totaleconomy:block-break-info", player).orElse("0").equals("1")) {
                List<BlockTrait<?>> traits = new ArrayList<>(state.getTraits());
                int count = traits.size();
                List<Text> traitTexts = new ArrayList<>(count);

                for (int i = 0; i < count; i++) {
                    Object traitValue = state.getTraitValue(traits.get(i)).orElse(null);
                    traitTexts.add(i, Text.of(traits.get(i).getName(), '=', traitValue != null ? traitValue.toString() : "null"));
                }

                Text t = Text.of(TextColors.GRAY, "TRAITS:\n    ", Text.joinWith(Text.of(",\n    "), traitTexts.toArray(new Text[traits.size()])));
                player.sendMessage(Text.of("Block-Name: ", blockName));
                player.sendMessage(t);
            }

            if (optPlayerJob.isPresent()) {
                Optional<TEActionReward> reward = Optional.empty();
                List<String> sets = optPlayerJob.get().getSets();

                for (String s : sets) {
                    Optional<TEJobSet> optSet = getJobSet(s);
                    if (!optSet.isPresent()) {
                        logger.warn("Job " + playerJob + " has the nonexistent set \"" + s + "\"");
                        continue;
                    }

                    Optional<TEAction> action = optSet.get().getActionFor("break", blockName);
                    if (!action.isPresent()) {
                        continue;
                    }

                    Optional<TEActionReward> currentReward = action.get().evaluateBreak(logger, state, blockCreator.orElse(null));
                    if (!reward.isPresent()) {
                        reward = currentReward;
                        continue;
                    }

                    if (!currentReward.isPresent()) {
                        continue;
                    }

                    // Use the one giving higher exp in case of duplicates
                    if (currentReward.get().getExpReward() > reward.get().getExpReward()) {
                        reward = currentReward;
                    }
                }

                if (reward.isPresent()) {
                    BigDecimal payAmount = new BigDecimal(reward.get().getMoneyReward());
                    Currency currency = totalEconomy.getDefaultCurrency();

                    if (reward.get().getCurrencyId() != null) {
                        Optional<Currency> currencyOpt = totalEconomy.getTECurrencyRegistryModule().getById("totaleconomy:" + reward.get().getCurrencyId());
                        if (currencyOpt.isPresent()) {
                            currency = currencyOpt.get();
                        }
                    }

                    boolean notify = getNotificationState(playerUniqueId);
                    if (notify) {
                        notifyPlayerOfJobReward(player, payAmount, currency);
                    }

                    TEAccount playerAccount = (TEAccount) accountManager.getOrCreateAccount(player.getUniqueId()).get();
                    playerAccount.deposit(currency, payAmount, event.getCause());

                    int expAmount = reward.get().getExpReward();
                    addExp(player, expAmount);
                    checkForLevel(player);
                }
            }
        }
    }

    /**
     * Used for the place option in jobs. Will check if the job has the place node and if it does it will check if the
     * block that was placed is present in the config of the player's job. If it is, it will grab the job exp reward as
     * well as the pay.
     *
     * @param event ChangeBlockEvent.Place
     */
    @Listener
    public void onPlayerPlaceBlock(ChangeBlockEvent.Place event) {
        if (event.getCause().first(Player.class).isPresent()) {
            Player player = event.getCause().first(Player.class).get();
            UUID playerUniqueId = player.getUniqueId();

            String playerJob = getPlayerJob(player);
            Optional<TEJob> optPlayerJob = getJob(playerJob, true);

            BlockState state = event.getTransactions().get(0).getFinal().getState();
            String blockName = state.getType().getName();

            // Enable admins to determine block information by displaying it to them - WHEN they have the flag enabled
            if (accountManager.getUserOption("totaleconomy:block-place-info", player).orElse("0").equals("1")) {
                List<BlockTrait<?>> traits = new ArrayList<>(state.getTraits());
                int count = traits.size();
                List<Text> traitTexts = new ArrayList<>(count);

                for (int i = 0; i < count; i++) {
                    Object traitValue = state.getTraitValue(traits.get(i)).orElse(null);
                    traitTexts.add(i, Text.of(traits.get(i).getName(), '=', traitValue != null ? traitValue.toString() : "null"));
                }

                Text t = Text.of(TextColors.GRAY, "TRAITS:\n    ", Text.joinWith(Text.of(",\n    "), traitTexts.toArray(new Text[traits.size()])));
                player.sendMessage(Text.of("Block-Name: ", blockName));
                player.sendMessage(t);
            }

            if (optPlayerJob.isPresent()) {
                Optional<TEActionReward> reward = Optional.empty();
                List<String> sets = optPlayerJob.get().getSets();

                for (String s : sets) {
                    Optional<TEJobSet> optSet = getJobSet(s);
                    if (!optSet.isPresent()) {
                        logger.warn("Job " + playerJob + " has the nonexistent set \"" + s + "\"");
                        continue;
                    }

                    Optional<TEAction> action = optSet.get().getActionFor("place", blockName);
                    if (!action.isPresent()) {
                        continue;
                    }

                    Optional<TEActionReward> currentReward = action.get().evaluatePlace(logger, state);
                    if (!reward.isPresent()) {
                        reward = currentReward;
                        continue;
                    }

                    if (!currentReward.isPresent()) {
                        continue;
                    }

                    // Use the one giving higher exp in case of duplicates
                    if (currentReward.get().getExpReward() > reward.get().getExpReward()) {
                        reward = currentReward;
                    }
                }

                if (reward.isPresent()) {
                    boolean notify = getNotificationState(playerUniqueId);
                    BigDecimal payAmount = new BigDecimal(reward.get().getMoneyReward());
                    Currency currency = totalEconomy.getDefaultCurrency();

                    if (reward.get().getCurrencyId() != null) {
                        Optional<Currency> currencyOpt = totalEconomy.getTECurrencyRegistryModule().getById("totaleconomy:" + reward.get().getCurrencyId());
                        if (currencyOpt.isPresent()) {
                            currency = currencyOpt.get();
                        }
                    }

                    if (notify) {
                        notifyPlayerOfJobReward(player, payAmount, currency);
                    }

                    TEAccount playerAccount = (TEAccount) accountManager.getOrCreateAccount(player.getUniqueId()).get();
                    playerAccount.deposit(currency, payAmount, event.getCause());

                    int expAmount = reward.get().getExpReward();
                    addExp(player, expAmount);

                    checkForLevel(player);
                }
            }
        }
    }

    /**
     * Used for the break option in jobs. Will check if the job has the break node and if it does it will check if the
     * block that was broken is present in the config of the player's job. If it is, it will grab the job exp reward as
     * well as the pay.
     *
     * @param event DestructEntityEvent.Death
     */
    @Listener
    public void onPlayerKillEntity(DestructEntityEvent.Death event) {
        Optional<EntityDamageSource> optDamageSource = event.getCause().first(EntityDamageSource.class);

        if (optDamageSource.isPresent()) {
            EntityDamageSource damageSource = optDamageSource.get();
            Entity killer = damageSource.getSource();
            Entity victim = event.getTargetEntity();

            if (!(killer instanceof Player)) {
                // If a projectile was shot to kill an entity, this will grab the player who shot it
                Optional<UUID> damageCreator = damageSource.getSource().getCreator();

                if (damageCreator.isPresent()) {
                    killer = Sponge.getServer().getPlayer(damageCreator.get()).get();
                }
            }

            if (killer instanceof Player) {
                Player player = (Player) killer;
                UUID playerUniqueId = player.getUniqueId();
                String victimName = victim.getType().getName();

                String playerJob = getPlayerJob(player);
                Optional<TEJob> optPlayerJob = getJob(playerJob, true);

                // Enable admins to determine victim information by displaying it to them - WHEN they have the flag enabled
                if (accountManager.getUserOption("totaleconomy:entity-kill-info", player).orElse("0").equals("1")) {
                    player.sendMessage(Text.of("Victim-Name: ", victimName));
                }

                if (optPlayerJob.isPresent()) {
                    Optional<TEActionReward> reward = Optional.empty();
                    List<String> sets = optPlayerJob.get().getSets();

                    for (String s : sets) {
                        Optional<TEJobSet> optSet = getJobSet(s);
                        if (!optSet.isPresent()) {
                            logger.warn("Job " + playerJob + " has the nonexistent set \"" + s + "\"");
                            continue;
                        }

                        Optional<TEAction> action = optSet.get().getActionFor("kill", victimName);
                        if (!action.isPresent()) {
                            continue;
                        }

                        Optional<TEActionReward> currentReward = action.get().getReward();
                        if (!reward.isPresent()) {
                            reward = currentReward;
                            continue;
                        }

                        if (!currentReward.isPresent()) {
                            continue;
                        }

                        // Use the one giving higher exp in case of duplicates
                        if (currentReward.get().getExpReward() > reward.get().getExpReward()) {
                            reward = currentReward;
                        }
                    }

                    if (reward.isPresent()) {
                        boolean notify = getNotificationState(playerUniqueId);
                        BigDecimal payAmount = new BigDecimal(reward.get().getMoneyReward());
                        Currency currency = totalEconomy.getDefaultCurrency();

                        if (reward.get().getCurrencyId() != null) {
                            Optional<Currency> currencyOpt = totalEconomy.getTECurrencyRegistryModule().getById("totaleconomy:" + reward.get().getCurrencyId());
                            if (currencyOpt.isPresent()) {
                                currency = currencyOpt.get();
                            }
                        }

                        if (notify) {
                            notifyPlayerOfJobReward(player, payAmount, currency);
                        }

                        TEAccount playerAccount = (TEAccount) accountManager.getOrCreateAccount(player.getUniqueId()).get();
                        playerAccount.deposit(currency, payAmount, event.getCause());

                        int expAmount = reward.get().getExpReward();
                        addExp(player, expAmount);

                        checkForLevel(player);
                    }
                }
            }
        }
    }

    /**
     * Used for the catch option in jobs. Will check if the job has the catch node and if it does it will check if the
     * item that was caught is present in the config of the player's job. If it is, it will grab the job exp reward as
     * well as the pay.
     *
     * @param event FishingEvent.Stop
     */
    @Listener
    public void onPlayerFish(FishingEvent.Stop event) {
        if (event.getCause().first(Player.class).isPresent()) {
            // No transaction, so execution can stop
            if (event.getTransactions().size() == 0) {
                return;
            }

            Transaction<ItemStackSnapshot> itemTransaction = event.getTransactions().get(0);
            ItemStack itemStack = itemTransaction.getFinal().createStack();
            Player player = event.getCause().first(Player.class).get();
            UUID playerUniqueId = player.getUniqueId();

            String playerJob = getPlayerJob(player);
            Optional<TEJob> optPlayerJob = getJob(playerJob, true);

            if (optPlayerJob.isPresent()) {
                if (itemStack.get(FishData.class).isPresent()) {
                    FishData fishData = itemStack.get(FishData.class).get();
                    String fishName = fishData.type().get().getName();

                    // Enable admins to determine fish information by displaying it to them - WHEN they have the flag enabled
                    if (accountManager.getUserOption("totaleconomy:entity-fish-info", player).orElse("0").equals("1")) {
                        player.sendMessage(Text.of("Fish-Name: ", fishName));
                    }

                    Optional<TEActionReward> reward = Optional.empty();
                    List<String> sets = optPlayerJob.get().getSets();

                    for (String s : sets) {
                        Optional<TEJobSet> optSet = getJobSet(s);

                        if (!optSet.isPresent()) {
                            logger.warn("Job " + playerJob + " has the nonexistent set \"" + s + "\"");
                            continue;
                        }

                        Optional<TEAction> action = optSet.get().getActionFor("catch", fishName);
                        if (!action.isPresent()) {
                            continue;
                        }

                        Optional<TEActionReward> currentReward = action.get().getReward();
                        if (!reward.isPresent()) {
                            reward = currentReward;
                            continue;
                        }

                        if (!currentReward.isPresent()) {
                            continue;
                        }

                        // Use the one giving higher exp in case of duplicates
                        if (currentReward.get().getExpReward() > reward.get().getExpReward()) {
                            reward = currentReward;
                        }
                    }

                    if (reward.isPresent()) {
                        boolean notify = getNotificationState(playerUniqueId);
                        BigDecimal payAmount = new BigDecimal(reward.get().getMoneyReward());
                        Currency currency = totalEconomy.getDefaultCurrency();

                        if (reward.get().getCurrencyId() != null) {
                            Optional<Currency> currencyOpt = totalEconomy.getTECurrencyRegistryModule().getById("totaleconomy:" + reward.get().getCurrencyId());
                            if (currencyOpt.isPresent()) {
                                currency = currencyOpt.get();
                            }
                        }

                        if (notify) {
                            notifyPlayerOfJobReward(player, payAmount, currency);
                        }

                        TEAccount playerAccount = (TEAccount) accountManager.getOrCreateAccount(player.getUniqueId()).get();
                        playerAccount.deposit(currency, payAmount, event.getCause());

                        int expAmount = reward.get().getExpReward();
                        addExp(player, expAmount);

                        checkForLevel(player);
                    }
                }
            }
        }
    }
}


text:
package omnitool::tool::standard_delete;
# Acts as a tool.pm sub-class, providing the standard and very basic delete function.
# Will only delete data which does not have any 'living' children, and presents a modal
# to confirm the delete before proceeding.
#
# Most tool.pm sub-classes will live within an Application's Perl Modules directory, but this
# is a core feature of OmniTool and will available as a tool.pm class for any Application/Tool.
#
# When using this for your tools, make the 'uri_path_base' be 'delete' and be sure the Tool Typre
# is set to 'Action - Modal' Note that

$omnitool::tool::standard_delete::VERSION = '6.0';

# make sure it's a sub-class of tool.pm, just like if it were in the application app code directory
use parent 'omnitool::tool';

# time to grow up, old man
use strict;

# we shall do everything in the perform_action() method
sub prepare_message {
	my $self = shift;

	my ($num);

	if ($self->{omniclass_object}->{data}{name} eq 'Not Named') { # does not use name, so substitute datatype name
		$self->{omniclass_object}->{data}{name} = 'This '.$self->{omniclass_object}{datatype_info}{name};
	}

	# first step:  do not allow them to proceed if this record has living children
	if ($self->{omniclass_object}->{data}{metainfo}{children}) {
		# how many children?  will be number of commas plus one
		$num = $self->{omniclass_object}->{data}{metainfo}{children} =~ tr/,//;
		$num++;

		$self->{json_results}{error_title} = 'ERROR: Unable to Delete Record';
		$self->{json_results}{error_message} = "You are unable to delete '".$self->{omniclass_object}->{data}{name}.
			"' at this time because it contains $num subordinate records.";

	# have they confirmed delete?
	} elsif (!$self->{luggage}{params}{confirm}) {

		$self->{json_results}{title} = 'Please Confirm Deletion';
		$self->{json_results}{message} = "Are you sure you wish to delete '".$self->{omniclass_object}->{data}{name}."'?";

		# confirmation button is handled in the jemplate
		$self->{json_results}{confirm_button_text} = 'Confirm';
		$self->{json_results}{confirm_button_uri} = $self->{my_json_uri}.'?confirm=1';

		# no 'close' button in the modal
		$self->{json_results}{no_close_button} = 1;

	} elsif ($self->{luggage}{params}{confirm}) {
		$self->{json_results}{title} = $self->{omniclass_object}->{datatype_info}{name}.' Record Deleted';
		$self->{json_results}{message} = "You have successfully deleted '".$self->{omniclass_object}->{data}{name}."'.";
		# prevent gritter popup
		$self->{json_results}{no_gritter} = 1;

		# actually delete it
		$self->{omniclass_object}->delete(
			'data_code' => $self->{omniclass_object}->{data_code}
		);
	}

}

1;

redpajama_set_name: RedPajamaGithub


text:
angular.module('app').controller("ShipmentController",
  ['$location', '$scope', 'Restangular', 'AuthService',
  function ($location, $scope, Restangular, AuthService){
    if(!AuthService.isLoggedIn()){
      AuthService.setPageTryingToAccess();
      return $location.path('/sign_in');
    }

    // $scope.locations = Restangular.all('locations').getList().$object;
  }
]);


text:
package com.ewolff.user_registration.domain;

public class User {

	private String name;

	private String firstname;

	private String email;

	public void setName(String name) {
		this.name = name;
	}

	public void setFirstname(String firstname) {
		this.firstname = firstname;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public User() {
	}

	public User(String firstname, String name, String email) {
		super();
		this.firstname = firstname;
		this.name = name;
		this.email = email;
	}

	public String getName() {
		return name;
	}

	public String getFirstname() {
		return firstname;
	}

	public String getEmail() {
		return email;
	}

}


text:
include("cl_awards.lua")

local table = table
local string = string
local vgui = vgui
local pairs = pairs

CLSCORE = {}
CLSCORE.Events = {}
CLSCORE.Scores = {}
CLSCORE.TraitorIDs = {}
CLSCORE.DetectiveIDs = {}
CLSCORE.Players = {}
CLSCORE.StartTime = 0
CLSCORE.Panel = nil

CLSCORE.EventDisplay = {}

local skull_icon = Material("HUD/killicons/default")

surface.CreateFont("WinHuge", {font = "Trebuchet24",
                               size = 72,
                               weight = 1000,
                               shadow = true})

-- so much text here I'm using shorter names than usual
local T = LANG.GetTranslation
local PT = LANG.GetParamTranslation

function CLSCORE:GetDisplay(key, event)
   local displayfns = self.EventDisplay[event.id]
   if not displayfns then return end
   local keyfn = displayfns[key]
   if not keyfn then return end

   return keyfn(event)
end

function CLSCORE:TextForEvent(e)
   return self:GetDisplay("text", e)
end

function CLSCORE:IconForEvent(e)
   return self:GetDisplay("icon", e)
end

function CLSCORE:TimeForEvent(e)
   local t = e.t - self.StartTime
   if t >= 0 then
      return util.SimpleTime(t, "%02i:%02i")
   else
      return "     "
   end
end

-- Tell CLSCORE how to display an event. See cl_scoring_events for examples.
-- Pass an empty table to keep an event from showing up.
function CLSCORE.DeclareEventDisplay(event_id, event_fns)
   -- basic input vetting, can't check returned value types because the
   -- functions may be impure
   if not tonumber(event_id) then
      Error("Event ??? display: invalid event id\n")
   end
   if (not event_fns) or type(event_fns) != "table" then
      Error(Format("Event %d display: no display functions found.\n", event_id))
   end
   if not event_fns.text then
      Error(Format("Event %d display: no text display function found.\n", event_id))
   end
   if not event_fns.icon then
      Error(Format("Event %d display: no icon and tooltip display function found.\n", event_id))
   end

   CLSCORE.EventDisplay[event_id] = event_fns
end

function CLSCORE:FillDList(dlst)

   for k, e in pairs(self.Events) do

      local etxt = self:TextForEvent(e)
      local eicon, ttip = self:IconForEvent(e)
      local etime = self:TimeForEvent(e)

      if etxt then
         if eicon then
            local mat = eicon
            eicon = vgui.Create("DImage")
            eicon:SetMaterial(mat)
            eicon:SetTooltip(ttip)
            eicon:SetKeepAspect(true)
            eicon:SizeToContents()
         end

         dlst:AddLine(etime, eicon, "  " .. etxt)
      end
   end
end

function CLSCORE:BuildEventLogPanel(dpanel)
   local margin = 10

   local w, h = dpanel:GetSize()

   local dlist = vgui.Create("DListView", dpanel)
   dlist:SetPos(0, 0)
   dlist:SetSize(w, h - margin*2)
   dlist:SetSortable(true)
   dlist:SetMultiSelect(false)

   local timecol = dlist:AddColumn(T("col_time"))
   local iconcol = dlist:AddColumn("")
   local eventcol = dlist:AddColumn(T("col_event"))

   iconcol:SetFixedWidth(16)
   timecol:SetFixedWidth(40)

   -- If sortable is off, no background is drawn for the headers which looks
   -- terrible. So enable it, but disable the actual use of sorting.
   iconcol.Header:SetDisabled(true)
   timecol.Header:SetDisabled(true)
   eventcol.Header:SetDisabled(true)

   self:FillDList(dlist)
end

function CLSCORE:BuildScorePanel(dpanel)
   local margin = 10
   local w, h = dpanel:GetSize()

   local dlist = vgui.Create("DListView", dpanel)
   dlist:SetPos(0, 0)
   dlist:SetSize(w, h)
   dlist:SetSortable(true)
   dlist:SetMultiSelect(false)
   dlist:SetPaintBackground(false)

   local colnames = {"", "col_player", "col_role", "col_kills1", "col_kills2", "col_points", "col_team", "col_total"}
   for k, name in pairs(colnames) do
      if name == "" then
         -- skull icon column
         local c = dlist:AddColumn("")
         c:SetFixedWidth(18)
      else
         dlist:AddColumn(T(name))
      end
   end

   -- the type of win condition triggered is relevant for team bonus
   local wintype = WIN_NONE
   for i=#self.Events, 1, -1 do
      local e = self.Events[i]
      if e.id == EVENT_FINISH then
         wintype = e.win
         break
      end
   end

   local scores = self.Scores
   local nicks = self.Players
   local bonus = ScoreTeamBonus(scores, wintype)

   for id, s in pairs(scores) do
      if id != -1 then
         local was_traitor = s.was_traitor
         local role = was_traitor and T("traitor") or (s.was_detective and T("detective") or "")

         local surv = ""
         if s.deaths > 0 then
            surv = vgui.Create("ColoredBox", dlist)
            surv:SetColor(Color(150, 50, 50))
            surv:SetBorder(false)
            surv:SetSize(18,18)

            local skull = vgui.Create("DImage", surv)
            skull:SetMaterial(skull_icon)
            skull:SetTooltip("Dead")
            skull:SetKeepAspect(true)
            skull:SetSize(18,18)
         end

         local points_own   = KillsToPoints(s, was_traitor)
         local points_team  = (was_traitor and bonus.traitors or bonus.innos)
         local points_total = points_own + points_team

         local l = dlist:AddLine(surv, nicks[id], role, s.innos, s.traitors, points_own, points_team, points_total)

         -- center align
         for k, col in pairs(l.Columns) do
            col:SetContentAlignment(5)
         end

         -- when sorting on the column showing survival, we would get an error
         -- because images can't be sorted, so instead hack in a dummy value
         local surv_col = l.Columns[1]
         if surv_col then
            surv_col.Value = type(surv_col.Value) == "Panel" and "1" or "0"
         end
      end
   end

   dlist:SortByColumn(6)
end

function CLSCORE:AddAward(y, pw, award, dpanel)
   local nick = award.nick
   local text = award.text
   local title = string.upper(award.title)

   local titlelbl = vgui.Create("DLabel", dpanel)
   titlelbl:SetText(title)
   titlelbl:SetFont("TabLarge")
   titlelbl:SizeToContents()
   local tiw, tih = titlelbl:GetSize()

   local nicklbl = vgui.Create("DLabel", dpanel)
   nicklbl:SetText(nick)
   nicklbl:SetFont("DermaDefaultBold")
   nicklbl:SizeToContents()
   local nw, nh = nicklbl:GetSize()

   local txtlbl = vgui.Create("DLabel", dpanel)
   txtlbl:SetText(text)
   txtlbl:SetFont("DermaDefault")
   txtlbl:SizeToContents()
   local tw, th = txtlbl:GetSize()

   titlelbl:SetPos((pw - tiw) / 2, y)
   y = y + tih + 2

   local fw = nw + tw + 5
   local fx = ((pw - fw) / 2)
   nicklbl:SetPos(fx, y)
   txtlbl:SetPos(fx + nw + 5, y)

   y = y + nh

   return y
end

-- double check that we have no nils
local function ValidAward(a)
   return a and a.nick and a.text and a.title and a.priority
end

local wintitle = {
   [WIN_TRAITOR] = {txt = "hilite_win_traitors", c = Color(190, 5, 5, 255)},
   [WIN_INNOCENT] = {txt = "hilite_win_innocent", c = Color(5, 190, 5, 255)}
}

function CLSCORE:BuildHilitePanel(dpanel)
   local w, h = dpanel:GetSize()

   local title = wintitle[WIN_INNOCENT]
   local endtime = self.StartTime
   for i=#self.Events, 1, -1 do
      local e = self.Events[i]
      if e.id == EVENT_FINISH then
         endtime = e.t

         -- when win is due to timeout, innocents win
         local wintype = e.win
         if wintype == WIN_TIMELIMIT then wintype = WIN_INNOCENT end

         title = wintitle[wintype]
         break
      end
   end

   local roundtime = endtime - self.StartTime

   local numply = table.Count(self.Players)
   local numtr = table.Count(self.TraitorIDs)

   local bg = vgui.Create("ColoredBox", dpanel)
   bg:SetColor(Color(50, 50, 50, 255))
   bg:SetSize(w,h)
   bg:SetPos(0,0)

   local winlbl = vgui.Create("DLabel", dpanel)
   winlbl:SetFont("WinHuge")
   winlbl:SetText( T(title.txt) )
   winlbl:SetTextColor(COLOR_WHITE)
   winlbl:SizeToContents()
   local xwin = (w - winlbl:GetWide())/2
   local ywin = 30
   winlbl:SetPos(xwin, ywin)

   bg.PaintOver = function()
                     draw.RoundedBox(8, xwin - 15, ywin - 5, winlbl:GetWide() + 30, winlbl:GetTall() + 10, title.c)
                  end

   local ysubwin = ywin + winlbl:GetTall()
   local partlbl = vgui.Create("DLabel", dpanel)

   local plytxt = PT(numtr == 1 and "hilite_players2" or "hilite_players1",
                     {numplayers = numply, numtraitors = numtr})

   partlbl:SetText(plytxt)
   partlbl:SizeToContents()
   partlbl:SetPos(xwin, ysubwin + 8)

   local timelbl = vgui.Create("DLabel", dpanel)
   timelbl:SetText(PT("hilite_duration", {time= util.SimpleTime(roundtime, "%02i:%02i")}))
   timelbl:SizeToContents()
   timelbl:SetPos(xwin + winlbl:GetWide() - timelbl:GetWide(), ysubwin + 8)

   -- Awards
   local wa = math.Round(w * 0.9)
   local ha = h - ysubwin - 40
   local xa = (w - wa) / 2
   local ya = h - ha

   local awardp = vgui.Create("DPanel", dpanel)
   awardp:SetSize(wa, ha)
   awardp:SetPos(xa, ya)
   awardp:SetPaintBackground(false)

   -- Before we pick awards, seed the rng in a way that is the same on all
   -- clients. We can do this using the round start time. To make it a bit more
   -- random, involve the round's duration too.
   math.randomseed(self.StartTime + endtime)

   -- Attempt to generate every award, then sort the succeeded ones based on
   -- priority/interestingness
   local award_choices = {}
   for k, afn in pairs(AWARDS) do
      local a = afn(self.Events, self.Scores, self.Players, self.TraitorIDs, self.DetectiveIDs)
      if ValidAward(a) then
         table.insert(award_choices, a)
      end
   end

   local num_choices = table.Count(award_choices)
   local max_awards = 5

   -- sort descending by priority
   table.SortByMember(award_choices, "priority")

   -- put the N most interesting awards in the menu
   for i=1,max_awards do
      local a = award_choices[i]
      if a then
         self:AddAward((i - 1) * 42, wa, a, awardp)
      end
   end
end

function CLSCORE:ShowPanel()
   local margin = 15

   local dpanel = vgui.Create("DFrame")
   local w, h = 700, 500
   dpanel:SetSize(700, 500)
   dpanel:Center()
   dpanel:SetTitle(T("report_title"))
   dpanel:SetVisible(true)
   dpanel:ShowCloseButton(true)
   dpanel:SetMouseInputEnabled(true)
   dpanel:SetKeyboardInputEnabled(true)
   dpanel.OnKeyCodePressed = util.BasicKeyHandler

   -- keep it around so we can reopen easily
   dpanel:SetDeleteOnClose(false)
   self.Panel = dpanel

   local dbut = vgui.Create("DButton", dpanel)
   local bw, bh = 100, 25
   dbut:SetSize(bw, bh)
   dbut:SetPos(w - bw - margin, h - bh - margin/2)
   dbut:SetText(T("close"))
   dbut.DoClick = function() dpanel:Close() end

   local dsave = vgui.Create("DButton", dpanel)
   dsave:SetSize(bw,bh)
   dsave:SetPos(margin, h - bh - margin/2)
   dsave:SetText(T("report_save"))
   dsave:SetTooltip(T("report_save_tip"))
   dsave:SetConsoleCommand("ttt_save_events")

   local dtabsheet = vgui.Create("DPropertySheet", dpanel)
   dtabsheet:SetPos(margin, margin + 15)
   dtabsheet:SetSize(w - margin*2, h - margin*3 - bh)
   local padding = dtabsheet:GetPadding()

   -- Highlight tab
   local dtabhilite = vgui.Create("DPanel", dtabsheet)
   dtabhilite:SetPaintBackground(false)
   dtabhilite:StretchToParent(padding,padding,padding,padding)
   self:BuildHilitePanel(dtabhilite)

   dtabsheet:AddSheet(T("report_tab_hilite"), dtabhilite, "icon16/star.png", false, false, T("report_tab_hilite_tip"))

   -- Event log tab
   local dtabevents = vgui.Create("DPanel", dtabsheet)
--   dtab1:SetSize(650, 450)
   dtabevents:StretchToParent(padding, padding, padding, padding)
   self:BuildEventLogPanel(dtabevents)

   dtabsheet:AddSheet(T("report_tab_events"), dtabevents, "icon16/application_view_detail.png", false, false, T("report_tab_events_tip"))

   -- Score tab
   local dtabscores = vgui.Create("DPanel", dtabsheet)
   dtabscores:SetPaintBackground(false)
   dtabscores:StretchToParent(padding, padding, padding, padding)
   self:BuildScorePanel(dtabscores)

   dtabsheet:AddSheet(T("report_tab_scores"), dtabscores, "icon16/user.png", false, false, T("report_tab_scores_tip"))

   dpanel:MakePopup()

   -- makepopup grabs keyboard, whereas we only need mouse
   dpanel:SetKeyboardInputEnabled(false)
end

function CLSCORE:ClearPanel()

   if self.Panel then
      -- move the mouse off any tooltips and then remove the panel next tick

      -- we need this hack as opposed to just calling Remove because gmod does
      -- not offer a means of killing the tooltip, and doesn't clean it up
      -- properly on Remove
      input.SetCursorPos( ScrW()/2, ScrH()/2 )
      local pnl = self.Panel
      timer.Simple(0, function() pnl:Remove() end)
   end
end

function CLSCORE:SaveLog()
   if self.Events and #self.Events <= 0 then
      chat.AddText(COLOR_WHITE, T("report_save_error"))
      return
   end

   local logdir = "ttt/logs"
   if not file.IsDir(logdir, "DATA") then
      file.CreateDir(logdir)
   end

   local logname = logdir .. "/ttt_events_" .. os.time() .. ".txt"
   local log = "Trouble in Terrorist Town - Round Events Log\n".. string.rep("-", 50) .."\n"

   log = log .. string.format("%s | %-25s | %s\n", " TIME", "TYPE", "WHAT HAPPENED") .. string.rep("-", 50) .."\n"

   for _, e in pairs(self.Events) do
      local etxt = self:TextForEvent(e)
      local etime = self:TimeForEvent(e)
      local _, etype = self:IconForEvent(e)
      if etxt then
         log = log .. string.format("%s | %-25s | %s\n", etime, etype, etxt)
      end
   end

   file.Write(logname, log)

   chat.AddText(COLOR_WHITE, T("report_save_result"), COLOR_GREEN, " /garrysmod/data/" .. logname)
end

function CLSCORE:Reset()
   self.Events = {}
   --self.StoredEvents = nil
   self.TraitorIDs = {}
   self.DetectiveIDs = {}
   self.Scores = {}
   self.Players = {}
   self.RoundStarted = 0

   self:ClearPanel()
end

function CLSCORE:Init(events)
   -- Get start time and traitors
   local starttime = nil
   local traitors = nil
   local detectives = nil
   for k, e in pairs(events) do
      if e.id == EVENT_GAME and e.state == ROUND_ACTIVE then
         starttime = e.t
      elseif e.id == EVENT_SELECTED then
         traitors = e.traitor_ids
         detectives = e.detective_ids
      end

      if starttime and traitors then
         break
      end
   end

   -- Get scores and players
   local scores = {}
   local nicks = {}
   for k, e in pairs(events) do
      if e.id == EVENT_SPAWN then
         scores[e.sid] = ScoreInit()
         nicks[e.sid] = e.ni
      end
   end

   scores = ScoreEventLog(events, scores, traitors, detectives)

   self.Players = nicks
   self.Scores = scores
   self.TraitorIDs = traitors
   self.DetectiveIDs = detectives
   self.StartTime = starttime
   self.Events = events
end

function CLSCORE:ReportEvents(events)
   self:Reset()

   self:Init(events)
   self:ShowPanel()
end

function CLSCORE:Reopen()
   if self.Panel and self.Panel:IsValid() and not self.Panel:IsVisible() then
      self.Panel:SetVisible(true)
   end
end

local buff = ""
local function ReceiveReportStream(len)
   local cont = net.ReadBit() == 1

   buff = buff .. net.ReadString()

   if cont then
      return
   else
      -- do stuff with buffer contents

      local json_events = buff -- util.Decompress(buff)
      if not json_events then
         ErrorNoHalt("Round report decompression failed!\n")
      else
         -- convert the json string back to a table
         local events = util.JSONToTable(json_events)

         if istable(events) then
            CLSCORE:ReportEvents(events)
         else
            ErrorNoHalt("Round report event decoding failed!\n")
         end
      end

      -- flush
      buff = ""
   end
end
net.Receive("TTT_ReportStream", ReceiveReportStream)

local function SaveLog(ply, cmd, args)
   CLSCORE:SaveLog()
end
concommand.Add("ttt_save_events", SaveLog)


text:
package rs.in.zivanovic.app.rest.dto;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 */
@XmlRootElement(name = "error")
@XmlAccessorType(XmlAccessType.FIELD)
public class Error {

    public Error(String detail, String sourcePointer) {
        this.detail = detail;
        this.source = new Source(sourcePointer);
    }

    public String detail;
    public Source source;

    @XmlRootElement(name = "source")
    @XmlAccessorType(XmlAccessType.FIELD)
    public static class Source {

        public Source(String pointer) {
            this.pointer = pointer;
        }
        public String pointer;

    }
}


text:
using CraftingGame.Physics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Terrain;

namespace CraftingGame.Items
{
    public abstract class StackableItemBase : ItemBase
    {
        public abstract bool Consumable { get; }
        public abstract bool Placable { get; }

        public virtual TerrainType PlacableTerrainType => TerrainType.NotGenerated;

        public virtual void Consume(PlayerObject player)
        {
        }
    }
}


text:
package com.dassmeta.passport.core.service;

public abstract interface CertificationService {
	// public abstract UserDetailServiceResponse loadUserDetail(String paramString1, String paramString2);
}


text:
package com.eharmony.aloha.models.vw.jni.multilabel

import java.io.File

import com.eharmony.aloha.audit.impl.OptionAuditor
import com.eharmony.aloha.audit.impl.tree.{RootedTree, RootedTreeAuditor}
import com.eharmony.aloha.dataset.vw.multilabel.VwMultilabelRowCreator
import com.eharmony.aloha.dataset.vw.multilabel.VwMultilabelRowCreator.LabelNamespaces
import com.eharmony.aloha.dataset.vw.multilabel.json.VwMultilabeledJson
import com.eharmony.aloha.factory.ModelFactory
import com.eharmony.aloha.id.ModelId
import com.eharmony.aloha.io.StringReadable
import com.eharmony.aloha.io.sources.{ExternalSource, ModelSource}
import com.eharmony.aloha.io.vfs.Vfs
import com.eharmony.aloha.models.Model
import com.eharmony.aloha.models.multilabel.MultilabelModel
import com.eharmony.aloha.semantics.compiled.CompiledSemanticsInstances
import com.eharmony.aloha.semantics.func.GenFunc0
import org.apache.commons.vfs2.VFS
import org.junit.Assert._
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.BlockJUnit4ClassRunner
import spray.json.DefaultJsonProtocol.{IntJsonFormat, StringJsonFormat}
import spray.json.{DefaultJsonProtocol, JsonWriter, RootJsonFormat, pimpString}
import vowpalWabbit.learner.{VWActionScoresLearner, VWLearners}

import scala.annotation.tailrec
import scala.collection.breakOut
import scala.util.Random

/**
  * Created by ryan.deak on 9/11/17.
  */
@RunWith(classOf[BlockJUnit4ClassRunner])
class VwMultilabelModelTest {
  import VwMultilabelModelTest._

  @Test def testTrainedModelWorks(): Unit = {
    val model = Model

    try {
      // Test the no label case.
      testEmpty(model(""))

      // Test all elements of the power set of labels (except the empty set, done above).
      for {
        labels <- powerSet(AllLabels.toSet).filter(ls => ls.nonEmpty)
        x       = labels.mkString(",")
        y       = model(x)
      } testOutput(y, labels, ExpectedMarginalDist)
    }
    finally {
      model.close()
    }
  }

  @Test def testTrainedModelCanBeParsedAndUsed(): Unit =
    testModel(None)

  @Test def testTrainedModelCanBeParsedAndUsedWithLabels67(): Unit =
    testModel(Option(Set(LabelSix, LabelSeven)))

  @Test def testTrainedModelCanBeParsedAndUsedWithLabels678(): Unit =
    testModel(Option(Set(LabelSix, LabelSeven, LabelEight)))

  @Test def testTrainedModelCanBeParsedAndUsedWithNoLabels(): Unit =
    testModel(Option(Set.empty), modelShouldProduceOutput = false)

  // This is really more of an integration test.
  @Test def testTrainingAndTesting(): Unit = {

    // ------------------------------------------------------------------------------------
    //  Preliminaries
    // ------------------------------------------------------------------------------------

    type Lab = Int
    type Dom = Vector[Lab]  // Not an abuse of notation.  Domain is indeed a vector of labels.

    val semantics = CompiledSemanticsInstances.anyNameIdentitySemantics[Dom]
    val optAud = OptionAuditor[Map[Lab, Double]]()

    // ------------------------------------------------------------------------------------
    //  Dataset and test example set up.
    // ------------------------------------------------------------------------------------

    // Marginal Distribution:          Pr[8] = 0.80 = 20 / 25 = (12 + 8) / 25
    //                                 Pr[4] = 0.40 = 10 / 25 = ( 2 + 8) / 25
    //
    val unshuffledTrainingSet: Seq[Dom] = Seq(
      Vector(    )  -> 3,   //            pr = 0.12 =  3 / 25   <-- JPD
      Vector(   8)  -> 12,  //            pr = 0.48 = 12 / 25
      Vector(4   )  -> 2,   //            pr = 0.08 =  2 / 25
      Vector(4, 8)  -> 8    //            pr = 0.32 =  8 / 25
    ) flatMap {
      case (k, n) => Vector.fill(n)(k)
    }

    val trainingSet = new Random(0).shuffle(unshuffledTrainingSet)

    val labelsInTrainingSet = trainingSet.flatten.toSet.toVector.sorted

    val testExample: Dom = Vector.empty

    val marginalDist = labelsInTrainingSet.map { label =>
      val z = trainingSet.size.toDouble
      label -> trainingSet.count(row => row contains label) / z
    }.toMap

    // ------------------------------------------------------------------------------------
    //  Prepare dataset specification and read training dataset.
    // ------------------------------------------------------------------------------------

    val datasetSpec = VFS.getManager.resolveFile(EndToEndDatasetSpec)
    val datasetJson = StringReadable.fromVfs2(datasetSpec).parseJson.convertTo[VwMultilabeledJson]

    val rc =
      new VwMultilabelRowCreator.Producer[Dom, Lab](labelsInTrainingSet).
        getRowCreator(semantics, datasetJson).get

    // ------------------------------------------------------------------------------------
    //  Prepare parameters for VW model that will be trained.
    // ------------------------------------------------------------------------------------

    val binaryVwModel = File.createTempFile("vw_", ".bin.model")
    binaryVwModel.deleteOnExit()

    val cacheFile = File.createTempFile("vw_", ".cache")
    cacheFile.deleteOnExit()

    val origParams =
      s"""
         | --quiet
         | --csoaa_ldf mc
         | --loss_function logistic
         | -f ${binaryVwModel.getCanonicalPath}
         | --passes 40
         | --cache_file ${cacheFile.getCanonicalPath}
         | --holdout_off
         | --learning_rate 5
         | --decay_learning_rate 0.9
       """.stripMargin.trim.replaceAll("\n", " ")

    // Get the namespace names from the row creator.
    val nsNames = rc.namespaces.map(_._1)(breakOut): Set[String]

    // Take the parameters and augment with additional parameters to make
    // multilabel w/ probabilities work correctly.
    val vwParams = VwMultilabelModel.updatedVwParams(origParams, nsNames, 2) fold (
      e => throw new Exception(e.errorMessage),
      ps => ps
    )

    // ------------------------------------------------------------------------------------
    //  Train VW model
    // ------------------------------------------------------------------------------------

    val vwLearner = VWLearners.create[VWActionScoresLearner](vwParams)
    trainingSet foreach { row =>
      val x = rc(row)._2
      vwLearner.learn(x)
    }
    vwLearner.close()

    // ------------------------------------------------------------------------------------
    //  Create Aloha model JSON
    // ------------------------------------------------------------------------------------

    val modelJson = VwMultilabelModel.json(
      datasetSpec = Vfs.apacheVfs2ToAloha(datasetSpec),
      binaryVwModel = Vfs.javaFileToAloha(binaryVwModel),
      id = ModelId(1, "NONE"),
      labelsInTrainingSet = labelsInTrainingSet,
      labelsOfInterest = Option.empty[String],
      externalModel = false,
      numMissingThreshold = Option(0)
    )

    // ------------------------------------------------------------------------------------
    //  Instantiate Aloha Model
    // ------------------------------------------------------------------------------------

    val factory = ModelFactory.defaultFactory(semantics, optAud)
    val modelTry = factory.fromString(modelJson.prettyPrint) // Use `.compactPrint` in prod.
    val model = modelTry.get

    // ------------------------------------------------------------------------------------
    //  Test Aloha Model
    // ------------------------------------------------------------------------------------

    val output = model(testExample)
    model.close()

    output match {
      case None => fail()
      case Some(m) =>
        assertEquals(marginalDist.keySet, m.keySet)
        marginalDist foreach { case (k, v) =>
          assertEquals(s"For key '$k':", v, m(k), 0.01)
        }
    }
  }

  /**
    *
    * @param desiredLabels Notice since this is a Set, label order doesn't matter.
    * @param modelShouldProduceOutput whether the model is expected to
    */
  private[this] def testModel(
      desiredLabels: Option[Set[Label]],
      modelShouldProduceOutput: Boolean = true
  ): Unit = {

    val factory =
      ModelFactory.defaultFactory(
        CompiledSemanticsInstances.anyNameIdentitySemantics[Set[Label]],
        OptionAuditor[Map[Label, Double]]()
      )

    // "${desired_labels_from_input}.toVector" returns the input passed to the model in
    // the form of a Vector.  See anyNameIdentitySemantics for more information.
    val desiredLabelFn = desiredLabels map (_ => "${desired_labels_from_input}.toVector")
    val json = modelJson(TrainedModel, AllLabels, desiredLabelFn)

    val modelTry = factory.fromString(json)
    val model = modelTry.get  // : Model[Set[Label], Option[Map[Label, Double]]]
    val x = desiredLabels getOrElse Set.empty
    val y = model(x)
    model.close()

    y match {
      case None =>
        if (modelShouldProduceOutput)
          fail("Model should produce output.  Produced None.")
      case Some(m) =>
        if (!modelShouldProduceOutput)
          fail(s"Model should not produce output.  Produced: $m")
        else {
          val expected = desiredLabels match {
            case None         => ExpectedMarginalDist
            case Some(labels) => ExpectedMarginalDist.filterKeys(labels.contains)
          }

          // The keys should be the same set, not a super set.
          assertEquals(expected.keySet, m.keySet)

          // Test the value associated with the label.
          expected foreach { case (k, v) =>
            assertEquals(s"For key '$k':", v, m(k), 0.01)
          }
        }
    }
  }

  private[this] def testEmpty(yEmpty: PredictionOutput): Unit = {
    assertEquals(None, yEmpty.value)
    assertEquals(Vector("No labels provided. Cannot produce a prediction."), yEmpty.errorMsgs)
    assertEquals(Set.empty, yEmpty.missingVarNames)
    assertEquals(None, yEmpty.prob)
  }

  private[this] def testOutput(
      y: PredictionOutput,
      labels: Set[Label],
      expectedMarginalDist: Map[Label, Double]
  ): Unit = y.value match {
    case None => fail()
    case Some(labelMap) =>
      // Should that model gives back all the keys that were request.
      assertEquals(labels, labelMap.keySet)

      // The expected return value.  We check keys first to make sure the model
      // doesn't return extraneous key-value pairs.
      val exp = expectedMarginalDist.filterKeys(label => labels contains label)

      // Check that the values returned are correct.
      exp foreach { case (label, expPr) =>
        assertEquals(expPr, labelMap(label), 0.01)
      }
  }
}

object VwMultilabelModelTest {
  private type Label  = String
  private type Domain = String
  private type PredictionOutput = RootedTree[Any, Map[Label, Double]]

  private[this] val TrainingEpochs = 30

  private val LabelSix   = "six"
  private val LabelSeven = "seven"
  private val LabelEight = "eight"

  private val ExpectedMarginalDist = Map(
    LabelSix   -> 0.6,
    LabelSeven -> 0.7,
    LabelEight -> 0.8
  )

  /**
    * The order here is important because it's the same as the indices in the training data.
    - LabelSeven is _C0_ (index 0)
    - LabelEight is _C1_ (index 1)
    - LabelSix   is _C2_ (index 2)
    */
  private val AllLabels = Vector(LabelSeven, LabelEight, LabelSix)

  private val EndToEndDatasetSpec =
    "res:com/eharmony/aloha/models/vw/jni/multilabel/dataset_spec.json"

  private lazy val Model: Model[Domain, RootedTree[Any, Map[Label, Double]]] = {
    val featureNames = Vector(FeatureName)
    val features     = Vector(GenFunc0("", (_: Domain) => Iterable(("", 1d))))

    // Get the list of labels from the comma-separated list passed in the input string.
    val labelsOfInterestFn =
      GenFunc0("",
        (x: Domain) =>
          x.split("\\s*,\\s*")
           .map(label => label.trim)
           .filter(label => label.nonEmpty)
           .toVector
      )

    val namespaces = List(("X", List(0)))
    val labelNs = VwMultilabelRowCreator.determineLabelNamespaces(namespaces.unzip._1.toSet).get.labelNs

    val predProd = VwSparseMultilabelPredictorProducer[Label](
      modelSource = TrainedModel,
      defaultNs   = List.empty[Int],
      namespaces  = namespaces,
      labelNamespace = labelNs,
      numLabelsInTrainingSet = AllLabels.size
    )

    MultilabelModel(
      modelId             = ModelId(1, "model"),
      featureNames        = featureNames,
      featureFunctions    = features,
      labelsInTrainingSet = AllLabels,
      labelsOfInterest    = Option(labelsOfInterestFn),
      predictorProducer   = predProd,
      numMissingThreshold = Option.empty[Int],
      auditor             = Auditor)
  }

  private def tmpFile() = {
    val f = File.createTempFile(classOf[VwMultilabelModelTest].getSimpleName + "_", ".vw.model")
    f.deleteOnExit()
    f
  }

  private val LabelNamespaces(labelNs, dummyLabelNs) =
    VwMultilabelRowCreator.determineLabelNamespaces(Set.empty).get

  private def vwTrainingParams(modelFile: File) = {

    // NOTES:
    //  1. `--csoaa_rank`  is needed by VW to make a VWActionScoresLearner.
    //  2. `-q YX`  forms the cross product of features between the label-based features in Y
    //     and the side information in X.  If the features in namespace Y are unique to each
    //     class, the cross product effectively makes one model per class by interacting the
    //     class features to the features in X.  Since the class labels vary (possibly)
    //     independently, this cross product is capable of creating independent models
    //     (one per class).
    //  3. `--ignore_linear Y`  is provided because in the data, there is one constant feature
    //     in the Y namespace per class.  This flag acts essentially the same as the
    //     `--noconstant`  flag in the traditional binary classification context.  It omits the
    //     one feature related to the class (the intercept).
    //  4. `--noconstant`  is specified because there's no need to have a "common intercept"
    //     whose value is the same across all models.  This should be the job of the
    //     first-order features in Y (the per-class intercepts).
    //  5. `--ignore y`  is used to ignore the features in the namespace related to the dummy
    //     classes.  We need these two dummy classes in training to make  `--csoaa_ldf mc`
    //     output proper probabilities.
    //  6. `--link logistic`  doesn't actually seem to do anything.
    //  7. `--loss_function logistic`  works properly during training; however, when
    //     interrogating the scores, it is important to remember they appear as
    //     '''negative logits'''.  This is because the CSOAA algorithm uses '''costs''', so
    //     "smaller is better".  So, to get the probability, one must do `1/(1 + exp(-1 * -y))`
    //     or simply `1/(1 + exp(y))`.
    val flags =
      s"""
         | --quiet
         | --csoaa_ldf mc
         | --csoaa_rank
         | --loss_function logistic
         | -q ${labelNs}X
         | --noconstant
         | --ignore_linear X
         | --ignore $dummyLabelNs
         | -f
       """.stripMargin.trim

    (flags + " " + modelFile.getCanonicalPath).split("\n").map(_.trim).mkString(" ")
  }

  private val FeatureName = "feature"

  /**
    * A dataset that creates the following marginal distribution.
    - Pr[seven] = 0.7  where seven is _0
    - Pr[eight] = 0.8  where eight is _1
    - Pr[six]   = 0.6  where six   is _2
    *
    * The observant reader may notice these are oddly ordered.  On each line _1 appears first,
    * then _0, then _2.  This is done to show ordering doesn't matter.  What matters is the
    * class '''indices'''.
    */
  private val TrainingData =

    Vector(
      s"shared |X $FeatureName\n2147483648:0.0 |$dummyLabelNs neg\n2147483649:-0.084 |$dummyLabelNs pos\n1:0.0    |$labelNs _1\n0:-0.084 |$labelNs _0\n2:-0.084 |$labelNs _2",
      s"shared |X $FeatureName\n2147483648:0.0 |$dummyLabelNs neg\n2147483649:-0.024 |$dummyLabelNs pos\n1:0.0    |$labelNs _1\n0:0.0    |$labelNs _0\n2:0.0    |$labelNs _2",
      s"shared |X $FeatureName\n2147483648:0.0 |$dummyLabelNs neg\n2147483649:-0.336 |$dummyLabelNs pos\n1:-0.336 |$labelNs _1\n0:-0.336 |$labelNs _0\n2:-0.336 |$labelNs _2",
      s"shared |X $FeatureName\n2147483648:0.0 |$dummyLabelNs neg\n2147483649:-0.056 |$dummyLabelNs pos\n1:0.0    |$labelNs _1\n0:-0.056 |$labelNs _0\n2:0.0    |$labelNs _2",
      s"shared |X $FeatureName\n2147483648:0.0 |$dummyLabelNs neg\n2147483649:-0.144 |$dummyLabelNs pos\n1:-0.144 |$labelNs _1\n0:0.0    |$labelNs _0\n2:-0.144 |$labelNs _2",
      s"shared |X $FeatureName\n2147483648:0.0 |$dummyLabelNs neg\n2147483649:-0.224 |$dummyLabelNs pos\n1:-0.224 |$labelNs _1\n0:-0.224 |$labelNs _0\n2:0.0    |$labelNs _2",
      s"shared |X $FeatureName\n2147483648:0.0 |$dummyLabelNs neg\n2147483649:-0.036 |$dummyLabelNs pos\n1:0.0    |$labelNs _1\n0:0.0    |$labelNs _0\n2:-0.036 |$labelNs _2",
      s"shared |X $FeatureName\n2147483648:0.0 |$dummyLabelNs neg\n2147483649:-0.096 |$dummyLabelNs pos\n1:-0.096 |$labelNs _1\n0:0.0    |$labelNs _0\n2:0.0    |$labelNs _2"
    ).map(_.split("\n"))

  private lazy val TrainedModel: ModelSource = {
    val modelFile = tmpFile()
    val params = vwTrainingParams(modelFile)
    val learner = VWLearners.create[VWActionScoresLearner](params)
    for {
      _ <- 1 to TrainingEpochs
      d <- TrainingData
    } learner.learn(d)

    learner.close()

    ExternalSource(Vfs.javaFileToAloha(modelFile))
  }

  private val Auditor = RootedTreeAuditor.noUpperBound[Map[Label, Double]]()

  private implicit def vecWriter[K: JsonWriter]: RootJsonFormat[Vector[K]] =
    DefaultJsonProtocol.vectorFormat(DefaultJsonProtocol.lift(implicitly[JsonWriter[K]]))

  private[multilabel] def modelJson[K: JsonWriter](
      modelSource: ModelSource,
      labelsInTrainingSet: Vector[K],
      labelsOfInterest: Option[String] = None) = {

    val loi = labelsOfInterest.fold(""){ f =>
      val escaped = f.replaceAll("\"", "\\\"")
      s""""labelsOfInterest": "$escaped",\n"""
    }

    val json =
      s"""
         |{
         |  "modelType": "SparseMultilabel",
         |  "modelId": { "id": 1, "name": "NONE" },
         |  "features": {
         |    "feature": "1"
         |  },
         |  "numMissingThreshold": 0,
         |  "labelsInTrainingSet": ${toJsonString(labelsInTrainingSet)},
         |$loi
         |  "underlying": {
         |    "type": "vw",
         |    "modelSource": ${toJsonString(modelSource)},
         |    "namespaces": {
         |      "X": [
         |        "feature"
         |      ]
         |    }
         |  }
         |}
       """.stripMargin.trim
    json
  }

  private def toJsonString[A: JsonWriter](a: A): String =
    implicitly[JsonWriter[A]].write(a).compactPrint

  /**
    * Creates the power set of the provided set.
    * Answer provided by Chris Marshall (@oxbow_lakes) on
    * [[https://stackoverflow.com/a/11581323 Stack Overflow]].
    * @param generatorSet a set for which a power set should be produced.
    * @tparam A type of elements in the set.
    * @return the power set of `generatorSet`.
    */
  private def powerSet[A](generatorSet: Set[A]): Set[Set[A]] = {
    @tailrec def pwr(t: Set[A], ps: Set[Set[A]]): Set[Set[A]] =
      if (t.isEmpty) ps
      else pwr(t.tail, ps ++ (ps map (_ + t.head)))

    // powerset of empty set is the set of the empty set.
    pwr(generatorSet, Set(Set.empty[A]))
  }
}


text:
#include <stdlib.h>
#include <memory.h>

#include <string>

#include <mbedtls/md.h>

#include <boost/format.hpp>

#include "parser_types.h"
#include "exceptions.h"
#include "parser.h"
#include "packet.h"

namespace parse4880 {

KeyMaterialPacket::KeyMaterialPacket(ustring content)
    : PGPPacket(content) {
}

uint8_t KeyMaterialPacket::version() const {
  return version_;
}

int64_t KeyMaterialPacket::creation_time() const {
  return creation_time_;
}

uint8_t KeyMaterialPacket::public_key_algorithm() const {
  return public_key_algorithm_;
}

PublicKeyPacket::PublicKeyPacket(const ustring& data)
    : KeyMaterialPacket(data) {
  /*
   * A public key packet contains the following:
   *
   *   [1] Version
   *   [4] Creation time
   *   [1] Public key algorithm
   *   [?] Key material
   */
  if (data.length() < 1) {
    throw invalid_packet_error("Empty public-key packet");
  }

  version_ = data[0];
  if (version_ != 4) {
    throw unsupported_feature_error(-1, "non-v4 keys");
  }

  if (data.length() < 6) {
    throw invalid_packet_error("v4 public key packet too short");
  }

  creation_time_ = ReadInteger(data.substr(1,4));
  public_key_algorithm_ = data[5];
  key_material_ = data.substr(6);

  /*
   * The fingerprint is calculated as the SHA-1 hash of the following:
   *
   *   1. The constant octet 0x99
   *   2. A two-octet length of of the packet.
   *   3. The entirety of the packet data.
   */
  mbedtls_md_context_t md_ctx;
  const mbedtls_md_info_t* md_type = mbedtls_md_info_from_type(MBEDTLS_MD_SHA1);
  mbedtls_md_init(&md_ctx);
  mbedtls_md_setup(&md_ctx, md_type, 0);
  mbedtls_md_starts(&md_ctx);

  mbedtls_md_update(&md_ctx, reinterpret_cast<const unsigned char*>("\x99"), 1);
  mbedtls_md_update(&md_ctx, WriteInteger(data.length(),2).c_str(), 2);
  mbedtls_md_update(&md_ctx, data.c_str(), data.length());

  size_t digest_length = mbedtls_md_get_size(md_type);
  std::unique_ptr<uint8_t[]> digest(new uint8_t[digest_length]);
  memset(digest.get(), '\0', digest_length);
  mbedtls_md_finish(&md_ctx, reinterpret_cast<unsigned char*>(digest.get()));
  mbedtls_md_free(&md_ctx);

  fingerprint_ = ustring(digest.get(), digest_length);
}

uint8_t PublicKeyPacket::tag() const {
  return 6;
}

std::string PublicKeyPacket::str() const {
  const ustring& key_fingerprint = fingerprint();
  char key_id[41]; // Flawfinder: ignore (fingerprints have known length)
  for(int i = 0; i < 20; i+=1) {
    snprintf(key_id+i*2, 3, "%02X",
             static_cast<unsigned char>(key_fingerprint[i]));
  }
  return (boost::format("Public key: %s")
          % key_id).str();
}

const ustring& PublicKeyPacket::fingerprint() const {
  return fingerprint_;
}

const ustring& PublicKeyPacket::key_material() const {
  return key_material_;
}

PublicSubkeyPacket::PublicSubkeyPacket(ustring contents)
    : PublicKeyPacket(contents) {}

uint8_t PublicSubkeyPacket::tag() const {
  return 14;
}

std::string PublicSubkeyPacket::str() const {
  const ustring& key_fingerprint = fingerprint();
  char key_id[41]; // Flawfinder: ignore (fingerprints have known length)
  for(int i = 0; i < 20; i+=1) {
    snprintf(key_id+i*2, 3, "%02X",
             static_cast<unsigned char>(key_fingerprint[i]));
  }
  return (boost::format("Public subkey: %s") % key_id).str();
}

}


text:
package net.smartrss.gateway.model.google.web;

import net.smartrss.gateway.model.google.GoogleResponse;

/**
 * Created by Alexander on 03.02.2016.
 */
public class GoogleSearchResponse implements GoogleResponse {

}


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE resources [
	<!ENTITY appname "Slideshow">
	<!ENTITY author "Michael Standen">
	]>

<resources>
	<string name="app_name">&appname;</string>
	<string name="action_settings">Einstellungen</string>
	<string name="action_credits">Info</string>

	<string name="inaccessible">(unerreichbar)</string>
	<string name="go_home_folder">Hängengeblieben? Klicken Sie hier, nach Ihren Persönlichen Ordner zu gehen.</string>

	<string name="title_activity_image">&appname;</string>

	<string name="delete_button">Löschen</string>
	<string name="delete_dialog_title">Bild löschen</string>
	<string name="delete_dialog_message">Bist du sicher?</string>
	<string name="image_deleted">Bild gelöscht</string>
	<string name="image_not_deleted">Bild konnte nicht gelöscht werden</string>

	<string name="share_button">Teilen</string>
	<string name="share_via">Teilen durch…</string>

	<string name="image_detail_dimensions">Dimensionen: %1$dx%2$d</string>
	<string name="image_detail_size">Dateigröße: %1$s</string>
        <string name="image_detail_modified">Geändert: %1$s</string>

	<string name="image_description">Bild</string>
	<string name="logo_description">Logo</string>

	<string name="title_activity_credits">Info &appname;</string>
	<string name="credits_creator">by &author;</string>
	<string name="credits_content1">Slideshow ist eine einfache Anwendung für die Anzeige von Bildern auf Ihrem Handy.
	</string>
	<string name="credits_content2">Ohne zusätzlichen Quatsch, diese Anwendung ist die einfachste Diashow-Anwendung auf dem Markt.
	</string>
	<string name="credits_content3">Sie können den Quellcode anschauen, Bugs protokollieren, oder Funktionen auf
		Github anfordern.
	</string>
	<string name="credits_content4">Diese Anwendung ist völlig kostenlos und Open Source; lizenziert
		unter den MIT Lizenz.
	</string>
	<string name="credits_content5">Danke an Yan Tsui
		für die Prüfung und den Aussehen der &appname; Ikone.
	</string>

	<string name="title_activity_settings">Einstellungen</string>

	<string name="pref_title_show_hidden_files">Verborgene Dateien anzeigen</string>
	<string name="pref_description_show_hidden_files">Zeigt auch Dateien, die von anderen Dateimanagern versteckt sind.
	</string>

	<string name="pref_title_show_thumbnails">Vorschaubilder anzeigen</string>
	<string name="pref_description_show_thumbnails">Zeigt Miniaturbilder an. Wenn Sie dies ausschalten, erhöht sich die Leistung, aber Sie werden nicht in der Lage sein, Bilder von anderen Daten zu unterscheiden.
	</string>

	<string name="pref_title_use_device_root">Stammverzeichnis des Gerätes verwenden</string>
	<string name="pref_description_use_device_root">Aktiviere die Navigation zum Stammverzeichnis des Gerätes. Dies ermöglicht den Zugriff auf Dateien überall auf dem Gerät, einschließlich montierten Speicher wie SD-Karten.
	</string>

	<string name="pref_title_slide_delay">Folienverzögerung</string>
	<string name="pref_description_slide_delay">Klicken Sie auf, um die Anzahl der Sekunden zu ändern, in der ein Bild angezeigt wird, bevor Sie zum nächsten Bild wechseln.
	</string>

	<string name="pref_title_image_details">Bilddetails anzeigen</string>
	<string name="pref_description_image_details">Die Bilddetails während der Diashow überlagern.
	</string>

	<string name="pref_title_stop_on_complete">Aufhören, wenn fertig</string>
	<string name="pref_description_stop_on_complete">Die Diashow aufhören, sobald jedes Bild gezeigt wurde.
	</string>

	<string name="pref_title_reverse_order">Umgekehrte Reihenfolge</string>
	<string name="pref_description_reverse_order">Die Bilder in der Diashow in umgekehrter Reihenfolge anzeigen.
	</string>

	<string name="pref_title_random_order">Zufällige Reihenfolge
</string>
	<string name="pref_description_random_order">Die Bilder in der Diashow in zufällige Reihenfolge anzeigen.
	</string>
</resources>


text:
<TITLE>Review for Un flic (1971)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Un flic (1971)

reviewed by
Dragan Antulov

UN FLIC (1971)
A Film Review
Copyright Dragan Antulov 2000

Among those who like to find the major influence on
Tarantino's work, John Woo and his ultra-stylish gangster
films from Hong Kong are the most obvious choice. However,
Woo himself was actually influenced by another film maker,
French director Jean-Pierre Melville, who used to create
cult following among some critics in 1960s and 1970s.
Melville, the biggest fan of American culture among
sometimes snobbish French filmmakers, built his reputation
by making ultra-stylish gangster movies about cops and
robbers as cold, detached professionals with highly personal
codes of ethics. Many of those films are considered to be
the classics. That includes UN FLIC, Melville's last film,
directed in 1971, two years before his death.

The movie's nominal protagonist is Edouard Coleman (played
by Alain Delon), police inspector whose character became
emotionally numb after witnessing too many deaths, tragedies
and human degradation in his everyday line of work. His
friend Simon (played by Richard Crenna) owns a small night
club in Paris, and the friendship is unchallenged even by
Coleman having affair with his wife Cathy (played by
Catherine Deneuve). Two of them, however, belong to the
opposite sides of the law, although Coleman doesn't know it
yet. Simon has led violent bank robbery in small coastal
town and the loot is going to finance another, even more
daring and ambitious stunt. In the meantime, Coleman gets
tipped off about huge shipment of drugs being smuggled on
the train.

In his last film, Melville showed his strength and some
weaknesses. The best thing about Melville is a sense of
style, mostly evident in the beginning scene - brilliantly
staged heist, with great atmosphere, pacing and superb
acting. Actually, this film could be viewed as pure style
accompanied with not so interesting content. Characters
aren't fleshed out enough, although they are played by
really superb actors. Alain Delon is excellent as extremely
cold, with almost pathological inability to show emotions.
On the other hand, Catherine Deneuve is used more like a
pretty face than real character. For Melville, casting was
opportunity to express his Americanophilia - Delon's
opposite is played by very good Richard Crenna, and Michael
Conrad (of later HILL STREET BLUES fame) is more than fine
as one of his crime partners. Melville was obviously more
interested into making elaborate and very effective heist
scenes, and they work splendidly (although the latter one,
including train, suffers from too obvious use of poor
special effects). Unfortunately, what connects those scenes
is not so interesting, and, even more important, not that
well-done. Script relies on too many coincidences, but it
also gives interesting insight into Melville's contrasting
view of those who break and enforce law. While gangsters in
this film conduct painstakingly planed heists that require a
lot of discipline and skill, policemen don't use much brain
- cases are solved through informants or simply by roughing
up suspects. On the other hand, flaws of the script and
characters are compensated with well-done atmosphere, thanks
to the grey overtones of Walter Wottiz's photography and
suggestive soundtrack by Michel Colombier. All in all, UN
FLIC, despite being imperfect and far away from cult
reputation of its creator, still represents very interesting
piece of genre cinema.

RATING: 7/10 (+++)

Review written on January 10th 2000

Dragan Antulov a.k.a. Drax
Fido: 2:381/100
E-mail: dragan.antulov@st.tel.hr
E-mail: drax@purger.com
E-mail: dragan.antulov@altbbs.fido.hr

Filmske recenzije na hrvatskom/Movie Reviews in Croatian
http://film.purger.com

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews